Skip to content

napi: do not hand a threadsafe function's queue to call_js_cb with a null env at exit - #39810

Merged
Jarred-Sumner merged 1 commit into
mainfrom
farm/ecbd94ea/napi-tsfn-queued-items-at-exit
Aug 21, 2026
Merged

Jarred-Sumner merged 1 commit into
mainfrom
farm/ecbd94ea/napi-tsfn-queued-items-at-exit

Conversation

@robobun

@robobun robobun commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • process.exit() with items still queued on a napi_threadsafe_function calls the addon's call_js_cb once per item with env == NULL. Addons written for a live env crash there. Both signatures sit under ThreadSafeFunction::env_teardown: abort() in the addon (Sentry BUN-4MN5), and NAPI FATAL ERROR: Error::New napi_get_last_error_info from a node-addon-api TypedThreadSafeFunction callback (the env_teardown events 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() and process.exit() inside the callback take the same path.
  • Cause: phase 2 of env_teardown (src/runtime/napi/napi_body.rs) hands every drained item to call_js(NULL, NULL, ctx, item). Node runs nothing there on process.exit(). At env cleanup it delivers the items with the live env.
  • The opposite case was wrong too: after napi_tsfn_abort, dispatch_one still ran the queue as JS. Node hands it back with a null env.

Fix

  • Main thread: env_teardown drops the queue, as Node's process.exit() does. The finalizer still runs, as before.
  • Worker: env_teardown delivers each item as usual, live env and js_callback, so the addon frees its data. The VM is stopping, so napi_call_function reports napi_cannot_run_js, as in Node. A function already closing keeps the null env.
  • dispatch_one stops once the function is closing. The leftovers go to call_js_cb(NULL, NULL, ctx, data), as in Node.
  • Verified: test/napi/napi.test.ts, 5 new checkSameOutput cases, all red on the 1.4.0 release. Also the rest of the napi suites.

Background

  • call_js_cb gets 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_teardown runs from NapiEnv::cleanup(), a cleanup hook of VirtualMachine::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.
  • An exiting or terminated worker has its VmHandle in Stopping. NAPI_PREAMBLE then refuses calls that enter JS, like Node's can_call_into_js().
Notes

Repro: a C addon whose call_js_cb prints env, plus 6 scripts. node 26 vs bun 1.4.0 vs this branch:

scenario node 26 bun 1.4.0 this branch
main thread process.exit() with 3 queued nothing env=NULL x3 nothing (finalizer still runs)
main thread natural exit items delivered, JS refused items delivered by the loop before exit unchanged
worker process.exit() live env x3, call_function=10, finalize env=NULL x3 identical to node
worker.terminate() live env x3, call_function=10, finalize env=NULL x3 identical to node
napi_tsfn_abort with 3 queued NULL x3, finalize JS runs x3 identical to node
process.exit() inside the callback callback 1 only re-enters with env=NULL x2 callback 1 only (finalizer still runs)

The 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 reports napi_cannot_run_js (23) in both runtimes. The repro addon above uses the default version and gets napi_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 under Process_functionDlopen). Its event fc9c81ac (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 returned napi_invalid_arg, and node-addon-api's Error::New made that fatal. This change should end the env_teardown events 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_release tests 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 call into dispatch_one, so teardown can reuse the delivery code. The jsresult-swallow source lint is why delivery is split into deliver (returns the JsResult) and folded by each landing frame: report_error_or_terminate in the drain, dispatch::fold in the cleanup hook, like the finalizer next to it.

Also run: Node's test_threadsafe_function, test_worker_terminate, test_worker_terminate_finalization and test_cleanup_hook suites under test/napi/node-napi-tests, test/napi/napi-finalizer-delete-ref.test.ts, test/internal/source-lints/, and clippy on bun_runtime. napi > bigint conversion to int64/uint64 > returns the right error code timed 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_teardown and on_dispatch but 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

… 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.
@coderabbitai

coderabbitai Bot commented Aug 20, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

Your included review limit has been reached.

You’re in a promotional period — use the checkbox below to run this review for free:

  • Run 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 @coderabbitai review --use-credits.

You can also wait for the limit to reset (next review available in 21 minutes), then comment @coderabbitai review or push new commits to the PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 8b8d8b08-f58b-4c84-9dd5-00596103f04d

📥 Commits

Reviewing files that changed from the base of the PR and between f8d486a and ba3fe00.

📒 Files selected for processing (5)
  • src/runtime/napi/napi_body.rs
  • test/napi/napi-app/async_tests.cpp
  • test/napi/napi-app/module.js
  • test/napi/napi-app/tsfn-queued-items-worker.js
  • test/napi/napi.test.ts

Comment @coderabbitai help to get the list of available commands.

@robobun

robobun commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: the fix and its tests are on this branch. CI is green (Buildkite build 101842).

Reproduced with a small C addon whose call_js_cb prints the env it gets, under node 26, the bun 1.4.0 release, and this branch. On 1.4.0, process.exit() with 3 items queued prints env=NULL three times. An addon whose call_js_cb does not accept a null env then crashes in one of two ways: abort() (Sentry BUN-4MN5) or, for a node-addon-api TypedThreadSafeFunction, NAPI FATAL ERROR: Error::New napi_get_last_error_info (the env_teardown events in BUN-4KH6, for example event fc9c81ac). Worker exit, worker.terminate(), and process.exit() from inside the callback take the same path. With this branch each case prints what node prints. The table in the PR body has all six cases.

The 5 new cases in test/napi/napi.test.ts compare bun's stdout with node's. All 5 fail on the 1.4.0 release and pass here.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 in dispatch_one: queue drained under the lock, lock dropped for hand_back, lock reacquired for the thread_count == 0 finalizer check.
  • env_teardown phase 2: worker path delivers via deliver() with live env (folded through dispatch::fold); main thread drops the queue; the TsfnCallback::Js variant on a worker falls through without delivery (matches hand_back's no-op for that variant).
  • Microtask-drain move from call into dispatch_one preserves the "not before the first" ordering and still reaches self.call(task) when loop_mut() is None.
  • 5 new checkSameOutput tests 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.

@robobun

robobun commented Aug 20, 2026

Copy link
Copy Markdown
Collaborator Author
Updated 3:27 PM PT - Aug 20th, 2026

✅ @robobun, your commit ba3fe0034873f91e6355311d8db8d14a5f4cce93 passed in Build #101842! 🎉


🧪   To try this PR locally:

bunx bun-pr 39810

That installs a local version of the PR into your bun-39810 executable, so you can run:

bun-39810 --bun

@robobun

robobun commented Aug 20, 2026

Copy link
Copy Markdown
Collaborator Author

On the two points flagged above for a reviewer:

The closing branch of dispatch_one follows the shape of the existing call path: addon code runs with the lock dropped, and the state is read again under the lock afterwards. While the lock is dropped, nothing can add to the queue (enqueue reports napi_closing once the function is closing) and nothing can free the object (before env teardown, only the finalize task frees it, and this branch queues that task only after it has the lock again). A release that lands during the hand-back sees dispatch_state == Running, so it marks Pending instead of posting a task. on_dispatch then runs dispatch_one once more, which finds an empty queue and a finalizer that is already queued (maybe_queue_finalizer is a no-op in Closed). A release that lands after this branch returns schedules a dispatch, and that dispatch finalizes.

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 CleanupHandles does when it turns the loop a last time. The table in the PR body has the output of node 26, 1.4.0 and this branch for each case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants