Skip to content

Do not re-charge transferred ArrayBuffer contents to this Heap's GC pacing - #273

Open
Jarred-Sumner wants to merge 1 commit into
mainfrom
claude/arraybuffer-transfer-gc-pacing
Open

Jarred-Sumner wants to merge 1 commit into
mainfrom
claude/arraybuffer-transfer-gc-pacing

Conversation

@Jarred-Sumner

Copy link
Copy Markdown
Collaborator

Problem

Heap::addReference charges a buffer's bytes to GC allocation pacing (didAllocate) the first time a cell references it. The BYOB/byte-stream flow (and postMessage transfer lists, ArrayBuffer.prototype.transfer) transfers contents into a fresh ArrayBuffer, whose first view then re-charges the same bytes, so transfer-heavy code is paced at twice its real allocation rate. On a ReadableStream byte-source benchmark (512 × 64 KiB chunks, default reader, autoAllocateChunkSize), Bun runs 61 collections instead of 31 for identical work; a (new ArrayBuffer(1MiB)).transfer() loop runs 323 instead of 162.

Fix

ArrayBufferContents records which Heap charged its bytes:

  • the mark moves with the contents (detach/transferTo), so a same-heap transfer's new buffer is not charged again;
  • it is cleared when the charged buffer leaves the heap's incoming-reference set (GCIncomingRefCountedSet::sweep removal), so contents re-wrapped after this heap forgot them charge again;
  • it is compared against the referencing heap, so contents crossing into another heap (worker postMessage([buf])) are charged there normally;
  • collectIfNecessaryOrDefer() still runs on every first reference; tracking/marking are unchanged. Only the duplicate didAllocate is skipped.

Measurements (linux x64, Bun built against this branch)

workload before after
BYOB byte-source bench, GC count 61 31
transfer() loop (5000 × 1 MiB), GC count 323 162
worker receiving 3000 transferred 1 MiB buffers, peak worker RSS 42 MB 43 MB (still paced)
transfer/transferToFixedLength/resizable/structuredClone semantics — identical

The wall-clock effect on the byte-stream benchmark itself is small (~2%; that row is dominated by the spec's zero-fill of the auto-allocated buffer) — the win is the halved GC frequency for the whole class of transfer-heavy programs.

Non-goals (pre-existing double-charges of the same class, left alone)

  • JSWebAssemblyMemory re-wraps its contents on memory.grow, re-charging the full memory each time.
  • JSArrayBufferView::slowDownAndWasteMemory adopts an already-counted vector into a fresh (uncharged) ArrayBuffer.
  • ArrayBufferContents::shareWith (shared buffers) intentionally leaves the destination unmarked: each agent keeps charging its own wrapper, as today.

…acing

Heap::addReference charges a buffer's bytes to GC allocation pacing
(didAllocate) the first time a cell references it. Contents that arrive via
ArrayBuffer::transferTo were already charged when their source buffer was first
referenced in the same Heap, so transfer-heavy code (ReadableStream byte/BYOB
paths, postMessage transfer lists, ArrayBuffer.prototype.transfer) was paced at
twice its real allocation rate and ran twice as many collections.

ArrayBufferContents now records which Heap charged its bytes; the mark moves
with the contents (detach/transfer), is cleared when the charged buffer leaves
the Heap's incoming-reference set (so a later re-wrap charges again), and is
compared against the referencing Heap, so contents that cross into another Heap
(worker postMessage) are charged there normally. collectIfNecessaryOrDefer()
still runs on every first reference; buffer tracking and marking are unchanged.

On a ReadableStream byte-source benchmark reading 512 x 64 KiB chunks with a
default reader (autoAllocateChunkSize), collections drop from 61 to 31 for the
same work; a worker receiving 3000 transferred 1 MiB buffers keeps the same
bounded RSS as before (the receiving Heap still paces them).

Known, pre-existing double-charges of the same class that this change does not
attempt to fix: WebAssembly memory.grow re-wrapping its contents, and
JSArrayBufferView::slowDownAndWasteMemory adopting an already-counted vector.
@coderabbitai

coderabbitai Bot commented Jul 5, 2026

Copy link
Copy Markdown

Warning

Review limit reached

You’ve reached a temporary PR review limit under our Fair Usage Limits Policy.

Your recent review volume is higher than typical usage, so adaptive limits are currently applied.

Next review available in: 41 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 8ce3b04f-7acd-4e10-b78d-5aca827e8d5c

📥 Commits

Reviewing files that changed from the base of the PR and between 2a51dee and 4310787.

📒 Files selected for processing (3)
  • Source/JavaScriptCore/heap/GCIncomingRefCountedSetInlines.h
  • Source/JavaScriptCore/heap/Heap.cpp
  • Source/JavaScriptCore/runtime/ArrayBuffer.h

Comment @coderabbitai help to get the list of available commands.

preciseBytes += size;
return false;
}
object->willBeRemovedFromIncomingReferenceSet();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 This is a use-after-free: filterIncomingReferences() calls setIsDeferred(false), which does delete static_cast<T*>(this) when the native refcount is zero (the common case for a JS-only ArrayBuffer — JSArrayBuffer::m_impl is a raw pointer, not a RefPtr). GCIncomingRefCounted.h explicitly documents that filterIncomingReferences "may delete the object, and if it does so, this returns true", so the subsequent object->willBeRemovedFromIncomingReferenceSet() writes m_contents.m_gcPacingChargedHeap on freed memory. Move the hook to before filterIncomingReferences() (or fold it into filterIncomingReferences before setIsDeferred(false)).

