Skip to content

Add Function::from_callback() and call functions without copying - #8726

Merged
bartlomieju merged 3 commits into
mainfrom
biwanczuk/rust-jsg-from-callback
Nov 21, 2026
Merged

bartlomieju merged 3 commits into
mainfrom
biwanczuk/rust-jsg-from-callback

Conversation

@bartlomieju

@bartlomieju bartlomieju commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

This makes two changes to Rust JSG that cut the per-call cost of
creating and calling JavaScript functions from Rust. They matter most
to code that calls into JavaScript in a hot loop and needs the cost of
each call to match C++, such as a benchmark harness. workerd bench's
timing loop is one: it subtracts its own measured per-call overhead
from every case, so a call path costlier than the C++ one would bias
every result rather than just slow the tool down.

v8::Function::from_callback() creates a function from a raw
RawFunctionCallback with no data, like C++ v8::Function::New() with
a plain callback. A function created by Function::new() reaches its
data through a Wrappable on every call, so each call costs more than
V8's call of the callback itself. The callback can be an extern "C"
function that V8 calls directly, or one that jsg::function_callback()
builds from a closure that captures nothing. The trade-off against
Function::new() is that the function carries no state, has no
signature, and can be called with new. A raw extern "C" callback
also gets no Lock and no panic catching, so a panic in it aborts the
process; function_callback() provides both, and the doc comment
spells all of this out. New jsg-tests cover both kinds of callback,
the function's shape (name, length, new, any this), and a panic
in a closure callback becoming an internal error; the existing
pending-exception test now also covers from_callback().

local_function_call(), the shim behind Local<Function>::call(),
used to copy the arguments into a v8::LocalVector, a heap-allocated
vector, on every call with arguments. The Rust Local is
repr(transparent) over ffi::Local, and ffi-inl.h asserts that
ffi::Local has the same size and alignment as v8::Local, so the
arguments now pass to v8::Function::Call() as they are. V8 takes them
as non-const but, as checked against its source, only reads them. Every
Local<Function>::call() with arguments benefits. A new test checks
that a call passes every argument, in order, and only those, for zero
arguments, four, and a subslice. The shim also now rejects more
arguments than V8's int count can hold rather than truncating it.

In a --config=benchmark build on Linux, the bench runner's measured
overhead for an empty synchronous call went from 140-255 ns down to
76-119 ns; the C++ runner measured 50-95 ns. That case passes no
arguments, so the gain comes from from_callback(); the argument
change applies to the overhead case that passes one argument and to
cases with setup or a receiver. The remaining gap is calls across the
Rust/C++ boundary that aren't inlined.

@codecov-commenter

codecov-commenter commented Nov 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 20.00000% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.68%. Comparing base (f136fb7) to head (6fcc718).

Files with missing lines Patch % Lines
src/rust/jsg/v8.rs 0.00% 11 Missing ⚠️
src/rust/jsg/ffi.c++ 75.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main    #8726   +/-   ##
=======================================
  Coverage   67.68%   67.68%           
=======================================
  Files         839      839           
  Lines      214024   214034   +10     
  Branches    32530    32531    +1     
=======================================
+ Hits       144864   144871    +7     
- Misses      49910    49911    +1     
- Partials    19250    19252    +2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@bartlomieju
bartlomieju marked this pull request as ready for review November 20, 2026 10:27
@bartlomieju
bartlomieju requested review from a team as code owners November 20, 2026 10:27

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Superseded by the review of 7f1ec287.

This review, of 561d39a2

💬 Approved with comments — No correctness issues in the FFI or the new API; the only note is an INFO that the Rust JSG README doesn't document Function::from_callback() yet.

Findings: 1 info (1 is an inline comment on the diff)

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


📝 Documentation: 💬 1 info

The Rust JSG README does not document the new Function::from_callback() API.

Recommendation: 💬 Optional Nits

  • [INFO] Rust JSG README doesn't document Function::from_callback() or its trade-offs. (src/rust/jsg/v8.rs:2461)
View full review
  • src/rust/jsg/README.md explains how to create functions from Rust closures with Function::new, but doesn't mention the new public Function::from_callback() or its trade-offs.

✅ All other checks passed

📋 Code Quality: ✅ LGTM

local_function_call() passes the argument slice to V8 without copying it. This relies on ffi::Local having the same layout as v8::Local, which ffi-inl.h asserts. An empty slice becomes nullptr with a count of 0. from_callback() uses the existing function_new shim with undefined as data and keeps its error handling (Error::pending). The new tests cover both an extern "C" callback and one built with function_callback().


Reviewed commit: 561d39a2

Comment thread src/rust/jsg/v8.rs Resolved
@bartlomieju
bartlomieju force-pushed the biwanczuk/rust-jsg-from-callback branch from 561d39a to 7f1ec28 Compare November 20, 2026 10:38

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Superseded by the review of 37f5688c.

This review, of 7f1ec287

