Skip to content

Move workerd bench's BenchController to Rust - #8729

Merged
bartlomieju merged 1 commit into
mainfrom
biwanczuk/bench-rust-controller
Nov 23, 2026
Merged

bartlomieju merged 1 commit into
mainfrom
biwanczuk/bench-rust-controller

Conversation

@bartlomieju

@bartlomieju bartlomieju commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

This PR moves the rest of workerd bench to Rust. BenchController and
the runner that times its cases move from api/bench.{h,c++} into a new
crate, bench-api, and Rust takes over dispatching the event, so
everything in workerd bench except the C++ entry glue now runs in
Rust. The controller keeps C++'s class name, error messages and option
parsing.

The runner's reactions are registered with IoContext::then_or_catch(),
doing the same V8 work per call as C++. Its own overhead is higher than
C++'s because of calls across the Rust/C++ boundary that ThinLTO doesn't
inline: in a --config=benchmark build on Linux, an async call costs it
about 2.9 µs against 1.7 µs, and a sync call 87 ns against 56 ns. The
overhead is subtracted from every sample, so this only limits how finely
the fastest cases resolve.

One behavior differs, on a path a benchmark is unlikely to take. Without
the handle_cross_request_promise_resolution compatibility flag (on by
default since 2024-10-14), settling a case's promise from another
request makes the runner's reaction fail. C++ rejected the group with
the I/O error; here the group is reported as hung and the error is
logged as an unhandled rejection.

The bench tests in server-test and every @smoke bench target pass
unchanged.

@bartlomieju
bartlomieju force-pushed the biwanczuk/bench-rust-controller branch from 9b1c238 to 46dc515 Compare November 20, 2026 09:58
Base automatically changed from biwanczuk/bench-rust to main November 20, 2026 11:27
@bartlomieju
bartlomieju force-pushed the biwanczuk/bench-rust-controller branch from 46dc515 to bed349d Compare November 20, 2026 11:50

@guybedford guybedford left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The port is faithful: I checked argument coercion, null/undefined options, handler return values, the yield between batches and the clocks against the C++, and they match.

Three comments on the runner, none blocking.

Comment thread src/workerd/api/bench-api/runner.rs Resolved
Comment thread src/workerd/api/bench-api/runner.rs Resolved
Comment thread src/workerd/api/bench-api/runner.rs Resolved
@bartlomieju
bartlomieju force-pushed the biwanczuk/bench-rust-controller branch from bed349d to 7ce9b11 Compare November 23, 2026 09:42
@codecov-commenter

codecov-commenter commented Nov 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 74.11616% with 205 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.85%. Comparing base (1adff5d) to head (70065c4).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
src/workerd/api/bench-api/runner.rs 77.60% 131 Missing ⚠️
src/workerd/api/bench-api/options.rs 0.00% 41 Missing ⚠️
src/workerd/api/bench-api/lib.rs 64.81% 19 Missing ⚠️
src/workerd/api/bench-api/ffi.rs 78.12% 7 Missing ⚠️
src/workerd/io/worker-entrypoint.c++ 60.00% 2 Missing and 2 partials ⚠️
src/workerd/api/global-scope.c++ 88.88% 0 Missing and 2 partials ⚠️
src/workerd/io/worker.c++ 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #8729      +/-   ##
==========================================
- Coverage   68.01%   67.85%   -0.16%     
==========================================
  Files         846      848       +2     
  Lines      219198   215282    -3916     
  Branches    32587    32498      -89     
==========================================
- Hits       149081   146085    -2996     
+ Misses      50876    49998     -878     
+ Partials    19241    19199      -42     

☔ 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 force-pushed the biwanczuk/bench-rust-controller branch from 7ce9b11 to fc705dc Compare November 23, 2026 10:25
@bartlomieju
bartlomieju marked this pull request as ready for review November 23, 2026 10:25
@bartlomieju
bartlomieju requested review from a team as code owners November 23, 2026 10:25

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

This review, of fc705dc2

💬 Approved with comments — The port looks faithful, and the earlier fix that keeps finish_stage errors out of fail_case is in this head. What remains is non-blocking: a deleted traversal-limit regression test with nothing replacing it, no unit tests for the runner state machine, and comments that point at the removed C++.