Extended reasoning...

What the bug is. GCIncomingRefCountedSet<T>::sweep() now does:

if (!object->filterIncomingReferences(...)) { ...; return false; }
object->willBeRemovedFromIncomingReferenceSet();   // <-- new
return true;

But when filterIncomingReferences() returns true, it has already called this->setIsDeferred(false) (see GCIncomingRefCountedInlines.h:88 and :113). DeferrableRefCounted::setIsDeferred(false) (DeferrableRefCounted.h:105-111) clears the deferred flag and, if the resulting refcount is 0, executes delete static_cast<T*>(this). The header comment for filterIncomingReferences() at GCIncomingRefCounted.h:80-83 states this contract explicitly: "This may delete the object, and if it does so, this returns true." The pre-PR sweep() respected that by never touching object after a true return; the added line does not.

Why the refcount is commonly zero here. JSArrayBuffer stores the buffer as a raw pointer — ArrayBuffer* m_impl (JSArrayBuffer.h:82) — not a RefPtr. The constructor takes RefPtr<ArrayBuffer>&& but only assigns arrayBuffer.get() to m_impl; the RefPtr is dropped. Ownership from the JS side is expressed solely via the deferred flag set in addIncomingReference() (this->setIsDeferred(true)). So an ArrayBuffer referenced only from JavaScript sits at native refcount 0 with the deferred bit as its sole keep-alive.

Step-by-step trigger.

  1. new ArrayBuffer(1024) in JS. JSArrayBuffer::create runs; Heap::addReference → GCIncomingRefCountedSet::addReference → addIncomingReference sets the deferred flag. The temporary RefPtr<ArrayBuffer> is destroyed → native refcount becomes 0, deferred bit is set.
  2. The JSArrayBuffer wrapper becomes unreachable.
  3. GC runs. sweep() calls filterIncomingReferences(isMarked); the singleton wrapper cell is unmarked, so it takes the hasSingleton() branch, sets m_encodedPointer = 0, calls this->setIsDeferred(false).
  4. setIsDeferredBase(false) clears the flag → m_refCount == 0 → delete static_cast<ArrayBuffer*>(this). filterIncomingReferences() returns true.
  5. Back in sweep(), object->willBeRemovedFromIncomingReferenceSet() runs and stores nullptr into object->m_contents.m_gcPacingChargedHeap — a heap write to freed memory.

Impact. This is the ordinary collection path for every pure-JS ArrayBuffer (and every wasteful-typed-array buffer whose last wrapper dies). It fires on essentially every GC that reclaims such a buffer. Under ASAN it will trip heap-use-after-free immediately; in release builds it is a silent 8-byte write into a freed ArrayBuffer slot, i.e. heap corruption / a security-relevant regression.

Fix. Call the hook before the object can be freed. Simplest: invoke it just before filterIncomingReferences() — writing nullptr into a buffer that survives the filter is harmless because the buffer stays in m_vector and addReference() won't return true for it again, so Heap::addReference won't reach the pacing check. Alternatively, thread the clear into filterIncomingReferences() (e.g. a callback, or clear inline) before each setIsDeferred(false) call site.

