Skip to content

Third round of TS streams perf improvements - #8188

Merged
jasnell merged 12 commits into
mainfrom
jasnell/ts-streams-perf-pass-3
Nov 4, 2026
Merged

jasnell merged 12 commits into
mainfrom
jasnell/ts-streams-perf-pass-3

Conversation

@jasnell

@jasnell jasnell commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

Across the full benchmark TypeScript is now 0.22x the C++ time overall (262 cases), down from 0.28x at the PR 8174 head. 17 cases are still slower than C++, down from 24.

@jasnell
jasnell added this pull request to stack #8175 November 3, 2026 16:27
@jasnell
jasnell requested review from a team as code owners November 3, 2026 16:27

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the review of ffb97226.

This review, of fd98894b

💬 Approved with comments — No correctness, security or performance problems were found in the streams changes. One stale developer-guide reference to the removed utils.getPrivate() and one documentation nit remain.

Findings: 1 warning · 1 info (1 is an inline comment on the diff)

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.

🔧 Fix with your agent

Paste the following into your coding agent to investigate and fix these issues.

Fix the following code review issues found in pull request #8188.

Before making changes, review each issue and present a brief summary table:
- For each finding, state whether you agree, disagree, or need clarification
- If you disagree (e.g., the fix would require disproportionate changes
  for minimal ROI, or the finding is factually incorrect), explain why
- If you need to clarify something before deciding, ask those questions
- Then share your plan for which issues to tackle and in what order

## WARNING (1)

### [Documentation] src/workerd/jsg/README.md:155-156 still documents `utils.getPrivate(object, "kName")` for bootstrap code, but this pull request removes it in favour of `utils.getPrivateSymbol(name)` used as a property key; update the guidance.

## INFO (1)

### [AGENTS.md] AGENTS.md says body consumption always copies bytes out, but queued byte streams' large chunks are now kept uncopied.
- **File:** src/tests/streams/readable/AGENTS.md:136

📖 AGENTS.md: 💬 1 info

The body-memory test description overstates when body collection copies chunks.

Recommendation: 💬 Optional Nits

  • [INFO] AGENTS.md says body consumption always copies bytes out, but queued byte streams' large chunks are now kept uncopied. (src/tests/streams/readable/AGENTS.md:136)
View full review
  • src/tests/streams/readable/AGENTS.md:136 says body consumption always copies bytes out as they arrive, but large chunks from a queued byte stream are now kept without a copy.

📝 Documentation: ⚠️ 1 warning

The JSG README still points bootstrap code to the removed utils.getPrivate().

Recommendation: 📝 Minor Comments

  • [WARNING] src/workerd/jsg/README.md:155-156 still documents utils.getPrivate(object, "kName") for bootstrap code, but this pull request removes it in favour of utils.getPrivateSymbol(name) used as a property key; update the guidance.
View full review
  • src/workerd/jsg/README.md:155-156 still tells per-isolate bootstrap code to use utils.getPrivate(object, "kName"). This pull request removes that utility (and setPrivate) and replaces it with utils.getPrivateSymbol(name), which returns a key used as object[key]. Update the guidance so bootstrap code written from it does not call a function that no longer exists.

✅ All other checks passed

🔒 Security: ✅ LGTM

No security issues found. Private-symbol keys from getPrivateSymbol() can only be named by code that holds the key, and they are not reflected or seen by Proxy traps.


📋 Code Quality: ✅ LGTM

No issues found in the streams, queue or bootstrap changes.


⚡ Performance: ✅ LGTM

The changes cut per-stream and per-read work: the writable controller's signal is created on first use, callbacks are called through FunctionPrototypeCall without binding them, tee cursors' liveness is checked less often, the anchor cursor is held strongly, and large chunks are copied out on their own when a body is collected. I found no complexity regressions or unbounded growth.


Reviewed commit: fd98894b

Comment thread src/tests/streams/readable/AGENTS.md Resolved

@guybedford guybedford left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice set of wins, the queue and ownership reasoning all checked out for me locally (respond/respondWithNewView/auto-allocate all transfer, tee copies for all but the last reader, identity never revisits copied after full delivery). One point on the owned-chunk path in the body collector, plus a couple of nits.

Comment thread src/per_isolate/webstreams/readable.ts Resolved
Comment thread src/per_isolate/webstreams/queue.ts Resolved
Comment thread src/per_isolate/webstreams/queue.ts Resolved
@jasnell
jasnell force-pushed the jasnell/ts-streams-perf-pass-3 branch from fd98894 to ffb9722 Compare November 3, 2026 22:38

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the review of 78d6be81.

