Commit Graph
49744 Commits
Author SHA1 Message Date
Gürgün Dayıoğlu dd7bff52ce src: cache trace category lookups on hot paths
The sync fs, fs dir, AsyncWrap and vm.Script tracing guards called
TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED directly, which does a
by-name search in the tracing controller on every call. Use
TRACE_EVENT_CATEGORY_ENABLED instead, which caches the category
pointer per call site like the other TRACE_EVENT macros. Perfetto
already provides it; add an equivalent for the legacy tracing build.

Assisted-by: claude:opus-5.5
Signed-off-by: Gürgün Dayıoğlu <hey@gurgun.day>
PR-URL: https://github.com/nodejs/node/pull/67502
Reviewed-By: James M Snell <jasnell@gmail.com>
2026-11-23 20:45:49 +00:00
dennev 642300f7aa http: do not reuse expired free sockets
A free socket with an idle timeout is normally destroyed by its timer.
When the event loop is blocked long enough for that timeout to expire,
the timer cannot run, and `addRequest()` can reuse the socket even
though the server may already have closed the connection. This can
cause the request to fail with `ECONNRESET`.

Record when a socket enters the free pool and, before reuse, remove and
destroy a free socket whose idle timeout has expired according to the
timers' clock.

Refs: https://github.com/nodejs/node/issues/54293
Assisted-by: a closed-source coding agent
Signed-off-by: dennev <dennev13@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67292
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Ethan Arrowood <ethan@arrowood.dev>
2026-11-23 20:16:46 +00:00
Vladimir Morozov 5cddcfc08f build: keep PGO settings out of addon builds
Gate PGO generation and use flags on configuring_node so native addons
do not inherit Node.js-specific profiling settings from process.config.
The inherited Windows profile-use option is unquoted and breaks addon
builds when their paths contain spaces.

Preserve Node.js PGO flags and the Windows host-toolset exclusion.
Expand configuring_node early for the Windows target condition.

Refs: https://github.com/nodejs/node-addon-api/pull/1763
Signed-off-by: Vladimir Morozov <vmorozov@microsoft.com>
Assisted-by: AI coding assistant
PR-URL: https://github.com/nodejs/node/pull/67638
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Stefan Stojanovic <stefan.stojanovic@janeasystems.com>
2026-11-23 19:42:04 +00:00
Rafael Gonzaga 1a8cf165f5 path: avoid building error label per argument in resolve
Signed-off-by: RafaelGSS <rafael.nunu@hotmail.com>
PR-URL: https://github.com/nodejs/node/pull/66616
Reviewed-By: Ulises Gascón <ulisesgascongonzalez@gmail.com>
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
2026-11-23 18:03:00 +00:00
RafaelGSS 0b0d4053b8 child_process: copy split permission flag values
Signed-off-by: RafaelGSS <rafael.nunu@hotmail.com>
PR-URL: https://github.com/nodejs/node/pull/66725
Reviewed-By: Ulises Gascón <ulisesgascongonzalez@gmail.com>
2026-11-23 14:55:12 -03:00
Yaroslav Chuhai be1b3d62cf url: keep urlToHttpOptions() result in fast mode
urlToHttpOptions() built its result with `__proto__: null` ahead of a
spread, which makes V8 create the object in dictionary mode. Every
http.request() and https.request() called with a string or URL goes
through it, and ClientRequest immediately copies the result, so both
the property stores and the copy took the slow path.

Use `__proto__: kEmptyObject` instead, as ClientRequest already does
for its option copies. The object stays in fast mode and still
inherits nothing.

Signed-off-by: Yaroslav Chuhai <yaroslavchuhai@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67683
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: René <contact.9a5d6388@renegade334.me.uk>
Reviewed-By: James M Snell <jasnell@gmail.com>
2026-11-23 17:36:38 +00:00
Hamza Kargin d2dbf592ec stream: retry read after construct when hwm is 0
A read() made while construct() is pending is refused and leaves
needReadable set. After construction, maybeReadMore() does not read
for a non-flowing stream with highWaterMark: 0, so _read() was never
called and consumers such as toArray() or for await waited forever.

Retry the refused read once construction finishes when highWaterMark
is 0.

Fixes: https://github.com/nodejs/node/issues/67668
Assisted-by: AI coding agents
Signed-off-by: Hamza Kargın <hamzakargin@outlook.com>
PR-URL: https://github.com/nodejs/node/pull/67670
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Christian Aurich Zanettini Martins <christian.aurichzm@gmail.com>
2026-11-23 17:25:34 +00:00
Paolo Insogna 4da7a4baaf http: compute body chunk length from decoded bytes
Convert base64, base64url and hex strings to a Buffer before computing
the chunk length, so the announced length matches the bytes written
even when the input contains characters skipped while decoding.

