Repository navigation
stream: preserve mutable chunks in Web Stream adapters - #64579
seungwoo505 wants to merge 23 commits into
Conversation
|
Review requested:
|
| @@ -1260,4 +1262,5 @@ module.exports = { | |||
| validateHeaderName, | |||
| validateHeaderValue, | |||
| OutgoingMessage, | |||
| outgoingMessagePrototypeWrite, | |||
There was a problem hiding this comment.
The Web Streams adapter uses this export to compare the active write() method with the original OutgoingMessage.prototype.write.
This distinction preserves the native validation behavior without applying it to overridden write() implementations.
The reference is captured here so a later prototype monkey-patch is not mistaken for the original method.
97f5318 to
c08321a
Compare
|
Hi @bjohansebas, just a friendly follow-up on this. |
|
Sorry for the radio silence. Can you rebase again? |
|
Sorry, I just saw your message. |
c08321a to
062b9a0
Compare
|
Hi @mcollina, I’ve rebased the PR onto the latest main and resolved the conflicts. |
|
Benchmark GHA (webstreams / adapters): https://github.com/nodejs/node/actions/runs/36556500893 Results
Benchmark results:
|
|
The benchmark shows a significant drop for |
|
I’ve confirmed the performance regression shown in the benchmark. |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #64579 +/- ##
==========================================
- Coverage 90.59% 90.58% -0.02%
==========================================
Files 802 802
Lines 286656 287368 +712
Branches 55383 55578 +195
==========================================
+ Hits 259710 260318 +608
- Misses 17058 17140 +82
- Partials 9888 9910 +22
🚀 New features to boost your workflow:
|
3c2a3c3 to
620db54
Compare
|
Hi @panva, I've pushed updates to reduce the extra scheduling and Promise allocations in write completion, and to optimize BufferSource copying. |
|
Benchmark GHA (webstreams / adapters): https://github.com/nodejs/node/actions/runs/36878990003 Results
Benchmark results:
|
|
I wonder if we should also check an asynchronous Writable with The case below defers both callbacks with diff --git a/benchmark/webstreams/adapters.js b/benchmark/webstreams/adapters.js
--- a/benchmark/webstreams/adapters.js
+++ b/benchmark/webstreams/adapters.js
@@ -15,6 +15,7 @@ const bench = common.createBenchmark(main, {
'readable-to-web',
'readable-from-web',
'writable-to-web',
+ 'writable-to-web-async-writev',
'writable-from-web',
],
});
@@ -68,6 +69,26 @@ async function writableToWeb(n) {
bench.end(n);
}
+async function writableToWebAsyncWritev(n) {
+ const chunk = Buffer.alloc(1024);
+ const streamWritable = new Writable({
+ highWaterMark: 64 * 1024,
+ // Defer completion so subsequent writes can be batched in writev().
+ write(chunk, encoding, callback) {
+ setImmediate(callback);
+ },
+ writev(chunks, callback) {
+ setImmediate(callback);
+ },
+ });
+ const writer = Writable.toWeb(streamWritable).getWriter();
+ bench.start();
+ for (let i = 0; i < n; i++)
+ await writer.write(chunk);
+ await writer.close();
+ bench.end(n);
+}
+
function writableFromWeb(n) {
const chunk = Buffer.alloc(1024);
const writableStream = new WritableStream({
@@ -99,6 +120,9 @@ function main({ n, kind }) {
case 'writable-to-web':
writableToWeb(n);
break;
+ case 'writable-to-web-async-writev':
+ writableToWebAsyncWritev(n);
+ break;
case 'writable-from-web':
writableFromWeb(n);
break; |
|
I've added the writable-to-web-async-writev benchmark you suggested. |
|
I've investigated ways to reduce the regression while preserving the existing completion guarantees and error propagation, but haven't found an effective alternative so far. |
|
Benchmark GHA (webstreams / adapters.js): https://github.com/nodejs/node/actions/runs/37113468541 Results
Benchmark results:
|
| // in the queue, and wait our turn. Otherwise, call _write | ||
| // If we return false, then we need a drain event, so set that flag. | ||
| function writeOrBuffer(stream, state, chunk, encoding, callback) { | ||
| function writeOrBuffer(stream, state, chunk, encoding, callback, onwrite) { |
There was a problem hiding this comment.
We should not be modifying this function for this
There was a problem hiding this comment.
I added onwrite as part of the copied-chunk _writev batching optimization to preserve async context across buffered writes.
Could you elaborate on your concern with changing writeOrBuffer() here?
I’d like to revise the approach accordingly.
There was a problem hiding this comment.
none of what you are talking about here matches the PR title, description or the bug you are trying to fix
There was a problem hiding this comment.
Thanks for the feedback.
I verified that the patch still fixes the buffer reuse bug and preserves _writev batching without changing writeOrBuffer().
|
@mcollina I’ve been thinking about your comment that the changes no longer match the PR title and description. Looking back at the version you initially approved, I think the changes were fairly limited and focused on fixing the bug. After @panva pointed out the performance regression, I tried to address it. In the process, the scope grew, and the PR ended up looking quite different from what I originally submitted. I was wondering if we could discuss how best to revise the PR from here. I’d appreciate your thoughts. |
Wait for native write callbacks when they can safely represent chunk consumption. For Duplex streams, corked writes, and custom or legacy write methods, pass private BufferSource copies to preserve completion timing. Coordinate callback completion with backpressure, aborts, and stream errors so a settled Web Streams write no longer exposes mutable bytes still retained by the native stream. Preserve native HTTP validation and SharedArrayBuffer backing when fallback copies are required. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Cover native callback completion, fallback copies, aborts, and error propagation for mutable BufferSource chunks passed to Node.js Web Streams adapters. Verify HTTP validation, SharedArrayBuffer backing, and Duplex and compression paths. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Rely on native stream validation after copying array buffer views. Keep object-mode writes on their existing completion timing, and remove adapter-only HTTP detection and prototype capture. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Remove overlapping override coverage. Verify object-mode writes settle independently of native callbacks. Exercise the Writable.toWeb(Duplex) path and keep native HTTP validation coverage. Assisted-by: Codex Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Use the Float16Array constructor captured during Node.js initialization instead of reading it from globalThis when the adapter is loaded. This prevents changes to the global constructor from affecting chunk cloning. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Use private Buffer storage for ArrayBuffer-backed copies and reuse it for Buffer inputs. Read view metadata through intrinsic getters and avoid redundant type checks. Preserve view types, raw bytes, and independent backing. Cover initialized backing without requiring an exact allocation size. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Observe synchronous native write completion without waiting for a public write callback tick. Resume pending writes without allocating a promise capability when async hooks and context propagation allow it. Coordinate callback completion, drain, and abort while preserving async context, Promise reaction order, and error delivery. Cover mixed completion modes, lifecycle changes, and modified Promise properties. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Preserve the original HTTP write type error when cloning an invalid DataView fails. Only restore validation for the unmodified native write method, leaving overridden methods on the copy fallback. Cover resizing before and after enqueue and changes to HTTP write methods. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Reject close() when the native stream was destroyed before finishing, so end() cannot mask a premature close before eos reports it. Preserve the native error when available and cover synchronous and asynchronous destruction, legacy streams, and normal autoDestroy. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Remove cases now covered by the dedicated copy and lifecycle tests. Keep compression coverage focused on completing a write before reading output and preserving bytes after the input is reused. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Document when a mutable chunk can be reused after writer.write() fulfills, and prohibit mutation while the write is pending. Explain copying in byte mode, reference passing in object mode, and preservation of bytes retained by a Duplex readable side. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Add an asynchronous Writable.toWeb() benchmark with write and writev callbacks deferred by setImmediate. Use 1 KiB chunks and a 64 KiB highWaterMark to measure changes in native batching. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Copy small byte chunks after observing asynchronous writes so the adapter can accept subsequent writes without waiting for each native callback. Keep large chunks on the callback path and separate copied batching from the regular synchronous write path. Carry queued write completion context through native Writable buffering and writev batches. Preserve ALS state with async hooks and legacy context propagation. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Add regression coverage for byte reuse, large chunks, mixed writev batches, and errors reported after early acceptance of copied writes. Check ALS context across queued writes and writev completion with async hooks and legacy context propagation, including init-hook boundaries. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Remove references to the retired legacy AsyncLocalStorage path and AsyncContextFrame.enabled. Preserve AsyncResource callbacks when async hooks are enabled and use frame swapping otherwise. Remove obsolete --no-async-context-frame subprocess runs from the context regression tests. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Prepare independent ArrayBuffers in bounded batches. Recycle a backing store after its last owner releases it and track native ownership per group. Cover reuse, trimming, transfers and native aliases. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Copy small byte views into private storage and release the native pool when the stream finishes or fails. Preserve callback context and cover retained, transferred and interleaved writes. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Track the first write request directly and start eligible writes without creating a controller queue entry. Cover reentrant writes during size calculation and promise creation. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Check the source before taking a buffer from a warmed copy batch. Keep shared inputs on the shared-copy path and test that the next ordinary write can use the reserved buffer. Consolidate write completion handling in Writable.toWeb and clarify chunk reuse for Duplex streams. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Restore the bundled V8 sources and remove Node's private V8 hooks. Keep batch allocation and recycling on public V8 APIs, and exercise shared writes through the Node stream adapter. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Queue copied chunks through Writable.write() and restore the shared Writable buffering path. Keep direct completion for borrowed buffers. Remove the unused write request helper and align the batching tests with the adapter's byte order and Promise context behavior. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
Reuse the captured write method for the Buffer fast path so custom accessors are evaluated once. Keep completion, drain, and abort results available while the pending write is set up. Cover reentrant completion and abort from writableNeedDrain and async hooks. Remove test steps that duplicate existing checks. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
8690263 to
0025e4b
Compare
Use separate promise handlers to record write completion and rejection while keeping the setImmediate checkpoint. Signed-off-by: seungwoo <zoozoo1302@gmail.com>
|
The recommendations in: advise you should tackle only one issue at a time and that you should not open any new PRs until your first PR has been approved. You have opened a new PR #67983 in addition to this one. To stay within the guidelines, you may de-prioritize this PR or other open PRs by setting them to draft status. Until the first PR has been approved and has landed in the Waiting until the first PR has landed ensures that you as a contributor have experienced the complete process from PR submission to successful landing. After this has been completed, any new PRs or new commits to an existing PR are treated to rules for regular Contributors. GitHub Actions CI workflows are then run automatically without intervention by a team member. |
Thank you for pointing me to the first-time contributor guide. |
Thank you! Considering also the previous review comments about this PR, it may be cleaner and easier to understand if you close this PR and start a new one at a later time with matching title / description / commits. |
When a Node.js writable is converted with
Writable.toWeb(), the Web Streamswrite()promise can currently settle as soon as the nativewrite()callreturns
true. That return value only represents backpressure, so the nativestream may still retain the supplied mutable BufferSource. Reusing the buffer
after awaiting the Web write can therefore change bytes that have not yet been
consumed.
This change:
unmodified
Writable;drain, aborts, and native streamerrors;
and legacy write paths where waiting for a callback would change existing
completion behavior;
The original native
Writable.prototype.writeandOutgoingMessage.prototype.writemethods are captured so patched methods andaccessors are classified and invoked consistently.
Validation included:
make -j4 test(full test suite passed)git diff --checkFixes: #64549