Repository navigation
napi: do not hand a threadsafe function's queue to call_js_cb with a null env at exit - #39810
Conversation
… null env at exit Since the env teardown added for threadsafe functions, every item still queued when the env went away was passed to the addon's call_js_cb with env and js_callback both null. That happened on the main thread's process.exit() and natural exit too, and from inside the callback when it was the one calling process.exit(). Most call_js_cb implementations are written for a live env and abort on a null one. env_teardown on the main thread now drops the queue, as Node's process.exit() does. In a worker, whose env really goes away while the addon's threads live on, each item is delivered the normal way, with the live env and js_callback, so the addon can free it; calling into JS is refused because the worker is stopping. This is what Node's CleanupHandles does. A function that was already closing keeps the abort contract. dispatch_one no longer runs queued items once the function is closing (napi_tsfn_abort). They go back to call_js_cb with a null env, as Node's DispatchOne and EmptyQueue do, and the function finalizes once the last thread reference is gone.
|
Warning Review limit reachedYour included review limit has been reached. You’re in a promotional period — use the checkbox below to run this review for free:
On-demand reviews are free for the next 31 days. After that, they cost $0.25 per reviewed file. How can I continue?Run this review now using the option above, or comment You can also wait for the limit to reset (next review available in 21 minutes), then comment An organization admin can change what happens after included review limits in Billing. How do review limits work?CodeRabbit enforces per-developer PR review limits within each organization. For paid Pro and Pro+ reviews, CodeRabbit uses a developer's included PR review attempts over the past 7 days to set the current hourly allowance. At typical activity levels, the full plan allowance applies. Higher sustained activity can lower the allowance until earlier attempts leave the 7-day window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (5)
Comment |
|
Status: the fix and its tests are on this branch. CI is green (Buildkite build 101842). Reproduced with a small C addon whose The 5 new cases in |
There was a problem hiding this comment.
I reviewed this PR and didn't find any bugs. Because it reworks lock-drop/reacquire and addon re-entry paths in ThreadSafeFunction::dispatch_one and branches env_teardown behavior on main-thread vs worker, a human look at the threading/lifetime discipline and the Node-compat design choice would still be worthwhile.
What was reviewed:
- The new
is_closing()fast-path indispatch_one: queue drained under the lock, lock dropped forhand_back, lock reacquired for thethread_count == 0finalizer check. env_teardownphase 2: worker path delivers viadeliver()with live env (folded throughdispatch::fold); main thread drops the queue; theTsfnCallback::Jsvariant on a worker falls through without delivery (matcheshand_back's no-op for that variant).- Microtask-drain move from
callintodispatch_onepreserves the "not before the first" ordering and still reachesself.call(task)whenloop_mut()isNone. - 5 new
checkSameOutputtests pin exact stdout against Node for process exit, exit-inside-callback, worker exit/terminate, and abort-with-queue.
Extended reasoning...
Overview
This PR changes what happens to items still queued on a napi_threadsafe_function when it stops being dispatched, fixing a Sentry-reported abort (BUN-4MN5) introduced in 1.4.0. It touches src/runtime/napi/napi_body.rs (dispatch_one, call, new deliver/take_queue/hand_back helpers, and env_teardown phase 2), plus a new C++ test fixture in async_tests.cpp, JS drivers in module.js and a new worker fixture, and 5 new checkSameOutput cases in napi.test.ts.
Security risks
None identified. This is Node-API compat/teardown behavior; no untrusted input parsing, auth, or network surface is touched.
Level of scrutiny
High. This is exactly the "Native code: memory safety" category REVIEW.md flags as the most-blocked: it changes lock discipline in dispatch_one (drain queue under lock → drop lock → call addon's call_js_cb with null env → reacquire lock → check thread_count → maybe queue finalizer), and it makes a deliberate Node-compat design decision to branch env_teardown on worker_ref().is_some() — main thread silently drops the queue, workers deliver each item with the live env. Both the re-entrancy window during hand_back and the main-vs-worker split are the kind of choices a maintainer should confirm.
Other factors
The change is thorough and well-justified: the PR description tabulates node 26 vs bun 1.4.0 vs this branch across 6 scenarios, the 5 new tests pin exact stdout against Node via checkSameOutput, and the refactor (splitting call → deliver so teardown can reuse delivery, moving the microtask drain up into dispatch_one) is explained. The existing abort_then_last_release and orphaned-tsfn tests cover adjacent lifecycle. No prior human reviews on the PR. Given the thread-safety sensitivity and the semantic decision embedded in the worker/main-thread branch, I'm deferring rather than approving.
|
Updated 3:27 PM PT - Aug 20th, 2026
✅ @robobun, your commit ba3fe0034873f91e6355311d8db8d14a5f4cce93 passed in 🧪 To try this PR locally: bunx bun-pr 39810That installs a local version of the PR into your bun-39810 --bun |
|
On the two points flagged above for a reviewer: The closing branch of The main thread and worker split: on the main thread, env teardown is process exit. Node runs nothing of a threadsafe function there. To hand the items back at that point, Bun would have to pass a null env (the crash this fixes) or run addon callbacks during exit. In a worker, the addon's threads outlive the env and still own the data behind each item, so they get the items back, as Node's |
Problem
process.exit()with items still queued on anapi_threadsafe_functioncalls the addon'scall_js_cbonce per item withenv == NULL. Addons written for a live env crash there. Both signatures sit underThreadSafeFunction::env_teardown:abort()in the addon (Sentry BUN-4MN5), andNAPI FATAL ERROR: Error::New napi_get_last_error_infofrom a node-addon-apiTypedThreadSafeFunctioncallback (theenv_teardownevents in BUN-4KH6). New in 1.4.0 with napi: keep threadsafe functions alive after their env is torn down #34067. Worker exit,worker.terminate()andprocess.exit()inside the callback take the same path.env_teardown(src/runtime/napi/napi_body.rs) hands every drained item tocall_js(NULL, NULL, ctx, item). Node runs nothing there onprocess.exit(). At env cleanup it delivers the items with the live env.napi_tsfn_abort,dispatch_onestill ran the queue as JS. Node hands it back with a null env.Fix
env_teardowndrops the queue, as Node'sprocess.exit()does. The finalizer still runs, as before.env_teardowndelivers each item as usual, live env andjs_callback, so the addon frees its data. The VM is stopping, sonapi_call_functionreportsnapi_cannot_run_js, as in Node. A function already closing keeps the null env.dispatch_onestops once the function is closing. The leftovers go tocall_js_cb(NULL, NULL, ctx, data), as in Node.test/napi/napi.test.ts, 5 newcheckSameOutputcases, all red on the 1.4.0 release. Also the rest of the napi suites.Background
call_js_cbgets each queued item with the env and the JS function. The docs allow both to be null for items left at teardown. Few addons handle it.env_teardownruns fromNapiEnv::cleanup(), a cleanup hook ofVirtualMachine::on_exit, on every kind of exit. napi: keep threadsafe functions alive after their env is torn down #34067 added it for dead worker loops.VmHandleinStopping.NAPI_PREAMBLEthen refuses calls that enter JS, like Node'scan_call_into_js().Notes
Repro: a C addon whose
call_js_cbprintsenv, plus 6 scripts. node 26 vs bun 1.4.0 vs this branch:process.exit()with 3 queuedenv=NULLx3process.exit()call_function=10, finalizeenv=NULLx3worker.terminate()call_function=10, finalizeenv=NULLx3napi_tsfn_abortwith 3 queuedNULLx3, finalizeprocess.exit()inside the callbackenv=NULLx2The 5 new tests: process exit, exit inside the callback, worker exit, worker terminate, abort with a queue. Each compares bun's stdout with node 26's. The napitests addon is built with
NAPI_EXPERIMENTAL, so the refused call reportsnapi_cannot_run_js(23) in both runtimes. The repro addon above uses the default version and getsnapi_pending_exception(10) in both.Sentry: BUN-4MN5 is this crash as an
abort()in the addon. BUN-4KH6 groups on the panic message, and most of its events are a different bug (an addon failing in its init underProcess_functionDlopen). Its eventfc9c81ac(1.4.0, macOS, 08-21) is this one:Process_functionReallyExit,Bun__Process__exit,VirtualMachine::on_exit,NapiEnv::cleanup,abortThreadSafeFunctions,env_teardown(napi_body.rs:2987 in 1.4.0), five addon frames,napi_fatal_error. The callback got a null env, a Node-API call returnednapi_invalid_arg, and node-addon-api'sError::Newmade that fatal. This change should end theenv_teardownevents in both issues. BUN-4KH6 stays open for the dlopen cause.After abort, the function still finalizes only when the last thread reference is gone (unchanged). The existing
abort_then_last_releasetests cover that order.The finalizer still running at main-thread exit is the pre-existing 1.4.0 behavior: Bun runs napi env cleanup on
process.exit(), Node does not. An existing test depends on it and it is not the crashing call, so it is kept.Natural exit of a worker with items queued (possible only for an unref'd function) takes the same worker path. Script is still allowed at that point in Bun, so a callback that calls into JS runs it there, where Node refuses it. Whether script is allowed during env cleanup is a VM-level question outside this change.
The microtask drain between calls moves from
callintodispatch_one, so teardown can reuse the delivery code. Thejsresult-swallowsource lint is why delivery is split intodeliver(returns theJsResult) and folded by each landing frame:report_error_or_terminatein the drain,dispatch::foldin the cleanup hook, like the finalizer next to it.Also run: Node's
test_threadsafe_function,test_worker_terminate,test_worker_terminate_finalizationandtest_cleanup_hooksuites undertest/napi/node-napi-tests,test/napi/napi-finalizer-delete-ref.test.ts,test/internal/source-lints/, and clippy onbun_runtime.napi > bigint conversion to int64/uint64 > returns the right error codetimed out once locally at 5 s under the debug build (three sequential node+bun spawns). It does not touch threadsafe functions and passed in another run.#39656 (async cleanup hooks) touches neighbouring lines of
env_teardownandon_dispatchbut not this behavior.no test proof · iteration 0 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/napi/napi.test.ts