Assisted-By: OpenAI GPT-5.6 Sol <openai/gpt-5.6-sol>
Signed-off-by: Paolo Insogna <paolo@cowtech.it>
PR-URL: https://github.com/nodejs/node/pull/67615
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Ethan Arrowood <ethan@arrowood.dev>
2026-11-23 17:15:43 +00:00
Rafael Gonzaga bb0acecc20 permission: reject empty reference in drop()
An empty reference passed to process.permission.drop() fell through to
dropping the whole scope, while has() treats it as not granted. Throw
ERR_INVALID_ARG_VALUE instead, in both the JS wrapper and the binding.

Signed-off-by: RafaelGSS <rafael.nunu@hotmail.com>
PR-URL: https://github.com/nodejs/node/pull/66732
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Ulises Gascón <ulisesgascongonzalez@gmail.com>
2026-11-23 16:51:42 +00:00
Chengzhong Wu 527dd80a41 lib: implement source map scopes decoder
Implements the stage 3 https://github.com/tc39/ecma426/blob/main/proposals/scopes.md
proposal decoder. This does not implement the stack trace formatter of
the scopes. The stack trace formatter will be in a follow-up.

Signed-off-by: Chengzhong Wu <cwu631@bloomberg.net>
PR-URL: https://github.com/nodejs/node/pull/67594
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
2026-11-23 16:43:40 +00:00
Chengzhong Wu b11733a351 lib: move source map VLQ decoding into its own module
Signed-off-by: Chengzhong Wu <cwu631@bloomberg.net>
PR-URL: https://github.com/nodejs/node/pull/67594
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
2026-11-23 16:43:39 +00:00
Zelalem Habtamu 3ece3fdb43 os: fix abort on negative zero pid or priority
Fixes: https://github.com/nodejs/node/issues/67648
Assisted-by: Claude Code
Signed-off-by: Zelalem Habtamu <zelalemhab19@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67651
Reviewed-By: Ethan Arrowood <ethan@arrowood.dev>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Stefan Stojanovic <stefan.stojanovic@janeasystems.com>
2026-11-23 16:43:27 +00:00
Christian Aurich Zanettini Martins 3cac7b92c8 build: re-run configure to regenerate out/Makefile
The out/Makefile rule runs gyp directly, without -Dconfiguring_node=1
and the other arguments configure.py passes. After a gyp file or
configure.py changes, the makefiles lose -fPIE and -pie, every object
is rebuilt, and node is only a PIE if the compiler defaults to it.

config.status writes config.gypi and out/Makefile together, so list
the gyp files under config.gypi and have out/Makefile depend on it
alone. out/Makefile only re-runs config.status itself when it is
missing or not newer than config.gypi, as after make clean. Building
through make with --ninja now also regenerates build.ninja after a
gyp change.

Signed-off-by: Christian Aurich Zanettini Martins <christian.aurichzm@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67534
Refs: https://github.com/nodejs/node/pull/67386
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
2026-11-23 13:51:49 +00:00
Yuya Inoue 3669956ded test: keep response open in http2 response limits test
The server ended the response before the request body arrived, so it
also sent RST_STREAM(NO_ERROR). When that frame reaches the client in
the same read as the rejected headers, the stream is closed by the
peer reset before the client's own reset is sent. On v26.x the request
then closes without an 'error' event and the test times out.

Leave the response open so that only the client resets the stream.

Refs: https://github.com/nodejs/node/pull/67114
Signed-off-by: inoway46 <inoueyuya416@gmail.com>
Assisted-by: Claude Code
PR-URL: https://github.com/nodejs/node/pull/67656
Refs: https://github.com/nodejs/node/actions/runs/44631511460
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
2026-11-23 11:15:53 +00:00
Tim Perry 1ad01d3f39 tls: disable TLS renegotiation by default, with a warning if enabled
This is the next step in the deprecation process for this, for v27. For
now we'll keep this available on an opt-in basis, but the following step
will be to remove it completely.

One case here does not warn: enabling renegotiation client side
explicitly, and using it just to accept server-initiated renegotiations.
This will be retained for legacy server support scenarios. Initiating
renegotiation from the client side still emits a warning.

Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67618
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
2026-11-23 08:55:38 +00:00
Christian Aurich Zanettini Martins 237d19297d quic: fix abort on handshake failure in connect()
Endpoint::Connect() marked the session as wrapped before sending the
first flight, while JavaScript had no QuicSession for it yet. If the
session closed during that send, for example with ciphers: '', nothing
called destroy() and the CHECK in Session::EmitClose() aborted the
process. Send the first flight before marking the session as wrapped,
so connect() rejects with ERR_QUIC_CONNECTION_FAILED instead.