This review, of ffb97226

💬 Approved with comments — One WARNING with a real impact: in the body collector, chunks kept without copying hold buffers that the memory limit does not count. The other WARNING is a stale developer-guide reference, which has no runtime effect. Neither makes the change unsafe to merge.

Findings: 2 warnings · 1 info (1 is an inline comment on the diff)

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.

🔧 Fix with your agent

Paste the following into your coding agent to investigate and fix these issues.

Fix the following code review issues found in pull request #8188.

Before making changes, review each issue and present a brief summary table:
- For each finding, state whether you agree, disagree, or need clarification
- If you disagree (e.g., the fix would require disproportionate changes
  for minimal ROI, or the finding is factually incorrect), explain why
- If you need to clarify something before deciding, ask those questions
- Then share your plan for which issues to tackle and in what order

## WARNING (2)

### [Code Quality] Owned chunks are kept as views over their whole transferred buffer, but the body memory limit counts only byteLength, so a source of small views over large buffers can hold many times the limit (also raised by @guybedford [approver]).
- **File:** src/per_isolate/webstreams/readable.ts:4790

### [Documentation] src/workerd/jsg/README.md:155-156 (and the comments at jsg.h:508-509 and events.h:17) still document utils.getPrivate/setPrivate, which this pull request removes in favour of utils.getPrivateSymbol(name) used as a property key.
- **File:** src/workerd/jsg/README.md:156

## INFO (1)

### [AGENTS.md] The guide says body consumption always copies bytes out, but large chunks from queued byte streams are now kept without a copy.
- **File:** src/tests/streams/readable/AGENTS.md:136

📖 AGENTS.md: 💬 1 info

The readable test guide still says body consumption always copies bytes out.

Recommendation: 💬 Optional Nits

  • [INFO] The guide says body consumption always copies bytes out, but large chunks from queued byte streams are now kept without a copy. (src/tests/streams/readable/AGENTS.md:136)
View full review
  • src/tests/streams/readable/AGENTS.md:136 says body consumption copies bytes out as they arrive. Large chunks from a queued byte stream are now kept without a copy.

📋 Code Quality: ⚠️ 1 warning

The body collector keeps an owned chunk's view over its whole backing buffer, but the memory limit counts only byteLength.

Recommendation: 📝 Minor Comments

  • [WARNING] Owned chunks are kept as views over their whole transferred buffer, but the body memory limit counts only byteLength, so a source of small views over large buffers can hold many times the limit (also raised by @​guybedford [approver]). (src/per_isolate/webstreams/readable.ts:4790)
View full review
  • Owned chunks retain more memory than the limit counts (src/per_isolate/webstreams/readable.ts:4787-4791, 4896-4898, 4928, 4938).
    • collectChunks treats every queued byte stream's chunks as owned. CollectedBytes.append then pushes a chunk of 16 KiB or more as the view itself.
    • enqueue() transfers the chunk's whole buffer, so a view such as new Uint8Array(new ArrayBuffer(1 << 20), 0, 16384) keeps 1 MiB alive until assembly.
    • The limit check counts only the 16 KiB, so the collector can hold about 64x the limit.
    • Fix: keep the view only when it spans its buffer, or most of it, and copy it otherwise. toArrayBuffer() already uses the same whole-buffer test.
    • The comment above the class (readable.ts:4743-4744, "so nothing is retained per chunk") no longer holds for these chunks either.
    • @​guybedford [approver] raised the same point, and the code at this commit has not changed it.

📝 Documentation: ⚠️ 1 warning

The JSG guide and two header comments still describe the removed utils.getPrivate/setPrivate.

Recommendation: 📝 Minor Comments

  • [WARNING] src/workerd/jsg/README.md:155-156 (and the comments at jsg.h:508-509 and events.h:17) still document utils.getPrivate/setPrivate, which this pull request removes in favour of utils.getPrivateSymbol(name) used as a property key. (src/workerd/jsg/README.md:156)
View full review
  • src/workerd/jsg/README.md:155-156 still tells per-isolate bootstrap code to use utils.getPrivate(object, "kName"). This pull request removes that utility in favour of utils.getPrivateSymbol(name), used as a property key.
  • src/workerd/jsg/jsg.h:508-509 makes the same claim.
  • src/workerd/api/events.h:17 still says utils.setPrivate(port, BRAND, true).

