Repository navigation
[JSC] Return unused MarkedBlock pages after sweeping; let idle optimized code age out - #542
Conversation
… sweeping A MarkedBlock is 16 KB; on systems with 4 KB pages a block that survives a collection because of a handful of live cells still keeps all four pages resident. After a sweep-only sweep (destructors have run, no free list is being built) compute from the liveness bits which interior OS pages hold no live cell and OSAllocator::decommit() them; re-commit before the block is swept to a free list or handed back to the aligned allocator. Dead cells in those pages then read as zapped, which the free-list sweep already handles. Structure blocks are excluded because a cell's destructor may read its Structure after that Structure's block was swept in the same cycle, and nothing is done during heap shutdown. No-op where the OS page is not smaller than a block (e.g. 16 KB pages) and on Windows. Options::decommitUnusedMarkedBlockPages (default on). On a long-running app whose heap after a full GC is ~42 MB of live cells spread over ~6.5k blocks (39% utilised), this returns 45-80 MB of RSS after each full collection with no measurable change in run time.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (10)
Included review availability: Your plan provides up to 5 included reviews per hour; 1 remains after this review. WalkthroughChangesThe change adds configurable JavaScriptCore memory and code aging
Merge Risk: ⚪ Minimal · up to The change is merge-ready after normal checks and review; no actionable merge-blocking risk remains. 🚥 Pre-merge checks | ✅ 3 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description gives a detailed explanation of the changes, rationale, behavior, configuration, and measurements. It does not provide the required Bugzilla link, review status, or the template-style changed-file/function list. Warning Git: CodeRabbit could not clone the repository, so clone-backed analysis was skipped and this review may be incomplete. Verify repository clone access, such as SSH credentials, before requesting another full review. If clone access is intentionally unavailable, use Comment |
…d bit sets directly Resolve once per block which bit set conveys liveness (the rules isLive() applies per cell), then test each OS page's atom range with findBit plus one bit for a cell straddling in from the previous page, instead of calling isLive() for every cell.
Preview Builds
|
…SE); elsewhere decommitted pages fault back in on their own
|
Cost measurement (Linux x64, 8 pinned cores): GC-churn microbenchmark (60 rounds × 300k small objects, 1-in-512 kept), 3 runs each:
With counters compiled in: ~10–13k Large TUI app, 100 scripted turns, interleaved on/off/on/off: wall 14.1 / 13.8 s (on) vs 14.1 / 14.3 s (off), CPU 18.3 / 17.9 s vs 18.1 / 18.5 s, frame counts identical. Follow-up commits: page liveness now comes straight from the mark / newlyAllocated bit sets (one |
…ired blocks Blocks swept after an eden collection are the young ones and get refilled straight away, so decommitting their dead pages mostly buys page faults; blocks that are mostly full (markingRetired) have nothing to give back. Adds Heap::lastCollectionScope().
|
Now restricted to sweeps that follow a full collection and to blocks that are not Cost, GC-bound microbenchmark (allocate 300k small objects × 60 rounds, 1/512 kept), 10 interleaved runs on 8 pinned cores:
i.e. ~3% on a loop that only allocates and collects, all of it kernel-side (madvise + ~2k refaults); unchanged on the real app run (14.1/13.8 s vs 14.1/14.3 s for 100 turns). |
…to A/B the eager policy
|
Why "full collections only": a benchmark where the policies actually diverge — bursty allocation with 120 ms think-gaps (so the incremental sweeper runs between bursts) on top of a large fragmented old generation (
Eager costs ~15–20% CPU here (kernel time from 3.5× the madvise calls, decommitting young blocks that the next burst refills) for ~10 MB more; full-only keeps most of the RSS win at a cost inside the run-to-run spread. On a benchmark that is nothing but allocation (every GC ends up Full) the two are indistinguishable, as expected. |
There was a problem hiding this comment.
Findings marked 🟡 are optional suggestions and need no follow-up push.
Still open from earlier reviews (3):
- 🔴
Source/JavaScriptCore/heap/MarkedBlock.cpp:503—The Structure-subspace exclusion only checks heap()->structureSpace, but BrandedStructure and WebAssemblyGCStructure (b… - Also unresolved: 2 minor or pre-existing.
|
Server / build workloads (Bun release build linked against this branch, option off vs on, interleaved runs, Linux x64):
Nothing measurable; the cost only shows on the synthetic all-full-GC loop above (~3%). |
There was a problem hiding this comment.
Code review found no new issues
No new issues were found in this update; 5 findings from earlier reviews are still open above.
Still open from earlier reviews (5):
- 🔴
Source/JavaScriptCore/heap/MarkedBlock.cpp:503—The Structure-subspace exclusion only checks heap()->structureSpace, but BrandedStructure and WebAssemblyGCStructure (b… - Also unresolved: 4 minor or pre-existing.
…de nobody uses Old-age CodeBlock jettison only ever applied to LLInt/Baseline blocks: an optimizing-JIT block re-marked itself in determineLiveness() as long as the structures it references were alive, and pinned its baseline alternative, so in a long-running app anything that ever tiered up stayed forever. - DFG blocks age like baseline ones, using the tier-up counter DFG code already decrements at returns and loop back-edges as the sign of life (useExecutionCountForCodeBlockAging, now on by default). A DFG block that is past its TTL with no observed execution no longer re-marks itself in determineLiveness() and no longer pins m_alternative, so it and its baseline block go together. DFG blocks compiled without tier-up checks have no signal and are kept; FTL blocks are kept as before (small, expensive to rebuild). - A baseline block jettisoned for old age drops the UnlinkedCodeBlock's cached copy of its code (m_unlinkedBaselineCode) if it is that code. - After a full collection, cached baseline code that has had no other owner for two consecutive full collections is released; previously that cache kept the machine code of every function that ever reached baseline for the lifetime of its unlinked code. Also: ExecutableAllocator::allocatedByteCount(), YarrCodeBlock::codeSize() and CodeBlock::agedOut() for diagnostics. Large TUI app, 100 turns then 90 s idle with periodic full GCs: JIT memory 48.8 MB committed / 46.9 MB live -> 13.5 / 9.0 MB; CodeBlocks 9.0k -> 2.8k; RSS 464 -> 323 MB, with code still running left alone.
There was a problem hiding this comment.
This pull request has been reviewed several times and this review found new issues. Where they share a root cause, one fix may close them together.
Findings marked 🟡 are optional suggestions and need no follow-up push.
Still open from earlier reviews (5):
- 🔴
Source/JavaScriptCore/heap/MarkedBlock.cpp:503—The Structure-subspace exclusion only checks heap()->structureSpace, but BrandedStructure and WebAssemblyGCStructure (b… - Also unresolved: 4 minor or pre-existing.
- decommitUnusedPages: exclude every Structure subspace (BrandedStructure, WebAssemblyGCStructure too), skip empty blocks on the no-destructor path, assert the bit-vector lock discipline around isMarkingRetired, widen the page mask to 16 bits so 64 KB-block configurations (Linux arm64) work, include order. - releaseUnusedSharedBaselineCode: no HeapIterationScope in the end phase (allocation is already stopped), reset the two-strike flag when an entry is dropped, and compile only under USE(BUN_JSC_ADDITIONS). - The m_agedOut short-circuits and the unlinked-baseline-cache drop are USE(BUN_JSC_ADDITIONS)-only so a plain JSCOnly build keeps upstream's retention behaviour.
|
Addressed the review findings in the latest commit: all Structure iso-subspaces excluded (not just |
There was a problem hiding this comment.
I reviewed this update and all nine findings from earlier rounds are now addressed — no new issues found. Given how deep this reaches into GC internals (MarkedBlock page decommit, sweep ordering, CodeBlock liveness/aging across tiers), a human pass is still worthwhile before merge.
What was reviewed
- Structure-subspace exclusion now covers every
FOR_EACH_JSC_STRUCTURE_ISO_SUBSPACEentry;m_decommittedPageswidened to 16 bits with the guard raised accordingly;isMarkingRetiredbracketed by the assert/release lock pattern; bothdecommitUnusedPages()call sites skip empty blocks; wtf includes reordered. releaseUnusedSharedBaselineCode()no longer opens aHeapIterationScopein the End phase, is guarded byENABLE(JIT) && USE(BUN_JSC_ADDITIONS), and resets the unused-at-last-full-GC flag after clearing the cache.- The
m_agedOutearly-outs indetermineLiveness()andvisitCodeBlockEdge()are nowUSE(BUN_JSC_ADDITIONS)-guarded so non-Bun builds keep base retention behavior. - Also considered whether the DFG "no tier-up checks" keep-alive guard misses
!useFTLJIT()/ unsupported-FTL-target cases — it does, but the effect is only that such DFG blocks age out and recompile at DFG on next use, not a correctness or crash issue.
Extended reasoning...
Overview
This PR makes two substantial changes to JavaScriptCore memory management: (1) after a full-GC sweep, MarkedBlock::Handle decommits interior OS pages that hold no live cell, tracked in a 16-bit bitmap and recommitted before free-listing or freeing; (2) DFG CodeBlocks now participate in execution-count-based aging (FTL exempt), an aged-out optimizing block no longer re-proves liveness or pins its baseline alternative, and cached shared baseline JIT code on UnlinkedCodeBlock is released when it has been sole-owner across two consecutive full GCs. Twelve files are touched across bytecode/, heap/, jit/, runtime/, and yarr/.
Security risks
Heap and GC changes are inherently security-sensitive. The page-decommit path must never decommit memory a live cell (or a destructor about to run) can read — the Structure-subspace exclusion, header-page keep, straddling-cell check, retired-block skip, shutdown skip, and Windows exclusion are all load-bearing for that invariant. The CodeBlock-aging change alters which optimizing CodeBlocks survive GC; getting this wrong could jettison code that is on-stack (mitigated by the existing currently-executing checks) or leak. I found no concrete exploitable path in this revision, but the blast radius of a mistake here is use-after-free / arbitrary read of zeroed pages during destruction.
Level of scrutiny
High. This is core GC/heap machinery with subtle ordering dependencies (sweep vs. destructor vs. decommit, End-phase invariants, concurrent marking versions, thread-safety-analysis annotations). Nine issues were raised and fixed across six review rounds, which itself signals the change is non-trivial. Automated review cannot substitute for a maintainer who knows the sweeper/allocator state machine and the platforms' madvise semantics.
Other factors
All previously raised findings — the BrandedStructure/WebAssemblyGCStructure subspace gap, the 8-bit page mask disabling Linux ARM64, the -Wthread-safety build break on isMarkingRetired, the double stopAllocating() via HeapIterationScope in End phase, the missing USE(BUN_JSC_ADDITIONS) guards around m_agedOut and the Options accessor, the stale two-GC flag, the empty-block decommit churn, and the include ordering — are verifiably fixed in the current diff. The remaining candidate (DFG blocks compiled without tier-up checks when FTL is disabled still age out) was examined and is a recompile-cost concern only, not a correctness bug. No test additions accompany the change; behavior is gated by runtime Options and USE(BUN_JSC_ADDITIONS) where appropriate. Given the domain, human sign-off remains appropriate.
…e aged-out flag instead of adding a member (it already recorded that this cycle's visit decided old age, previously only under verifyGC)
) Stacked on #40987 (WebKit upgrade) and pins WebKit to oven-sh/WebKit `491b5cc236e9` — fork `main` with oven-sh/WebKit#542 / #546 / #547 (MarkedBlock page release, CodeBlock aging that reaches optimized code), #543 / #548 (module loader), #545, #529. ### What `GarbageCollectionController`'s repeating timer (1 s while the heap is changing, 30 s once it isn't) already issues one `collectAsync` per tick and reads `blockBytesAllocated`. This makes that one request a **full** collection on two ticks per quiet period: when the JS heap hasn't grown (by more than 2 MB) for `BUN_IDLE_RELEASE_SECONDS` (default 30; `0` = off; main thread only; not while a debugger is attached), and again 65 s of quiet later. The first also `MADV_PAGEOUT`s a standalone executable's embedded module graph (Linux; clean file-backed pages that fault back on demand; honours `BUN_FEATURE_FLAG_DISABLE_STANDALONE_MADVISE`). One `u32` of state, no new timer, no syscalls or clock reads per tick; when an idle collection is due before the next 30 s tick, that tick is pulled forward. ### Why Full collections are where JSC ages out CodeBlocks that no longer run and releases the memory behind them (WebKit#542/#546). JSC's own `FullGCActivityCallback` is allocation-paced — it fires at most once after the last allocation burst and never again without new allocation — so a process waiting for input never gets there. Two are the minimum with sampled execution counters: the first records which code is still running, the second (a lease later) frees what hasn't run since. ### Numbers Large `--compile --bytecode` TUI app, 100 scripted turns, then 150 s hands-off; same binary, three interleaved pairs: | after 150 s idle | `BUN_IDLE_RELEASE_SECONDS=0` | default | |---|---|---| | RSS | 460 / 477 / 491 MB | **373 / 380 / 365 MB** | With the feature on, RSS is ~400–440 MB after the first idle collection (~50 s) and ~365–380 MB after the second (~110 s); JIT memory 45 → ~14 MB. Cost while busy: none. Cost while idle: two concurrent full GCs per quiet period. ### Tests `test/js/bun/gc/gc-controller-cadence.test.ts`: with `BUN_JSC_logGC=1`, a `FullCollection` appears while a script sits idle with `BUN_IDLE_RELEASE_SECONDS=2`, and none with `=0`. --------- Co-authored-by: robobun <[email protected]> Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Two independent pieces, both aimed at long-running apps that sit idle between bursts of work.
1. Return unused OS pages inside partially live MarkedBlocks
A MarkedBlock is 16 KB; on 4 KB-page systems a block kept alive by a few scattered survivors keeps all four pages resident (measured in a large app: ~6.5k blocks, 39% utilised after a full GC). After a sweep-only sweep following a full collection,
MarkedBlock::Handle::decommitUnusedPages()derives from the mark/newlyAllocated bit sets which interior OS pages hold no live cell andOSAllocator::decommit()s them (page 0 with the header stays; retired blocks are skipped). Re-committed (Darwin only; elsewhere they fault back as zero pages) before the block is swept to a free list or freed. Dead cells then read as zapped, which the free-list sweep already handles. Structure blocks are excluded (a destructor may read its Structure after that Structure's block was swept in the same cycle) and nothing happens at shutdown. No-op with ≥16 KB pages and on Windows.Options::decommitUnusedMarkedBlockPages(default on);…AfterEdenCollections(default off) re-enables the eager variant for comparison.2. Let idle optimized code age out; release cached baseline code nobody uses
Old-age CodeBlock jettison only ever applied to LLInt/Baseline blocks: an optimizing block re-marked itself in
determineLiveness()while its structures were alive and pinned its baseline alternative, so anything that ever tiered up stayed forever (measured: 9k CodeBlocks / 47 MB JIT after minutes of idle).useExecutionCountForCodeBlockAging, now default on). A DFG block past its TTL with no observed execution no longer re-marks itself and no longer pinsm_alternative. DFG blocks without tier-up checks have no signal and are kept; FTL is kept as before (small, expensive to rebuild).m_unlinkedBaselineCode) with no other owner for two consecutive full collections is released — that cache previously kept the machine code of every function that ever reached baseline for the life of its unlinked code.Numbers (large Bun
--compileTUI app, 100 scripted turns)Anonymous RSS right after a full GC, three paired runs (part 1): 440/476/430 MB → 379/395/384 MB. No measurable throughput change on express (hello + 256 KB chunked echo),
next build,next start; ~3% on a synthetic allocate-and-collect loop (kernel time).After 3 min idle with periodic full GCs (parts 1+2): JIT memory 48.8 MB committed / 46.9 live → 11.6 / 7.4 MB; CodeBlocks 9.0k → 2.8k (FTL + their baseline + what still runs); RSS ~470 → ~316 MB together with the Bun-side idle full-GC trigger (oven-sh/bun#40998). Code that is still running is left alone (verified with a busy variant).