Signed-off-by: Christian Aurich Zanettini Martins <christian.aurichzm@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67617
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Tim Perry <pimterry@gmail.com>
2026-11-23 08:47:15 +00:00
Nigro Simone 1ef44440a9 src: skip the async id stack when nobody sees it
With no async hook and no executionAsyncResource() user, every
InternalCallbackScope pushed and popped the async ids on the stack, only
for executionAsyncId() and triggerAsyncId() to read the top. Swap the
two ids in place instead: they are all that those two and
process.nextTick() read. executionAsyncResource() is the only reader of
the stack: the scopes that skip it form a chain in AsyncHooks, counted
in a new field, kLazyScopes, and JS asks C++ for the innermost one only
while that count is not zero. The checks for a corrupted stack stay.

Refs: https://github.com/nodejs/performance/issues/24
Signed-off-by: Nigro Simone <nigro.simone@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/66511
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
2026-11-23 07:13:45 +00:00
Hamza Kargin 45d1554464 fs: read data when highWaterMark is 0
ReadStream.prototype._read() passed the requested size straight to
the end-of-range check, so a size of 0 ended the stream before any
data was read. This happened for createReadStream() with
highWaterMark: 0, and since #66956 for every fs.ReadStream after
stream.setDefaultHighWaterMark(false, 0).

Read 64 KiB, the ReadStream default, when the requested size is 0.

Fixes: https://github.com/nodejs/node/issues/67667
Refs: https://github.com/nodejs/node/pull/66956
Assisted-by: AI coding agents
Signed-off-by: Hamza Kargın <hamzakargin@outlook.com>
PR-URL: https://github.com/nodejs/node/pull/67669
Reviewed-By: Christian Aurich Zanettini Martins <christian.aurichzm@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
2026-11-23 07:13:32 +00:00
Mattias Buelens ba42a2efee stream: fix stale byte stream queue size
Re-read the byte controller's queue size before filling each pending
read request. A released BYOB reader can leave a partially filled
pull-into descriptor that is enqueued while a default reader has
multiple pending reads. Caching the queue size causes the loop to
dequeue from an empty queue after fulfilling the first read request.

Add a regression test for one, two, and three pending reads and verify
that any remaining queued bytes are preserved.

Signed-off-by: Mattias Buelens <mattias@buelens.com>
PR-URL: https://github.com/nodejs/node/pull/67499
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
2026-11-23 06:57:22 +00:00
Nigro Simone d32f1bd113 stream: run a replaced write() in the flowing pipe
pipe() calls dest.write(). The fast path of a flowing pipe hands the
chunks of a source that pushes from _read() to dest._write() directly,
so a write() replaced on the instance or overridden in a subclass no
longer runs. A response that is a Writable, wrapped by compression
middleware, sent a gzip body with uncompressed chunks in it.

Take the fast path only when write() is Writable.prototype.write.

Refs: https://github.com/nodejs/node/pull/66182
Signed-off-by: Nigro Simone <nigro.simone@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/66596
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
2026-11-23 06:35:15 +00:00
Tamir Duberstein 660c104059 test: check the TLS server name on address-family fallback locally
The TLS address-selection test connects to nodejs.org twice. A reset
can fail the test before the handshake completes, and the addresses
returned by DNS determine whether the client ever tries a second one.

Run a TLS server on IPv4 loopback. With address-family selection
enabled, return IPv6 loopback first so the client has to switch TCP
handles. Check which server name reaches the server and keep certificate
verification enabled on the client.

Refs: https://github.com/nodejs/node/issues/46679
Assisted-by: Codex
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67595
Reviewed-By: Tierney Cyren <hello@bnb.im>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
2026-11-23 12:35:07 +10:30
James M Snell 10f56c3331 lib: graduate the --process-timeout option
Signed-off-by: James M Snell <jasnell@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67506
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Christian Aurich Zanettini Martins <christian.aurichzm@gmail.com>
2026-11-22 22:32:41 +00:00
Christian Aurich Zanettini Martins 2566f1b73d fs: fix abort on negative zero write length
`validateOffsetLengthWrite()` accepts -0 as a length, but V8 does not
represent -0 as an Int32 value, so the `IsInt32()` check in the binding
aborted the process in `fs.write()`, `fs.writeSync()` and
`filehandle.write()`.

Coerce the validated length to an int32 before the call, as `fs.read()`
already does.