✅ All other checks passed

🔒 Security: ✅ LGTM

Private-symbol keys from getPrivateSymbol() can be named only by code that holds the key, and Proxy traps neither reflect nor see them. The memory-limit gap in the body collector's owned-chunk path is covered in the code quality section.


⚡ Performance: ✅ LGTM

The changes cut per-stream and per-read work:

  • Callbacks are called without binding them.
  • The writable controller creates its signal on first use.
  • Tee cursors' liveness is checked less often.
  • The anchor cursor is held strongly.
  • Large chunks are copied out on their own.

There are no complexity regressions.


Reviewed commit: ffb97226

Comment thread src/per_isolate/webstreams/readable.ts Resolved
@codecov-commenter

codecov-commenter commented Nov 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.88889% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 68.79%. Comparing base (4f3c0c3) to head (ef1ee30).

Files with missing lines Patch % Lines
src/workerd/api/per-isolate-bootstrap.c++ 88.88% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #8188      +/-   ##
==========================================
- Coverage   68.79%   68.79%   -0.01%     
==========================================
  Files         743      743              
  Lines      194569   194556      -13     
  Branches    30158    30155       -3     
==========================================
- Hits       133862   133853       -9     
  Misses      42998    42998              
+ Partials    17709    17705       -4     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Base automatically changed from jasnell/ts-streams-perf-pass-2 to main November 3, 2026 23:09
Every WritableStreamDefaultController created an AbortController for
its signal, and abort() signaled it: with no reason, that builds an
AbortError DOMException, with its stack trace, and dispatches an abort
event. Most streams never expose the signal, so constructing every
WritableStream, and the writable side of every TransformStream and
identity stream, paid for an AbortController no code could see, and
aborting an idle stream cost 5x the C++ implementation.

The AbortController is now created when controller.signal is first
read. Until then no code can listen to the signal or read its reason,
so an abort only records the reason, and the first read creates an
already-aborted signal with it. The one difference no test or user
can rely on: a reasonless abort's AbortError is created at that first
read, so its stack trace is the read's.

Vs the previous commit, TS cell:
  abort() an idle stream                 13.1 -> 0.5 us (C++ 2.5)
  abort() with 16 queued writes          17.4 -> 3.3 us (C++ 17.4)
  WritableStream construction x16        10.6 -> 4.1 us (C++ 18.1)
  IdentityTransformStream x16            39.3 -> 31.8 us (C++ 8.8)
  TransformStream construction x16       39.1 -> 34.1 us (C++ 110)
