Repository navigation
Conversation
Heap::arrayBufferSize() previously returned only m_arrayBuffers.size(),
which tracks ArrayBuffer-backed storage registered via addReference()
(JSArrayBuffer, WastefulTypedArray, DataView). FastTypedArray and
OversizeTypedArray views allocate their own vectors (primitive Gigacage
auxiliary space and Gigacage::tryMalloc respectively) without an
ArrayBuffer, so new Uint8Array(n) and Buffer.alloc(n) were invisible to
the counter until .buffer materialized a WastefulTypedArray.
Under USE(BUN_JSC_ADDITIONS), add an atomic m_typedArrayVectorBytes
counter to Heap and include it in arrayBufferSize():
- reportTypedArrayVectorBytesAllocated/Deallocated are called from
JSArrayBufferView::finishCreation (Fast/Oversize), finalize
(Oversize), and slowDownAndWasteMemory (both) so the counter moves
immediately for the C++ allocation paths and stays balanced across
the FastTypedArray/OversizeTypedArray to WastefulTypedArray
transition.
- JSGenericTypedArrayView::visitChildrenImpl reports Fast/Oversize
byteSize via a new SlotVisitor counter; on full GC the visited sum
replaces m_typedArrayVectorBytes in sweepArrayBuffers, matching the
semantics of GCIncomingRefCountedSet::sweep. This covers DFG/FTL
inline-allocated FastTypedArrays (which bypass finishCreation) and
reclaims bytes for collected FastTypedArrays that have no finalizer.
OversizeTypedArray bytes are tracked exactly. FastTypedArray bytes are
exact after a full GC; between GCs, JIT inline-allocated FastTypedArrays
(<= fastSizeLimit elements) are undercounted until the next full GC.
|
Warning Review limit reachedYou’ve reached a temporary PR review limit under our Fair Usage Limits Policy. Next review available in: 24 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (9)
Comment |
| if (thisObject->m_mode == OversizeTypedArray) { | ||
| #if USE(BUN_JSC_ADDITIONS) | ||
| Heap::heap(cell)->reportTypedArrayVectorBytesDeallocated(thisObject->byteLengthRaw()); | ||
| #endif | ||
| Gigacage::free(Gigacage::Primitive, thisObject->vector()); | ||
| } |
There was a problem hiding this comment.
🔴 After a full GC, sweepArrayBuffers() resets m_typedArrayVectorBytes to the live-only visited sum, but JSArrayBufferView::finalize() for dead OversizeTypedArrays runs later (in WeakBlock::sweep(), not reap()) and subtracts each dead array's bytes from a counter that already excludes it — under-reporting still-live typed-array bytes until the next full GC. Gate this decrement on the last collection scope being Eden (or drop it and let the visited-sum reset handle full-GC accounting).
Extended reasoning...
What the bug is
On a full collection, Heap::sweepArrayBuffers() (Heap.cpp:2506) now assigns m_typedArrayVectorBytes = m_typedArrayVectorBytesVisited, i.e. the sum over live Fast/Oversize views observed during marking. But the CFinalizer registered for OversizeTypedArray (JSArrayBufferView::finalize) also calls reportTypedArrayVectorBytesDeallocated(byteLengthRaw()), and that finalizer fires after the counter has already been reset to live-only. Each dead Oversize array therefore subtracts its byte length from a counter that no longer includes it.
Code path / ordering
In Heap::runEndPhase():
reapWeakHandles()(Heap.cpp:1797) →MarkedSpace::reapWeakSets()→WeakBlock::reap()(WeakBlock.cpp:160-183). This only doesweakImpl->setState(WeakImpl::Dead); it does not invokeWeakHandleOwner::finalize.sweepArrayBuffers()(Heap.cpp:1799) runs; on a full GC it overwritesm_typedArrayVectorByteswithm_typedArrayVectorBytesVisited(live bytes only).setNeedFinalize()(Heap.cpp:1853) is called.Heap::finalize()→sweepInFinalize()(Heap.cpp:2345) then runs, andMarkedBlock::Handle::sweep()/PreciseAllocation::sweep()reachWeakBlock::sweep()(WeakBlock.cpp:80-98), which is wherefinalize(weakImpl)actually fires for each Dead impl. For blocks not swept insweepInFinalize(), this happens even later viasweepSynchronously()or the incremental sweeper.CFinalizerOwner::finalize→JSArrayBufferView::finalize→reportTypedArrayVectorBytesDeallocated(byteLengthRaw())for each deadOversizeTypedArray.
So the decrement in step 4 always lands on a counter that step 2 already reset to only-live bytes.
Why nothing prevents it
reportTypedArrayVectorBytesDeallocated clamps to zero, which hides underflow but doesn't prevent under-counting when other live vectors remain. The PR's own verification only exercised the case where everything is released before gc(true): visited=0, then 8×8MB of finalizer subtractions clamp 0→0, so it looked correct. The "100k × 256 held" case uses FastTypedArray (no finalizer), so it doesn't hit this either.
Step-by-step example
- Allocate two 8 MB
Uint8Arrays (bothOversizeTypedArray, both go throughfinishCreation→ counter = 16 MB). - Drop the reference to one, keep the other.
Bun.gc(true):- Marking visits the live one →
m_typedArrayVectorBytesVisited = 8 MB. sweepArrayBuffers()setsm_typedArrayVectorBytes = 8 MB. ✅- Sweep runs
WeakBlock::sweep(); the dead 8 MB array's finalizer callsreportTypedArrayVectorBytesDeallocated(8 MB)→ counter becomes 0. ❌
- Marking visits the live one →
process.memoryUsage().arrayBuffersnow reports 0 for the still-live 8 MB view, and stays wrong until the next full GC re-establishes the visited sum.
More generally, after any full GC that collects some but not all Oversize typed arrays, arrayBufferSize() under-reports by the total byte length of the collected ones (clamped at 0). This directly contradicts the PR's "OversizeTypedArray: exact after full GC" row.
Impact
process.memoryUsage().arrayBuffers is the user-visible surface this PR is fixing, and mixed live/dead large typed arrays across a GC is the common case in long-running servers. The result is a systematic under-report until the next full GC.
Fix
Gate the decrement on the last collection scope, e.g.:
if (thisObject->m_mode == OversizeTypedArray) {
#if USE(BUN_JSC_ADDITIONS)
JSC::Heap* heap = Heap::heap(cell);
if (heap->lastCollectionScope() != CollectionScope::Full)
heap->reportTypedArrayVectorBytesDeallocated(thisObject->byteLengthRaw());
#endif
Gigacage::free(Gigacage::Primitive, thisObject->vector());
}(exposing m_lastCollectionScope if needed). The decrement is still required after an Eden collection, where sweepArrayBuffers() does not reset the counter and the finalizer is the only place these bytes are subtracted. Dropping the decrement unconditionally would instead over-count Oversize arrays collected by Eden GCs until the next full GC.
| case FastTypedArray: { | ||
| if (vector) | ||
| visitor.markAuxiliary(vector); | ||
| #if USE(BUN_JSC_ADDITIONS) | ||
| visitor.reportTypedArrayVectorBytesVisited(byteSize); | ||
| #endif | ||
| break; | ||
| } | ||
|
|
||
| case OversizeTypedArray: { | ||
| visitor.reportExtraMemoryVisited(byteSize); | ||
| #if USE(BUN_JSC_ADDITIONS) | ||
| visitor.reportTypedArrayVectorBytesVisited(byteSize); | ||
| #endif |
There was a problem hiding this comment.
🟡 Minor accounting imprecision: if a Fast/Oversize view is visited during a concurrent full GC and then the mutator calls .buffer on it (slowDownAndWasteMemory), its bytes end up counted in both m_typedArrayVectorBytesVisited (which becomes m_typedArrayVectorBytes at sweep) and m_arrayBuffers. The reportTypedArrayVectorBytesDeallocated call decrements m_typedArrayVectorBytes, but that value is discarded on full GC in favor of the visited sum. Statistics-only, self-corrects on the next full GC, and mirrors the existing m_extraMemorySize imprecision for the Oversize→Wasteful transition — probably fine to accept, just worth being aware of.
Extended reasoning...
What the bug is
During a concurrent full GC (default on Bun's x86_64/ARM64 targets), the mutator continues to run while marker threads visit cells. DeferGCForAWhile in slowDownAndWasteMemory() only bumps m_deferralDepth; it does not pause an in-progress concurrent collection. This means a marker thread can visit a Fast/Oversize typed array view — adding its byteSize to m_typedArrayVectorBytesVisited — and afterwards the mutator can promote that same view to WastefulTypedArray via .buffer, adding the same bytes to m_arrayBuffers via addReference(). When the full GC finishes, arrayBufferSize() reports those bytes twice, and the over-count persists until the next full GC.
The specific code path
- Full GC begins.
willStartCollection()(Heap.cpp:2464) resetsm_typedArrayVectorBytesVisited = 0. The collector enters the Concurrent phase and the mutator resumes. - A marker thread visits view A via
JSGenericTypedArrayView::visitChildrenImpl(JSGenericTypedArrayViewInlines.h:719-732). UndercellLock()it observesm_mode == FastTypedArray(orOversizeTypedArray) and callsvisitor.reportTypedArrayVectorBytesVisited(byteSize). Withm_isFirstVisit == trueon the collector stack this accumulates into the per-visitorm_typedArrayVectorBytesand later flushes intoHeap::m_typedArrayVectorBytesVisitedviapropagateExternalMemoryVisitedIfNecessary(). - The mutator executes
A.buffer, enteringslowDownAndWasteMemory()(JSArrayBufferView.cpp:330-340). It callsheap->reportTypedArrayVectorBytesDeallocated(byteLengthRaw())— which decrementsm_typedArrayVectorBytes, notm_typedArrayVectorBytesVisited— then undercellLock()flipsm_mode = WastefulTypedArrayand callsheap->addReference(this, buffer.get()), which doesm_arrayBuffers.m_bytes += buffer->gcSizeEstimateInBytes(). - End phase (world stopped).
sweepArrayBuffers()(Heap.cpp:2508-2510) runsm_arrayBuffers.sweep(), which recomputesm_bytes = preciseBytes— including A's buffer, since A is marked and retains it. Then, becausecollectionScope() == Full, it overwritesm_typedArrayVectorBytes = m_typedArrayVectorBytesVisited, which still includes A's byteSize from step 2. arrayBufferSize() = m_arrayBuffers.size() + m_typedArrayVectorBytesnow counts A's backing bytes twice.
Why existing code doesn't prevent it
- The
cellLock()held in bothvisitChildrenImplandslowDownAndWasteMemoryonly guarantees each side sees a consistent snapshot; it does not order the visit relative to the mode transition. reportTypedArrayVectorBytesDeallocated()in step 3 adjustsm_typedArrayVectorBytes, but on full GC that value is unconditionally overwritten withm_typedArrayVectorBytesVisited, so the decrement is discarded.- Any subsequent write-barrier re-visit of A runs from the mutator stack with
m_isFirstVisit == false, soreportTypedArrayVectorBytesVisitedis a no-op and cannot correct the visited sum. - The PR's
.buffer promote 8 views delta: 768 (no double count)verification was performed outside a concurrent GC, so it does not exercise this interleaving.
Step-by-step example
- Uint8Array A of 8 MB is allocated as
OversizeTypedArray.m_typedArrayVectorBytes = 8M. - Concurrent full GC starts;
m_typedArrayVectorBytesVisited = 0. - Marker visits A →
m_typedArrayVectorBytesVisited = 8M. - Mutator runs
A.buffer:reportTypedArrayVectorBytesDeallocated(8M)setsm_typedArrayVectorBytes = 0(irrelevant),m_mode = WastefulTypedArray,addReference→m_arrayBuffers.m_bytes += 8M. sweepArrayBuffers():m_arrayBuffers.sweep()recomputesm_bytes = 8M(A is live); thenm_typedArrayVectorBytes = m_typedArrayVectorBytesVisited = 8M.arrayBufferSize() = 8M + 8M = 16M— double-counted.- On the next full GC,
visitChildrenImplsees A asWastefulTypedArrayand does not add it to the visited sum, soarrayBufferSize()returns to 8M.
Impact and fix
This is a statistics-only transient over-report in process.memoryUsage().arrayBuffers, bounded by the total size of views promoted via .buffer during a single concurrent full GC, and it self-corrects on the following full GC. It does not affect GC scheduling, memory safety, or correctness. It also mirrors an existing accepted imprecision: an OversizeTypedArray promoted to Wasteful during concurrent marking already leaves its byteSize in m_extraMemorySize via reportExtraMemoryVisited.
If you want to tighten it, one option is to also atomically subtract byteLengthRaw() from m_typedArrayVectorBytesVisited in slowDownAndWasteMemory() when a full GC is in progress (saturating at 0 handles the visit-not-yet-happened ordering). Given the low impact and the existing precedent, it also seems reasonable to just note this as a known imprecision.
| #if USE(BUN_JSC_ADDITIONS) | ||
| // The backing bytes are now owned by the ArrayBuffer and will be counted by | ||
| // m_arrayBuffers via addReference() below. | ||
| heap->reportTypedArrayVectorBytesDeallocated(byteLengthRaw()); | ||
| #endif |
There was a problem hiding this comment.
🟡 This unconditionally subtracts byteLengthRaw() to balance the increment from finishCreation(), but DFG/FTL inline-allocated FastTypedArrays never went through finishCreation() (as the PR notes), so their bytes were never added. When such a view is promoted via .buffer, the decrement erases bytes that were counted for other views — the clamp-to-0 in reportTypedArrayVectorBytesDeallocated hides underflow but not the erasure. Statistics-only and self-corrects on the next full GC, so not blocking; just noting that the "stays balanced across the Fast→Wasteful transition" claim doesn't quite hold for the JIT path.
Extended reasoning...
What the bug is
slowDownAndWasteMemory() calls heap->reportTypedArrayVectorBytesDeallocated(byteLengthRaw()) unconditionally for every Fast/Oversize → Wasteful transition. The intent is to balance the reportTypedArrayVectorBytesAllocated() call made in JSArrayBufferView::finishCreation(). But FastTypedArrays created by the DFG/FTL inline-allocation fast path never call finishCreation() — the JIT emits code that allocates the vector from primitiveGigacageAuxiliarySpace and initializes m_mode/m_vector/m_length directly (see SpeculativeJIT::emitNewTypedArrayWithSizeInRegister and FTL compileNewTypedArray). The PR description explicitly acknowledges this ("DFG/FTL inline-allocated FastTypedArrays which bypass finishCreation").
So for a JIT-inlined FastTypedArray, allocation contributes +0 to m_typedArrayVectorBytes, but promotion via .buffer still contributes −byteLengthRaw(). Since reportTypedArrayVectorBytesDeallocated saturates at 0 (oldSize > size ? oldSize - size : 0) rather than tracking a signed balance or a per-view "was counted" flag, each such promotion silently steals bytes that belong to other, correctly-counted typed arrays.
Step-by-step example
- LLInt allocates
new Uint8Array(1_000_000)→finishCreation()runs →m_typedArrayVectorBytes = 1_000_000. - A DFG/FTL-compiled hot loop does
let a = new Uint8Array(256); use(a.buffer);.NewTypedArraywith an Int32 size is inline-allocated (nofinishCreation(), no increment). The.buffergetter reachespossiblySharedBuffer()→slowDownAndWasteMemory(), which callsreportTypedArrayVectorBytesDeallocated(256). - After ~4000 iterations,
m_typedArrayVectorBytesis clamped to 0 even though the 1 MB array is still live. process.memoryUsage().arrayBuffersno longer reflects the 1 MB backing store until the next full GC re-derives the count from marking.
Why existing code doesn't prevent it
- There is no per-view bit recording whether
reportTypedArrayVectorBytesAllocatedwas ever called for it, soslowDownAndWasteMemory()cannot distinguish a C++-created FastTypedArray from a JIT-inlined one. reportTypedArrayVectorBytesDeallocatedclamps to 0 instead of tracking a signed balance, so the underflow is hidden but the bytes belonging to other arrays are still erased.- The visited-sum reset in
sweepArrayBuffers()fixes this on full GC, but only after the fact; between the promotion and the next full GC the counter is transiently wrong in the negative direction (whereas the PR's accuracy table only documents JIT arrays as undercounted).
Impact
Affects only arrayBufferSize() / process.memoryUsage().arrayBuffers. It does not affect GC scheduling (extraMemorySize() uses m_extraMemorySize, not this counter), memory safety, or JS semantics. The counter is already documented as approximate for the JIT path before full GC; this just makes the transient error worse (under-reports other arrays too, not just the JIT ones). Self-corrects when the next full GC replaces m_typedArrayVectorBytes with m_typedArrayVectorBytesVisited.
Possible fix
Skip the decrement when the view's bytes were never counted. One option: since inline JIT allocation only ever produces small FastTypedArrays and never OversizeTypedArray, and there's no cheap way to distinguish JIT vs C++ FastTypedArrays, you could either (a) accept the transient skew and drop the FastTypedArray decrement entirely (the full-GC reset already keeps it bounded), or (b) leave it as-is given the impact is a diagnostic-only counter that self-heals. If exactness matters, a spare bit in m_mode/header set from finishCreation() would let slowDownAndWasteMemory() decrement only when the allocation was actually counted.
Preview Builds
|
ArrayBuffer payloads now retain their allocation-origin charge across worker transfers while external memory follows the current holder. Previously, unmaterialized typed-array vectors were missing, GC-holder estimates moved the wrong charge between VMs, and worker statistics waited for the worker event loop to become idle. The engine keeps separate origin, holder, native-object, and GC-epoch accounting. Fast/Oversize vectors are registered in C++, DFG and FTL, reconciled before sweep, and retired once during materialization. A packed weak link preserves view size, and Eden collections scan only the young prefix. Resizable, shared, native-adopted and WebAssembly storage have explicit ownership rules. JavaScript heap reporting and worker limits share the same backing-store classification. Worker inspections run on the owning VM thread through traps, an idle drain and atomic-wait wakeup. Teardown disposes pending callbacks. The matching Bun adapter is included in the existing qualification pipeline; engine and Bun must be rebuilt together. This extends the read-only engine check. Artifact publication remains a coordinator action. Builds on [oven-sh#303](oven-sh#303) and [oven-sh/bun#34406](oven-sh/bun#34406); thanks @robobun. Integrated onto source-position main `e9d324af5`. Exact-head [CI run 37242889997](https://github.com/openclaw/WebKit/actions/runs/37242889997) is green at `e95a3ef91cf0fda2d4e65ddc250513c0c669565c`. The accounting adapter is 010, after the common stack-position adapter 009. Validation on one direct AWS c7a.24xlarge Linux host, using the unchanged lane recipe: - JSC accounting and sampling: LLInt, baseline JIT, DFG, FTL and concurrent GC; namespace and source-position regressions also pass. - Node 24.21.0 and paired Bun: 24/24 API/ownership modes each, covering transfer, origin exit, detach, resize, native, shared, WebAssembly and serialization behavior. - Focused process (19), worker (7), native-buffer (1), worker-limit (14) and serializer (60) cases pass; combined source-position suites pass 96/96. - Unchanged OpenClaw worker-cpu/task-pool/transfer consumers: 38/38. Busy/waiting worker reads complete in approximately 1 ms. - Expanded paired fork selection: 45 files plus 2 dependency checks, 47/47 all-pass on both arms, identical outcomes and zero regressions. - Rust checks: 12/12 targets; subsequent runtime edits are C++/JS. - Codex P2 reviews: scoped-clean for engine and Bun. - Supplementary TSan accounting/lifecycle run passes with documented exact-frame suppressions for pre-existing GC races; 1,280 inspections and 1,280 queued cancellations across 20 VM lifetimes. This is scoped qualification, not an unsuppressed race-free claim. The only GC synchronization changes retained are atomic extra/external visited totals and the exercised parallel-helper activity assertion lock. One initial API run exposed startup allocation timing in the new busy/wait fixture, also reproducible on the prior candidate. Settling startup before allocating the fresh payload preserves all assertions, the 64 KiB bound, and the consumer. Node and Bun then passed 20 busy plus 20 wait repetitions each before the complete rerun. ABBA, eight samples per arm, against paired current-main engine plus the same common Bun adapters: | Workload | Before (ms) | After (ms) | Change | |---|---:|---:|---:| | buffer | 146.4802 | 149.3238 | +1.94% | | fast | 31.3784 | 31.4235 | +0.14% | | materialize | 144.8020 | 149.6641 | +3.36% | | oversize | 145.4974 | 146.3678 | +0.60% | | small | 4.6612 | 5.0975 | +9.36% | | stats | 2097.6425 | 2111.8061 | +0.68% | | eden-retained | 34.7131 | 34.8259 | +0.33% | Tiny-array tracking costs approximately 2.2 ns per allocation in this workload. These costs are explicit; no consumer assertion or benchmark threshold was relaxed.
…113) Make ArrayBuffer and external-memory reporting reflect fresh allocations, transfer ownership, native storage and reclamation without counting backing stores as JavaScript heap. Classify allocation mode explicitly across the Rust/C++ boundary, preserve node:v8's wire envelope, and inspect busy or atomically waiting workers on their owning VM thread. Rebased after #128's fixed OpenClaw WebKit pin. Preserve all accounting assertions while removing fixture-owned references and separating setup compilation from measurements; stabilize native conversion output under backpressure. Builds on oven-sh#34406 and oven-sh/WebKit#303; thanks @robobun. Validation: scoped-clean P2 review; five-mode accounting matrices on macOS and Linux plus Node 24.21.0 controls; full N-API, worker and serializer regressions; OpenClaw worker-CPU consumers; plain selection with zero new regressions. Exact-head native CI: https://github.com/openclaw/bun/actions/runs/37366689402
Heap::arrayBufferSize()previously returned onlym_arrayBuffers.size(), which tracksArrayBuffer-backed storage registered viaaddReference()(JSArrayBuffer, WastefulTypedArray, DataView).FastTypedArrayandOversizeTypedArrayviews allocate their own vectors (primitive Gigacage auxiliary space andGigacage::tryMallocrespectively) without anArrayBuffer, sonew Uint8Array(n)andBuffer.alloc(n)were invisible to the counter until.buffermaterialized aWastefulTypedArray.Under
USE(BUN_JSC_ADDITIONS), add an atomicm_typedArrayVectorBytescounter toHeapand include it inarrayBufferSize():reportTypedArrayVectorBytesAllocated/Deallocatedare called fromJSArrayBufferView::finishCreation(Fast/Oversize),finalize(Oversize), andslowDownAndWasteMemory(both) so the counter moves immediately for the C++ allocation paths and stays balanced across the Fast/Oversize to Wasteful transition.JSGenericTypedArrayView::visitChildrenImplreports Fast/OversizebyteSizevia a newSlotVisitorcounter; on full GC the visited sum replacesm_typedArrayVectorBytesinsweepArrayBuffers, matching the semantics ofGCIncomingRefCountedSet::sweep. This covers DFG/FTL inline-allocatedFastTypedArrays (which bypassfinishCreation) and reclaims bytes for collectedFastTypedArrays that have no finalizer.Accuracy
new ArrayBuffer(n)/ WastefulTypedArray / DataViewnew Uint8Array(n), n > 1000)Verification
Built against Bun with
build:localand verified viaprocess.memoryUsage().arrayBuffers:Hot JIT loop, 100k x Uint8Array(256) held: 862720 before GC (LLInt/baseline iterations only), 25600000 after
Bun.gc(true)(exact). 3M non-escaping Uint8Array(8): 0 after GC.