From 8293fceca36435f9247d13b6c37cf6584d8a4d09 Mon Sep 17 00:00:00 2001 From: Sosuke Suzuki Date: Mon, 24 Aug 2026 20:23:50 +0900 Subject: [PATCH] Request the post-entry-point full collection asynchronously After the entry point has been evaluated and before the event loop starts, the main thread and every worker ran a full collection through `JSC__VM__runGC(vm, sync=false)`, which still called `collectSync(Full)`: the first event-loop tick waited for marking the freshly loaded heap, which is the largest it gets at startup. Nothing depends on that collection completing synchronously, and its return value was discarded. Replace the two call sites with a dedicated `JSC__VM__collectAfterEntryPoint` that drops unlinked code blocks (`DeleteAllCodeIfNotCollecting`) and then requests the full collection with `collectAsync`. `runGC` loses its `sync` parameter: only the `Bun.gc(true)` path remains. Dropping the unlinked code blocks is kept on purpose: on a large --compile --bytecode application, a variant that keeps them has the same startup time but +20 MB of resident payload pages, since the unlinked code keeps its source providers and cached bytecode reachable. The worker-exit streaming-fetch test relied on the synchronous collection delaying the worker's first tick, so that the expired 150 ms exit timer and the pending fetch completions were processed in the same tick; with the collection asynchronous the timer can fire before any response has arrived on a slow debug build. It now exits shortly after the first response has been touched, and keeps the "no fetch ever arrived" guard as a 5 s fallback. --- src/js_parser/lib.rs | 2 +- src/jsc/VM.rs | 15 ++++++++-- src/jsc/VirtualMachine.rs | 4 +-- src/jsc/bindings/bindings.cpp | 28 +++++++++++-------- src/jsc/bindings/headers.h | 3 +- src/jsc/web_worker.rs | 4 +-- src/runtime/cli/run_command.rs | 4 +-- src/runtime/hw_exports.rs | 2 -- .../workers/worker-terminate-lifetime.test.ts | 12 +++++--- 9 files changed, 43 insertions(+), 31 deletions(-) diff --git a/src/js_parser/lib.rs b/src/js_parser/lib.rs index 6668dce79446..b48f8990101a 100644 --- a/src/js_parser/lib.rs +++ b/src/js_parser/lib.rs @@ -140,7 +140,7 @@ pub mod Macro { /// `bun_bundler::ThreadPool::Worker::deinit` after both per-worker /// `MacroContext` boxes are freed — every other `MacroContext::deinit` /// path is either inside JS execution or inside a GC sweep, where - /// re-entering `run_gc(true)` is unsound. + /// re-entering `run_gc()` is unsound. #[inline] pub fn collect_vm_garbage() { __bun_macro_collect_vm_garbage(); diff --git a/src/jsc/VM.rs b/src/jsc/VM.rs index 092d29a0f87a..f199b07f1f11 100644 --- a/src/jsc/VM.rs +++ b/src/jsc/VM.rs @@ -26,7 +26,8 @@ unsafe extern "C" { safe fn JSC__VM__releaseAPILock(vm: &VM); safe fn JSC__VM__reportExtraMemory(vm: &VM, size: usize); safe fn JSC__VM__shrinkFootprint(vm: &VM); - safe fn JSC__VM__runGC(vm: &VM, sync: bool) -> usize; + safe fn JSC__VM__runGC(vm: &VM) -> usize; + safe fn JSC__VM__collectAfterEntryPoint(vm: &VM); safe fn JSC__VM__heapSize(vm: &VM) -> usize; safe fn JSC__VM__collectAsync(vm: &VM); safe fn JSC__VM__executionForbidden(vm: &VM) -> bool; @@ -86,8 +87,16 @@ impl VM { JSC__VM__shrinkFootprint(self) } - pub fn run_gc(&self, sync: bool) -> usize { - JSC__VM__runGC(self, sync) + /// Synchronous full collection that also drops all unlinked code + /// (`Bun.gc(true)`); returns the heap size afterwards. + pub fn run_gc(&self) -> usize { + JSC__VM__runGC(self) + } + + /// Drops unlinked code and starts a concurrent full collection; for the + /// one point right after the entry module has evaluated. + pub fn collect_after_entry_point(&self) { + JSC__VM__collectAfterEntryPoint(self) } pub(crate) fn heap_size(&self) -> usize { diff --git a/src/jsc/VirtualMachine.rs b/src/jsc/VirtualMachine.rs index ce4d14f5341f..7e945d74fde4 100644 --- a/src/jsc/VirtualMachine.rs +++ b/src/jsc/VirtualMachine.rs @@ -1279,7 +1279,7 @@ impl VirtualMachine { bun_core::Global::mimalloc_cleanup(false); let vm = self.global().vm(); if sync { - return vm.run_gc(true); + return vm.run_gc(); } vm.collect_async(); vm.heap_size() @@ -3390,7 +3390,7 @@ pub fn collect_macro_vm_garbage() { } debug_assert!(!vm_ref.is_main_thread); debug_assert_eq!(vm_ref.macro_guard_depth, 0); - vm_ref.jsc_vm().run_gc(true); + vm_ref.jsc_vm().run_gc(); } fn normalize_source(source: &[u8]) -> &[u8] { diff --git a/src/jsc/bindings/bindings.cpp b/src/jsc/bindings/bindings.cpp index f6087b73cca7..005afd0719f2 100644 --- a/src/jsc/bindings/bindings.cpp +++ b/src/jsc/bindings/bindings.cpp @@ -5117,7 +5117,7 @@ JSC::EncodedJSValue JSC__JSValue__toError_(JSC::EncodedJSValue JSValue0) #pragma mark - JSC::VM -size_t JSC__VM__runGC(JSC::VM* vm, bool sync) +size_t JSC__VM__runGC(JSC::VM* vm) { JSC::JSLockHolder lock(vm); @@ -5128,19 +5128,12 @@ size_t JSC__VM__runGC(JSC::VM* vm, bool sync) #endif vm->finalizeSynchronousJSExecution(); - - if (sync) { - vm->clearSourceProviderCaches(); - vm->heap.deleteAllUnlinkedCodeBlocks(JSC::PreventCollectionAndDeleteAllCode); - vm->heap.collectNow(JSC::Sync, JSC::CollectionScope::Full); + vm->clearSourceProviderCaches(); + vm->heap.deleteAllUnlinkedCodeBlocks(JSC::PreventCollectionAndDeleteAllCode); + vm->heap.collectNow(JSC::Sync, JSC::CollectionScope::Full); #if IS_MALLOC_DEBUGGING_ENABLED && OS(DARWIN) - malloc_zone_pressure_relief(nullptr, 0); + malloc_zone_pressure_relief(nullptr, 0); #endif - } else { - vm->heap.deleteAllUnlinkedCodeBlocks(JSC::DeleteAllCodeIfNotCollecting); - vm->heap.collectSync(JSC::CollectionScope::Full); - } - vm->finalizeSynchronousJSExecution(); #if IS_MALLOC_DEBUGGING_ENABLED && OS(DARWIN) @@ -5152,6 +5145,17 @@ size_t JSC__VM__runGC(JSC::VM* vm, bool sync) return vm->heap.sizeAfterLastFullCollection(); } +// The entry point has been evaluated and the event loop is about to start: +// module-initialization bytecode will not run again, so let it go, but +// collect concurrently — a synchronous full collection here stalls the first +// event-loop tick for as long as marking the freshly loaded heap takes. +void JSC__VM__collectAfterEntryPoint(JSC::VM* vm) +{ + JSC::JSLockHolder lock(vm); + vm->heap.deleteAllUnlinkedCodeBlocks(JSC::DeleteAllCodeIfNotCollecting); + vm->heap.collectAsync(JSC::CollectionScope::Full); +} + [[ZIG_EXPORT(nothrow)]] bool JSC__VM__isJITEnabled() { return JSC::Options::useJIT(); diff --git a/src/jsc/bindings/headers.h b/src/jsc/bindings/headers.h index 8c58db44f1a5..b6a281da8789 100644 --- a/src/jsc/bindings/headers.h +++ b/src/jsc/bindings/headers.h @@ -298,6 +298,7 @@ CPP_DECL void JSC__JSValue__toZigException(JSC::EncodedJSValue JSValue0, JSC::JS CPP_DECL size_t JSC__VM__blockBytesAllocated(JSC::VM* arg0); CPP_DECL void JSC__VM__collectAsync(JSC::VM* arg0); +CPP_DECL void JSC__VM__collectAfterEntryPoint(JSC::VM* arg0); CPP_DECL JSC::VM* JSC__VM__create(unsigned char HeapType0); CPP_DECL void JSC__VM__deleteAllCode(JSC::VM* arg0, JSC::JSGlobalObject* arg1); CPP_DECL void JSC__VM__drainMicrotasks(JSC::VM* arg0); @@ -311,7 +312,7 @@ CPP_DECL void JSC__VM__notifyNeedDebuggerBreak(JSC::VM* arg0); CPP_DECL void JSC__VM__notifyNeedShellTimeoutCheck(JSC::VM* arg0); CPP_DECL void JSC__VM__notifyNeedTermination(JSC::VM* arg0); CPP_DECL void JSC__VM__releaseWeakRefs(JSC::VM* arg0); -CPP_DECL size_t JSC__VM__runGC(JSC::VM* arg0, bool arg1); +CPP_DECL size_t JSC__VM__runGC(JSC::VM* arg0); CPP_DECL void JSC__VM__enableControlFlowProfiler(JSC::VM* arg0); CPP_DECL void JSC__VM__shrinkFootprint(JSC::VM* arg0); CPP_DECL void JSC__VM__throwError(JSC::VM* arg0, JSC::JSGlobalObject* arg1, JSC::EncodedJSValue JSValue2); diff --git a/src/jsc/web_worker.rs b/src/jsc/web_worker.rs index c8992a60697d..30a24fbc683a 100644 --- a/src/jsc/web_worker.rs +++ b/src/jsc/web_worker.rs @@ -943,9 +943,7 @@ impl WebWorker { // don't run the GC if we don't actually need to if vm.is_event_loop_alive() || vm.event_loop_mut().tick_concurrent_with_count() > 0 { vm.global().vm().release_weak_refs(); - // `Arena = bumpalo::Bump` has no collect; global mimalloc - // handles reclamation. - let _ = vm.global().vm().run_gc(false); + vm.global().vm().collect_after_entry_point(); } // Always do a first tick so we call CppTask without delay after diff --git a/src/runtime/cli/run_command.rs b/src/runtime/cli/run_command.rs index e4266d2dfb96..6e419687658c 100644 --- a/src/runtime/cli/run_command.rs +++ b/src/runtime/cli/run_command.rs @@ -1463,9 +1463,7 @@ impl Run<'_> { // don't run the GC if we don't actually need to if vm.is_event_loop_alive() || vm.event_loop_ref().tick_concurrent_with_count() > 0 { vm.global().vm().release_weak_refs(); - // `bun_alloc::Arena` has no per-heap collect to run alongside this - // GC; it would only be a memory-usage hint, not correctness. - let _ = vm.global().vm().run_gc(false); + vm.global().vm().collect_after_entry_point(); vm.tick(); } diff --git a/src/runtime/hw_exports.rs b/src/runtime/hw_exports.rs index dbffa586ddd7..e742277333cd 100644 --- a/src/runtime/hw_exports.rs +++ b/src/runtime/hw_exports.rs @@ -401,8 +401,6 @@ pub fn bindgen_bunobject_dispatch_gc( ) -> bool { // SAFETY: `arg_force`/`out` are valid C++ stack locals. let force = unsafe { *arg_force }; - // `garbage_collect(force)`: mimalloc cleanup, then sync `runGC(true)` - // when `force`, else `collect_async()` + `heap_size()`. // SAFETY: bun_vm() never null for a Bun-owned global. unsafe { *out = global.bun_vm().as_mut().garbage_collect(force) }; true diff --git a/test/js/web/workers/worker-terminate-lifetime.test.ts b/test/js/web/workers/worker-terminate-lifetime.test.ts index 1f3cd6f81934..b6a461e582e8 100644 --- a/test/js/web/workers/worker-terminate-lifetime.test.ts +++ b/test/js/web/workers/worker-terminate-lifetime.test.ts @@ -986,14 +986,18 @@ test( let ctrl; const body = new ReadableStream({ start(c) { ctrl = c; c.enqueue(new Uint8Array(1024)); } }); const p = fetch("\${server.url}", { method: "POST", body, duplex: "half" }) - .then((r) => { keep.push(r.body); const rd = r.body.getReader(); rd.read(); keep.push(rd); touched++; }) + .then((r) => { + keep.push(r.body); const rd = r.body.getReader(); rd.read(); keep.push(rd); + // Exit with that state alive, shortly after the first response has been touched. + if (touched++ === 0) setTimeout(() => process.exit(0), 30 + \${(i * 13) % 60}); + }) .catch(() => {}); keep.push(p, ctrl); setInterval(() => { try { ctrl.enqueue(new Uint8Array(512)); } catch {} }, 5); } - // Exit with that state alive; exit code 3 if no fetch ever reached it (the test would - // then not be exercising what it claims to). - setTimeout(() => process.exit(touched > 0 ? 0 : 3), 150 + \${(i * 13) % 60}); + // Exit code 3 if no fetch ever reached it (the test would then not be exercising what + // it claims to). + setTimeout(() => process.exit(3), 5000); \`, { eval: true }); w.on("error", (e) => { console.error(e); process.exit(1); }); w.on("exit", (code) => {