Findings: 2 info · 1 suggestion (3 are inline comments 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: 💬 2 info · 1 suggestion

The port looks faithful, and the earlier runner fixes are present. Two test gaps and a few comments that refer to the deleted C++ remain.

Recommendation: 💬 Optional Nits

  • [INFO] The regression test for bench groups larger than capnp's default traversal limit was deleted with bench-test.c++, and nothing replaces it for the decode in WorkerEntrypoint::bench(). (src/workerd/io/worker-entrypoint.c++:1176)
  • [INFO] runner.rs (warmup/calibrate/sample phases, setup/teardown, case_step/fail_case/finish_case error routing) has no unit tests; only end-to-end bench targets cover it. (src/workerd/api/bench-api/runner.rs:230)
  • [SUGGESTION] Comments say behaviour matches "C++", but this pull request deletes bench.c++ (also options.rs:109-110, runner.rs:711-712); state the behaviour directly. (src/workerd/api/bench-api/options-test.rs:69)
View full review

I checked that the approver's points from the earlier discussion are handled at this head. case_step (runner.rs:230-243) now calls finish_case outside its try_catch, so an error from finish_stage reaches drive and rejects the group, and fail_case only runs for a case that is still in progress.

Remaining notes, none blocking:

  • Traversal-limit regression test removed. bench-test.c++ covered a group larger than capnp's default traversal limit. That decoding now happens in WorkerEntrypoint::bench() (worker-entrypoint.c++:1175-1176, traversalLimitInWords = kj::maxValue), and no test covers it anymore.
  • No runner unit tests. runner.rs is about 890 lines of phase, setup/teardown and error-routing state machine. Only the end-to-end server-test and @smoke targets cover it.
  • Comments that refer to the removed C++. options.rs:109-110, runner.rs:711-712 and options-test.rs:69 say "as in C++", but this pull request deletes bench.c++. Per the repository's comment guidelines, they should state the behaviour directly.

✅ All other checks passed

🔒 Security: ✅ LGTM

No security issues found in the bench dispatch path or the FFI bridge.


📖 AGENTS.md: ✅ LGTM

The AGENTS.md "Where to Look" row for JS benchmarks now points at bench-api/ and bench-core/, matching the new layout.


⚡ Performance: ✅ LGTM

This is benchmark tooling only and does not touch a production hot path. The description documents the runner's higher per-call overhead compared with C++, and that overhead is subtracted from every sample.


📝 Documentation: ✅ LGTM

No issues found.


Reviewed commit: fc705dc2

Comment thread src/workerd/io/worker-entrypoint.c++ Resolved
Comment thread src/workerd/api/bench-api/runner.rs Resolved
BenchController, the first argument of a Worker's bench(b, env, ctx)
handler, and the runner that times its cases move from api/bench.c++
to a new crate, bench-api (src/workerd/api/bench-api/). Rust also takes
over the dispatch: ServiceWorkerGlobalScope::bench() keeps the check
that the Worker uses module syntax, wraps ctx and encodes the
BenchParams, then hands the exported handler to bench_run() (through
Worker::Api::runBench(), as workerd-api links the crate), which checks
that bench is a function, makes the controller, calls the handler,
runs the cases, measures the runner's overhead and resolves with the
encoded group. WorkerEntrypoint reads the group back into the report.
This completes the move of `workerd bench` to Rust, apart from the
command line, which was already there.

The controller is a #[jsg_resource] with run(), blackBox() and the
options property, and keeps the class name, error messages and
TypeError/RangeError types of C++. BenchCaseOptions, Options and
BenchDuration are a #[jsg_struct] and a #[jsg_oneof], and the duration
and count parsing ports as it was. As in C++ JSG, which calls the
functions of a struct's fields with the struct as `this`, setup and
teardown get the options object as `this`, which the runner keeps
traced for that; the timed function gets undefined, and the internal
(blackBox) case the controller. Exceptions are described by their
stack, or else their string conversion, as before, and the string
conversion keeps lone surrogates (WTF-8) as kj::String did.

The runner is a chain of promise reactions over the controller, whose
state lives in a RefCell on it. They are registered with
IoContext::then_or_catch(), so a reaction outside the IoContext that
started the run fails, as addFunctor() made the C++ continuations do.
Each step that finishes a case returns its result, and the runner goes
on to the next case outside the step, so that a failure then, such as
measuring the overhead, rejects the group rather than failing a case
that has finished. Each batch yields to the KJ event loop first, through
await_io_and_run() over a future that is pending once, as
kj::evalLater() did, and each call of the timed function runs in its own
HandleScope, through with_handle_scope(). The internal (empty) case is a
V8 callback that does nothing, through Function::from_callback(), so
that the measured overhead is that of the call alone, as in C++.

The clocks move to bench-core's clock module, which reads
CLOCK_MONOTONIC and CLOCK_THREAD_CPUTIME_ID through libc, the clocks
kj's systemPreciseMonotonicClock() and BenchTiming read (on Windows,
QueryPerformanceCounter through Instant, and GetThreadTimes). The
factory reads them through the server bridge, so startup groups and
cases are timed with the same code. bench-core's bridge for
fillBenchReport() goes, keeping only the one to kj::GlobFilter:
fillBenchReport(), its tests in bench-test.c++, and the defaults and
median() duplicated with a TODO are gone with api/bench.{h,c++}, as are
BenchExportedHandler and EW_BENCH_ISOLATE_TYPES. WorkerEntrypoint reads
the encoded group with no traversal limit, as the shim did, since a
group can be larger than capnp's default limit. A new server-test case
checks this with a group past that limit, in place of the deleted
bench-test.c++ test.