Writable suite geomean 0.62x; transform, identity, encoding,
compression and digest 0.96-0.99x.
Every queued ReadableStream's controller creates the stream's own
queue cursor, the queue's anchor. Like the cursors that tee and detach
fork, it held its owner, the controller's stream, in a WeakRef, and
registered with the orphan-detection FinalizationRegistry, holding a
second WeakRef. But the controller holds its stream, so the anchor can
never be orphaned while anything can reach the queue; #prune already
skipped it. The WeakRefs (each also added to the job's keep-alive set)
and the registration were a third of the cost of constructing a
ReadableStream.

A cursor constructed without a cursor to fork from is now the anchor:
it holds its owner strongly and joins the queue without a cleanup
registration (addAnchorCursor). A forked cursor takes its start state
from the cursor it forks, and keeps the weak owner and registration.

Vs the previous commit, TS cell:
  ReadableStream construction x16        18.3 ->  5.7 us (C++ 28.3)
  byte ReadableStream construction x16   20.1 ->  5.6 us (C++ 21.1)
  TransformStream construction x16       33.8 -> 14.8 us (C++ 111)
  IdentityTransformStream x16            30.7 -> 12.9 us (C++ 8.8)
  DecompressionStream construction x16   63.6 -> 36.6 us (C++ 33.0)
  TextEncoderStream construction x16     37.5 -> 15.2 us (C++ 123)
Geomean over all 11 suites 0.91x; readable 0.80x, transform 0.80x.
The controllers called each source, sink and transformer callback
through uncurryThis(callback), which binds a new function per callback
per stream, so constructing a stream with a full sink, or an
IdentityTransformStream, bound up to seven functions. They now call
the callbacks through a new FunctionPrototypeCall primordial
(uncurryThis(Function.prototype.call)), which is as immune to a
patched Function.prototype.call and costs no allocation. One-shot
calls through uncurryThis (iterator methods in ReadableStream.from(),
native pipe extractors) use it too.

Vs the previous commit, TS cell:
  IdentityTransformStream x16                  12.9 -> 11.8 us (C++ 8.7)
  WritableStream construction, full sink x16    4.8 ->  4.2 us
  TransformStream construction x16             14.7 -> 13.7 us
Geomean over all 11 suites 0.99x; the per-chunk paths that call
write(), transform(), pull() and size() are unchanged or slightly
faster.
Once every branch of a tee has canceled, the source's cancel
algorithm receives an AggregateError carrying every branch's reason.
It was built even for a source without a cancel algorithm, or one
already canceled, where nothing can observe it, and capturing its
stack trace was most of the cost of canceling both branches. It is now
built only for a cancel algorithm to receive.

Vs the previous commit, TS cell:
  tee(), cancel both branches   15.5 -> 4.2 us (C++ 7.9)
The identity streams deliver each write's bytes to their readable side
in the copy they took at write(), through the byte controller's batch
enqueue, which ran enqueue()'s steps for each: validating the view and
transferring its buffer, as the spec requires for a source's chunks so
that the source cannot change them once enqueued. No code outside the
identity stream holds these copies, so the transfer only cost a new
ArrayBuffer and a detach per chunk. The batch enqueue now queues them
as they are; enqueue() still validates and transfers.

A reader may detach the buffer of a chunk it read; a new test checks
that this changes nothing for the stream, its writes, or a tee branch.

Vs the previous commit, TS cell:
  IdentityTransformStream throughput 256 x 64 B   200 -> 165 us
  FixedLengthStream throughput 256 x 64 B         209 -> 172 us
  byte stream pipeThrough() identity, 256 x 64 B  521 -> 445 us
                                                  (C++ 283)
  value stream pipeTo() identity, 256 x 64 B      425 -> 355 us
Identity suite geomean 0.94x; readable-byte, piping, compression and
body unchanged.
The body collector copies each chunk into blocks that double in size
up to 1 MiB, then concatenates the blocks into the result. A body of
large chunks paid for blocks mostly left unused: sixteen 64 KiB chunks
filled 64 KiB to 512 KiB blocks and then allocated a zero-filled 1 MiB
block for the last chunk alone, so 2 MiB was allocated and zeroed for
1 MiB of body before the result was assembled.

A chunk of 16 KiB or more that the block in progress can't hold is now
copied out on its own, by constructing a Uint8Array from it, which
copies without zero-filling first; the block in progress is trimmed to
what it holds. Smaller chunks are packed into blocks as before, each
now sized to the capacity of the blocks before it, so the total
capacity doubles with each block. A declared length still sizes the
first block, which is now allocated up front so large chunks land in
it too.

A new test reads small and large chunks interleaved around the
threshold, undeclared and declared.

Vs the previous commit, TS cell:
  arrayBuffer() of a value stream 16 x 64 KiB    187 -> 134 us
                                                 (C++ 157)
  arrayBuffer() of a value stream 64 x 4 KiB    54.1 -> 43.6 us
  arrayBuffer() of a byte stream 16 x 64 KiB     246 -> 199 us
  text() of a value stream 64 x 4 KiB           88.7 -> 79.2 us
  clone() of a value stream body, 64 x 4 KiB     115 -> 93 us
Body suite geomean 0.97x; compression, identity, transform and
readable unchanged.
Once close is requested, each read completion checks whether the read
drained a consumer and the stream should close. For a stream whose
queue has several consumers (tee branches), that check dereferenced
every consumer's owner from its cursor's WeakRef and tested each
cursor, on every read until the end.

A read moves only its own stream's cursor, so if that cursor has not
reached the close sentinel no consumer has drained and the walk would
change nothing. The read completion steps now pass the stream that
read, and the queued controller returns early when that stream's
cursor still has data before the sentinel. Other callers (close(),
cancel, tee, detach) still walk every consumer.

Vs the previous commit, TS cell:
  byte stream tee, read both branches 256 x 64 B   325 -> 291 us
                                                   (C++ 227)
  byte stream tee, read both branches 64 x 4 KiB   135 -> 123 us
  tee, read both branches, enqueued x256           162 -> 123 us
  tee, read one branch, cancel the other x256     78.2 -> 61.3 us
readable-byte geomean 0.99x, readable 0.99x; identity and piping
unchanged.
Each read from a queue with several cursors (tee branches) checked the
liveness of every cursor twice: once deciding whether the entry read
must be copied for another cursor still to read, and once reclaiming
the entries every cursor has passed. Each check dereferences the
cursor owner's WeakRef, which also keeps the owner alive to the end of
the job.

The copy decision now checks only the cursors that have not yet read
the entry, skipping the orphans among them. Reclamation checks only the
slowest cursor, and again after pruning it if it was orphaned, until a
live cursor is the slowest: an orphan ahead of it holds nothing back,
and the walks that read backpressure or the consumers still prune every
cursor first.

A new test collects one tee branch, having read none of the chunks or
most of them, and checks that what its sibling reads is released.

Vs the previous commit, TS cell:
  byte stream tee, read both branches 256 x 64 B   288 -> 266 us
                                                   (C++ 227)
  byte stream tee, read both branches 64 x 4 KiB   127 -> 114 us
  tee, read both branches, enqueued x256           133 -> 110 us
  tee, read both branches, pull() x256             249 -> 226 us
readable-byte geomean 0.99x, readable 0.96x; identity unchanged.
Every ReadableStream and WritableStream constructor stamped the brand
C++ recognizes TypeScript streams by through utils.setPrivate(), and
checked its source or sink for the native marker through
utils.getPrivate(): two calls into C++ per stream, each looking up the
private symbol by name, and the stamp then adding the property from
C++, outside the constructor's inline caches.

utils.getPrivateSymbol(name) now hands the bootstrap scripts the V8
private symbol itself (v8::Private::ForApi, as a template property,
the way Node.js exposes its own private symbols), looked up once per
key. The streams read and write the markers as ordinary keyed
properties, which reach the same slots C++ reads by name: private
symbols are not inherited, reflected or seen by Proxy traps, so the
markers keep those guarantees. setPrivate() and getPrivate() had no
other callers and are removed.

A new test checks that a Proxy source, sink or strategy sees only its
members' reads by name.

Vs the previous commit, TS cell:
  IdentityTransformStream x16                  11.6 -> 7.0 us
                                               (C++ 8.8)
  FixedLengthStream x16                        11.6 -> 7.2 us
                                               (C++ 8.9)
  ReadableStream construction, no source x16    5.6 -> 3.7 us
  WritableStream construction, no sink x16      4.1 -> 2.2 us
Identity geomean 0.95x, readable 0.94x, writable 0.86x; body
unchanged.
The body collector copies a chunk of 16 KiB or more out on its own
and assembles the copies once at the end. For a queued byte stream
the copy is unnecessary: enqueue() transfers each chunk's buffer, the
identity streams enqueue copies of their own, and a tee hands every
branch but the last to read an entry a copy of it, so the chunks the
collector drains are reachable by nothing else. The collector now
keeps such chunks as they are, and a body of one chunk spanning its
whole buffer is handed over without any copy. Value streams' chunks,
which their source may still hold, are copied as before.

A new test consumes each branch of a teed byte stream of large chunks
as a body, in either order, and checks that writing into one result
leaves the other branch's bytes intact.

Vs the previous commit, TS cell:
  arrayBuffer() of a byte stream 16 x 64 KiB     199 -> 141 us
                                                 (C++ 937)
Body geomean 0.98x; compression and identity unchanged.
@jasnell
jasnell force-pushed the jasnell/ts-streams-perf-pass-3 branch from ffb9722 to 78d6be8 Compare November 3, 2026 23:09

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the review of 3040eccc.

This review, of 78d6be81

💬 Approved with comments — One WARNING with a real impact: in the body collector, chunks kept without copying hold buffers that the memory limit does not count. The other WARNING is a stale developer-guide reference, which has no runtime effect. Neither makes the change unsafe to merge.

Findings: 2 warnings · 1 info

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.

🔧 Fix with your agent

Paste the following into your coding agent to investigate and fix these issues.

Fix the following code review issues found in pull request #8188.

Before making changes, review each issue and present a brief summary table:
- For each finding, state whether you agree, disagree, or need clarification
- If you disagree (e.g., the fix would require disproportionate changes
  for minimal ROI, or the finding is factually incorrect), explain why
- If you need to clarify something before deciding, ask those questions
- Then share your plan for which issues to tackle and in what order

## WARNING (2)

### [Code Quality] Owned chunks are kept as views over their whole transferred buffer, but the body memory limit counts only byteLength, so a source of small views over large buffers can hold many times the limit (also raised by @guybedford [approver]).
- **File:** src/per_isolate/webstreams/readable.ts:4790

### [Documentation] src/workerd/jsg/README.md:155-156 (and the comments at jsg.h:508-509 and events.h:17) still document utils.getPrivate/setPrivate, which this pull request removes in favour of utils.getPrivateSymbol(name) used as a property key.
- **File:** src/workerd/jsg/README.md:156

## INFO (1)

### [AGENTS.md] The guide says body consumption always copies bytes out, but large chunks from queued byte streams are now kept without a copy.
- **File:** src/tests/streams/readable/AGENTS.md:136

📖 AGENTS.md: 💬 1 info

The readable test guide still says body consumption always copies bytes out.

Recommendation: 💬 Optional Nits

  • [INFO] The guide says body consumption always copies bytes out, but large chunks from queued byte streams are now kept without a copy. (src/tests/streams/readable/AGENTS.md:136)
View full review
  • src/tests/streams/readable/AGENTS.md:136 says body consumption copies bytes out as they arrive. Large chunks from a queued byte stream are now kept without a copy.

📋 Code Quality: ⚠️ 1 warning

The body collector keeps an owned chunk's view over its whole backing buffer, but the memory limit counts only byteLength.

Recommendation: 📝 Minor Comments

  • [WARNING] Owned chunks are kept as views over their whole transferred buffer, but the body memory limit counts only byteLength, so a source of small views over large buffers can hold many times the limit (also raised by @​guybedford [approver]). (src/per_isolate/webstreams/readable.ts:4790)
View full review
  • Owned chunks retain more memory than the limit counts (src/per_isolate/webstreams/readable.ts:4787-4791, 4896-4898, 4928, 4938).
    • collectChunks treats every queued byte stream's chunks as owned. CollectedBytes.append then pushes a chunk of 16 KiB or more as the view itself.
    • enqueue() transfers the chunk's whole buffer, so a view such as new Uint8Array(new ArrayBuffer(1 << 20), 0, 16384) keeps 1 MiB alive until assembly.
    • The limit check counts only the 16 KiB, so the collector can hold about 64x the limit.
    • Fix: keep the view only when it spans its buffer, or most of it, and copy it otherwise. toArrayBuffer() already uses the same whole-buffer test.
    • The comment above the class (readable.ts:4743-4744, "so nothing is retained per chunk") no longer holds for these chunks either.
    • @​guybedford [approver] raised the same point, and the code at this commit has not changed it.

📝 Documentation: ⚠️ 1 warning

The JSG guide and two header comments still describe the removed utils.getPrivate/setPrivate.

Recommendation: 📝 Minor Comments

  • [WARNING] src/workerd/jsg/README.md:155-156 (and the comments at jsg.h:508-509 and events.h:17) still document utils.getPrivate/setPrivate, which this pull request removes in favour of utils.getPrivateSymbol(name) used as a property key. (src/workerd/jsg/README.md:156)
View full review
  • src/workerd/jsg/README.md:155-156 still tells per-isolate bootstrap code to use utils.getPrivate(object, "kName"). This pull request removes that utility in favour of utils.getPrivateSymbol(name), used as a property key.
  • src/workerd/jsg/jsg.h:508-509 makes the same claim.
  • src/workerd/api/events.h:17 still says utils.setPrivate(port, BRAND, true).

✅ All other checks passed

🔒 Security: ✅ LGTM

Private-symbol keys from getPrivateSymbol() can be named only by code that holds the key, and Proxy traps neither reflect nor see them. The memory-limit gap in the body collector's owned-chunk path is covered in the code quality section.


⚡ Performance: ✅ LGTM

The changes cut per-stream and per-read work:

  • Callbacks are called without binding them.
  • The writable controller creates its signal on first use.
  • Tee cursors' liveness is checked less often.
  • The anchor cursor is held strongly.
  • Large chunks are copied out on their own.

There are no complexity regressions.


Reviewed commit: 78d6be81 — same changes as ffb97226, so this is that commit's review (no new review was run; line numbers are as of ffb97226)

The body collector kept a large chunk it owns as a view, which keeps
the chunk's whole buffer alive while the memory limit counts only the
view's bytes. A source enqueueing 16 KiB views of 1 MiB buffers made
the collector retain 64 times what it accounted for. Such a chunk is
now kept only if it spans its whole buffer, and copied otherwise.
That still covers the identity streams' and tee's copies, a full
buffer passed to enqueue(), and the single-chunk handover.

Also drop the queue's checks for its own cursor before isOrphaned():
that cursor holds its owner strongly, so it is never orphaned. And
rewrap two comments that ran past the column width.

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the review of ef1ee306.

This review, of 3040eccc

💬 Approved with comments — The earlier memory-limit concern is fixed. What remains is one WARNING about stale developer docs for removed bootstrap utilities, with no runtime effect, plus two INFO notes about test coverage and a comment.

Findings: 1 warning · 2 info (2 are inline comments on the diff)

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.

🔧 Fix with your agent

Paste the following into your coding agent to investigate and fix these issues.

Fix the following code review issues found in pull request #8188.

Before making changes, review each issue and present a brief summary table:
- For each finding, state whether you agree, disagree, or need clarification
- If you disagree (e.g., the fix would require disproportionate changes
  for minimal ROI, or the finding is factually incorrect), explain why
- If you need to clarify something before deciding, ask those questions
- Then share your plan for which issues to tackle and in what order

## WARNING (1)

### [Documentation] src/workerd/jsg/README.md:155-156, src/workerd/jsg/jsg.h:508-509 and src/workerd/api/events.h:17 still document utils.getPrivate/setPrivate, which this pull request replaces with utils.getPrivateSymbol(name) used as a property key.

## INFO (2)

### [Code Quality] No test covers the copy branch for an owned chunk that does not span its buffer.
- **File:** src/per_isolate/webstreams/readable.ts:4791

### [Code Quality] The opening sentence of the `CollectedBytes` comment ('nothing is retained per chunk') contradicts the kept-chunk path the same comment describes later.
- **File:** src/per_isolate/webstreams/readable.ts:4744

📋 Code Quality: 💬 2 info

The earlier memory-limit finding is fixed. Two INFO notes remain: the new copy branch has no test, and a comment's opening sentence is stale.

Recommendation: 💬 Optional Nits

  • [INFO] No test covers the copy branch for an owned chunk that does not span its buffer. (src/per_isolate/webstreams/readable.ts:4791)
  • [INFO] The opening sentence of the CollectedBytes comment ('nothing is retained per chunk') contradicts the kept-chunk path the same comment describes later. (src/per_isolate/webstreams/readable.ts:4744)
View full review
  • Fixed: owned chunks are now kept only when they span their whole buffer (readable.ts:4790-4793). Any other view is copied, so the memory the collector retains matches what the body limit counts.
  • Fixed: the anchor cursor's redundant isOrphaned() short-circuits are removed from queue.ts.
  • INFO: the copy branch for owned views that don't span their buffer has no test.
  • INFO: the opening sentence of the CollectedBytes comment still says nothing is retained per chunk.

📝 Documentation: ⚠️ 1 warning

Three references still describe the removed utils.getPrivate/utils.setPrivate.

Recommendation: 📝 Minor Comments

  • [WARNING] src/workerd/jsg/README.md:155-156, src/workerd/jsg/jsg.h:508-509 and src/workerd/api/events.h:17 still document utils.getPrivate/setPrivate, which this pull request replaces with utils.getPrivateSymbol(name) used as a property key.
View full review

src/workerd/jsg/README.md:155-156, src/workerd/jsg/jsg.h:508-509 and src/workerd/api/events.h:17 still tell bootstrap code to call utils.getPrivate(object, name) or utils.setPrivate(...). This pull request removes both in favour of utils.getPrivateSymbol(name), used as a property key. Update these references so developers aren't sent to functions that no longer exist. This has no runtime effect.


✅ All other checks passed

🔒 Security: ✅ LGTM

  • Keys from getPrivateSymbol() are private symbols. Code that does not hold a key cannot name it, and Proxy traps neither reflect nor see it.
  • FunctionPrototypeCall is captured before any user code runs, so later changes to Function.prototype cannot redirect calls made through it.
  • The marker check in native.ts still requires the value to be exactly true.

📖 AGENTS.md: ✅ LGTM

No new issues found. One earlier note that the author chose to leave as is remains open.


⚡ Performance: ✅ LGTM

  • #gc in queue.ts now checks only the slowest cursor on each pass. Every pass either stops or removes a cursor, so the loop runs at most once per cursor.
  • The fix in the body collector copies only the views that don't span their buffer, so the fast path for whole-buffer chunks is unchanged.

Reviewed commit: 3040eccc

Comment thread src/per_isolate/webstreams/readable.ts Resolved
Comment thread src/per_isolate/webstreams/readable.ts Resolved
A new test consumes a byte stream whose large chunks are views into
larger buffers, which the body collector copies out rather than keep,
among chunks that span their buffers and small ones, and a body of one
such view. The bytes outside each view hold a marker, so a copy taken
from the wrong offset or of the wrong length fails it.

Also reword the opening of the collector's comment, which said no
chunk is retained, although the large chunks it keeps are.

@clanky-the-clanker clanky-the-clanker Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💬 Approved with comments — No correctness defects. One WARNING about stale developer docs for the removed bootstrap utilities has no runtime effect, and one INFO notes the new test can't detect a regression in the copy-vs-keep fix.

Findings: 1 warning · 1 info (1 is an inline comment on the diff)

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.

🔧 Fix with your agent

Paste the following into your coding agent to investigate and fix these issues.

Fix the following code review issues found in pull request #8188.

Before making changes, review each issue and present a brief summary table:
- For each finding, state whether you agree, disagree, or need clarification
- If you disagree (e.g., the fix would require disproportionate changes
  for minimal ROI, or the finding is factually incorrect), explain why
- If you need to clarify something before deciding, ask those questions
- Then share your plan for which issues to tackle and in what order

## WARNING (1)

### [Documentation] src/workerd/jsg/README.md:155-156, src/workerd/jsg/jsg.h:508-509 and src/workerd/api/events.h:17 still document utils.getPrivate/setPrivate, which this pull request replaces with utils.getPrivateSymbol(name) used as a property key. No runtime effect.

## INFO (1)

### [Code Quality] The new largeViewsIntoLargerBuffersAssembleIntact test checks only the output bytes, so it passes whether the collector copies a non-spanning view or keeps it.
- **File:** src/tests/streams/readable/integration-body-memory.js:195

📋 Code Quality: 💬 1 info

No correctness defects; the new body-memory test cannot tell a copied chunk from a kept one.

Recommendation: 💬 Optional Nits

  • [INFO] The new largeViewsIntoLargerBuffersAssembleIntact test checks only the output bytes, so it passes whether the collector copies a non-spanning view or keeps it. (src/tests/streams/readable/integration-body-memory.js:195)
View full review
  • The CollectedBytes comment now matches the code: no chunk is retained except the large chunks kept as they are.
  • INFO: largeViewsIntoLargerBuffersAssembleIntact (integration-body-memory.js:190-215) checks only the assembled bytes. Suppose the ArrayBufferPrototypeByteLengthGet(buffer) === byteLength condition in CollectedBytes.append (readable.ts:4790-4793) were removed, so the collector kept every owned large view. The test would still pass, because assembly reads only the bytes inside each view. So it covers copy offsets, but not the memory-accounting fix.
  • Checked with no findings: the #gc loop in queue.ts removes one cursor per pass, so it terminates. The lazy writable signal replays a recorded abort. The early return in maybeCloseStream(readBy) is correct. GetPrivateSymbol builds keys with v8::Private::ForApi, which matches the key jsg::JsObject::getPrivate/setPrivate use.

📝 Documentation: ⚠️ 1 warning

Developer docs still reference the removed utils.getPrivate/setPrivate.

Recommendation: 📝 Minor Comments

  • [WARNING] src/workerd/jsg/README.md:155-156, src/workerd/jsg/jsg.h:508-509 and src/workerd/api/events.h:17 still document utils.getPrivate/setPrivate, which this pull request replaces with utils.getPrivateSymbol(name) used as a property key. No runtime effect.
View full review
  • WARNING: src/workerd/jsg/README.md:155-156, src/workerd/jsg/jsg.h:508-509 and src/workerd/api/events.h:17 still tell bootstrap code to use utils.getPrivate(object, name) / utils.setPrivate(...). This pull request removes both in favour of utils.getPrivateSymbol(name), used as a property key. Update these references. This has no runtime effect.

✅ All other checks passed

🔒 Security: ✅ LGTM

No security issues in the changed code.


📖 AGENTS.md: ✅ LGTM

No new issues.


⚡ Performance: ✅ LGTM

  • #gc in queue.ts runs at most once per cursor.
  • The anchor cursor no longer needs a WeakRef or a FinalizationRegistry registration.
  • maybeCloseStream returns early, so a read after close no longer walks every tee consumer.
  • FunctionPrototypeCall replaces the per-stream bound callbacks.
  • Large chunks are copied out on their own or kept whole only when they span their buffer.

Reviewed commit: ef1ee306

@jasnell
jasnell merged commit d965779 into main Nov 4, 2026
36 of 38 checks passed
@jasnell
jasnell deleted the jasnell/ts-streams-perf-pass-3 branch November 4, 2026 00:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants