Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions src/jsc/VirtualMachine.zig
Original file line number Diff line number Diff line change
Expand Up @@ -753,8 +753,29 @@ pub inline fn packageManager(this: *VirtualMachine) *PackageManager {
pub fn garbageCollect(this: *const VirtualMachine, sync: bool) usize {
@branchHint(.cold);
Global.mimalloc_cleanup(false);
if (sync)
return this.global.vm().runGC(true);
if (sync) {
const size = this.global.vm().runGC(true);
// The sync GC above ran JS finalizers which freed external backing
// stores into the native allocators, but those allocators cache
// freed pages rather than returning them to the OS immediately:
//
// - JSC-native allocations (ArrayBuffer contents via Gigacage,
// WTF::StringImpl bodies via FastCompactMalloc) land in libpas
// page caches and are only decommitted when the background
// pas_scavenger thread runs. Under sustained allocation churn
// it never gets ahead and RSS ratchets toward OOM while the JS
// heap stays flat.
// - Bun-native allocations (Blob bytes, external string payloads,
// bun.default_allocator) land on mimalloc per-thread heaps and
// are only `madvise(MADV_DONTNEED)`'d back after the segment
// purge delay elapses.
//
// A user calling `Bun.gc(true)` expects RSS to drop, so scavenge
// both allocators synchronously. See #21560, #27514, #28741.
Comment thread
robobun marked this conversation as resolved.
Resolved
jsc.wtf.releaseFastMallocFreeMemory();
Global.mimalloc_cleanup(true);
return size;
}

this.global.vm().collectAsync();
return this.global.vm().heapSize();
Expand Down
11 changes: 11 additions & 0 deletions src/jsc/WTF.zig
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@ pub const WTF = struct {
WTF__releaseFastMallocFreeMemoryForThisThread();
}

extern fn WTF__releaseFastMallocFreeMemory() void;

/// Runs `bmalloc::api::scavenge()` -> `pas_scavenger_run_synchronously_now()`,
/// which decommits libpas/Gigacage free pages back to the OS. Without this,
/// freed ArrayBuffer backing stores and WTF::StringImpl bodies sit in libpas
/// page caches until the background scavenger thread runs.
pub fn releaseFastMallocFreeMemory() void {
jsc.markBinding(@src());
WTF__releaseFastMallocFreeMemory();
}

pub fn parseDouble(buf: []const u8) !f64 {
jsc.markBinding(@src());

Expand Down
5 changes: 5 additions & 0 deletions src/jsc/bindings/wtf-bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -289,4 +289,9 @@ extern "C" void WTF__releaseFastMallocFreeMemoryForThisThread()
WTF::releaseFastMallocFreeMemoryForThisThread();
}

extern "C" void WTF__releaseFastMallocFreeMemory()
{
WTF::releaseFastMallocFreeMemory();
}

}
83 changes: 83 additions & 0 deletions test/js/bun/util/bun-gc-releases-rss.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// https://github.com/oven-sh/bun/issues/21560
// https://github.com/oven-sh/bun/issues/27514
Comment thread
robobun marked this conversation as resolved.
Resolved
//
// `Bun.gc(true)` ran a sync JS GC and called `mi_collect(false)`, but never
// scavenged libpas (JSC's allocator) or forced a mimalloc purge. So after GC
// freed ArrayBuffer contents / WTF::StringImpl bodies into libpas page
// caches, and Blob bytes / external payloads into mimalloc thread heaps,
// RSS stayed at peak even though the JS heap was empty. Under sustained
// allocation churn this ratchets RSS toward OOM while heap stats look flat.
//
// Linux-only: only on Linux does `madvise(MADV_DONTNEED)` make the kernel
// drop pages from RSS immediately. macOS uses `MADV_FREE_REUSABLE` (lazy,
// reclaimed only under pressure) and Windows uses `VirtualAlloc(MEM_RESET)`
// (stays in the working set), so `process.memoryUsage().rss` doesn't move
// there even though the fix is working. The runtime change applies on every
// platform; only the RSS-based measurement here is non-portable.

import { expect, test } from "bun:test";
import { bunEnv, bunExe, isLinux } from "harness";

test.skipIf(!isLinux)("Bun.gc(true) returns freed libpas/mimalloc pages to the OS (#21560)", async () => {
// Churn a mixed workload (typed arrays -> libpas Gigacage, large strings
// -> libpas FastCompactMalloc) through a rolling window so the allocators
// build up a page cache, then drop everything and Bun.gc(true). Measure
// how much of the peak RSS growth is released.
const fixture = `
const hold = 8;
const iters = 200;
const ring = new Array(hold);

function round(r) {
const ta = new Uint8Array(2_000_000);
for (let i = 0; i < ta.length; i += 4096) ta[i] = r & 0xff;
const s = Buffer.alloc(2_000_000, (r & 0x7f) | 0x20).toString("latin1");
return { ta, s };
}

const start = process.memoryUsage().rss;
let peak = start;
for (let r = 1; r <= iters; r++) {
ring[r % hold] = round(r);
const rss = process.memoryUsage().rss;
if (rss > peak) peak = rss;
}
for (let i = 0; i < ring.length; i++) ring[i] = undefined;

Bun.gc(true);

const final = process.memoryUsage().rss;
const growth = peak - start;
const released = peak - final;
const pct = (released / growth) * 100;
console.log(JSON.stringify({
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
startMB: (start / 1048576).toFixed(1),
peakMB: (peak / 1048576).toFixed(1),
finalMB: (final / 1048576).toFixed(1),
growthMB: (growth / 1048576).toFixed(1),
releasedPct: pct.toFixed(1),
}));
Comment thread
robobun marked this conversation as resolved.
Resolved
`;

await using proc = Bun.spawn({
cmd: [bunExe(), "--smol", "-e", fixture],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});

const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stderr).toBe("");
const { startMB, peakMB, finalMB, growthMB, releasedPct } = JSON.parse(stdout);
console.log({ startMB, peakMB, finalMB, growthMB, releasedPct });

// 8 rounds live * ~4MB each = ~32MB minimum working set; RSS growth must
// be meaningful or the released% assertion below proves nothing.
expect(Number(growthMB)).toBeGreaterThan(20);

// Without the fix: ~0% released (libpas/mimalloc keep the pages until the
// background pas_scavenger / mimalloc purge timer runs, which never gets
// ahead under churn). With the fix: consistently >90% released.
expect(Number(releasedPct)).toBeGreaterThan(50);
expect(exitCode).toBe(0);
});
Loading