Repository navigation
napi: run external buffer finalizers on the JS thread when a collection ends on the collector thread #43757
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
napi: run external buffer finalizers on the JS thread when a collection ends on the collector thread #43757
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| // NAPI_VERSION=8, so Bun defers the finalizers of these buffers out of the collection. | ||
| // Each finalizer records whether it ran on the thread that created its buffer. | ||
| #include <js_native_api.h> | ||
| #include <node_api.h> | ||
| #include <stdint.h> | ||
| #include <stdlib.h> | ||
|
|
||
| #ifdef _WIN32 | ||
| #include <windows.h> | ||
| static uintptr_t current_thread(void) { return (uintptr_t)GetCurrentThreadId(); } | ||
| #else | ||
| #include <pthread.h> | ||
| 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; | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔴 nit: the new test waits a fixed 4000ms (plus 100ms) instead of observing the finalizers, so on a slow debug/ASAN runner where the idle collection lands late it reports Why this was flaggedThe test at test/napi/napi-app/module.js:1751-1754 issues two bare Verification: nit. Triggering condition: a debug/ASAN CI runner where the idle full collection of the ~2M-object heap (400k Map entries each with an object and two arrays) plus its ArrayBuffer sweep and the JS-thread task hop take longer than the fixed window. Mechanism verified in the diff at test/napi/napi-app/module.js:1751-1754: `await new Promise(resolve => setTimeout(resolve, 100)); globalThis.buffers =… |
||
| 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. | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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)( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 nit (optional): the Windows skip at napi.test.ts:491 has no stated reason in the code; the reason (libuv keeps the collection on the JS thread) is only in the PR description. Fix: put that one-line reason on the skipIf so a reader knows the test is not merely flaky there. Why this was flaggednapi.test.ts:491 uses it.skipIf(isWindows) and the comment on napi.test.ts:490 explains the collector-thread end phase but not why Windows is excluded. REVIEW.md requires skipped platforms to carry the observed reason. A maintainer who later sees the test unskipped or failing on Windows cannot tell from the code whether the idle collection can end on the collector thread there. The base branch has no such test. Verification: nit. Triggering condition: any reader of the test on Windows or after the Windows GC path changes. The diff at /home/claude/bun/test/napi/napi.test.ts:490-491 adds |
||
| "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", [], { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win Create an isolated temporary directory for this multi-file test. This test runs the As per coding guidelines: “for multi-file tests, create a temporary directory using 🤖 Prompt for AI AgentsSource: Coding guidelines |
||
| 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({ | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟣 pre-existing, not blocking: A Worker using a Node-API addon can have a buffer finalizer run after the addon's instance data has already been finalized, which the base branch never did (it crashed or ran inline). The new off-thread branch at napi_body.rs:5465-5485 posts the finalizer as a concurrent task and returns before the
is_shutting_down()/has_run_cleanup_hooks()gate at napi_body.rs:5492. If the Worker is terminated while that idle collection is on the collector thread,on_exitrunsNapiEnv::cleanup()first (VirtualMachine.rs:2276), thenclose_and_waitruns the queued task viarelease_unrun(napi_body.rs:78-81). …A small fix can ride a push you are already making; otherwise a short reply is enough.
Why this was flagged
…Fix: on the JS thread, when the posted task is drained, apply the same shutdown gate as the JS-thread path (drop it once cleanup hooks ran, or run it as a cleanup hook before
NapiEnv::cleanup()finalizes instance data).Trigger: a Worker loaded a Node-API addon whose external buffers die in an idle collection whose end phase runs on the collector thread (Bun__JSC_onBeforeWait releases access at BunJSCEventLoop.cpp:139), and the parent calls worker.terminate() (or the worker exits) before the JS thread drains the posted task. Entry point: NapiEnv::doFinalizer (napi.h:427) -> Bun__napi_enqueue_finalizer (napi_body.rs:2505) -> NapiFinalizerTask::schedule off-thread branch (napi_body.rs:5465). What goes wrong: the off-thread branch returns at napi_body.rs:5485 without consulting
vm.is_shutting_down()/vm.has_run_cleanup_hooks()(napi_body.rs:5492-5503), which on the JS-thread path either drops the task or turns it into a cleanup hook. The task sits in the Regular loop's concurrent queue. On exit,on_exitsetsis_shutting_down, runsrun_cleanup_hooks()(VirtualMachine.rs:2276)…Verification: nit (narrow race; the base segfaults on this exact route, and the same post-cleanup ordering already exists on the base through the JS-thread task queue). Trigger: a Worker's external buffer dies in a collection whose end phase runs on the collector thread while the worker's JS thread is parked, and worker.terminate() lands before the JS thread's next tick() drains the posted task. Mechanism…