Repository navigation
[JSC] Count an adopted typed array vector once, and stop counting the ArrayBuffers an eden collection freed - #684
Conversation
…n when its ArrayBuffer adopts it A typed array past the fast size limit owns a malloc'ed vector. Its ConstructionContext reports the vector with reportExtraMemoryAllocated(). slowDownAndWasteMemory() (reading .buffer, subarray(), anything that needs the ArrayBuffer) wraps the same vector with ArrayBuffer::createAdopted(), and Heap::addReference() then called didAllocate() for the whole buffer. Nothing of that size was allocated, so a program that does this to each array it makes ran twice as many collections as its allocation asks for. Heap::addReference() takes the number of bytes that were already reported and leaves them out of didAllocate(). The adoption passes the vector's length, so only the ArrayBuffer itself counts as new. The size of the heap (m_arrayBuffers) still gets the whole buffer. A fast typed array is unchanged: its buffer is a copy in the C heap, which is an allocation. $vm.heapTotalBytesAllocated() exposes Heap::totalBytesAllocated() for the test.
GCIncomingRefCountedSet::sweep() frees a buffer in any collection, once no marked cell references it, but since 252368@main it lowers m_bytes only in a full collection. m_bytes is part of Heap::extraMemorySize(). After one eden's worth of dead buffers the heap looked as large as its limit, Heap::updateAllocationLimits() saw an eden-to-old ratio under minEdenToOldGenerationRatio, and the next collection was a full one. A program that allocates ArrayBuffers alternated eden and full collections. An eden sweep now sets m_bytes to what the last sweep left plus the current size of the live objects that were added since. Those objects are at the end of the vector, and they are the only ones an eden collection can find dead: an object that stayed in the set at the last sweep had a marked cell then, and an eden collection keeps every mark. m_bytes never goes below what the last sweep left, so an eden collection still cannot shrink the heap, which is what 252368@main was after. A full sweep recomputes everything, as before.
|
Warning Review limit reached
On-demand reviews are free for the next 4 days. After that, they cost $0.25 per reviewed file. Or wait 8 minutes for your next included review. View limit detailsLimit details: You’ve used all 5 included reviews currently available. Review configuration: ⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Essentials Run ID: 📒 Files selected for processing (8)
Comment |
|
Status
|
|
Preview build of 527d50c: |
There was a problem hiding this comment.
Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.
Beyond the inline finding, I checked the sweep rewrite's ordering assumption in Source/JavaScriptCore/heap/GCIncomingRefCountedSetInlines.h: m_vector is touched only by addReference() (append) and sweep() (stable in-place compaction), so entries added since the last sweep are exactly the tail past m_sizeAfterLastSweep, and the eden formula m_bytesAfterLastSweep + preciseBytesAddedSinceLastSweep cannot take m_bytes below what the last sweep left. The bytesAlreadyReported path only fires for OversizeTypedArray, where the adopted vector was reported at construction, and the std::min guard rules out underflow in release builds.
Extended reasoning...
This is the findings-present ruled-out note. The change touches GC pacing (Heap::addReference, GCIncomingRefCountedSet::sweep), which is core heap accounting and warrants a human look regardless; the inline finding on the new test's hard dependency on $vm.heapTotalBytesAllocated() under a default (non-Bun) configure already signals that. What I additionally verified from the code: no other code path removes from or reorders m_vector (grep across heap/ shows only lastChanceToFinalize, addReference, size, and sweep use m_arrayBuffers), the compaction loop preserves relative order, and the Eden branch only adds non-negative sizes to the previous sweep's total, so the Heap::updateAllocationLimits() invariant the PR cites holds. The bytesAlreadyReported parameter defaults to 0 for every other caller, and the single non-zero caller passes buffer->byteLength() for a buffer that adopted the view's own vector, which is at most gcSizeEstimateInBytes().
|
CI is green on the third attempt. In the first two, the one red job was That test does not touch typed arrays or |
…ffers an eden collection freed Pins the preview build of oven-sh/WebKit#684. A typed array of more than 1000 elements owns a malloc'ed vector, which the heap counts when the array allocates it. Reading .buffer, subarray() and Buffer's slice() wrap that vector in an ArrayBuffer, and the heap counted the vector as allocated a second time. A chunk loop ran twice the collections. An eden collection frees the ArrayBuffers that died young, but the size of the heap kept counting them until the next full collection. One eden's worth of dead buffers made the heap look full, so every second collection of a program that allocates ArrayBuffers was a full one. The test counts the collections of these loops with BUN_JSC_logGC=1 and the concurrent collector off.
Bumps `WEBKIT_VERSION` from `c28156899e5f` to `000c48997255` (current oven-sh/WebKit `main`). The `autobuild-000c48997255272cd7e3ae7047e87b955b38989b` release exists. oven-sh/WebKit changes picked up: - [JSC] Count an adopted typed array vector once, and stop counting the ArrayBuffers an eden collection freed (oven-sh/WebKit#684) - [JSC] Run a CommonJS module's generator before its importing graph links, not when its fetch completes (oven-sh/WebKit#662) - SourceCodeKey: restore source string comparison in operator== (oven-sh/WebKit#346) - [JSC] Hand Bun__reportUnhandledError the async context the failed queueMicrotask job ran in (oven-sh/WebKit#685) - [JSC] AbstractModuleRecord::link: one throw scope for the whole function (oven-sh/WebKit#688) - [JSC] An Exception remembers the async context it was thrown in (oven-sh/WebKit#689) Not built or tested locally; relying on CI.
…ped arrays and ArrayBuffers A typed array of more than 1000 elements owns a malloc'ed vector. Reading .buffer, subarray() and Buffer's slice() wrap that vector in an ArrayBuffer. Before oven-sh/WebKit#684 the heap counted the vector as allocated a second time there, and it kept counting ArrayBuffers that an eden collection had freed, so every second collection of such a loop was a full one. main has the fix since #43022. These tests count the collections of six loops with BUN_JSC_logGC=1 and the concurrent collector off. They fail on Bun 1.4.2 and pass on main.
…9189) ### Problem - 13 open test-only PRs add or tighten regression tests for JavaScriptCore behavior (JIT tiers, garbage collection, Yarr, `Date.parse`, stack traces). Each one waits for its own review and its own CI run. - None of them changes `src/`. The tests already pass on main. ### Fix - This PR folds 13 open test-only PRs into one branch. Each commit is one PR, applied on main (`d3d074e32`) with no other change. Notes lists them. - Verified: the 15 touched test files pass on main with the release build on Linux x64 (527 tests pass, 0 fail). 14 of them also pass with the debug ASAN build (536 pass, 0 fail). `gc-controller-cadence.test.ts` builds standalone executables, so I ran it with the release build only. - One more commit answers review: the large-environment stack tests now skip when the soft stack limit is under 8 MB (`36cc5602dd`). Before, they failed there with `E2BIG`. - The original PRs are closed in favor of this one. ### Background - Most of these tests pin fixes that reached main through WebKit upgrades: no tail calls in generator and async bodies, the Yarr surrogate mask, typed array accounting in the collector, a DFG `!` fold. - The other tests cover `Error.stackTraceLimit`, `util.getCallSites`, `Uint8Array.prototype.setFromBase64`, non-ASCII white space in `Date.parse`, and an import cycle that writes a module variable early. - Each commit stands alone. To drop one test from this PR, revert its commit. <details><summary>Notes</summary> | PR | Commit | Title | |---|---|---| | #35290 | `4202a47ab` | test: cover non-ASCII white space in Date.parse | | #39453 | `64ffe6869` | Test Uint8Array.prototype.setFromBase64 into a zero-length target | | #40231 | `d4c592fb6` | Add regression tests for the Yarr JIT surrogate mask | | #42321 | `d1b832532` | test: module variables written through an import cycle before the module runs (oven-sh/WebKit#624) | | #42335 | `7cc721499` | Add tests for the WebKit cf1b36ec8703 upgrade: no tail calls in generator and async bodies | | #42501 | `2d63ff35b` | test: cover Error.stackTraceLimit stores from hot sites and util.getCallSites frame counts | | #42658 | `8b224c511` | Add a regression test for oven-sh/WebKit#649: a collection inside a host function hook freed the JIT code of the caller | | #42880 | `eb5365ba1` | test: import of a module whose code generation fails keeps its exception checked | | #42979 | `3f2401021` | Add tests for oven-sh/WebKit#684: a typed array vector counts as allocated once, and dead ArrayBuffers do not force full collections | | #44302 | `3c3223b7d` | Test that recursion checks hold with a large environment on Linux | | #45220 | `46c4fcb46` | Test `!` of Int32 arithmetic under a bitwise operator in DFG code (WebKit 96115d8717) | | #46873 | `921106ac1` | test: run the domjit.test.ts loops in a child process and assert the FTL tier | | #47137 | `eb854ed20` | test: cover the two Yarr fixes that came with WebKit 23d7f1dcef62 | </details>
Problem
Buffer.allocUnsafe(16384)) and reads.bufferor callssubarray()collects twice as often as it should, and every third collection is full. Bun 1.4.3, 100k chunks: 195 eden alone, 266 eden + 132 full with.subarray(0, 10).JSArrayBufferView::slowDownAndWasteMemory()adopts the vector thatConstructionContextalready reported, andHeap::addReference()callsdidAllocate()for it again.GCIncomingRefCountedSet::sweep()frees dead buffers in any collection but lowersm_bytesonly in a full one (252368@main). One eden of dead buffers makes the heap look full, so the next collection is full.Fix
Heap::addReference()takesbytesAlreadyReportedand leaves those bytes out ofdidAllocate().m_arrayBuffersstill gets the whole buffer.m_bytesto what the last sweep left plus the live objects added since. Only those can die in an eden collection, and the heap never shrinks below the last sweep (Heap::updateAllocationLimits()asserts that).slice()loop runs 396 eden + 0 full, not 546 + 273: loop time -50%, CPU -60%, same peak RSS.JSTests/stresstests that fail on main, and 4107 stress runs (Notes).Background
OversizeTypedArray(over 1000 elements) owns a malloc'ed vector and has noArrayBufferuntil JS asks for one.Heap::didAllocate()counts allocated bytes. The heap collects when they pass the eden budget.m_arrayBuffersholds every referencedArrayBuffer. Its total,m_bytes, is part of the heap size.Notes
Numbers from Bun. Two release builds of oven-sh/bun#42979 from the same machine, one with
WEBKIT_VERSIONleft at c281568 (base) and one with the preview build of this PR (pin). linux x64, medians of 7 interleaved runs (5 for the second table) on a loaded machine.chunkisBuffer.allocUnsafe(16384),sliceadds.slice(0, 10),ArrayBufferisnew ArrayBuffer(16384), all 200k times.streamis a 64 KBBuffer.allocUnsafewith twosubarray()views, 50k times.With 2 million small objects alive, where a full collection has something to mark:
In Bun the loops that die young keep their peak RSS. A ring of 512
new ArrayBuffer(65536)that the loop overwrites round-robin (buffers that die old) goes from 175 to 210 MB, with the collections of the same ring of plain Buffers (33 eden + 17 full, wherebaseruns 25 + 25). The tables for that are in oven-sh/bun#42979.Numbers from the
jscshell.jscshell from this branch, release, linux x64, with the heap options Bun sets (--largeHeapSize=8388608 --heapGrowthSteepnessFactor=1 --heapGrowthMaxIncrease=2). Medians of 7 interleaved runs (5 for the second table) on a loaded machine, so read the times as about ±10%.mainis c281568,1is commit 1 alone,1+2is this PR.chunkisnew Uint8Array(16384),subarrayisnew Uint8Array(16384).subarray(0, 10),ArrayBufferisnew ArrayBuffer(16384), all 200k times.streamis a 64 KB chunk with two subarrays, 50k times.The same loops with 2 million small objects alive, where a full collection has something to mark:
With the stock options of the shell (32 MB eden, nothing alive) the three builds are within noise of each other: a collection of an empty heap costs almost nothing.
Peak RSS. With both commits these loops have about the footprint of the chunk-alone loop, which is higher than what they have on main: 16 KB loops 29 to 32 MB become 37 (chunk alone: 31), 64 KB loops 29 to 34 MB become 55 to 60 (chunk alone: 40), 1 MB loops 31 MB become 42 to 57 (chunk alone: 57). On main these loops collect two to three times as often as the budget says, and every full collection also runs the allocator's scavenge (
Heap::didFinishCollection,USE(MIMALLOC)), which an eden collection does not. The peak is bounded: ten times the iterations give the same number. WithMIMALLOC_PURGE_DELAY=0the 64 KBArrayBufferloop peaks at 43 MB and not 59. With 2 million objects alive theArrayBufferloop goes down from 894 to 697 MB.Buffers that die old. A ring of buffers that the loop overwrites round-robin: each buffer survives as many allocations as the ring has slots, so most are old when they die, and only a full collection frees them. Same shell and options, medians of 5 runs.
ArrayBufferisnew ArrayBuffer(n),.bufferis aUint8Arraywhose.bufferwas read,chunkis theUint8Arrayalone.With this PR a ring of
ArrayBuffers runs the collections and has the peak RSS of the same ring of bare typed arrays (thechunkrows are the same on both builds). Full collections still come when old garbage has grown the heap, one in three here. Where main is lower (183 or 147 MB against 208), it is because it runs a full collection every second time.Why both commits are here. Commit 1 alone halves the collections but leaves the alternation, and in the second table its
subarrayloop then has the RSS that theArrayBufferloop has on main (875 MB). Commit 2 alone removes the full collections but leaves twice the eden collections (98 + 0 for 100ksubarraychunks in the stock shell, against 49 + 0 with both). The code of the two does not overlap, so they can be split if that is easier to land.One thing for a maintainer to decide. The cost of this PR is peak RSS in two places. In the
jscshell, whose allocator has no purge thread, buffer churn on a small heap peaks at about the level of the bare typed array loop and no longer below it. In Bun that peak does not move, but a ring ofArrayBuffers that die old peaks 20% higher (175 to 210 MB), at the level of the same ring of plain Buffers. Both follow from one thing: memory that anArrayBufferowns now gets the collection policy that every other allocation gets, and on main it was collected two to three times as often. If that RSS matters more than the collections, the smaller change is commit 1 alone. An option on top of this PR is to run the allocator's scavenge after an eden collection that freed many buffer bytes. I did not do that here.Why an eden sweep can only remove objects that were added since the last sweep. The sweep removes an object when none of the cells that reference it is marked. An object that stayed in the set at the last sweep had a marked cell then. An eden collection does not clear marks (
MarkedSpace::beginMarking()bumps only the eden version), so that cell is still marked and the object stays. New objects are appended and the sweep keeps the order, so the objects added since the last sweep are the end of the vector. If this ever failed for an object, it would keep counting until the next full sweep, which is what main does for every object. A size that changed after the object was counted (a transfer takes the contents away,resize()changes the length) does not matter for an old object: it keeps what the last sweep counted. A new object counts with its current size. The test coversresize()up and down andtransfer()between eden collections.History. 252262@main made the sweep recompute
m_bytesin every collection, to fix the size after a transfer. An eden sweep could then take the heap below what the last collection left, when an old buffer lost its contents. 252368@main answered that by updatingm_bytesonly in a full collection, which also keeps every dead young buffer counted until then.Without the JIT the VM is in mini mode and every collection is a full one (
Heap::useGenerationalGC()), so commit 2 changes nothing there, and its test skips itself.Not in this PR: other places where the first reference counts bytes this heap already has.
ArrayBuffer.prototype.transfer(),structuredClone()with a transfer list andpostMessage()within one heap. The contents move to a newArrayBuffer, and its first reference counts them as allocated again. A 4 MiBtransfer()still counts 4 MiB as allocated with this PR. Do not re-charge transferred ArrayBuffer contents to this Heap's GC pacing #273 is about that case, with a mark onArrayBufferContents.WebAssembly.Memory. The memory reports its own bytes, and eachArrayBufferthat wraps it counts them again, also aftergrow().#273 lists the adoption that commit 1 fixes as a non-goal, and it changes the same three lines of
Heap::addReference(). Either order works. If #273 lands first, commit 1 becomes "set the mark beforeaddReference()". If this lands first, #273 has a three-line conflict. #303 adds a counter next tosweepArrayBuffers()and does not conflict in code.The size of the heap for an array that was already old. An oversize array that a collection visited has its bytes in
m_extraMemorySize(visitChildrenreports them). When it later gets anArrayBuffer,m_arrayBuffersadds the same bytes, and the next full collection corrects the total. That was so before this PR and still is: a mutator-side subtraction would race with concurrent marking.The tests.
oversize-typed-array-buffer-is-not-allocated-twice.jsreads$vm.heapTotalBytesAllocated()(new,USE(BUN_JSC_ADDITIONS), returnsHeap::totalBytesAllocated(), the sum that the pacing uses) around each step, so it does not depend on when a collection runs. It also checks with$vm.heapExtraMemorySize()that the size of the heap has the vector once, before and after.buffer. On main with only the helper added it fails withreading .buffer of an oversize array allocated 4196688 bytes.eden-collection-stops-counting-dead-array-buffers.jschecks$vm.heapExtraMemorySize()aroundedenGC(): dead young buffers stop counting, live ones count, an old buffer counts until a full collection, and no eden collection leaves the heap smaller than the one before it. On main it fails withthe heap holds 16780375 more bytes after an eden collection of 16 dead 1 MB buffers.runDefault("--useConcurrentGC=0"), because a concurrent full collection rebuildsm_extraMemorySizewhile the mutator runs. By hand each passed 20 of 20 runs with: default options,--useConcurrentGC=0,--useJIT=0,--useDFGJIT=0, eager JIT thresholds.--filteron typed array,ArrayBuffer,DataView, transfer, resizable, shared and memory tests,--memory-limited --child-processes=4: 4107 runs pass. One fails,big-int-out-of-memory-tests.js.default, and it fails the same way with ajscbuilt from main (current footprint: 636420096 exceeds limit: 629145600).updateAllocationLimits()did not run in them. It runs in the debug build of Add tests for oven-sh/WebKit#684: a typed array vector counts as allocated once, and dead ArrayBuffers do not force full collections bun#42979 (below) and in Bun's ASAN lane in CI.Bun side. oven-sh/bun#42979 pins the build of this PR and adds a test that counts the collections of these loops with
BUN_JSC_logGC=1. On a debug build (ASAN, assertions on) with the pin, every loop of that test runs 39 eden + 0 full collections, andtest/js/bun/gc/,test/js/node/buffer.test.jsand the structured clone tests pass.