Signed-off-by: Christian Aurich Zanettini Martins <christian.aurichzm@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67524
Refs: https://github.com/nodejs/node/pull/65888
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
2026-11-22 22:13:12 +00:00
Daniel Lemire a16ff8bb44 src: reserve simdjson padding in parsePackageJSON
`parsePackageJSON()` copies its input into a `std::string` with no
spare capacity. `simdjson::pad()` then appends `SIMDJSON_PADDING`
spaces, so every call reallocated and copied the whole document.
Reserve room for the padding when the input is copied so that the
append happens in place. The padding stays within the string's size,
so simdjson never reads past the end of the string.

Add a benchmark that parses the package.json files under deps/.

Assisted-by: an AI coding agent
Signed-off-by: Daniel Lemire <daniel@lemire.me>
PR-URL: https://github.com/nodejs/node/pull/67623
Refs: https://github.com/nodejs/node/issues/55584
Refs: https://github.com/nodejs/node/pull/55591
Refs: https://github.com/nodejs/node/pull/67620
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: James M Snell <jasnell@gmail.com>
2026-11-22 20:49:03 +00:00
Paolo Insogna 97d5d90135 https: encode all TLS fields in agent names
`https.Agent#getName()` joined several TLS options with `:` without
encoding them, so a value containing `:` could shift into the next field
and produce the same name as a different set of options. A `DataView`
passed as `dhparam` was also reduced to its type name.

Encode the remaining string, boolean, number, buffer and array valued
options, including `sigalgs`, with `getTlsOptionKey()`, which prefixes
the type and the length, like the options that were already encoded.

Assisted-By: OpenAI GPT-5.6 Sol <openai/gpt-5.6-sol>
Signed-off-by: Paolo Insogna <paolo@cowtech.it>
PR-URL: https://github.com/nodejs/node/pull/67641
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
2026-11-22 19:10:52 +00:00
Jiawen Geng f428cf213b sqlite: skip query trace while an exception is pending
Database::TraceCallback published sqlite.db.query from SQLite's
profile callback without checking for a pending JavaScript exception.
SQLite runs that callback from sqlite3_step() when a statement fails
and from sqlite3_reset(), so a throwing SQL function or an
out-of-range integer conversion called subscriber JS while an
exception was already set. Debug builds abort in V8's Invoke, and
release builds drop the original error or replace it with an empty
ERR_SQLITE_ERROR.

Return before publishing when the isolate has a pending exception or
JavaScript cannot be entered.

Assisted-by: Cursor Grok 4.7
Signed-off-by: gengjiawen <technicalcute@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67538
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
2026-11-22 18:50:06 +00:00
Jiawen Geng 3189560355 sqlite: finalize statements prepared during close
Database::FinalizeStatements() range-iterates statements_ and then
clears the set. Finalizing a statement with an open virtual-table
cursor runs the generator's finally block, which can prepare a new
statement and insert it into the set being iterated. That statement
is never finalized, so it keeps running after close() releases the
connection, and run() then dereferences a null connection.

Erase each statement before finalizing it and continue until the set
is empty, so statements created from that JavaScript are finalized
before the connection is released.

Assisted-by: Cursor Grok 4.7
Signed-off-by: gengjiawen <technicalcute@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67539
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
2026-11-22 18:49:50 +00:00
Antoine du Hamel 9a2046e198 tools: avoid early exit in release proposal linter
The current script exits at the first error, instead of listing all the
errors to fix.

Signed-off-by: Antoine du Hamel <duhamelantoine1995@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67666
Reviewed-By: Ruy Adorno <ruy@vlt.sh>
Reviewed-By: Tierney Cyren <hello@bnb.im>
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
2026-11-22 18:43:21 +00:00
Livia Medeiros 626d61a82c lib: replace SafePromiseAll with SafePromiseAllReturn*
`SafePromiseAllReturnArrayLike` and `SafePromiseReturnVoid` are
safer, faster alternatives to `SafePromiseAll`. The latter should
be used only when we expose returned value directly to userspace.

Signed-off-by: LiviaMedeiros <livia@cirno.name>
PR-URL: https://github.com/nodejs/node/pull/67602
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Chemi Atlow <chemi@atlow.co.il>
Reviewed-By: Jordan Harband <ljharb@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
2026-11-22 17:03:56 +00:00
James M Snell d46aeccac0 stream: swap the order of stream/iter result fields
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>
2026-11-22 08:28:25 -08:00
James M Snell 4220edbd3c stream: only release stream/iter reads cancellable while pending
Since e372bb1dca every kNextUncancellable read of a from() async source
registered a hook that releases the read when the normalization is
cancelled while it is pending. pipeTo() without a signal never cancels
then, and paid for the hook on every read: 2-5% on async pipes to a
write-only sink, measured in isolation.

