ArrayPrototypePush() is listed among the primordials with known
performance issues. Append with an indexed store instead where
stream/iter collects chunks or batches: batching sources in from() and
fromSync(), flattening transform output in pull() and pullSync(), the
batches of push() and of Readable sources, the output of the zlib/iter
transforms and the chunks collected by bytes() and similar consumers.
Like ArrayPrototypePush(), an indexed store is unaffected by changes to
Array.prototype.push and runs setters defined for indices on
Array.prototype.
bytes() is about 13% faster, pullSync() through a generator transform
and push() about 6%, and the other paths up to 4%.
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>
The hand-written stream/iter iterators queue calls made while another
one is in progress, as async generators do. They were queued in an
array taken off the front with ArrayPrototypeShift(), which copies the
rest of the queue, so calling next() many times without waiting was
quadratic: 160,000 concurrent next() calls on a from() iterator took 7
seconds.
Use a RingBuffer, kept once created, of QueuedOperation objects. The
same case takes 330 ms.
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>
Reads requested from a broadcast() consumer while another one is
pending were queued in an array and taken off the front with
ArrayPrototypeShift(), which copies the rest of the queue. Settling
many of them was quadratic: ending the writer with 160,000 reads
pending took 22 seconds.
Use a RingBuffer, starting small since the queue is rarely used. The
same case takes 56 ms. A new test covers the order in which several
pending reads are settled.
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>
merge() queued every batch from its sources in an array, taking each
off the front with ArrayPrototypeShift(), which copies the rest of the
queue: up to one entry per source.
Use a RingBuffer. Merging async generators yielding 16-byte chunks,
one per batch, is about 6% faster with 2 sources, 9% with 8 and 36%
with 64.
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>
When the output collected by a zlib/iter transform exceeded a batch,
drainBatch() took buffers off the front of the pending array with
ArrayPrototypeShift(), which copies the rest of the array. The sync
transforms collect all output for an input chunk before draining it, so
a small input that decompresses to many buffers took quadratic time:
with a chunkSize of 1024, decompressing 128 MiB took 5.6 seconds,
growing four times when the output doubles.
Take each batch from the front with a single slice, advancing an index,
and clear the slots taken so that the buffers can be collected. The
batches are unchanged; decompressing 128 MiB as above takes 151 ms.
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>
pull() read its pipeline through an async generator delegating to it
with yield*, and without transforms the pipeline was another such
generator around the source, each costing several promises per batch.
The pipelines already start lazily and queue calls as an async
generator does, so use the pipeline directly, and write the pipeline
without transforms out by hand: it checks the signal on the first
next(), then passes every call to the iterator reading the source.
Results are now IterResult objects, like those of the other stream/iter
iterators; one test compared them as ordinary objects.
With an async generator yielding 16-byte chunks, one per batch, pull()
is about 42% faster without transforms and 30% faster with a signal,
and about 12% faster through a transform.
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>
To read a source until a signal aborts, yieldAbortable() used an async
generator calling abortableNext() for every value, which added an abort
listener, raced the value against the abort with SafePromiseRace() and
removed the listener again with SafePromisePrototypeFinally(). This
made pull(), which always reads through its own signal, and pipeTo()
and the consumers with a signal about four times slower than without
one.
Write the generator out by hand with a single abort listener for the
whole iteration, held weakly so that the signal does not keep the
iterator alive, and wait for each value with a single promise that an
abort rejects. Aborts before, while and after reading a value, closing
the source on errors and aborts, and return() and throw() behave as
before.
With an async generator yielding 16-byte chunks, one per batch, pull()
is about 3.6x faster with or without a transform, pipeTo() with a
signal and a transform about 3.4x, and bytes() and array() with a
signal about 4.4x; pull() allocates about 7 KB less per chunk.
New tests cover an abort while the source is producing a value and the
removal of the listener.
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>
pipeTo() and pull() ran a pipeline of transforms through two async
generator layers for every batch: one applying each run of stateless
transforms, and the pipeline itself, which checks for an abort before
passing each batch on and cleans up when done. Each costs several
promises and an async frame per batch.
Write both out by hand, behaving the same way: the source is opened by
the first next(), calls made while one is in progress are queued, an
error from the source ends the pipeline without closing it, an error
from a transform closes it, return() and throw() close what is being
read, and the transforms' signal is aborted when the pipeline fails or
is stopped early. Transforms returning batches or chunks synchronously
take a single promise per batch for each layer; results that have to be
waited for or normalized asynchronously, the flush, and stateful
transforms are still handled by async generators.
With an async generator yielding 16-byte chunks, one per batch,
pipeTo() through one or two stateless transforms allocates about 900
bytes less per chunk and is about 38% faster.
The queue of operations for these iterators moves to utils.js. New
tests cover closing the source and aborting the transforms' signal.
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>
from() normalized a sync iterable source with an async generator, which
costs several promises and an async frame for every batch, even though
the source is read synchronously.
Read the source with a sync generator instead, which collects chunks
into batches as before, and normalize the values that need it, such as
promises, in an async iterator written out by hand around it. The sync
generator's for...of reads and closes the source as before: return()
and throw() are passed to it, after closing the value being normalized,
and an error normalizing a value is thrown into it, closing the source
as for an error in the loop body. As an async generator does, the
iterator stays busy until the tick after a result, so that calls made
synchronously after one are queued behind it.
With 16-byte chunks, one per batch, this allocates about 150 bytes less
per chunk; iterating from() is about 15% faster and pipeTo() about 11%
faster. Sources of single chunks, which are batched, are unchanged.
The queue of operations is now shared with the iterator for async
sources, and uses ArrayPrototypeShift(). New tests cover batching,
errors, closing and queuing for sync sources.
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>
from() normalized an async iterable source with an async generator
looping over it with for await, which costs several promises and an
async frame for every batch.
Replace it with an iterator written out by hand that behaves the same
way: nothing happens until the first next(), calls made while one is in
progress are queued, an error from the source ends the iteration
without closing the source, an error normalizing a value closes the
source first, return() closes the value being normalized and the source
and propagates errors from closing them, and throw() closes them
ignoring such errors. Values that are already Uint8Array[] batches or
Uint8Arrays take one promise per batch; any other value is normalized
by an async generator as before. Sync iterable sources are unchanged.
With an async generator yielding 16-byte chunks, this allocates about
440 bytes less per chunk; pipeTo() is about 28% faster and iterating
from() about 38% faster.
The results of the iterator are now IterResult objects, like those of
the other stream/iter iterators, rather than ordinary objects; one
test compared them as such. New tests cover the behavior above.
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>
The iterator through which from() reads an async source, to stay
cancellable while the source is pending, had an async next() that
awaited waitForNormalization() for every value: an async function
frame and promise, plus another promise and reactions for the wait.
Make next() a plain function that waits for the source's result with a
single promise, which a cancellation rejects directly. The result
checks, the closing of the source on cancellation and the precedence
between the source's result and a cancellation are unchanged.
With an async generator yielding 16-byte chunks, this allocates about
450 bytes less per chunk; pipeTo() is about 9% faster and iterating
from() about 11% 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>
pipeTo() and pipeToSync() created a batch entry for every batch, with
an array and a seven-field snapshot per chunk, to reject a chunk that
is resized or detached after being accepted. For the common
single-chunk batch, check the view around writeSync() with the
snapshot kept in locals instead, and create a batch entry in pipeTo()
only to fall back to write(). Views on SharedArrayBuffers and batches
of more chunks are still snapshotted as before, since writing one chunk
can change another.
With 16-byte chunks, one per batch, this saves about 100-175 bytes of
allocation per chunk: pipeTo() from a sync source is about 17% faster,
pipeToSync() about 15% faster and pipeTo() from an async generator
about 7% faster.
A new test covers detaching, resizing and growing a shared view in
writeSync() for both, and the fallback to write().
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>
When a source value is already a Uint8Array[] batch, from() and
fromSync() yielded it through `yield* yieldBoundedBatch(value)`, which
creates a generator for every batch only to split batches larger than
128 chunks. In the async normalization, yield* of a sync generator
also costs several extra promise ticks per batch.
Yield batches within the bound directly, and delegate to
yieldBoundedBatch() only for larger ones. Empty batches are still
skipped.
With 16-byte chunks, one per batch: pipeTo() from a sync iterable is
about 2x faster and iterating from() over it about 2.8x faster; from an
async generator, pipeTo() is about 1.5x and iteration about 1.7x
faster; pipeToSync() is about 1.4x 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>
The callback of the `newSession` event only checked that the handle was
still set. If a TLS error destroyed the socket while the callback was
pending, calling it afterwards still completed the handshake and
emitted `'secure'` and `'secureConnection'` on the destroyed socket.
Return early from it if the socket is already destroyed.
The callbacks of `OCSPRequest`, `SNICallback` and `resumeSession` do not
need the same check: the handshake does not read while they are
pending, so a TLS error cannot destroy the socket in the meantime, and
if the socket is closed some other way the existing `_handle` checks
already cover it.
Also, when the `SNICallback` returns a context that has no certificate,
for example one that only provides CAs, the handshake uses the
certificate of the server. The `OCSPRequest` event was still emitted
with the certificate and the issuer of that context, which are both
`null`. Use the context of the server in that case, so that the event
reports the certificate that is actually in use.
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/67650
Reviewed-By: Ethan Arrowood <ethan@arrowood.dev>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
CustomBufferJSListener keeps only the raw address (uv_buf_t) of the
user-supplied onread buffer, without retaining the backing store. If
application code transfers (and thereby detaches) that buffer during the
onread callback, for example by enqueuing a view into a byte
ReadableStream, the backing store is moved away from under the listener
and the raw address is left dangling. Reading subsequent peer data into
that address then corrupts memory the application owns, and if the
backing store is later released, it becomes a use-after-free.
Retain the backing store in CustomBufferJSListener so the raw address
never dangles, and stop reading when the onread callback detaches the
buffer so the stale address is not handed back to libuv.
Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: https://github.com/nodejs/node/pull/67542
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Paolo Insogna <paolo@cowtech.it>
The tests started one request chain per CPU, each issuing a new request
on every event loop turn until the first response arrived. On a loaded
macOS host this put more than 128 connections in flight, overflowing
the listen queue. The kernel then drops an incomplete connection and
answers its final ACK with a RST, so the client fails with
`connect ECONNRESET`.
Use a fixed number of concurrent requests and a fixed total instead.
Drive-by: the error handler in test-gc-http-client-onerror rethrows,
fix the comment that says it does nothing.
Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: https://github.com/nodejs/node/pull/67607
Refs: https://github.com/nodejs/node/issues/41399
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
Reviewed-By: Jake Yuesong Li <jake.yuesong@gmail.com>
Reviewed-By: Christian Aurich Zanettini Martins <christian.aurichzm@gmail.com>
Import attributes were created in C++ with v8::Object::New() and a
null prototype, once per module request and once per import() call.
Every import() call also created a `{ __proto__: null }`
diagnostics_channel context, which was discarded when module.import
had no subscribers. V8 creates all of these in dictionary mode.
Build the attributes from an ordinary object with its prototype set to
null, and only create the trace context when there are subscribers.
Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: https://github.com/nodejs/node/pull/67554
Refs: https://github.com/nodejs/node/pull/67552
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
V8 background jobs, such as concurrent Sparkplug and Maglev compiles,
can run into the heap limit. They then post a GC request to the main
thread and park in CollectionBarrier::AwaitCollectionBackground()
until the main thread collects garbage or the isolate is torn down.
process.exit() does neither. DefaultProcessExitHandlerInternal()
calls DisposePlatform() while the isolate is still alive and not
running JS, and NodePlatform::Shutdown() joins the worker threads.
A worker that is parked at that point never wakes up, and the join
hangs forever.
Pass the exiting isolate down to NodePlatform::Shutdown(). While the
workers finish their current tasks, the main thread checks every
10ms whether a foreground task was posted for that isolate. If so,
it drops the queued tasks, which would never run on this path, and
performs a GC so that the parked workers can finish. Normal exits
dispose the isolate before the platform and are not affected.
Fixes: https://github.com/nodejs/node/issues/64274
Signed-off-by: Manzoor Wani <manzoorwani.jk@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/66171
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Using `__proto__: null` on objects will properties immediately
puts them into the slower DictionaryProperties mode. Using a
`__proto__: { __proto: null }, ...` pattern, however, keeps
the objects in FastProperties mode.
Technically this is an observable change since calling
`Object.getPrototoTypeOf(...)` some of these will no longer
return `null`. So a decision needs to be made about whether
these types of changes are `semver-major` or not.
Signed-off-by: James M Snell <jasnell@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/66678
Reviewed-By: Robert Nagy <ronagy@icloud.com>
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: Ulises Gascón <ulisesgascongonzalez@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
V8 cannot collect block coverage for functions that are deserialized
from the code cache, so it only reports how many times each of them
ran. With a warm compile cache, branches that never ran inside those
functions are reported as covered, and tools that merge reports from
several processes can report functions that ran as never run.
The documentation recommended turning the cache off by hand. Do it
automatically when coverage collection starts with the process, through
NODE_V8_COVERAGE or --experimental-test-coverage.
The compile cache tests stop propagating NODE_V8_COVERAGE to the
processes they spawn, so that they keep working when the test suite
itself runs with coverage.
Signed-off-by: Shelley Vohr <shelley.vohr@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67120
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com>
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Document which digest and MAC options apply and how output lengths
work. Clarify signature contexts and distinguish required parameters
from optional defaults in Web Crypto.
Signed-off-by: Filip Skokan <panva.ip@gmail.com>
Assisted-by: Codex
PR-URL: https://github.com/nodejs/node/pull/67565
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>