Skip to content

[JSC] A collection hint that the heap can turn down - #1085

Draft
robobun wants to merge 1 commit into
mainfrom
robobun/768fe9fd/collect-async-if-allocated
Draft

robobun wants to merge 1 commit into
mainfrom
robobun/768fe9fd/collect-async-if-allocated

Conversation

@robobun

@robobun robobun commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • Bun's GC timer calls Heap::collectAsync() every second. An idle program gets Eden collections that free nothing.
  • A byte count in Bun cannot decide it: the heap counts a cell late or never, and only the heap knows if the request would run as a Full collection.

Fix

  • Heap::collectAsyncIfNecessary() is collectAsync() for a hint. The heap turns it down only if the collection would be an Eden one with nothing to sweep.
  • A hint that is turned down leaves JSC's own Eden timer off, as an Eden collection that frees nothing does. It ages the observers' caches and drops the string buffers that the sweeper drops.
  • Verified: two JSTests in five configurations. Each of six clauses fails a test when it is removed (Notes).

Background

  • A request without a scope runs as a Full collection in a Full-only heap, after an Eden collection that left little room, and over criticalGCMemoryThreshold. The heap turns none of those down.
  • A block gets its eden bit when an allocator takes it, and a precise allocation joins the nursery. prepareForAllocation() resets both. The hint reads them and the bytes counted this cycle, so no allocation path changes.
  • Considered a flag set in every allocation slow path (version 1): one more store per slow path, and a copy of what the eden bits say.

Downsides

  • A hint that is turned down costs 2 µs in a loop, and about 65 µs from Bun's 1 s timer. Most of it is one read of the process's memory use, for the critical threshold.
  • Retired wasm code, replaced JIT stubs and the remembered set wait for the next collection (numbers in GC timer: collect at a tick only when JSC has something to collect bun#49398).
  • After a Full collection that left little room, main's empty Eden collection left the next Full one owing. The hint asks for neither.
Notes
  • Heap::collect(), the allocators and the code of every other request are as before. The change in Source/ is 105 added lines: the entry point, MarkedSpace::isEdenEmpty(), Collector::collectsOnlyFull() (the first test of decideCollectionScope(), now with a name), and the shell function.
  • The order inside the hint is the order of 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, and collectAsync() 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 for collectAsync(). This version has as many as collectAsync().) A request that does not cover the hint, an Eden one from EdenGCActivityCallback, 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 of Collector::decideCollectionScope(), which the hint calls with a fresh reading of the critical threshold.
  • What an Eden collection sweeps: BlockDirectory::snapshotUnsweptForEdenCollection() adds the eden bits to the unswept bits, and the precise allocations are swept from m_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.
  • Why the bytes are read as well. Memory is counted without a cell: reported extra memory (a rope that gets its characters), a butterfly that grows in place. An Eden collection measures that growth in updateAllocationLimits(), and it can leave a Full collection owing.
  • Why the nursery is read as well. The first cells of a type with its own subspace are lower-tier precise cells (IsoSubspace::tryAllocateLowerTierPrecise()). They are in no block, and the heap counts no bytes for them. A new WeakSet after gc() is one.
  • The critical threshold is read with 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.
  • What an Eden collection with nothing to sweep does, step by step, and what a hint that is turned down does instead:
An Eden collection with nothing to sweep A hint that is turned down
willStartCollection(): records m_sizeBeforeLastEdenCollect, cancels the Eden timer, tells the observers records the size. The timer is not armed, since nothing was allocated. No collection ran, so the observers are not told
marking: the roots again, and the remembered set nothing. The remembered set waits for the next collection
pruneDeadReferences(): weak handles and tables, array buffers, dead code blocks nothing: no cell died
end phase: replaced JIT stubs, retired wasm callees nothing. They wait for the next collection
prepareForAllocation(): starts the sweeper, resets the allocators and the eden record calls clearConcurrentRetainedDataIfPossible(), which is all that the sweeper would do here. The eden record is empty
updateAllocationLimits(): records m_sizeAfterLastEdenCollect, tests minEdenToOldGenerationRatio, tells the Full timer, reads the critical threshold records the size and reads the threshold. The Full timer's call is a no-op for a heap that did not change. The ratio is not tested (below)
didFinishCollection() and recordCollectionTime(): m_lastCollectionScope, m_lastEdenGCLength, the observers nothing: no collection ran
sweepAndClearCachesInEpilogue(): the caches that refer to cells, the old buffers of strings that became atoms, the observers' caches, Wasm::TypeInformation::cleanupIfRequested() the caches that refer to cells stay valid, since no cell died. The buffers: clearConcurrentRetainedDataIfPossible(). The observers' caches: clearCachesAfterEmptyEdenCollection(). The wasm types wait
  • With both sizes equal, EdenGCActivityCallback::deathRate() is 0, and didAllocate() 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.
  • The ratio. After a Full 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 that bun:ffi keeps 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 a GCOwnedDataScope, which only a build with assertions tracks.
  • clearConcurrentRetainedDataIfPossible() drops the old buffers of strings that JSString::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.
  • Who may read the bits: the thread with heap access (BlockDirectory::assertMayAccessBitsUnlocked()). The hint runs on the mutator thread.
  • With useGlobalGC the heap answers for itself. Each heap's own thread asks for it.
  • Each clause, removed one at a time in a local build:
