Skip to content

napi: pass NULL js_callback to call_js when no func supplied - #36845

Merged
dylan-conway merged 2 commits into
mainfrom
farm/d4378f5e/napi-tsfn-null-callback-and-cap
Aug 3, 2026
Merged

dylan-conway merged 2 commits into
mainfrom
farm/d4378f5e/napi-tsfn-null-callback-and-cap

Conversation

@robobun

@robobun robobun commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator

Split from #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 #13771, closes #30543)

Node's DispatchOne (src/node_api.cc#L452-L462):

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()).


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

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

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Changes

Thread-safe function callback handling

Layer / File(s) Summary
Null callback dispatch
src/runtime/napi/napi_body.rs
The callback path opens a handle scope. It passes a null napi_value when no JavaScript callback exists.
Null callback regression coverage
test/napi/napi-app/standalone_tests.cpp, test/napi/napi-app/module.js, test/napi/napi.test.ts
Native and JavaScript tests create a thread-safe function without a callback and verify that call_js receives NULL.

Possibly related PRs

  • oven-sh/bun#36801: Both changes update N-API thread-safe-function dispatch and add null-callback tests.
  • oven-sh/bun#36831: Both changes update thread-safe-function callback dispatch and handle-scope behavior.

Suggested reviewers: jarred-sumner

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The implementation addresses the NULL js_callback requirements from [#13771] and [#30543] and adds regression coverage.
Out of Scope Changes check ✅ Passed The implementation and tests are directly related to the linked issue requirements, with no unrelated changes identified.
Title check ✅ Passed The title clearly and concisely describes the primary change: passing a NULL js_callback when no JavaScript callback is supplied.
Description check ✅ Passed The description explains the change, motivation, linked issues, and verification, with only minor differences from the template headings.

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

@github-actions github-actions Bot added the claude label Aug 3, 2026
@github-actions

github-actions Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Found 2 issues this PR may fix:

  1. Prisma crashing when logging is enabled #15291 - Prisma crashes with Call JavaScript callback failed in threadsafe function / code: "FunctionExpected", which is exactly what napi-rs raises when napi_call_function gets Bun's encoded undefined instead of a NULL js_callback.
  2. napi panic crash #17285 - Fatal at napi-rs threadsafe_function.rs:749 with InvalidArg, get_named_property error: the TSFN call fails with function_expected, leaving return_value NULL, and napi_get_named_property on NULL returns napi_invalid_arg — a mechanical match for the NULL js_callback fix.

If this is helpful, copy the block below into the PR description to auto-close these issues on merge.

Fixes #15291
Fixes #17285

🤖 Generated with Claude Code

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

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).

Comment thread src/runtime/napi/napi_body.rs Resolved
Comment thread test/napi/napi.test.ts Resolved
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.
@robobun robobun changed the title napi: pass NULL js_callback to call_js when no func supplied; cap TSFN dispatch at 1000 per tick napi: pass NULL js_callback to call_js when no func supplied Aug 3, 2026

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

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() returns None exactly when func was NULL at creation (StrongOptional::empty()), matching Node's ref.IsEmpty() check.
  • Test uses checkSameOutput against Node with a bounded poll and an atomic sentinel; fails under USE_SYSTEM_BUN=1 per the description.
  • The EmptyQueue-at-teardown path (napi_body.rs:2871) already passes napi_value(0) for js_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.

@dylan-conway
dylan-conway merged commit e336819 into main Aug 3, 2026
50 of 53 checks passed
@dylan-conway
dylan-conway deleted the farm/d4378f5e/napi-tsfn-null-callback-and-cap branch August 3, 2026 20:15
springmin pushed a commit to springmin/bun that referenced this pull request Aug 3, 2026
…#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 -->
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.

Panic with vite+lightningcss when using visitors

2 participants