💬 Approved with comments — No correctness issues in the no-copy call path or in from_callback(). There are two INFO notes: the guard throws from a shim that isn't declared Result, though no real call can reach it, and the README is missing the new API.

Findings: 2 info (1 is an inline comment on the diff)

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


📋 Code Quality: 💬 1 info

The FFI change and the new API are correct. One INFO: the new KJ_REQUIRE throws from a shim that isn't declared Result.

Recommendation: 💬 Optional Nits

  • [INFO] New KJ_REQUIRE in local_function_call throws from a shim that isn't declared Result, so an oversized slice panics instead of being rejected. (src/rust/jsg/ffi.c++:652)
View full review
  • src/rust/jsg/ffi.c++:652: KJ_REQUIRE(args.size() <= INT_MAX, ...) throws a KJ exception. local_function_call is declared in v8.rs:604-609 as returning a plain MaybeLocal, not Result<MaybeLocal>. The rule in ffi.h:243-244 says a shim that can throw must be declared Result. Otherwise an oversized slice turns into a panic rather than the rejection the description promises.
    • Only a slice of more than 2^31 Locals reaches it, so no real call can.

I found nothing wrong in these:

  • Passing the slice without a copy. The layout is asserted in ffi-inl.h, and an empty slice becomes nullptr with a count of 0.
  • The order of the exceptionPending guard.
  • How from_callback() handles an error (Error::pending).
  • The new tests.

📝 Documentation: 💬 1 info

The Rust JSG README still doesn't document Function::from_callback().

Recommendation: 💬 Optional Nits

  • [INFO] Rust JSG README (and src/rust/AGENTS.md) don't document Function::from_callback() or its trade-offs. (src/rust/jsg/v8.rs:2468)
View full review
  • src/rust/jsg/v8.rs:2468 adds the public Function::from_callback() with a thorough doc comment.
    • The README's "Functions from Rust closures" section (src/rust/jsg/README.md:968-998) covers only Function::new().
    • src/rust/AGENTS.md:17 also lists only Function::new.
    • A short note in both on when to use from_callback() would help: it carries no state, has no signature, and gets no Lock or panic catching with a raw extern "C" callback.

✅ All other checks passed

🔒 Security: ✅ LGTM

No security issues found.


⚡ Performance: ✅ LGTM

The change cuts per-call cost as intended. local_function_call no longer allocates a LocalVector for each call, and from_callback() skips the Wrappable lookup on each call. I found no regressions.


Reviewed commit: 7f1ec287

Comment thread src/rust/jsg/ffi.c++ Resolved
Two changes to Rust JSG that the timing loop of workerd bench needs to
cost as little per call as its C++ version.

v8::Function::from_callback() creates a function from a raw
RawFunctionCallback with no data, like C++ v8::Function::New() with a
plain callback. A function from Function::new() reaches its data
through a Wrappable on every call, so a call costs more than the
callback itself does. The bench runner measures its own per-call
overhead by timing an empty function, and that function must cost no
more than C++'s did, or the runner subtracts too much from every
case. The callback can be an extern "C" function that V8 calls
directly, or one that jsg::function_callback() makes from a closure
that captures nothing. The function has no data and no signature, and
can be called with new; a raw extern "C" callback also gets no lock and
no panic handling, which the doc comment spells out.

local_function_call() copied the arguments into a v8::LocalVector, a
heap-allocated vector, on every call with arguments. The Rust Local is
repr(transparent) over ffi::Local, which ffi-inl.h asserts has the
layout of a v8::Local, so the arguments now pass to
v8::Function::Call() as they are. Every Local<Function>::call() with
arguments benefits. A new test checks that a call passes every
argument, in order, and only those.
@bartlomieju
bartlomieju force-pushed the biwanczuk/rust-jsg-from-callback branch from 7f1ec28 to 37f5688 Compare November 20, 2026 10:41

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Superseded by the review of 1fe4a49c.

This review, of 37f5688c

💬 Approved with comments — I found no correctness, security or performance problems in the no-copy call path or in Function::from_callback(), and the new README section covers the API and its trade-offs. One INFO note remains: the KJ_REQUIRE in a shim that isn't declared Result, which no real call can reach.

Findings: 1 info

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


📋 Code Quality: 💬 1 info

No correctness problems. One INFO note is still open: the KJ_REQUIRE guard sits in a shim that isn't declared Result.

Recommendation: 💬 Optional Nits

  • [INFO] KJ_REQUIRE in local_function_call throws from a shim that isn't declared Result, so an oversized slice panics instead of being rejected. (src/rust/jsg/ffi.c++:652)
View full review

🔄 Since last review: 1 finding resolved, 1 preserved, 0 new

  • src/rust/jsg/ffi.c++:652: KJ_REQUIRE(args.size() <= INT_MAX, ...) throws a KJ exception, but local_function_call is declared in src/rust/jsg/v8.rs:604 as returning a plain MaybeLocal, not Result<MaybeLocal>.
    • An oversized slice therefore panics instead of being rejected.
    • Only a slice of more than 2^31 Locals can reach this guard, so no real call does.