removed what fails
the nursery test in isEdenEmpty() "a hint after a lower-tier precise cell", in both runs of the first test
the eden bits in isEdenEmpty() "a hint after one object", in both runs of the first test
!totalBytesAllocatedThisCycle() "a hint after extra memory was reported", in both runs of the first test
!m_shouldDoFullCollection "a hint after an Eden collection that left a Full one owing", in both runs of the first test
!Collector::collectsOnlyFull() "a hint after a Full collection", in the runs without the generational collector and in a mini VM
the critical threshold "a hint after a Full collection", in the run over the threshold
  • No JSTest fails without the two tests for a request that is queued or under way. They need a collection that is still under way, and the shell's collections end where they begin. Bun has the tests for them and for the decline path (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.js has 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.js runs 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).
  • 40 of 40 runs of each of the 5 configurations pass on a release build of the jsc shell, and run-jsc-stress-tests passes both files. Both tests are listed in JSTests/BUN-TEST-DIFFERENCES.md.
  • Cost of a hint, Bun release build, 1,000,000 calls in a loop after a Full collection: 1.9 to 2.0 µs each when the heap turns it down, 2.0 to 2.1 µs after node:http, node:crypto, node:zlib, bun:sqlite and 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/statm is 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), and Heap::collectAsyncIfNecessary() is 741 bytes of that. No allocation path changes: Heap::didAllocate() and LocalAllocator::allocateSlowCase() have the same sizes in both binaries.
  • Not used: 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.
  • Neighbours. [JSC] Cells get an allocation limit of their own, which extra memory raises by no more than the cells do #1072 adds a second reason for 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.
  • Rebased onto cad01dc, the fork's main, which Bun's main pins. The heap code did not change between that and the earlier bases (499846f, e2fe703).
  • History. Version 1 put the test inside 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 to MarkedSpace::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 of collect(), wantsFullCollection(), the observers' caches, and the table above.

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Preview build of 4336cd2: autobuild-preview-pr-1085-4336cd21

@robobun
robobun force-pushed the robobun/768fe9fd/collect-async-if-allocated branch 2 times, most recently from db66f73 to fbd9946 Compare November 21, 2026 05:27
@robobun robobun changed the title [JSC] A collection hint that the heap can turn down, and a notice when a quiet heap grows [JSC] A collection hint that the heap can turn down, and a notice when a quiet heap allocates again Nov 21, 2026
@robobun
robobun force-pushed the robobun/768fe9fd/collect-async-if-allocated branch from fbd9946 to bf97c96 Compare November 21, 2026 12:09
@robobun robobun changed the title [JSC] A collection hint that the heap can turn down, and a notice when a quiet heap allocates again [JSC] A collection hint that the heap can turn down Nov 21, 2026
@robobun
robobun force-pushed the robobun/768fe9fd/collect-async-if-allocated branch 2 times, most recently from 3ba7fe9 to 1a8b7a6 Compare November 21, 2026 13:48
@robobun
robobun force-pushed the robobun/768fe9fd/collect-async-if-allocated branch from 1a8b7a6 to 80e1b16 Compare November 21, 2026 20:13
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
robobun force-pushed the robobun/768fe9fd/collect-async-if-allocated branch from 80e1b16 to cc0d0fd Compare November 21, 2026 23:41
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
robobun force-pushed the robobun/768fe9fd/collect-async-if-allocated branch from cc0d0fd to 58632f7 Compare November 22, 2026 17:48
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
robobun force-pushed the robobun/768fe9fd/collect-async-if-allocated branch from 58632f7 to 7ac8222 Compare November 22, 2026 21:46
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
robobun force-pushed the robobun/768fe9fd/collect-async-if-allocated branch from 7ac8222 to 4336cd2 Compare November 23, 2026 16:11
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.
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.

2 participants