The runner's own overhead is higher than C++'s in a --config=benchmark
build on Linux (medians of 6 interleaved runs on one machine): an async
call costs it about 2.9 us against 1.7 us, a sync call 87 ns against
56 ns, and a call of blackBox() from JavaScript 156 ns against 63 ns.
The reactions do the same V8 work as C++ (an opaque wrapper and two
functions per call); the difference is calls across the Rust/C++
boundary, which ThinLTO doesn't inline. The overhead is subtracted from
every sample, so it limits only how finely the fastest cases resolve.

server-test's existing bench cases and every @smoke target pass
unchanged.
@bartlomieju
bartlomieju force-pushed the biwanczuk/bench-rust-controller branch from fc705dc to 70065c4 Compare November 23, 2026 11:44

@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 with comments — The port is faithful and the earlier runner and test-coverage notes are fixed. The only open note is an INFO: runner.rs has no unit tests.

Findings: 1 info

Not opened by the correctness review: 1 changed file it was meant to read
  • src/workerd/api/bench-api/runner.rs

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


📋 Code Quality: 💬 1 info

Two earlier notes are fixed; runner.rs still has no unit tests.

Recommendation: 💬 Optional Nits

  • [INFO] runner.rs has no unit tests for its phase, setup/teardown and error-routing state machine; only end-to-end bench targets cover it. (src/workerd/api/bench-api/runner.rs:230)
View full review
  • No unit tests for the runner. Nothing unit-tests runner.rs's phases (warmup, calibrate, sample), its setup/teardown handling, or how case_step, fail_case and finish_case route errors. Only the end-to-end server-test and @smoke bench targets cover them, and neither reaches the finish_stage error path fixed in this pull request.
  • Fixed: the traversal-limit regression test is replaced by a new server-test.c++ test.
  • Fixed: the "as in C++" comments are gone.

✅ All other checks passed

🔒 Security: ✅ LGTM

No security issues in the bench dispatch path or the Rust/C++ bridge. The result bytes are checked to be an ArrayBuffer whose length is a multiple of the word size, then copied into an aligned buffer before decoding. The unbounded traversal limit applies only to the runner's own encoded output.


📖 AGENTS.md: ✅ LGTM

The AGENTS.md "Where to Look" row for JS benchmarks now points at bench-api/ and bench-core/, which matches the new layout.


⚡ Performance: ✅ LGTM

This is benchmark tooling, not a production request path. The description documents the higher per-call overhead compared with C++, and that overhead is subtracted from every sample. call_batch reads the clocks only between batches.


📝 Documentation: ✅ LGTM

No issues found.


Reviewed commit: 70065c45

@bartlomieju
bartlomieju merged commit 7e0605d into main Nov 23, 2026
23 checks passed
@bartlomieju
bartlomieju deleted the biwanczuk/bench-rust-controller branch November 23, 2026 16:58
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.

3 participants