Releasing is now asked for with kNextUncancellable(true), by the callers
that can cancel while a read is pending (pull() pipelines, pipeTo() with
a signal, the consumers with a signal). pipeTo() without a signal reads
as it did before e372bb1dca, with the same handlers.

pipeTo() of an async source to a write-only sink, no signal, 16-byte
chunks, isolated: 0.95-0.97x before this change, 0.98-1.01x after,
against the parent of e372bb1dca.

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>
2026-11-22 08:28:25 -08:00
James M Snell dcff791b1c stream: lighten single-chunk stream/iter broadcast()/share() batches
As for push() writes, broadcast() writes and the source batches share()
buffers were each kept as a BatchEntry with an array of views, also for
the common case of a single chunk, and broadcast's write() first wrapped
its chunk in an array.

createEntry() returns the chunk's FixedByteView for a single-chunk batch
and a BatchEntry otherwise; validateBatchEntry() and splitBatchEntry()
take either. broadcast() and share() buffer their batches with it, and
push()'s writev() too.

Allocation per chunk, two consumers, 16-byte chunks:
- share(), sync source: 722 -> 626 bytes; async source: 1944 -> 1848
- Broadcast.from(), sync source: 868 -> 752 bytes; async: 1873 -> 1783

testBufferedBatchViewResizeRejected checks that a view resized in a
buffered multi-chunk batch still rejects the read, for broadcast() and
share(). It also passes before this change.

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>
2026-11-22 08:27:34 -08:00
James M Snell 65b12f744a stream: skip batch entry for single-chunk stream/iter push() writes
Every push() write allocated, before the chunk was buffered, a [chunk]
array, a BatchEntry with a views array, and a FixedByteView; a read of
several buffered writes then validated each into an array of its own and
copied those into the batch it returns. That was most of what a write
costs (192 of 223 bytes for a 16-byte chunk, without pointer
compression).

A single-chunk write() or writeSync() now buffers the chunk's
FixedByteView itself, which has the byteLength a BatchEntry has; entries
are told apart by `views`, which a FixedByteView lacks. writev() keeps
its BatchEntry. A read validates the buffered views straight into the
batch it returns, and a pending write is checked without collecting its
chunks. The checks are the same as before.

Allocation per write (16-byte chunks; the consumer reads the buffered
writes as they come):
- writeSync(), falling back to write(): 223 -> 70 bytes
- await write(): 397 -> 246 bytes
- strings (pooled encoding): 315 -> 185 bytes

testBufferedEntriesReadTogether checks that single-chunk and batch
writes read together are delivered in order, and that a view resized
among them rejects the read. It also passes before this change.

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>
2026-11-22 08:27:34 -08:00
James M Snell e372bb1dca stream: avoid a promise per stream/iter from() read in pipelines
A pull() pipeline, pipeTo() with a signal and the consumers with a
signal reject their own pending pull, pipe or read when they are
aborted, and ignore the read of the source that is still pending then.
Yet they read a from() async source with its cancellable next(), which
gives every read a promise of its own so that a cancellation can reject
it at once: about 230 bytes per batch, for a rejection nobody waits for.

They now read such sources with kNextUncancellable, as pipeTo() without
a signal already did, when nothing but stream/iter code waits for the
reads: always for pipeTo() and the consumers, and for pull() pipelines
without stateful transforms. A stateful transform's generator waits for
the source in user code, so with one the reads stay cancellable and its
finally block still runs at once.

What makes this possible is that a cancellation now releases a pending
kNextUncancellable read instead of waiting for it: the normalization
ends, the source is closed at once (as for a cancelled next(), errors
ignored), and the operations queued behind the read, such as the
return() that cancelled it, run. The read settles when the source's
next() does, rejecting with the cancellation reason, and is ignored. A
pipeline stopped with return() or throw() while a pull is pending closes
its (stateless) transform layers without waiting for them, since they
wait for that read.

Allocation per batch, 16-byte chunks, async source:
- pipeTo() with a signal: 967 -> 738 bytes (as without a signal)
- pull() with one transform: 1518 -> 1289 bytes
- pipeTo() with a signal and one transform: 1829 -> 1601 bytes

