Repository navigation
Conversation
|
Preview build of 4336cd2: |
robobun
force-pushed
the
robobun/768fe9fd/collect-async-if-allocated
branch
2 times, most recently
from
November 21, 2026 05:27
db66f73 to
fbd9946
Compare
robobun
force-pushed
the
robobun/768fe9fd/collect-async-if-allocated
branch
from
November 21, 2026 12:09
fbd9946 to
bf97c96
Compare
robobun
force-pushed
the
robobun/768fe9fd/collect-async-if-allocated
branch
2 times, most recently
from
November 21, 2026 13:48
3ba7fe9 to
1a8b7a6
Compare
robobun
force-pushed
the
robobun/768fe9fd/collect-async-if-allocated
branch
from
November 21, 2026 20:13
1a8b7a6 to
80e1b16
Compare
robobun
added a commit
to oven-sh/bun
that referenced
this pull request
Nov 21, 2026
The preview adds Heap::collectAsyncIfAllocated() to 499846f18f75. The pin moves to the merged commit when that pull request lands.
robobun
force-pushed
the
robobun/768fe9fd/collect-async-if-allocated
branch
from
November 21, 2026 23:41
80e1b16 to
cc0d0fd
Compare
robobun
added a commit
to oven-sh/bun
that referenced
this pull request
Nov 22, 2026
The preview adds Heap::collectAsyncIfAllocated() to 499846f18f75. This commit is here so that CI can run. When that pull request has merged, the pin comes from main and this commit goes away.
robobun
force-pushed
the
robobun/768fe9fd/collect-async-if-allocated
branch
from
November 22, 2026 17:48
cc0d0fd to
58632f7
Compare
robobun
added a commit
to oven-sh/bun
that referenced
this pull request
Nov 22, 2026
The preview adds Heap::collectAsyncIfNecessary() to 499846f18f75. This commit is here so that CI can run. When that pull request has merged, the pin comes from main and this commit goes away.
robobun
force-pushed
the
robobun/768fe9fd/collect-async-if-allocated
branch
from
November 22, 2026 21:46
58632f7 to
7ac8222
Compare
robobun
added a commit
to oven-sh/bun
that referenced
this pull request
Nov 22, 2026
The preview adds Heap::collectAsyncIfNecessary() to e2fe703936f3. This commit is here so that CI can run. When that pull request has merged, the pin comes from main and this commit goes away.
Bun's GC timer asks for a collection once a second, and once every 30 s
in a program that has gone quiet, in case the program has stopped
allocating. It asks with Heap::collectAsync(), which runs every request.
A program that allocates nothing gets one Eden collection per request:
it frees nothing and wakes the marking threads.
Heap::collectAsyncIfNecessary() is collectAsync() for such a hint. The
heap turns the hint down only if its collection would be an Eden one
with nothing to sweep:
- The request would run as an Eden collection. A Full collection can
free what was allocated before the last collection, so the heap turns
down no request that would run as one: in a heap that collects only
Full (no generational collector, a mini VM), after an Eden collection
that left a Full one owing, and over the critical memory threshold.
Heap::wantsFullCollection() has the last two for the hint and for
Collector::decideCollectionScope(). The hint reads the threshold anew,
because a heap that allocates nothing does not otherwise find out that
the process went over it.
- No cell was allocated since the last collection ended. The heap
already keeps that: a block that an allocator takes has its eden bit
set, a precise allocation is appended to the nursery, and
prepareForAllocation() resets both at the end of a collection. An Eden
collection sweeps exactly those blocks and that part of the list.
MarkedSpace::isEdenEmpty() reads them, and no allocation path changes.
- No memory was counted since then (totalBytesAllocatedThisCycle()).
Memory is counted without a cell: reported extra memory, a butterfly
that grows in place. An Eden collection measures that growth, and it
can leave a Full collection owing.
The hint begins as collect(Async) does. A queued request that covers it
is left alone, without a safepoint, so that a collection which the
mutator conducts ends where it ends for collectAsync(). Another request
(an Eden one from EdenGCActivityCallback) gets its safepoint, and the
heap answers only when none is queued or under way.
When the heap turns a hint down, it does what the collection would have
done for what is not a cell:
- It records an Eden collection that freed nothing. The death rate of
EdenGCActivityCallback is then 0, so that timer stays off until a
collection frees something. Without this the timer would collect the
next burst of allocations soon after it starts, and promote what is
still in use.
- It ages the caches of the heap's observers
(clearCachesAfterEmptyEdenCollection()): the UTF-8 copies that bun:ffi
keeps of the strings it passed. A collection that skips marking
(canSkipMarking(), compiled images) now does the same.
- It calls clearConcurrentRetainedDataIfPossible(), which drops the old
buffers of strings that became atoms. Otherwise only a collection or
the sweeper drops them, and only a collection arms the sweeper.
Two things are left out on purpose. What else a collection releases
without a cell (retired wasm code, replaced JIT stubs, the remembered
set) waits for the next collection. And after a Full collection that
left little room, an Eden collection that frees nothing would leave the
next Full collection owing, with nothing allocated in between. The heap
asks for neither of the two.
A byte count alone cannot say that no cell was allocated: a cell is
counted when its allocator has used up a free list, and a lower-tier
precise cell is never counted.
Heap::collect() and the code of every other request do not change.
Collector::collectsOnlyFull() names the first test of
decideCollectionScope(), which the hint shares.
The jsc shell gets collectAsyncIfNecessary() for the tests.
Tests: JSTests/stress/bun-collect-async-if-necessary.js
JSTests/stress/bun-collect-async-if-necessary-full-only.js
robobun
force-pushed
the
robobun/768fe9fd/collect-async-if-allocated
branch
from
November 23, 2026 16:11
7ac8222 to
4336cd2
Compare
robobun
added a commit
to oven-sh/bun
that referenced
this pull request
Nov 23, 2026
The preview adds Heap::collectAsyncIfNecessary() to cad01dc3cd19. This commit is here so that CI can run. When that pull request has merged, the pin comes from main and this commit goes away.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Heap::collectAsync()every second. An idle program gets Eden collections that free nothing.Fix
Heap::collectAsyncIfNecessary()iscollectAsync()for a hint. The heap turns it down only if the collection would be an Eden one with nothing to sweep.Background
criticalGCMemoryThreshold. The heap turns none of those down.prepareForAllocation()resets both. The hint reads them and the bytes counted this cycle, so no allocation path changes.Downsides
Notes
Heap::collect(), the allocators and the code of every other request are as before. The change inSource/is 105 added lines: the entry point,MarkedSpace::isEdenEmpty(),Collector::collectsOnlyFull()(the first test ofdecideCollectionScope(), now with a name), and the shell function.Heap::collect(Async). A queued request that covers the hint is left alone, with no safepoint: a collection that the mutator conducts leaves its concurrent phase only at a poll, andcollectAsync()does not poll it either. (Version 5 polled first. In a heap that collects only Full it then ended the collection under way and asked for the next one in the same call: 17 Full collections in 12 idle seconds with 20 MB live and no JIT, against 12 forcollectAsync(). This version has as many ascollectAsync().) A request that does not cover the hint, an Eden one fromEdenGCActivityCallback, gets its safepoint. If a request is still queued or under way after that, the hint returns true and asks for nothing: what was allocated before a collection ends is that collection's. Then the heap is read with no collection running, and the decline path writes with none running.Heap::wantsFullCollection()is the per-heap test ofCollector::decideCollectionScope(), which the hint calls with a fresh reading of the critical threshold.BlockDirectory::snapshotUnsweptForEdenCollection()adds the eden bits to the unswept bits, and the precise allocations are swept fromm_preciseAllocationsNurseryOffsetForSweep.MarkedBlock::Handle::specializedSweep()sets a block's eden bit when it sweeps to a free list, which is the only way an allocator gets a block.BlockDirectory::prepareForAllocation()clears the bits.updateAllocationLimits(), and it can leave a Full collection owing.IsoSubspace::tryAllocateLowerTierPrecise()). They are in no block, and the heap counts no bytes for them. Anew WeakSetaftergc()is one.MemoryThresholdCallType::Direct. The cached flag is refreshed at the end of a collection and at every 100th cached call, so a heap that allocates nothing and collects nothing would not find out that the process went over the threshold.willStartCollection(): recordsm_sizeBeforeLastEdenCollect, cancels the Eden timer, tells the observerspruneDeadReferences(): weak handles and tables, array buffers, dead code blocksprepareForAllocation(): starts the sweeper, resets the allocators and the eden recordclearConcurrentRetainedDataIfPossible(), which is all that the sweeper would do here. The eden record is emptyupdateAllocationLimits(): recordsm_sizeAfterLastEdenCollect, testsminEdenToOldGenerationRatio, tells the Full timer, reads the critical thresholddidFinishCollection()andrecordCollectionTime():m_lastCollectionScope,m_lastEdenGCLength, the observerssweepAndClearCachesInEpilogue(): the caches that refer to cells, the old buffers of strings that became atoms, the observers' caches,Wasm::TypeInformation::cleanupIfRequested()clearConcurrentRetainedDataIfPossible(). The observers' caches:clearCachesAfterEmptyEdenCollection(). The wasm types waitEdenGCActivityCallback::deathRate()is 0, anddidAllocate()schedules no collection until a collection frees something. Without that, the timer keeps the rate of the last Eden collection that freed something. It then collects the next burst of allocations 0.1 to 1 s after it starts, and promotes what is still in use. Bun's controller also reads the block bytes at its tick to tell a working program from an idle one, and it would read them after that collection.updateAllocationLimits()sets the limits and tests no ratio. The next Eden collection tests it, also when it frees nothing. Where the growth factor after a Full collection is under 1.5 (resident memory close to the RAM that JSC sees, or--minEdenToOldGenerationRatio), that leaves a Full collection owing, and with one request a second the heap ran an Eden and a Full collection in turns for as long as the program waited. The hint does not ask for that pair: the second Full collection would follow the first with nothing allocated in between. [JSC] Cells get an allocation limit of their own, which extra memory raises by no more than the cells do #1072 adds a second rule to the same branch. It reads what an Eden collection measured, so a hint that is turned down has nothing new for it either.clearCachesAfterEmptyEdenCollection()ages the caches of the heap's observers, which today is the UTF-8 copies thatbun:ffikeeps of the strings it passed (FFIContext::clearCachesInEpilogue(), Memory fixes in bun:ffi, ErrorInstance and RunLoopBun #1032). The collector's own shortcut for compiled images (canSkipMarking()) skipped the whole epilogue and now calls it too. That shortcut still keeps the old string buffers: no stack was scanned there, and an epilogue can run under aGCOwnedDataScope, which only a build with assertions tracks.clearConcurrentRetainedDataIfPossible()drops the old buffers of strings thatJSString::swapToAtomString()parked. It does nothing while JavaScript is on the stack, so the shell function and Bun's test helper cannot show it. Bun's test for it goes through the timer. The hint is for a caller that is where the sweeper's timer could run.BlockDirectory::assertMayAccessBitsUnlocked()). The hint runs on the mutator thread.useGlobalGCthe heap answers for itself. Each heap's own thread asks for it.isEdenEmpty()isEdenEmpty()!totalBytesAllocatedThisCycle()!m_shouldDoFullCollection!Collector::collectsOnlyFull()test/js/bun/gc/gc-controller-cadence.test.ts): "a hint does not run the collection that is queued" (100,000 hints in one turn of JavaScript leave a dropped object uncollected, with no clock in it), "keeps the collections of a program that allocates nothing" (three kinds of heap that collect only Full, with the concurrent collector: a Full collection at every second tick, and not at every tick, on Linux and macOS), "a hint that JSC turned down leaves JSC's own eden timer off", "a tick that JSC turns down frees the characters that strings left behind", "a tick that JSC turns down lets bun:ffi drop its copy of a string", and "runs the full collection that an eden collection left owing, and no more".JSTests/stress/bun-collect-async-if-necessary.jshas two runs with--minEdenToOldGenerationRatio=2, so that every Eden collection leaves a Full one owing: one with the concurrent collector and one without.JSTests/stress/bun-collect-async-if-necessary-full-only.jsruns without the generational collector, in a mini VM, and over the critical memory threshold (--criticalGCMemoryThreshold=0.000001, on Linux and macOS, where the heap reads the memory use).run-jsc-stress-testspasses both files. Both tests are listed inJSTests/BUN-TEST-DIFFERENCES.md.node:http,node:crypto,node:zlib,bun:sqliteand a server were loaded, 2.6 to 2.8 µs with 700 MB of live objects and 3.3 to 3.4 µs with 1,400 MB. The read of/proc/self/statmis most of it: the walk of the block directories alone was 0.10 to 0.13 µs in version 3. When a request that covers the hint is queued, a call costs 13 to 14 ns. One call a second, as Bun's timer makes it: a median of 64 µs (35 to 89), with its code and the file cold. With Bun's caller the binary's text is 1,805 bytes longer (156,237,937 to 156,239,742 bytes), andHeap::collectAsyncIfNecessary()is 741 bytes of that. No allocation path changes:Heap::didAllocate()andLocalAllocator::allocateSlowCase()have the same sizes in both binaries.m_hasAllocatedSinceLastCollection. Outside compiled images it is set again after every collection, and in compiled images it also turns on the shortcuts of an Eden collection with an empty Eden.m_shouldDoFullCollection, and the hint runs that collection too. [JSC] The marking helper threads join a collection once it has shown them enough work #800 and [JSC] A marking thread pays for the wake-up of another one with marking, and an idle helper leaves the collection #838 make a collection wake fewer helper threads. They lower the cost of each collection, and this PR removes the collections that have nothing to do.Heap::collect(), gave the hint a byte floor, and kept a flag that a collection cleared as it began. Version 2 moved a pass over the free lists toMarkedSpace::stopAllocating(). Version 3 read the eden bits and the nursery, and turned the hint down after a Full collection in every heap. It left JSC's Eden timer on, did not read the bytes, and read the state while a collection ran. Version 4 was the result of a review of version 3: the bytes, the fresh threshold, the Eden timer and the string buffers. This version is the result of a review of version 4: the order ofcollect(),wantsFullCollection(), the observers' caches, and the table above.