Repository navigation
[JSC] The buffer of an old WeakMap that has shrunk counts until the next full collection - #917
Conversation
…ext full collection Since #757 the heap counts the buffer of a WeakMap or WeakSet as it is behind a collection: reconcileWeakReferencesAtGCEnd() corrected what the visit had reported, at the end of any collection and for old tables too. For an old table that delete() has shrunk, that took the old buffer's bytes off the heap's size at the end of an eden collection. An eden collection only collects what was allocated since the last collection, and Heap::updateAllocationLimits() expects the size not to go below what that one left: ASSERTION FAILED: currentHeapSize >= m_sizeAfterLastCollect Without assertions, currentHeapSize - m_sizeAfterLastFullCollect wrapped to about 2^64 and went to the full collection's timer. The visit no longer reports the buffer. At the first visit the heap's count holds nothing for the table (it is new, or the collection is a full one, which counts from zero), and the end of the collection adds what the buffer has more than what is counted. So the count only goes up between full collections: - a table that a collection is the first to visit counts as that collection leaves it, without the room for the keys that it found dead, as before; - what an old table has grown by counts at the next collection, as before; - what an old table has shrunk by stops counting at the next full collection. GCIncomingRefCountedSet::sweep() keeps to the same rule for ArrayBuffers. Heap::didChangeVisitedExtraMemory(), the one way to lower the count, has no caller left and goes. The collector thread no longer reads m_buffer and m_capacity of a table that the mutator may be rehashing.
|
No actionable comments were generated in the recent review.
|
| Layer / File(s) | Summary |
|---|---|
Defer buffer accounting to reconciliation Source/JavaScriptCore/runtime/WeakMapImpl.cpp, Source/JavaScriptCore/runtime/WeakMapImplInlines.h, Source/JavaScriptCore/heap/Heap.h, Source/JavaScriptCore/heap/Heap.cpp |
Child visitation no longer reports buffer capacity. GC-end reconciliation reports extra memory only when capacity exceeds the amount already counted. The heap’s didChangeVisitedExtraMemory method is removed. |
Test collection accounting JSTests/stress/bun-weak-map-and-set-shrunk-before-eden-collection.js, JSTests/BUN-TEST-DIFFERENCES.md |
The stress test checks WeakMap and WeakSet accounting across eden and full collections, including growth, shrinkage, key loss, and optimized-code allocation. The test differences document lists the test. |
Possibly related PRs
- oven-sh/WebKit#883: Both changes modify WeakMap visitation and GC behavior involving buffer access.
- oven-sh/WebKit#781: Both changes address WeakMap buffer access during collection and rehashing.
Suggested reviewers: jarred-sumner
Priority:
Merge Risk: 
Minimal · up to 57cfc
-
No actionable accounting defect was established; the change is mergeable after normal checks.
Pre-merge checks: 
4
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands.
There was a problem hiding this comment.
I reviewed this PR and did not find any bugs. Because it changes how the GC's heap-size accounting is fed (which drives collection scheduling), deliberately diverges from upstream for shrunk old tables, and removes an exported Heap API, a human look from a GC owner would still be worthwhile.
What was reviewed:
- The new invariant in
reconcileWeakReferencesAtGCEnd(count only ever grows between full collections): checked thatm_extraMemorySizeis zeroed at full-GC start and that remembered-set re-visits come from the mutator stack withisFirstVisit()false, so an old table's count is never reset during an eden collection. - The JIT-inlined allocation path (
m_capacityCountedByHeapuninitialized): the field is only read afterm_buffer != emptyBuffer(), and both the first visit andmakeAndSetNewBufferwrite 0, so the concurrent writes cannot conflict. - Removal of
Heap::didChangeVisitedExtraMemory: no remaining reference anywhere in this tree; the Bun side is not visible here. - The test's size arithmetic (16384 buckets per 4096 keys, 64 KB margin) against the rehash/shrink thresholds and the
edenGC()/fullGC()return values in jsc.cpp.
Extended reasoning...
The change touches two JavaScriptCore files for WeakMap/WeakSet GC accounting (visitChildrenImpl and reconcileWeakReferencesAtGCEnd), deletes Heap::didChangeVisitedExtraMemory from Heap.h/Heap.cpp, and adds a stress test plus a doc row; it touches no security-sensitive surface. The core logic is about ten lines and I could verify the claimed invariant from SlotVisitor's first-visit semantics and Heap::updateAllocationLimits, and the hunt ended on a dry streak with no findings. I deferred rather than approved because /Source/JavaScriptCore and /JSTests are covered by CODEOWNERS, the fix intentionally leaves a shrunk old table over-counted until the next full collection (a behavioral trade-off a maintainer should endorse), and removing a JS_EXPORT_PRIVATE symbol has embedder impact that cannot be confirmed from this checkout.
|
Preview build of 57cfca8: |
### What does this PR do? Moves `WEBKIT_VERSION` from `982277c9dd3e` to `191c6a41380b`, the head of oven-sh/WebKit `main`. > [!NOTE] > The release `autobuild-191c6a41380bb1e2e54be4b6e50ecda83b189f96` was published at 10:39 UTC on 2026-10-27, after this went up. Builds #133617 and #133628 ran before that and failed where they download WebKit (HTTP 404). They say nothing about the change. The PR needs one new build. What the range brings: | Fork PR | What it changes | | --- | --- | | oven-sh/WebKit#912 | The ahead-of-time compiler (890 of the 942 files). Bun does not use it. Outside `aot/`: B3, the marked block cage and its reserve, `Interpreter::getStackTrace`, `ProxyObject`, `JSObject::putDirect`. | | oven-sh/WebKit#916 | The hardened Linux arm64 lanes are compiled without `-mtune`, so that glibc's `_FORTIFY_SOURCE` wrappers are inlined. | | oven-sh/WebKit#917 | The buffer of an old `WeakMap` or `WeakSet` that has shrunk counts until the next full collection. | The pin is the only change Bun needs: - `Heap::didChangeVisitedExtraMemory` is gone. Nothing in Bun calls it. - `Interpreter::getStackTrace` has one more parameter, at the end and with a default. Bun's five callers compile as they are. - The empty table of built-ins in `RemovedFeature.cpp`, which the debug and ASAN builds link: the range adds or removes no `builtinTable*` symbol, no entry of the two list macros and no `extern "C"` hook for the embedder. `BuiltinTable::typedArrayTypeOf`, which is new, is defined in the engine. - No asset is renamed in `lanes.mjs`, and no toolchain pin moves. - `BytecodeList.rb` is unchanged. The one change in the bytecompiler is for private names in object literals, which only built-in code can write, so the hashes in `bundler_bytecode_portable.test.ts` should stay. ### How did you verify your code works? Nothing was built. The list above is from reading the diff of the two commits against Bun's sources. The release has the same 77 asset names as the one of the old pin, all uploaded, and among them the 13 that the `build-bun` jobs of #133628 asked for. All 85 jobs of the fork's build of this commit passed, its JavaScriptCore tests on Linux x64 and arm64 included. `test/js/bun/jsc/webkit-upgrade-191c6a4138.test.ts` covers oven-sh/WebKit#917: | Binary | Result | | --- | --- | | `main`'s CI build (92e819d, linux x64, the old pin) | 0 pass, 2 fail: the heap is 262,032 bytes (`WeakMap`) and 129,498 bytes (`WeakSet`) smaller after the eden collection | | Bun 1.4.4 (an engine from before the bug) | 2 pass | Both the same with `BUN_GARBAGE_COLLECTOR_LEVEL` 0, 1 and 2. It has not run on the new engine yet: CI is the first run. `bun test test/internal/source-lints/` passes (186). --- _Generated by [Claude Code](https://claude.ai/code/session_01YF5TQxMfo4rBWHbttbVAhn)_ --------- Co-authored-by: Claude <[email protected]>
An eden collection could leave the heap's counted size below what the last collection left, once an old
WeakMaporWeakSethad shrunk. Builds with assertions abort; release builds hand a wrapped difference to the full collection's timer.Repro
jscASSERTION FAILED: currentHeapSize >= m_sizeAfterLastCollect(Heap::updateAllocationLimits)2663880 1617149: 1,046,731 below, socurrentHeapSize - m_sizeAfterLastFullCollectis 184467440737085048852650432 2650432, and the next full collection leaves 1602252Forced collections are not needed: 200,000 live keys, a few million short-lived allocations,
deleteof every key and a few million more allocations abort the same way with default flags.Cause
Introduced by #757 (
3d5b1926eb; on its branch903f4a971849, "The buffer of a WeakMap counts as it is behind a collection").680ef47cec, the commit before it, passes;3d5b1926ebfails;3d5b1926ebwith the one call ofdidChangeVisitedExtraMemoryswitched off passes.reconcileWeakReferencesAtGCEnd()corrected what the visit had reported, in both directions, at the end of any collection, for old tables too. Of the summands ofcurrentHeapSizethat call was the only thing that could lower one during an eden collection:m_oldGenerationCellBytes,m_deprecatedExtraMemorySizeand the visits only add, andGCIncomingRefCountedSet::sweep()already keeps the ArrayBuffers' bytes from falling, for this very reason.Only
deletegets an old table below what is counted for it. A table shrinks as soon as8 * keyCount <= capacity, so one that survives a collection has more thancapacity / 8keys, which are old by then and cannot die in an eden collection. (200 random runs withoutdeleteon the unpatched build with assertions: no abort. Withdelete: aborts.)Fix
The visit no longer reports the buffer. At the first visit the heap's count holds nothing for the table (it is new, or the collection is a full one, which counts from zero), so the visit sets
m_capacityCountedByHeapto 0, and the end of the collection adds what the buffer has more than what is counted. The count only goes up between full collections, so the invariant holds by construction.deleteshrank it, edenHeap::didChangeVisitedExtraMemory()has no caller left and goes, which leavesHeap.handHeap.cppas they were before #757 there. Nothing on the default branch of oven-sh/bun calls it. Theif constexpr (SlotVisitor)stays:--verifyGCvisits the cells again between marking and this, and would reset the count of old tables.Not done: skipping every decrease in an eden collection. That is four lines and also stops the abort. But it keeps the pre-shrink buffer of a young table counted, which #757 had fixed: in a loop that makes 3000 tables and keeps 64, the heap's size read 32.3 MB instead of 0.3 MB, with 7 full collections instead of none. The new test fails on it.
Not done: dropping the assertions and guarding the subtractions in
Heap.cpp. It changes upstream's text in three places and what the embedder reads fromsizeAfterLast*Collection(), and leaves the ArrayBuffers' rule without a reason.Test
stress/bun-weak-map-and-set-shrunk-before-eden-collection.js.fullGC()andedenGC()answer with the sizes that the assertion compares, so it fails without assertions too: on the unpatched release build in both modes that have eden collections (without the JIT every collection is a full one). It also holds the engine to what #757 brought: growth of an old table counts, a young table counts as its first collection leaves it, nothing counts twice. At most 98 ms in a mode.What was run
On
jscbuilt from this change, Release with and withoutENABLE_ASSERTS, Linux x64, clang 21:delete: the same at every step. Withdelete: the same behind every full collection, never lower behind an eden one. (The comparison rejects the four-line fix above on every seed.)--gcMaxHeapSize) and--collectContinuouslycollections, with--verifyGCand--scribbleFreeCells. No failure. The unpatched build fails 40 of 40 and 30 of 30.The whole of
run-javascriptcore-testsas CI runs it (126,377 runs, no failure) was run on the four-line version, not on this one: that is for CI here.Generated by Claude Code