test-stream-iter-abort-pending-read.js checks, for pull(), pipeTo() and
bytes(), with and without transforms and stopped by a signal, return()
or throw() while the source's next() is pending, that the call rejects
at once, the source is closed before that next() settles, and nothing
happens when it does. It also passes before this change.

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>
2026-11-22 08:27:34 -08:00
James M Snell a8faad05df stream: create the stream/iter share() read reaction once per consumer
share()'s #readAfterPull() created each consumer's afterPull() reaction
lazily with `state.afterPull ??= () => {...}`. Because the arrow
function captures `this` and `state`, V8 allocates its context on every
call of #readAfterPull(), even when afterPull() already exists: about 65
bytes per read that waits for the source.

afterPull() is now created by #createAfterPull(), so the context is only
allocated when it is.

share() fan-out, async source, two consumers, 16-byte chunks: 2065 ->
1944 bytes allocated per chunk.

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>
2026-11-22 08:27:34 -08:00
James M Snell ddf5a06268 stream: keep stream/iter broadcast waiters in reused lists
Broadcast notified waiting consumers by swapping #waiters for a new
SafeSet on every notification, so that a consumer re-waiting while being
notified was not processed twice. That happens for every chunk that
consumers wait for, and each Set operation allocates: the new Set, the
for...of iterator, and clear() or deleting the last entries (120-150
bytes each).

The waiters are now kept in two RingBuffers that are swapped back and
forth; the notified list is drained with shift() and cleared, keeping
its storage. A nested notification while the spare list is in use gets a
new one. A consumer detaching removes itself with indexOf()/removeAt(),
as it did with delete(); it is in the list at most once, as before.

Broadcast.from() fan-out, async source, two consumers, 16-byte chunks:
2036 -> 1873 bytes allocated per chunk.

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>
2026-11-22 08:27:34 -08:00
James M Snell 5e111aa370 stream: create stream/iter pending promises without a result object
The promises stream/iter creates per read, per write and per batch when
it has to wait (a pull() pipeline's pull, a from() async source's read,
a push() or broadcast() consumer's read and pending write, a share()
source read, drain waits, queued operations) were created with
PromiseWithResolvers(), which also allocates an object to return the
promise and its two functions in. Without pointer compression that is
299 bytes per call, against 214 for `new Promise(executor)` with an
executor that is created once.

newPendingPromise() / newResolveOnlyPromise() create the promise with a
shared executor that stores the resolving functions in module slots, and
takeResolve() / takeReject() take them from there right after. The
executor runs synchronously, so nothing can run in between. Paths that
create a promise once per stream or per call are unchanged.

Allocation per chunk (sampling heap profile, 16-byte chunks):
- for await over from(asyncSource): 1053 -> 967 bytes
- pull() with one transform, async source: 1692 -> 1518 bytes
- pull() with one transform, sync source: 917 -> 838 bytes

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>
2026-11-22 08:27:34 -08:00
James M Snell 09e0f99f9d stream: do not keep stream/iter from() sync sources busy for a tick
The iterator of from() over a sync iterable stayed busy until the
microtask after every result it produced synchronously, as an async
generator stays busy until the tick after a yield, so that a call made
synchronously after one was queued behind it. That cost a microtask per
batch, also when nothing was ever queued.

Settle each operation when its result is known instead, as the
normalizer of async sources does: a call made after one that finished
synchronously now runs at once, and calls queued while one was in
progress, such as behind a value normalized asynchronously, still run
a microtask later. Only calls made back to back without awaiting are
affected: a second next() reads the source during the call, and a
return() made after it no longer cancels it, as it did when it was
still queued. The other iterators of from(), for values and async
sources, already behaved this way. The queue's release() is no longer
used.

Iterating from() over a sync source yielding one-chunk batches is
about 1.38 times faster, now on par with a ReadableStream, and with
64-chunk batches about 7% faster.

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>
2026-11-22 08:27:34 -08:00
James M Snell bef7ce4622 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>
2026-11-22 08:27:34 -08:00
James M Snell 8fedfbf1bf stream: normalize stream/iter fromSync() inputs without generators
fromSync() returned null-prototype object literals, which V8 creates in
dictionary mode, whose iterators were sync generators: one for values
that need no normalization, and two layers, an outer generator
delegating to normalizeSyncSource(), for iterables, resumed for every
batch.

Use classes, as from() does since the previous commits: SyncBatchSource
for values, the sync counterpart of BatchSource, and SyncSource for
iterables, whose iterator reads the source with the SyncSourceReader of
from() and normalizes other values with normalizeSyncValue(). The
iterators behave as the generators did: iterables can be iterated
again, and return(), throw() and errors normalizing a value close the
source as for...of does. normalizeSyncSource() is no longer used.

