Skip to content

[JSC] The buffer of an old WeakMap that has shrunk counts until the next full collection - #917

Merged
dylan-conway merged 1 commit into
mainfrom
claude/jsc-weakmap-heap-assertion-e17c1u
Oct 27, 2026
Merged

dylan-conway merged 1 commit into
mainfrom
claude/jsc-weakmap-heap-assertion-e17c1u

Conversation

@dylan-conway

@dylan-conway dylan-conway commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

An eden collection could leave the heap's counted size below what the last collection left, once an old WeakMap or WeakSet had shrunk. Builds with assertions abort; release builds hand a wrapped difference to the full collection's timer.

Repro

const wm = new WeakMap(), keys = [];
for (let i = 0; i < 20000; i++) { const k = {}; keys.push(k); wm.set(k, 0); }
const full = fullGC();
for (const k of keys) wm.delete(k);
const eden = edenGC();
print(full, eden);
jsc before after
with assertions ASSERTION FAILED: currentHeapSize >= m_sizeAfterLastCollect (Heap::updateAllocationLimits) runs
release 2663880 1617149: 1,046,731 below, so currentHeapSize - m_sizeAfterLastFullCollect is 18446744073708504885 2650432 2650432, and the next full collection leaves 1602252

Forced collections are not needed: 200,000 live keys, a few million short-lived allocations, delete of every key and a few million more allocations abort the same way with default flags.

Cause

Introduced by #757 (3d5b1926eb; on its branch 903f4a971849, "The buffer of a WeakMap counts as it is behind a collection"). 680ef47cec, the commit before it, passes; 3d5b1926eb fails; 3d5b1926eb with the one call of didChangeVisitedExtraMemory switched 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 of currentHeapSize that call was the only thing that could lower one during an eden collection: m_oldGenerationCellBytes, m_deprecatedExtraMemorySize and the visits only add, and GCIncomingRefCountedSet::sweep() already keeps the ArrayBuffers' bytes from falling, for this very reason.

Only delete gets an old table below what is counted for it. A table shrinks as soon as 8 * keyCount <= capacity, so one that survives a collection has more than capacity / 8 keys, which are old by then and cannot die in an eden collection. (200 random runs without delete on the unpatched build with assertions: no abort. With delete: 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_capacityCountedByHeap to 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.

upstream before after
old table grew by 1 MB, eden not counted +1,054,047 +1,054,047
delete shrank it, eden falls to +5,555 stays
grew back to 256 KB, eden stays: not counted twice
full collection exact exact exact
50 young tables lose 4096 keys each to their first collection +13.1 MB +12,168 +12,168

Heap::didChangeVisitedExtraMemory() has no caller left and goes, which leaves Heap.h and Heap.cpp as they were before #757 there. Nothing on the default branch of oven-sh/bun calls it. The if constexpr (SlotVisitor) stays: --verifyGC visits 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 from sizeAfterLast*Collection(), and leaves the ArrayBuffers' rule without a reason.

Test

stress/bun-weak-map-and-set-shrunk-before-eden-collection.js. fullGC() and edenGC() 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 jsc built from this change, Release with and without ENABLE_ASSERTS, Linux x64, clang 21:

  • The heap's size behind each of 300 collections, over 2000 random lives of up to 12 tables, against the unpatched build. Without delete: the same at every step. With delete: the same behind every full collection, never lower behind an eden one. (The comparison rejects the four-line fix above on every seed.)
  • 460 random runs with assertions: forced, allocation-driven (--gcMaxHeapSize) and --collectContinuously collections, with --verifyGC and --scribbleFreeCells. No failure. The unpatched build fails 40 of 40 and 30 of 30.
  • By hand: contents after shrinking and refilling, a table that dies while over-counted, a heap snapshot in between, six VMs at once.

The whole of run-javascriptcore-tests as 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

…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.
@coderabbitai

coderabbitai Bot commented Oct 27, 2026

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 44b19c6b-3869-48d2-82a5-d14cd9f6444f
Commits

Reviewing files that changed from the base of the PR and between cdce396 and 57cfca8.

Files selected for processing: 6
  • JSTests/BUN-TEST-DIFFERENCES.md
  • JSTests/stress/bun-weak-map-and-set-shrunk-before-eden-collection.js
  • Source/JavaScriptCore/heap/Heap.cpp
  • Source/JavaScriptCore/heap/Heap.h
  • Source/JavaScriptCore/runtime/WeakMapImpl.cpp
  • Source/JavaScriptCore/runtime/WeakMapImplInlines.h
Files with no reviewable changes: 2
  • Source/JavaScriptCore/heap/Heap.h
  • Source/JavaScriptCore/heap/Heap.cpp

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 1 remain after this review.

Walkthrough

WeakMap and WeakSet buffer accounting now retains the previously counted capacity when a buffer shrinks and reports capacity increases during GC-end weak-reference reconciliation. A new stress test checks accounting across eden and full collections.

Changes

Weak collection buffer accounting

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: Normal

Merge Risk: Minimal · up to 57cfc

No actionable accounting defect was established; the change is mergeable after normal checks.

Pre-merge checks: Passed 4
Check name Status Explanation
Description check Passed The description clearly explains the WeakMap and WeakSet heap-accounting regression, the fix, and the validation performed.
Title check Passed The title clearly identifies the main change: a shrunken old WeakMap buffer remains counted until the next full collection.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
  • 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 that m_extraMemorySize is zeroed at full-GC start and that remembered-set re-visits come from the mutator stack with isFirstVisit() false, so an old table's count is never reset during an eden collection.
  • The JIT-inlined allocation path (m_capacityCountedByHeap uninitialized): the field is only read after m_buffer != emptyBuffer(), and both the first visit and makeAndSetNewBuffer write 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.

@dylan-conway
dylan-conway merged commit 191c6a4 into main Oct 27, 2026
80 checks passed
@github-actions

Copy link
Copy Markdown

Preview build of 57cfca8: autobuild-preview-pr-917-57cfca82

dylan-conway added a commit to oven-sh/bun that referenced this pull request Oct 27, 2026
### 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]>
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