Comment on lines 250 to 251
class ArrayBuffer final : public GCIncomingRefCounted<ArrayBuffer> {
public:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Nit: stray blank line added after public: — looks like an accidental leftover from editing (no other change here, and the other classes in this file don't have one).

Extended reasoning...

This is a purely cosmetic observation. The diff adds a single empty line immediately after the public: access specifier in class ArrayBuffer final : public GCIncomingRefCounted<ArrayBuffer>:

class ArrayBuffer final : public GCIncomingRefCounted<ArrayBuffer> {
public:
+
    JS_EXPORT_PRIVATE static Ref<ArrayBuffer> create(size_t numElements, unsigned elementByteSize);

There is no other change at this location — the substantive additions in this class (willBeRemovedFromIncomingReferenceSet(), gcPacingChargedHeap(), setGCPacingChargedHeap(), friend class Heap) all land further down. So this blank line is not separating anything new; it's just a stray insertion, most likely a leftover from moving lines around during editing.

It's also inconsistent with the local style in this file. Neither SharedArrayBufferContents nor ArrayBufferContents (nor the second public: / private: blocks in ArrayBuffer itself) put a blank line right after the access specifier.

Step-by-step:

  1. Before the patch, line 249 is public: and line 250 is the first create overload — no gap.
  2. The patch inserts a bare + line between them.
  3. No declaration was added or removed adjacent to that line, so the blank line serves no grouping purpose.
  4. Every other access specifier in ArrayBuffer.h is immediately followed by a declaration.

Impact: none — whitespace only. It does not affect compilation, ABI, or behavior in any way.

Fix: delete the blank line so public: is immediately followed by the first create declaration, matching the rest of the file.

@github-actions

github-actions Bot commented Jul 5, 2026

Copy link
Copy Markdown

Preview Builds

Commit Release Date
43107875 autobuild-preview-pr-273-43107875 2026-07-05 15:40:26 UTC

Jarred-Sumner pushed a commit to oven-sh/bun that referenced this pull request Sep 16, 2026
### Problem
- `node:zlib` one-shot calls got up to 2x slower for small inputs in
1.4.0: `gunzipSync` of 1 KB went from 3.1 us to 5.0 us. #35356 lowered
`largeHeapSize` to 8 MB, so these calls collect 4 times as often.
- A third of that load comes from `buffer.slice()` in `processChunkSync`
and `processCallback` (`src/js/node/zlib.ts`). The 16 KB output chunk
has no `ArrayBuffer` until the slice creates one. JSC then counts the
chunk as allocated again, and only a full collection corrects the heap
size. A 1 KB result also keeps its 16 KB chunk alive.

### Fix
- Both paths call `takeOutput`. It hands over a full chunk as it is and
copies a part of at most 16 KB with `Buffer.copyBytesFrom`. A larger
part of a custom `chunkSize` chunk, or any part with a fractional
`chunkSize`, is still a slice.
- Correct because the consumer gets the same bytes. Sync output of
several chunks still goes through `Buffer.concat`, which minizlib (used
by `tar`) replaces.
- Verified: `test/js/node/zlib/zlib.test.js` ("one-shot results"), where
main gives a 1 KB result a 16384-byte backing store. Also all of
`test/js/node/zlib/`, the 61 Node `test-zlib-*.js` files, and a minizlib
round trip. Self-reviewed: 3 concerns raised, 3 addressed (see Notes).
- Release build, main to this PR: `gunzipSync` 1 KB 4.99 to 2.97 us,
callback `gunzip` 39.0 to 34.0 us, 64 MB through gzip streams 166 to 131
ms. 120k `gunzipSync` calls: 410 eden + 136 full collections to 318 + 0.

### Background
- A typed array above 1000 bytes owns a malloc'ed vector and gets an
`ArrayBuffer` only when JS needs one (`.buffer`, `subarray`, Buffer's
`slice`). `JSArrayBufferView::slowDownAndWasteMemory` then reports the
vector to the GC again. It has a FIXME for this.
- JSC starts an eden collection when the bytes allocated since the last
one pass a budget. On a small heap that budget is `largeHeapSize`.
- `nativeDecodePullResult` in `BunStreamSource.cpp` already uses this
rule.

<details><summary>Notes</summary>

- Found from a perf ledger entry: node:zlib sync one-shot calls on 1 KB
inputs got 1.5x to 3.4x slower at 1.4.0 while `Bun.gunzipSync` got
faster. The JS wrapper and the native handle did not get slower.
`BUN_JSC_largeHeapSize=33554432` on main gives the 1.3.14 collection
counts exactly (105 eden + 34 full per 120k `gunzipSync`) and the 1.3.14
speed. The zstd rows have a second cause, fixed in #42914.
- GC-visible bytes for one `gunzipSync` call, from collections per 100k
calls: `Buffer.allocUnsafe(16384)` 16.4 KB, the slice 16.4 KB more, the
native handle 3.6 KB, the stream objects about 1 KB.
`Buffer.allocUnsafe(16384).subarray(0, 10)` alone runs 262 eden + 130
full collections per 100k, against 195 + 0 without the `subarray`. The
JSC side of this has its own follow-up. oven-sh/WebKit#273 fixes the
same double charge for transferred contents.
- All rows, ns per call, 1.3.14 / main / this PR, machine under load:
`gunzipSync` 1 KB 3056 / 4994 / 2974. `inflateSync` 1 KB 2837 / 4633 /
3450. `brotliDecompressSync` 1 KB 5308 / 8680 / 6170. `gzipSync` 1 KB
8267 / 10211 / 8347. `zstdDecompressSync` 1 KB 5021 / 15193 / 13701.
`gunzip` callback 1 KB 33154 / 38970 / 34016. `gzip` callback 1 KB 39866
/ 49531 / 45815. `gunzip` callback 1 MB 1.78 / 2.06 / 1.74 ms. 20k
flushed `createDeflate` writes 506 / 570 / 442 ms.
- A focused run of 8 alternating rounds for the sizes between the rows
above, main to this PR: `gunzipSync` 4 KB 8.12 to 7.26 us, 12 KB 12.27
to 12.38 us (CPU time 15.66 to 14.19 us), 1 MB 804 to 716 us, 600 KB
with `chunkSize: 1 << 20` 395 to 399 us (that one still takes the slice
path).
- Callback path: 30k `gunzip` calls of 1 KB run 129 eden + 43 full
collections on main and 86 + 0 with this PR.
- The 16 KB bound: with `chunkSize: 1 << 20` and 600 KB of output, a
copy of the whole part measured 5 to 10% slower than the slice and
raised peak RSS, so a large part stays a slice.
- A fractional `chunkSize` (valid in Node and in Bun) makes `offset` and
`have` fractional. `slice` truncates them and `Buffer.copyBytesFrom`
throws `ERR_OUT_OF_RANGE`, so the helper only copies integer ranges. The
new tests cover `chunkSize: 100.5` for the sync, callback, and
`_processChunk` paths.
- Self-review, all three addressed: a fractional `chunkSize` made
`Buffer.copyBytesFrom` throw (now an integer guard, with tests). The
callback path still sliced while the sync path did not (now one helper
for both, with tests for both). The code comment said a full collection
frees the chunk, when it only corrects the heap size (reworded).
- Not part of this PR: `src/js/internal/streams/iter/transform.ts`
already hands over a full chunk and copies a partial fill. It still uses
`subarray` for the tail of a chunk that it replaces, which is at most
once for each chunk.
- Node 26 returns a view into a 64 KB slab (`result.buffer.byteLength`
is 65536, `byteOffset` 16384). The size of the backing store is not a
compat contract.
- minizlib calls the sync `_processChunk` on a long-lived engine with
`Buffer.concat` replaced and the handle's `close` stubbed. It copies
`result[0]` because that one can be `_outBuffer`, which the next call
writes again. That still holds: a full first chunk is `_outBuffer`
itself, a small first part is now a fresh copy. pngjs reads `_outBuffer`
and `_outOffset` once in its constructor. Both fields keep their values
and meaning.
- `leak.test.ts` exceeds its `beforeAll` hook timeout on a debug ASAN
build with and without this change. It passes on the release build.
</details>

<!-- robobun:evidence:begin -->

---

**[human-review]** gate passed · iteration 0 · 2 files touched

<details><summary>fails on main (without fix)</summary>

```console
ASAN without fix: 12 failed, 2 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/node/zlib/zlib.test.js
bun test v1.4.3 (c6b7fcb)

test/js/node/zlib/zlib.test.js:
(pass) prototype and name and constructor > Gzip > Gzip.prototype should be instanceof Gzip.__proto__ [1.98ms]
(pass) prototype and name and constructor > Gzip > Gzip.prototype.constructor should be Gzip [1.92ms]
(pass) prototype and name and constructor > Gzip > Gzip.name should be Gzip [1.15ms]
(pass) prototype and name and constructor > Gzip > Gzip.prototype.__proto__.constructor.name should be Zlib [2.74ms]
(pass) prototype and name and constructor > Gunzip > Gunzip.prototype should be instanceof Gunzip.__proto__ [0.47ms]
(pass) prototype and name and constructor > Gunzip > Gunzip.prototype.constructor should be Gunzip [0.27ms]
(pass) prototype and name and constructor > Gunzip > Gunzip.name should be Gunzip [0.29ms]
(pass) prototype and name and constructor > Gunzip > Gunzip.prototype.__proto__.constructor.name should be Zlib [0.30ms]
(pass) prototype and name and constructor > Deflate > Deflate.prototype should be instanceof Deflate.__proto
... (truncated)

release without fix: 2 skipped
bun test v1.4.3-canary.1 (a8e4e90)

test/js/node/zlib/zlib.test.js:
(pass) prototype and name and constructor > Gzip > Gzip.prototype should be instanceof Gzip.__proto__ [0.02ms]
(pass) prototype and name and constructor > Gzip > Gzip.prototype.constructor should be Gzip [0.01ms]
(pass) prototype and name and constructor > Gzip > Gzip.name should be Gzip
(pass) prototype and name and constructor > Gzip > Gzip.prototype.__proto__.constructor.name should be Zlib [0.02ms]
(pass) prototype and name and constructor > Gunzip > Gunzip.prototype should be instanceof Gunzip.__proto__
(pass) prototype and name and constructor > Gunzip > Gunzip.prototype.constructor should be Gunzip
(pass) prototype and name and constructor > Gunzip > Gunzip.name should be Gunzip
(pass) prototype and name and constructor > Gunzip > Gunzip.prototype.__proto__.constructor.name should be Zlib
(pass) prototype and name and constructor > Deflate > Deflate.prototype should be instanceof Deflate.__proto__
(pass) prototype and name and constructor > Deflate > Deflate.prototype.constructor should be Deflate
(pass) prototype and name and constructor > Deflate > Deflate.name should be Deflate
(pass) pr
... (truncated)
```

</details>

<details><summary>passes on PR (with fix)</summary>

```console
ASAN with fix: 2 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/js/node/zlib/zlib.test.js
bun test v1.4.3 (c6b7fcb)

test/js/node/zlib/zlib.test.js:
(pass) prototype and name and constructor > Gzip > Gzip.prototype should be instanceof Gzip.__proto__ [1.83ms]
(pass) prototype and name and constructor > Gzip > Gzip.prototype.constructor should be Gzip [1.63ms]
(pass) prototype and name and constructor > Gzip > Gzip.name should be Gzip [0.98ms]
(pass) prototype and name and constructor > Gzip > Gzip.prototype.__proto__.constructor.name should be Zlib [1.81ms]
(pass) prototype and name and constructor > Gunzip > Gunzip.prototype should be instanceof Gunzip.__proto__ [0.44ms]
(pass) prototype and name and constructor > Gunzip > Gunzip.prototype.constructor should be Gunzip [0.26ms]
(pass) prototype and name and constructor > Gunzip > Gunzip.name should be Gunzip [0.27ms]
(pass) prototype and name and constructor > Gunzip > Gunzip.prototype.__proto__.constructor.name should be Zlib [0.31ms]
(pass) prototype and name and constructor > Deflate > Deflate.prototype should be instanceof Deflate.__proto
... (truncated)

release with fix: 2 skipped
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 786ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/142] gen JS modules (bundle-modules)
Preprocess modules (7327ms)
Bundle modules (114ms)
Postprocesss modules (21ms)
Bundle Functions (478ms)
Generate Code (52ms)

[8.00s] Bundled "src/js" for production
  2600 kb
  197 internal modules
  13 native modules
  50 internal functions across 16 files
[1/141] cargo bun_runtime → libbun_runtime.a
�[1m�[33mwarning�[0m�[1m: binary `bun_shim_impl` should have a kebab-case name�[0m
   �[1m�[94m|�[0m
�[1m�[94m 1�[0m �[1m�[94m|�[0m /workspace/bun/build/release/rust-target/.../bun_shim_impl
   �[1m�[94m|�[0m                                              �[1m�[33m^^^^^^^^^^^^^�[0m
   �[1m�[94m|�[0m
   �[1m�[94m= �[0m�[1mnote�[0m: `cargo::non_kebab_case_bins` is set to `warn` by default
�[1m�[96mhelp�[0m: to change the binary name to `bun-shim-impl`, convert `bin.name`
  �[1m�[94m--> �[0msrc/install/windows-shim/Cargo.toml:41:8
   �[1m�[94m|�[0m
�[1m�[94m41�[0m �[91m- �[0mname = �[91m"bun_shim_impl"�[0m
�[1m�[94m41�[0m �[92m+ �[0mname = �[92m"bun-shim-impl"�[0m
   �[1m
... (truncated)
```

</details>

<details><summary>diff hotspot</summary>

```
src/js/node/zlib.ts            | 20 +++++++++-
 test/js/node/zlib/zlib.test.js | 83 ++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 101 insertions(+), 2 deletions(-)
```

</details>

**gate history** · 1 passed · 0 rejected · iteration 0

<details><summary>evidence per changed file</summary>

```
file                            reads  edits  tests
src/js/node/zlib.ts                 3      3     18
test/js/node/zlib/zlib.test.js      2      4     15
```

</details>

<!-- robobun:evidence:end -->
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.

1 participant