Creating a sync stream from a value and reading it is about 18 times
faster. Reading a sync source one chunk per batch with for...of is
about 1.8 times faster, and piping it with pipeToSync() about 1.5 times
faster.

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>
2026-11-22 08:27:34 -08:00
James M Snell cdb4bb3319 stream: create stream/iter from() value streams as class instances
from() of a value that needs no normalization (a string, a buffer, a
Uint8Array[]) returned an object literal with a null prototype, which
V8 creates in dictionary mode, and each of its iterators was an object
literal passed to ObjectSetPrototypeOf(), a runtime call. Together they
were three quarters of the time to create and read such a stream.

Use two classes, BatchSource and BatchIterator, whose prototypes do not
inherit from Object.prototype either, as before.

Creating a stream from a 16-byte chunk and reading it is about 6.5
times faster, and from a one-chunk array about 5.5 times faster.

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>
2026-11-22 08:27:34 -08:00
James M Snell b3f4ce7077 stream: pump stream/iter Broadcast.from() sources with fewer layers
Broadcast.from() read its source through yieldAbortable(), adding a
promise, a race and an operation queue to every batch, and wrote each
batch with the public writevSync(), converting the batch from() had
already normalized as a Web IDL sequence and checking every chunk
again.

Read the source as pipeTo() does with a signal: one abort listener for
the whole pump, with raceSignal(), and, for a sync source with a
'strict' or 'unbounded' policy, batches read synchronously with
from()'s kNextSyncBatch while the writes succeed synchronously. The
first batch is still read asynchronously, so that it is written after
Broadcast.from() has returned and its consumers have been created; with
'drop-oldest' or 'drop-newest', whose writes always succeed, every batch
is. Write batches to the writer without converting them again. As
before, a cancellation or an abort closes the source without waiting
for a pending read, and an error writing a batch closes it.

With two consumers of Broadcast.from() of 16-byte chunks one per batch,
reading a sync source is about 1.9 times faster, and an async source
about 1.4 times faster.

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>
2026-11-22 08:27:34 -08:00
James M Snell 03f1b40542 stream: read stream/iter share() sync sources at once
A share() consumer that needed the next batch of the source always
waited for an asynchronous read of it, also when the source was a sync
iterable that from() can read synchronously, and every such read added
a reaction to clear the consumer's pending read when it settled.

When there is room in the buffer and no read of the source is pending,
read a batch of a sync source synchronously, with from()'s
kNextSyncBatch, as pipeTo() does: the consumer then gets it at once.
Values that from() normalizes asynchronously are still read
asynchronously. A read waiting for the source now clears itself from
the consumer's pending read when it settles, without a reaction of its
own; only next() calls queued behind another still add one.

With two consumers of a share of a sync source, one 16-byte chunk per
batch, reading is about 2.4 times faster, on par with tee() of a
ReadableStream, with 60% less allocated per chunk. For an async source
it is about 7% faster.

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>
2026-11-22 08:27:34 -08:00
James M Snell 7b656b0d58 stream: read stream/iter from() sync sources without a generator
from() read sync iterable sources with a sync generator doing
for...of over the source, resumed for every batch. Its next() calls
went through FunctionPrototypeCall(), which V8 does not inline for the
next() of a generator.

Read the source with SyncSourceReader, which does what that generator
did, written out by hand: it collects single chunks into batches,
splits oversized batches, flushes before other values, and closes the
source as for...of does on return(), throw() and cancellation. It
calls the next() of a generator as the constant
%GeneratorPrototype%.next, and an own next() method as
iterator.next(), so that V8 can inline either. Like for...of, it reads
next() only once.

Iterating from() over a sync source yielding one-chunk batches is about
15% faster, and over a generator yielding single chunks about 6-11%
faster. Piping a sync source to a writer is about 20% faster.

The microtask that keeps the normalizer busy until the tick after each
batch, for async generator parity, is the remaining per-batch cost;
note it.

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>
2026-11-22 08:27:33 -08:00
James M Snell 22fd89feab stream: apply stream/iter stateful transforms without async generators
Every stateful (generator) transform in an async pipeline added two
async generators of stream/iter's own to every batch, besides the
transform's: one to append the null flush signal to its source, and one
to read and normalize its output. Validated transforms, such as
compression, added one.

Write both out by hand. The source of the transform passes reads to the
pipeline with one reaction each, then yields null once, and passes
return() and throw() on as yield* does. The output is read with one
reaction per item, and normalized as before; outputs that are not async
iterables are still read by an async generator, as for await reads them.
The transform is still called on the first pull.

