Repository navigation
napi: pass NULL js_callback to call_js when no func supplied - #36845
Conversation
…N dispatch at 1000 per tick When napi_create_threadsafe_function is called with func == NULL, Node's DispatchOne passes js_callback = nullptr to call_js_cb. Bun was passing an encoded undefined (a non-zero napi_value), so addons that gate on js_callback != NULL (napi-rs, lightningcss) tried to call it as a function and panicked with 'expect Function, got: Undefined'. Also add Node's kMaxIterationCount cap to on_dispatch so a producer that enqueues faster than we drain cannot starve the event loop. The yield path re-schedules via schedule_dispatch and bails early when dispatch_one() has already queued the finalizer (closing == Closed) so it cannot double-dispatch a freed pointer. Fixes #13771
WalkthroughChangesThread-safe function callback handling
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Found 2 issues this PR may fix:
🤖 Generated with Claude Code |
There was a problem hiding this comment.
Beyond the inline nits, I also traced the yield path's dispatch_state transitions for a double-enqueue race with an addon-thread schedule_dispatch() between the Idle store and the swap — the swap-to-Pending in schedule_dispatch makes whichever side sees Idle the sole enqueuer, so no double-schedule. Also confirmed napi_value(0) is a proper null pointer at the C ABI (#[repr(transparent)] struct napi_value(i64) vs typedef struct napi_value__* napi_value), and that leaving dispatch_state == Pending on the closing == Closed early-return is harmless since thread_count == 0 at that point.
Extended reasoning...
Checked the new yield path in on_dispatch for races against addon-thread enqueue()/release() calling schedule_dispatch() concurrently: the store-Idle-then-swap-Pending sequence composes safely with the addon-side swap because only the side that observes Idle enqueues. Verified the closing == Closed early-return can leave dispatch_state as Pending without a lost wakeup — Closed implies thread_count == 0 so no further schedule_dispatch() callers exist and the already-queued finalizer task destroys the TSFN. Confirmed napi_value(0) matches the C-side napi_value null (repr(transparent) i64 over an opaque pointer typedef).
No issue has been filed about the unbounded dispatch loop, and the cap as implemented did not actually yield to setImmediate/timers/I-O (enqueue_task_concurrent is drained inside the same tick()). Restore the original unbounded loop and its explanatory comment.
There was a problem hiding this comment.
LGTM — the cap that my earlier comments were about has been dropped, so this is now just the NULL js_callback fix.
What was reviewed:
napi_value(0)is the correct null representation (#[repr(transparent)] struct napi_value(i64));cb_js.get()returnsNoneexactly whenfuncwas NULL at creation (StrongOptional::empty()), matching Node'sref.IsEmpty()check.- Test uses
checkSameOutputagainst Node with a bounded poll and an atomic sentinel; fails underUSE_SYSTEM_BUN=1per the description. - The
EmptyQueue-at-teardown path (napi_body.rs:2871) already passesnapi_value(0)forjs_callback, so this change makes the dispatch path consistent with it.
Extended reasoning...
Overview
After the follow-up commit dropped the kMaxIterationCount cap, this PR is a ~7-line Rust change in ThreadSafeFunction::dispatch_one's TsfnCallback::C arm plus a checkSameOutput test. When the TSFN was created with func == NULL (cb_js is StrongOptional::empty()), it now passes napi_value(0) to call_js_cb instead of the encoded undefined. This matches Node's DispatchOne (js_callback stays nullptr when ref.IsEmpty()), and it matches Bun's own teardown path at napi_body.rs:2871 which already passes napi_value(0).
Security risks
None. This changes which sentinel is passed for an already-absent callback; no new user-controlled input reaches native code, no allocation/lifetime changes.
Level of scrutiny
Low-to-medium. It's native N-API compat code, but the change is a one-branch value substitution with a direct upstream reference and a test that pins the observable behavior against Node. StrongOptional::get() returning None maps exactly to "no func supplied" (a Strong is a GC root, so a non-empty one can't spuriously return None), and napi_value is #[repr(transparent)] over i64 so napi_value(0) is bitwise-null on the C side.
Other factors
My two prior inline comments concerned the MAX_ITERATION_COUNT cap and its test; both were resolved by the author dropping that code entirely, and the PR description was updated to explain why. The remaining test follows the file's conventions (NODE_API_CALL, REGISTER_FUNCTION, atomic sentinel, bounded setImmediate poll) and is placed alongside the other napi_threadsafe_function tests.
…#36845) Split from oven-sh#36801 (1/5). ## What When the threadsafe function was created with `func == NULL`, pass `js_callback = NULL` to `call_js_cb` instead of an encoded `undefined`. ## Why (fixes oven-sh#13771, closes oven-sh#30543) Node's `DispatchOne` ([src/node_api.cc#L452-L462](https://github.com/nodejs/node/blob/v26.x/src/node_api.cc#L452-L462)): ```cpp napi_value js_callback = nullptr; if (!ref.IsEmpty()) { v8::Local<v8::Function> js_cb = v8::Local<v8::Function>::New(env->isolate, ref); js_callback = v8impl::JsValueFromV8LocalValue(js_cb); } env->CallbackIntoModule<false>( [&](napi_env env) { call_js_cb(env, js_callback, context, data); }); ``` When `ref` is empty (the caller passed `func = NULL` to `napi_create_threadsafe_function`), `js_callback` stays `nullptr`. Bun was passing `napi_value::create(env, cb_js.get().unwrap_or(JSValue::UNDEFINED))`, which is the encoded `undefined` value (a non-zero pointer). Addons such as napi-rs and lightningcss test `if (js_callback != NULL)` and, seeing a non-null value, try to `napi_call_function` it: ``` thread '<unnamed>' panicked at napi/src/threadsafe_function.rs:235:57: called `Result::unwrap()` on an `Err` value: Error { status: InvalidArg, reason: "expect Function, got: Undefined" } ``` ## Verification New `checkSameOutput` test fails under the released Bun: ``` $ USE_SYSTEM_BUN=1 bun test test/napi/napi.test.ts -t "passes NULL js_callback" - "js_callback == NULL: 1 + "js_callback == NULL: 0 ``` The `kMaxIterationCount` cap that was in the first revision of this PR has been dropped: no issue has been filed about the unbounded dispatch loop, and the cap as written did not yield to setImmediate/timers anyway (`enqueue_task_concurrent` is drained inside the same `tick()`). <!-- robobun:evidence:begin --> --- **no test proof** · iteration 3 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/napi/napi.test.ts <!-- robobun:evidence:end -->
Split from #36801 (1/5).
What
When the threadsafe function was created with
func == NULL, passjs_callback = NULLtocall_js_cbinstead of an encodedundefined.Why (fixes #13771, closes #30543)
Node's
DispatchOne(src/node_api.cc#L452-L462):When
refis empty (the caller passedfunc = NULLtonapi_create_threadsafe_function),js_callbackstaysnullptr. Bun was passingnapi_value::create(env, cb_js.get().unwrap_or(JSValue::UNDEFINED)), which is the encodedundefinedvalue (a non-zero pointer). Addons such as napi-rs and lightningcss testif (js_callback != NULL)and, seeing a non-null value, try tonapi_call_functionit:Verification
New
checkSameOutputtest fails under the released Bun:The
kMaxIterationCountcap that was in the first revision of this PR has been dropped: no issue has been filed about the unbounded dispatch loop, and the cap as written did not yield to setImmediate/timers anyway (enqueue_task_concurrentis drained inside the sametick()).no test proof · iteration 3 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/napi/napi.test.ts