From 16b7c9cfcb7d05d1db209d0f9a2a9c42f5b8ce62 Mon Sep 17 00:00:00 2001 From: Jarred Sumner Date: Mon, 21 Sep 2026 21:38:43 -0700 Subject: [PATCH] napi: run external buffer finalizers on the JS thread when a collection ends on the collector thread An idle collection can now end on the collector thread, where the external buffers of a Node-API addon are freed. Scheduling the addon's finalizer read the JS thread's VM from that thread and crashed, and an experimental addon's finalizer was called there directly. Both now post to the JS thread. --- src/jsc/bindings/napi.h | 3 +- src/runtime/napi/napi_body.rs | 18 +++---- test/napi/napi-app/binding.gyp | 11 ++++ .../external_buffer_finalizer_thread.c | 54 +++++++++++++++++++ test/napi/napi-app/module.js | 23 ++++++++ test/napi/napi.test.ts | 17 ++++++ 6 files changed, 113 insertions(+), 13 deletions(-) create mode 100644 test/napi/napi-app/external_buffer_finalizer_thread.c diff --git a/src/jsc/bindings/napi.h b/src/jsc/bindings/napi.h index e8a55a330436..024d45d4b318 100644 --- a/src/jsc/bindings/napi.h +++ b/src/jsc/bindings/napi.h @@ -423,7 +423,8 @@ struct NapiEnv : public WTF::RefCounted { return; } - if (mustDeferFinalizers() && inGC()) { + // A collection's end phase can run on the collector thread; an addon's finalizer only ever runs on the JS thread. + if (inGC() && (mustDeferFinalizers() || WTF::Thread::mayBeGCThread())) { Bun__napi_enqueue_finalizer(this, finalize_cb, data, finalize_hint); } else { finalize_cb(this, data, finalize_hint); diff --git a/src/runtime/napi/napi_body.rs b/src/runtime/napi/napi_body.rs index 50ea9d9276c9..aa7ffcb5e484 100644 --- a/src/runtime/napi/napi_body.rs +++ b/src/runtime/napi/napi_body.rs @@ -5461,18 +5461,8 @@ impl NapiFinalizerTask { } pub(crate) fn schedule(self: Box) { - // SAFETY: env is valid (held by NapiEnvRef). - let global_this = unsafe { &*self.finalizer.env.get() }.to_js(); - - // Inline of `JSGlobalObject::try_bun_vm` (the full impl lives in the - // gated `JSGlobalObject.rs`): the VM pointer is fetched unconditionally - // from C++; "main thread" is determined by whether the thread-local VM - // holder is populated. - // SAFETY: `bun_vm()` returns a valid `*mut VirtualMachine` for this global. - let vm: &VirtualMachine = global_this.bun_vm(); - let is_main_thread = VirtualMachine::get_or_null().is_some(); - - if !is_main_thread { + // `bun_vm()` reads a thread-local that is null on a GC thread, so check the thread first. + if VirtualMachine::get_or_null().is_none() { // Off the JS thread (e.g. an external buffer finalized from a GC // helper thread): post through the env's VM handle. If the VM is // already torn down the finalizer can never run; free the task but @@ -5495,6 +5485,10 @@ impl NapiFinalizerTask { return; } + // SAFETY: env is valid (held by NapiEnvRef). + let global_this = unsafe { &*self.finalizer.env.get() }.to_js(); + let vm: &VirtualMachine = global_this.bun_vm(); + if vm.is_shutting_down() { if vm.has_run_cleanup_hooks() { // `on_exit()` already drained cleanup hooks; we are inside the diff --git a/test/napi/napi-app/binding.gyp b/test/napi/napi-app/binding.gyp index b9588cf418d3..e4efdbf26093 100644 --- a/test/napi/napi-app/binding.gyp +++ b/test/napi/napi-app/binding.gyp @@ -330,6 +330,17 @@ "NAPI_VERSION=8", ], }, + { + "target_name": "external_buffer_finalizer_thread", + "sources": ["external_buffer_finalizer_thread.c"], + "include_dirs": [" +#include +#include +#include + +#ifdef _WIN32 +#include +static uintptr_t current_thread(void) { return (uintptr_t)GetCurrentThreadId(); } +#else +#include +static uintptr_t current_thread(void) { return (uintptr_t)pthread_self(); } +#endif + +static uint32_t finalized = 0; +static uint32_t finalized_off_thread = 0; + +static void finalize(napi_env env, void *data, void *hint) { + (void)env; + if ((uintptr_t)hint != current_thread()) { + finalized_off_thread++; + } + finalized++; + free(data); +} + +static napi_value create(napi_env env, napi_callback_info info) { + (void)info; + napi_value result = NULL; + napi_create_external_buffer(env, 8, calloc(1, 8), finalize, + (void *)current_thread(), &result); + return result; +} + +static napi_value stats(napi_env env, napi_callback_info info) { + (void)info; + napi_value out, v; + napi_create_object(env, &out); + napi_create_uint32(env, finalized, &v); + napi_set_named_property(env, out, "finalized", v); + napi_create_uint32(env, finalized_off_thread, &v); + napi_set_named_property(env, out, "finalizedOffThread", v); + return out; +} + +NAPI_MODULE_INIT() { + napi_value fn; + napi_create_function(env, "create", NAPI_AUTO_LENGTH, create, NULL, &fn); + napi_set_named_property(env, exports, "create", fn); + napi_create_function(env, "stats", NAPI_AUTO_LENGTH, stats, NULL, &fn); + napi_set_named_property(env, exports, "stats", fn); + return exports; +} diff --git a/test/napi/napi-app/module.js b/test/napi/napi-app/module.js index f9810c86fce7..423e38132470 100644 --- a/test/napi/napi-app/module.js +++ b/test/napi/napi-app/module.js @@ -1738,6 +1738,29 @@ nativeTests.test_external_buffer_worker_exit = async () => { console.log("stats after exit:", JSON.stringify(nativeTests.external_for_transfer_stats())); }; +// Bun-only: an idle collection ends on the collector thread; every finalizer still runs on the JS thread. +nativeTests.test_external_buffer_finalized_by_idle_collection = async () => { + const deferred = require("./build/Debug/external_buffer_finalizer_thread.node"); + globalThis.live = new Map(); + for (let i = 0; i < 400_000; i++) live.set(i, { id: i, name: "user-" + i, tags: ["a" + i, "b" + i] }); + const count = 200; + globalThis.buffers = []; + for (let i = 0; i < count; i++) { + buffers.push(nativeTests.create_external_buffer_for_transfer(8), deferred.create()); + } + // Old objects: only a full collection frees them, and the next one is the idle one. + Bun.gc(true); + await new Promise(resolve => setTimeout(resolve, 100)); + globalThis.buffers = null; + await new Promise(resolve => setTimeout(resolve, 4000)); + for (const [name, stats] of [ + ["experimental", nativeTests.external_for_transfer_stats()], + ["deferred", deferred.stats()], + ]) { + console.log(`${name}: finalized=${stats.finalized === count} finalizedOffThread=${stats.finalizedOffThread}`); + } +}; + // Bun-only: an orphaned threadsafe function is freed by whichever thread drops // its last reference, including a call that reports napi_closing. Every // iteration must end with as many live threadsafe functions as it started with. diff --git a/test/napi/napi.test.ts b/test/napi/napi.test.ts index ec49fce9f69e..6df20c4c9af1 100644 --- a/test/napi/napi.test.ts +++ b/test/napi/napi.test.ts @@ -487,6 +487,23 @@ describe.concurrent.skipIf(!canBuildNodeAddons())("napi", () => { ); }); + // The JS thread parks without heap access during an idle collection, so its end phase runs on the collector thread. + it.skipIf(isWindows)( + "an idle collection on the collector thread runs the finalizers on the JS thread", + async () => { + const result = await runOn(bunExe(), "test_external_buffer_finalized_by_idle_collection", [], { + BUN_IDLE_GC_SECONDS: "1", + BUN_GC_TIMER_DISABLE: undefined, + BUN_GC_TIMER_INTERVAL: undefined, + BUN_GC_RUNS_UNTIL_SKIP_RELEASE_ACCESS: "0", + } as any); + expect(result).toStartWith( + "experimental: finalized=true finalizedOffThread=0\ndeferred: finalized=true finalizedOffThread=0\n", + ); + }, + 30_000, + ); + it("a worker's buffers reach the parent as copies and are finalized by the worker's env teardown", async () => { const result = await checkSameOutput("test_external_buffer_worker_exit", []); const message = JSON.stringify({