For 16-byte chunks one per batch, iterating pull() with one stateful
transform is 23-31% faster, and with three 36-45% faster; compression
is unchanged.

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>
2026-11-22 08:27:33 -08:00
James M Snell b2c5fd1f5f stream: read stream/iter share() consumers without a chain per read
Every next() of a share() consumer chained on the consumer's previous
next() and ran an async function, also when the batch was already
buffered, as it is for every consumer but the first to read it. Every
read of the source ran an async function, and each consumer waiting
for it queued a promise of its own. Recomputing the slowest consumer's
cursor, once per batch with several consumers, allocated an object.

A next() that finds its batch buffered, or the end, now settles at
once, without waiting for anything. Only a next() that waits for the
source is waited for by the next one; when there is room in the buffer
it waits for the read with one reaction, without an async function.
Consumers waiting for the same read of the source share one promise,
which a cancellation resolves at once, and the read is handled by
functions created once per share. getMinCursor() reuses its result.

With two consumers of a share of 16-byte chunks one per batch, reading
a sync generator is about 1.8 times faster, and an async generator about
1.7 times faster, with 60% less allocated per chunk.

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>
2026-11-22 08:27:33 -08:00
James M Snell 2202b8e92e stream: encode small stream/iter strings into a pool
stream/iter encoded every string written, yielded or piped with
TextEncoder.encode(), into an ArrayBuffer of its own. Writing many
small strings, as a server-side renderer does, was then mostly the cost
of allocating them.

Encode strings whose UTF-8 encoding certainly fits in 8 KiB into a
64 KiB pool, as Buffer.from() does, with the fast API utf8WriteStatic(),
and pass on views of it. The pool is untransferable, so that
transferring the buffer of one chunk cannot detach the others.

For SSR-like strings of about 65 bytes, writing to a push() stream with
writeSync() is about 4 times faster, and with await write() about 2.2
times faster.

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>
2026-11-22 08:27:33 -08:00
James M Snell 8d818a8799 stream: write to stream/iter writers with only write() inline
pipeTo() to a writer without writeSync() created a batch entry with an
object for every chunk, and wrote it in an async function, which every
batch then awaited, even when write() returned undefined.

Write single chunks directly, checking the view's byteLength around
write() and after the promise it returns, and batches of several chunks
from a FixedBatch, which records their byteLengths in an array. Only a
promise returned by write() is awaited.

For 16-byte chunks one per batch, piping a sync generator to a writer
with only write() is about 2 times faster, as fast as to one with
writeSync(), and piping an async generator about 1.3 times faster.

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>
2026-11-22 08:27:33 -08:00
James M Snell a143f03cfd stream: check stream/iter byte views by their byteLength alone
To detect that a byte view was resized or detached after being
accepted, stream/iter recorded, for views not known to be of a
fixed-length, non-shared buffer, a snapshot object with the view's
buffer, the buffer's byteLength and detached state, and the view's
byteLength and byteOffset. Telling the two cases apart read every
view's buffer, which for a small typed array that V8 keeps on the heap,
such as one just allocated by a transform, moves its contents to a new
ArrayBuffer.

What stream/iter accounts for a view is its byteLength, and a view whose
bytes are no longer those accounted for has a different byteLength: a
detached view, a view out of bounds of a shrunk buffer, and a
length-tracking view of a resized or grown buffer. Record and check the
byteLength alone, without reading the buffer, for every view. A
fixed-length view of a resizable buffer that is resized while the view
stays in bounds, whose bytes are unchanged, is no longer rejected.

For 16-byte chunks, piping through a transform that copies each chunk
is about 1.6 times faster, and 2.8 times with pipeToSync(); piping a
sync generator of 64-chunk batches about 1.75 times faster; and piping a
sync generator one chunk per batch to a writer with writeSync() about
1.2-1.3 times faster.

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>
2026-11-22 08:27:33 -08:00
James M Snell 921a43b755 stream: read stream/iter from() async sources in one reaction
from() read an async source through yieldNormalizationAbortable(),
whose next() a cancellation can interrupt: for every batch it created a
promise with three closures, a reaction to the source's result, and an
iterator result, and the normalizer then took another reaction and
another iterator result. Only pipeTo() without a signal avoided this,
with kNextUncancellable.

Give yieldNormalizationAbortable() a read, kRead, that calls handlers
set once by the normalizer, so that it takes no closure, and handle the
source's result in the same reaction. The normalizer's pending read is
a promise of its own, which a cancellation rejects as before. A batch
passed on unchanged keeps the iterator result of the read.

For 16-byte chunks one per batch, iterating from() of an async
generator is 13-20% faster and allocates about 370 bytes less per
batch; piping one with a signal is 11-15% faster.

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>
2026-11-22 08:27:33 -08:00