I checked these and found nothing wrong:

  • Passing the slice without a copy, including an empty slice, which becomes nullptr with a count of 0.
  • from_callback() and its error path.
  • The new tests.
  • The new README section.

✅ All other checks passed

🔒 Security: ✅ LGTM

The no-copy argument pass depends on the layout assertion in ffi-inl.h, and the static_cast<int> is safe once the length check has passed. The doc comment on Function::from_callback() states the caller's responsibilities for a raw extern "C" callback.


📖 AGENTS.md: ✅ LGTM

No issues found.


⚡ Performance: ✅ LGTM

The change removes the per-call LocalVector allocation, and with from_callback() a call no longer goes through a Wrappable to reach its data. I found no regressions.


📝 Documentation: ✅ LGTM

The new README section documents Function::from_callback() and its trade-offs.


Reviewed commit: 37f5688c

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Superseded by the review of 6fcc7181.

This review, of 1fe4a49c

💬 Approved with comments — I found no correctness, security or performance problems in the no-copy call path or in Function::from_callback(), and the new README section covers the API and its trade-offs. One INFO note remains: the KJ_REQUIRE in a shim that isn't declared Result, which no real call can reach.

Findings: 1 info

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


📋 Code Quality: 💬 1 info

No correctness problems. One INFO note is still open: the KJ_REQUIRE guard sits in a shim that isn't declared Result.

Recommendation: 💬 Optional Nits

  • [INFO] KJ_REQUIRE in local_function_call throws from a shim that isn't declared Result, so an oversized slice panics instead of being rejected. (src/rust/jsg/ffi.c++:652)
View full review

🔄 Since last review: 1 finding resolved, 1 preserved, 0 new

  • src/rust/jsg/ffi.c++:652: KJ_REQUIRE(args.size() <= INT_MAX, ...) throws a KJ exception, but local_function_call is declared in src/rust/jsg/v8.rs:604 as returning a plain MaybeLocal, not Result<MaybeLocal>.
    • An oversized slice therefore panics instead of being rejected.
    • Only a slice of more than 2^31 Locals can reach this guard, so no real call does.

I checked these and found nothing wrong:

  • Passing the slice without a copy, including an empty slice, which becomes nullptr with a count of 0.
  • from_callback() and its error path.
  • The new tests.
  • The new README section.

✅ All other checks passed

🔒 Security: ✅ LGTM

The no-copy argument pass depends on the layout assertion in ffi-inl.h, and the static_cast<int> is safe once the length check has passed. The doc comment on Function::from_callback() states the caller's responsibilities for a raw extern "C" callback.


📖 AGENTS.md: ✅ LGTM

No issues found.


⚡ Performance: ✅ LGTM

The change removes the per-call LocalVector allocation, and with from_callback() a call no longer goes through a Wrappable to reach its data. I found no regressions.


📝 Documentation: ✅ LGTM

The new README section documents Function::from_callback() and its trade-offs.


Reviewed commit: 1fe4a49c — same changes as 37f5688c, so this is that commit's review (no new review was run; line numbers are as of 37f5688c)

@clanky-the-clanker clanky-the-clanker Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ Approved — Nothing in the changed code differs from the last reviewed commit. The one earlier note (the KJ_REQUIRE that no real call can reach) was answered by the author, and the code supports the answer. No new issues.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

No issues found. The doc comment on Function::from_callback() states what the caller must take care of when using a raw extern "C" callback.


📖 AGENTS.md: ✅ LGTM

No issues found.


📋 Code Quality: ✅ LGTM

The no-copy argument pass in src/rust/jsg/ffi.c++ is correct:

  • The layout assertion in ffi-inl.h guarantees that Local and v8::Local match.
  • An empty slice maps to nullptr with a count of 0.
  • The INT_MAX check guards the cast to int.

Function::from_callback() reuses ffi::function_new with undefined as the data. It maps a null result to Error::pending(), the same way Function::new does.

The tests cover:

  • both kinds of callback;
  • the function's shape;
  • a panic becoming an internal error;
  • the pending-exception path;
  • argument order.

The earlier KJ_REQUIRE note is closed: the author explained that an oversized slice would be a coding error, and only a slice of more than 2^31 elements can reach the check.


⚡ Performance: ✅ LGTM

Calls with arguments no longer allocate a LocalVector each time. A function created by from_callback() no longer goes through a Wrappable to reach its data on each call. No regressions.


📝 Documentation: ✅ LGTM

The README section documents Function::from_callback() and its trade-offs.


Reviewed commit: 6fcc7181

@bartlomieju
bartlomieju merged commit f82dd1e into main Nov 21, 2026
36 of 37 checks passed
@bartlomieju
bartlomieju deleted the biwanczuk/rust-jsg-from-callback branch November 21, 2026 08:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants