From 70065c4593be3ed3bb01b9efc1342405e4e17838 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Mon, 23 Nov 2026 11:19:24 +0100 Subject: [PATCH] Move workerd bench's BenchController to Rust 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. --- AGENTS.md | 2 +- src/workerd/api/BUILD.bazel | 3 - src/workerd/api/bench-api/BUILD.bazel | 24 + src/workerd/api/bench-api/ffi.rs | 98 ++ src/workerd/api/bench-api/lib-test.rs | 62 ++ src/workerd/api/bench-api/lib.rs | 256 +++++ src/workerd/api/bench-api/options-test.rs | 109 +++ src/workerd/api/bench-api/options.rs | 120 +++ src/workerd/api/bench-api/runner.rs | 892 ++++++++++++++++++ src/workerd/api/bench-core/BUILD.bazel | 13 +- src/workerd/api/bench-core/clock-test.rs | 28 + src/workerd/api/bench-core/clock.rs | 103 ++ src/workerd/api/bench-core/ffi-test.rs | 101 -- src/workerd/api/bench-core/ffi.rs | 124 --- src/workerd/api/bench-core/lib.rs | 42 +- src/workerd/api/bench-core/startup.rs | 8 +- src/workerd/api/bench-test.c++ | 93 -- src/workerd/api/bench.c++ | 535 ----------- src/workerd/api/bench.h | 193 ---- src/workerd/api/global-scope.c++ | 41 +- src/workerd/api/global-scope.h | 31 +- src/workerd/io/BUILD.bazel | 2 - src/workerd/io/worker-entrypoint.c++ | 14 +- src/workerd/io/worker.c++ | 7 +- src/workerd/io/worker.h | 14 +- src/workerd/server/BUILD.bazel | 2 + src/workerd/server/factory/worker-factory.c++ | 16 +- src/workerd/server/server-test.c++ | 47 +- src/workerd/server/server/bridge.rs | 6 + src/workerd/server/server/worker.rs | 11 +- src/workerd/server/workerd-api.c++ | 16 +- src/workerd/server/workerd-api.h | 7 +- 32 files changed, 1881 insertions(+), 1139 deletions(-) create mode 100644 src/workerd/api/bench-api/BUILD.bazel create mode 100644 src/workerd/api/bench-api/ffi.rs create mode 100644 src/workerd/api/bench-api/lib-test.rs create mode 100644 src/workerd/api/bench-api/lib.rs create mode 100644 src/workerd/api/bench-api/options-test.rs create mode 100644 src/workerd/api/bench-api/options.rs create mode 100644 src/workerd/api/bench-api/runner.rs create mode 100644 src/workerd/api/bench-core/clock-test.rs create mode 100644 src/workerd/api/bench-core/clock.rs delete mode 100644 src/workerd/api/bench-core/ffi-test.rs delete mode 100644 src/workerd/api/bench-core/ffi.rs delete mode 100644 src/workerd/api/bench-test.c++ delete mode 100644 src/workerd/api/bench.c++ delete mode 100644 src/workerd/api/bench.h diff --git a/AGENTS.md b/AGENTS.md index b76e8cc52d9..0393398e97e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -205,7 +205,7 @@ Be aware that workerd uses tcmalloc for memory allocation in the typical case. W | Durable Object storage | `src/workerd/io/actor-cache.{h,c++}` + `actor-sqlite.{h,c++}` | LRU cache over RPC / SQLite-backed | | Streams implementation | `src/workerd/api/streams/` | Has 842-line README; dual internal/standard impl | | Bazel build rules | `build/` | Custom `wd_*` macros; `wd_test.bzl` generates 3 test variants | -| JS benchmarks | `src/workerd/api/bench.{h,c++}`, `build/wd_bench.bzl` | `bench` handler; runner `BenchController`; report schema `io/bench.capnp`; driver `server/server/bench.rs` | +| JS benchmarks | `src/workerd/api/bench-api/`, `bench-core/`, `build/wd_bench.bzl` | Rust `BenchController` and runner (`bench-api`); report building, clocks (`bench-core`); schema `io/bench.capnp`; driver `server/server/bench.rs` | | Streams benchmarks | `src/bench/streams/` | C++ vs TS streams: the same modules under a cell per implementation; see its `AGENTS.md` | | Clone benchmarks | `src/bench/serialization/` | `structuredClone()`, C++ vs TS (`TS_STRUCTURED_CLONE`): object graphs, arrays, strings, options, cold calls | | TypeScript types | `types/` | Extracted from C++ RTTI + hand-written `defines/*.d.ts`; see `types/AGENTS.md` for detailed typings guidance | diff --git a/src/workerd/api/BUILD.bazel b/src/workerd/api/BUILD.bazel index 8c35c8145d8..3339f63ec09 100644 --- a/src/workerd/api/BUILD.bazel +++ b/src/workerd/api/BUILD.bazel @@ -13,7 +13,6 @@ filegroup( "actor-call-retry.c++", "actor-state.c++", "basics.c++", - "bench.c++", "blob.c++", "bootstrap-utils.c++", "cache.c++", @@ -75,7 +74,6 @@ filegroup( "actor-call-retry.h", "actor-state.h", "basics.h", - "bench.h", "blob.h", "bootstrap-utils.h", "cache.h", @@ -688,7 +686,6 @@ wd_cc_library( "streams/pendingabort-gc-uaf-test.c++", "actor-state-test.c++", "alarm-retry-test.c++", - "bench-test.c++", "basics-test.c++", "crypto/aes-test.c++", "crypto/impl-test.c++", diff --git a/src/workerd/api/bench-api/BUILD.bazel b/src/workerd/api/bench-api/BUILD.bazel new file mode 100644 index 00000000000..b70c988d462 --- /dev/null +++ b/src/workerd/api/bench-api/BUILD.bazel @@ -0,0 +1,24 @@ +load("//:build/wd_rust_crate.bzl", "wd_rust_crate") + +# BenchController, the first argument of a Worker's `bench()` handler, and the runner that times +# the cases it registers. C++ dispatches the bench event to it through bench_run() (ffi.rs). +wd_rust_crate( + name = "bench-api", + cxx_bridge_deps = [ + "//src/rust/jsg", + "//src/workerd/util:thread-scopes", + ], + cxx_bridge_hdrs = [], + cxx_bridge_src = "ffi.rs", + cxx_bridge_visibility = ["//visibility:public"], + proc_macro_deps = ["//src/rust/jsg-macros"], + test_deps = ["//src/rust/jsg-test"], + visibility = ["//visibility:public"], + deps = [ + "//src/rust/jsg", + "//src/workerd/api/bench-core", + "//src/workerd/io:bench_capnp_rust", + "//src/workerd/io/io-context", + "@crates_vendor//capnp", + ], +) diff --git a/src/workerd/api/bench-api/ffi.rs b/src/workerd/api/bench-api/ffi.rs new file mode 100644 index 00000000000..8c2719fe404 --- /dev/null +++ b/src/workerd/api/bench-api/ffi.rs @@ -0,0 +1,98 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +//! The bridge through which C++ dispatches the bench event to a Worker's `bench()` handler, and +//! the C++ it calls. + +#![allow( + unsafe_code, + reason = "the cxx bridge expands to unsafe FFI glue, and bench_run() takes C++'s raw isolate \ + and handles" +)] + +use jsg::v8; + +use crate::BenchController; +use crate::runner; + +#[cxx::bridge(namespace = "workerd::api")] +mod bridge { + #[namespace = "workerd::rust::jsg"] + unsafe extern "C++" { + include!("workerd/rust/jsg/ffi.h"); + include!("workerd/rust/jsg/v8.rs.h"); + + type Isolate = jsg::v8::ffi::Isolate; + type Local = jsg::v8::ffi::Local; + type MaybeLocal = jsg::v8::ffi::MaybeLocal; + } + + #[namespace = "workerd"] + unsafe extern "C++" { + include!("workerd/util/thread-scopes.h"); + + /// Whether the process runs `workerd bench`, the only command that dispatches the bench + /// event. Not `is_bench_mode`, which workerd-server's bridge declares: cxx names each + /// shim after the function and its namespace, so the two would collide at link time. + #[cxx_name = "isBenchMode"] + fn in_bench_mode() -> bool; + } + + extern "Rust" { + /// Runs the `bench()` handler of `handler`, a Worker's exported handler object, with + /// `env` and `ctx` (undefined if it has none), then the cases it registers. `params` is + /// an encoded `BenchParams` message, in words. Returns a promise for the group: an + /// `ArrayBuffer` that holds its `BenchReport.Group`, without its name, as an encoded + /// message, which rejects if the runner itself fails. Throws if `handler` has no + /// `bench()`. + unsafe fn bench_run( + isolate: *mut Isolate, + handler: Local, + env: Local, + ctx: Local, + params: &[u64], + ) -> MaybeLocal; + } +} + +/// # Safety +/// C++ calls this with the isolate locked, a context entered and a `HandleScope` open, in which +/// `handler`, `env` and `ctx` are handles. +unsafe fn bench_run( + isolate: *mut bridge::Isolate, + handler: bridge::Local, + env: bridge::Local, + ctx: bridge::Local, + params: &[u64], +) -> bridge::MaybeLocal { + // SAFETY: forwarded from the caller, who also passes `handler`, `env` and `ctx` in the scope + // that the closure's lock stands for. + unsafe { + v8::run_ffi_callback(isolate, |lock| { + // The handles are in the caller's scope, which is the lock's. + let (handler, env, ctx) = ( + v8::Local::::from_ffi(handler), + v8::Local::::from_ffi(env), + v8::Local::::from_ffi(ctx), + ); + // Fails closed anywhere but `workerd bench`. + if !bridge::in_bench_mode() { + return Err(jsg::Error::new_internal_error( + "the bench event is only supported by `workerd bench`", + )); + } + let handler_object = v8::Local::::try_from(handler).map_err(|_| { + jsg::Error::new_error("Entrypoint does not export a bench() function.") + })?; + let bench = handler_object.get(lock, "bench")?; + let bench = v8::Local::::try_from(bench).map_err(|_| { + jsg::Error::new_error("Entrypoint does not export a bench() function.") + })?; + let controller = BenchController::read(params) + .map_err(|err| jsg::Error::new_internal_error(err.to_string()))?; + let controller = jsg::Rc::new(lock, controller); + runner::start(lock, &controller, bench, handler, env, ctx) + }) + } +} diff --git a/src/workerd/api/bench-api/lib-test.rs b/src/workerd/api/bench-api/lib-test.rs new file mode 100644 index 00000000000..4325fcdc653 --- /dev/null +++ b/src/workerd/api/bench-api/lib-test.rs @@ -0,0 +1,62 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +use jsg_test::Harness; + +use super::*; + +fn describe(code: &str) -> Vec { + let mut description = Vec::new(); + Harness::new().run_in_context(|lock, ctx| { + let value = ctx.eval_raw(lock, code).unwrap(); + description = describe_exception(lock, value).unwrap(); + Ok(()) + }); + description +} + +/// A lone surrogate is kept as WTF-8, as C++ JSG's `kj::String` keeps it. +#[test] +fn strings_convert_to_wtf8() { + Harness::new().run_in_context(|lock, ctx| { + let value = ctx.eval_raw(lock, "'a\\ud800b\\u00e9'").unwrap(); + let string = v8::Local::::try_from(value).unwrap(); + assert_eq!(wtf8(lock, string), b"a\xed\xa0\x80b\xc3\xa9"); + Ok(()) + }); +} + +#[test] +fn exceptions_are_described_by_their_stack() { + let description = describe("(() => { const e = new TypeError('boom'); return e; })()"); + assert!( + description.starts_with(b"TypeError: boom\n"), + "{description:?}" + ); + assert_eq!(describe("({ stack: 'custom stack' })"), b"custom stack"); +} + +#[test] +fn exceptions_without_a_stack_are_converted_to_strings() { + assert_eq!(describe("'thrown string'"), b"thrown string"); + assert_eq!(describe("42"), b"42"); + assert_eq!( + describe("({ stack: 1, toString() { return 'object' } })"), + b"object" + ); +} + +#[test] +fn exceptions_that_cannot_be_converted_have_a_placeholder() { + let placeholder = b"(an exception that can't be converted to a string)"; + assert_eq!(describe("Symbol('s')"), placeholder); + assert_eq!( + describe("({ get stack() { throw 1; } })"), + placeholder.as_slice() + ); + assert_eq!( + describe("({ toString() { throw new Error('no'); } })"), + placeholder.as_slice() + ); +} diff --git a/src/workerd/api/bench-api/lib.rs b/src/workerd/api/bench-api/lib.rs new file mode 100644 index 00000000000..7932b45986b --- /dev/null +++ b/src/workerd/api/bench-api/lib.rs @@ -0,0 +1,256 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +//! `BenchController`, which a Worker's `bench(b, env, ctx)` handler uses to register cases, and +//! the runner that times them. Only `workerd bench` dispatches the bench event, through +//! [`ffi`]'s `bench_run()`. +//! +//! The runtime runs the timing loop: user code supplies the function to time and never sees a +//! high-resolution clock. For each case, the runner calls the function repeatedly to warm up, +//! calibrates a batch size, then times `samples` batches, reading the monotonic and thread CPU +//! clocks only between batches. Each sample is a batch's time divided by its number of calls. +//! +//! The bench types aren't in the generated TypeScript definitions: only `workerd bench` delivers +//! the bench event, so they aren't part of the API that deployed Workers see. + +mod ffi; +mod options; +mod runner; + +use std::cell::Cell; +use std::cell::RefCell; + +use bench_core::DEFAULT_MIN_TIME_NS; +use bench_core::DEFAULT_SAMPLES; +use bench_core::MAX_SAMPLES; +use bench_core::QUICK_MIN_TIME_NS; +use bench_core::QUICK_SAMPLES; +use jsg::FromJS; +use jsg::v8; +use jsg_macros::jsg_method; +use jsg_macros::jsg_property; +use jsg_macros::jsg_resource; +use jsg_macros::jsg_traced; +pub use options::BenchCaseOptions; +pub use options::BenchDuration; +pub use options::BenchOptions; +use options::parse_count; +use options::parse_duration; + +/// The warmup, when neither the case nor the command line sets one. +const DEFAULT_WARMUP_NS: u64 = 200_000_000; + +/// Under `--quick`, warmups are capped at this. +const QUICK_WARMUP_NS: u64 = 2_000_000; + +/// The most calls a batch makes. +const MAX_CALLS_PER_BATCH: u64 = 1 << 40; + +/// How long a case may run for, and how often it is sampled. +#[jsg_traced] +#[derive(Debug, Clone, Copy)] +struct Budget { + min_time_ns: u64, + warmup_ns: u64, + samples: u32, + /// Calls per batch; 0 calibrates. + batch: u64, +} + +/// A registered case. +struct Case { + name: Vec, + func: v8::TracedGlobal, + /// `this` for calls of `func`; undefined if none. + receiver: Option>, + /// Whether `func` gets an argument when there is no `setup`, in which case it is undefined. + pass_argument: bool, + setup: Option>, + teardown: Option>, + /// The options object, which is `this` for `setup` and `teardown`, as C++ JSG calls the + /// functions of a struct's fields with the struct's object. + options: Option>, + skip: bool, + budget: Budget, + /// A case that measures overhead, which the case filter doesn't apply to. + internal: bool, + /// Whether `func` returns a promise, once it has been called. Every call must agree, since + /// the overhead subtracted from the samples depends on it. + returns_promise: Cell>, +} + +impl jsg::Traced for Case { + fn trace(&self, visitor: &mut v8::GcVisitor) { + self.func.trace(visitor); + self.receiver.trace(visitor); + self.setup.trace(visitor); + self.teardown.trace(visitor); + self.options.trace(visitor); + } +} + +/// The first argument of a `bench()` handler. +#[jsg_resource] +pub struct BenchController { + case_filter: Vec, + quick: bool, + defaults: Budget, + cases: jsg::RefCell>, + /// Set once the cases start running; registering a case after that is an error. + running: Cell, + /// The runner's state, which `runner` owns. + run: RefCell, + /// The result of the setup of the batch in progress, which every call gets. + state: jsg::RefCell>>, + /// Settles the promise `bench_run()` returned. + resolver: jsg::RefCell>>, +} + +#[jsg_resource] +impl BenchController { + /// Registers a case. Cases run, in registration order, after `bench()` returns or its + /// promise resolves. `fn` may return a promise, which is awaited before the next call. + #[jsg_method] + fn run<'s>( + &self, + lock: &mut jsg::Lock<'s>, + name: jsg::JsString<'s>, + func: v8::Local<'s, v8::Function>, + options: Option>, + ) -> jsg::Result<()> { + if self.running.get() { + return Err(jsg::Error::new_error( + "BenchController.run() must be called by bench(), before it returns or its \ + promise resolves.", + )); + } + let name = wtf8(lock, *name); + if self.cases.borrow().iter().any(|c| c.name == name) { + return Err(jsg::Error::new_error(format!( + "A case named \"{}\" is already registered.", + String::from_utf8_lossy(&name) + ))); + } + + let options_object = options.unwrap_or_else(|| lock.undefined()); + let options = BenchCaseOptions::from_js(lock, options_object)?; + let mut budget = self.defaults; + if let Some(min_time) = &options.minTime { + budget.min_time_ns = parse_duration(min_time, "minTime")?; + } + if let Some(warmup) = &options.warmup { + budget.warmup_ns = parse_duration(warmup, "warmup")?; + } + if let Some(samples) = options.samples { + budget.samples = u32::try_from(parse_count(samples, MAX_SAMPLES.into(), "samples")?) + .unwrap_or_else(|_| unreachable!("at most MAX_SAMPLES")); + } + if let Some(batch) = options.batch { + budget.batch = parse_count(batch, MAX_CALLS_PER_BATCH, "batch")?; + } + if self.quick { + budget.min_time_ns = budget.min_time_ns.min(QUICK_MIN_TIME_NS); + budget.warmup_ns = budget.warmup_ns.min(QUICK_WARMUP_NS); + budget.samples = budget.samples.min(QUICK_SAMPLES); + } + let case = Case { + name, + func: func.to_traced_global(lock), + receiver: None, + pass_argument: false, + setup: options.setup, + teardown: options.teardown, + options: Some(options_object.to_traced_global(lock)), + skip: options.skip.unwrap_or(false), + budget, + internal: false, + returns_promise: Cell::new(None), + }; + self.cases.borrow_mut(lock).push(case); + Ok(()) + } + + /// Returns `value`. Passing a result through it keeps V8 from optimizing away the code that + /// computed it, since V8 can't see into the native call. + #[jsg_method] + fn black_box<'s>(&self, value: v8::Local<'s, v8::Value>) -> v8::Local<'s, v8::Value> { + value + } + + #[jsg_property(prototype, readonly)] + fn get_options(&self) -> BenchOptions { + BenchOptions { + filter: match self.case_filter.as_slice() { + b"" | b"*" => None, + filter => Some(String::from_utf8_lossy(filter).into_owned()), + }, + quick: self.quick, + } + } +} + +impl BenchController { + /// A controller for `params`, an encoded `BenchParams` message, in words. + fn read(params: &[u64]) -> capnp::Result { + let bytes: Vec = params.iter().flat_map(|word| word.to_ne_bytes()).collect(); + let message = + capnp::serialize::read_message(bytes.as_slice(), capnp::message::ReaderOptions::new())?; + let params: bench_capnp::bench_params::Reader<'_> = message.get_root()?; + let defaults = params.get_defaults()?; + let or = |value: u64, default: u64| if value > 0 { value } else { default }; + Ok(Self { + case_filter: params.get_case_filter()?.as_bytes().to_vec(), + quick: params.get_quick(), + defaults: Budget { + min_time_ns: or(defaults.get_min_time_ns(), DEFAULT_MIN_TIME_NS), + warmup_ns: or(defaults.get_warmup_ns(), DEFAULT_WARMUP_NS), + samples: match defaults.get_samples() { + 0 => DEFAULT_SAMPLES, + samples => samples, + }, + batch: defaults.get_batch(), + }, + cases: jsg::RefCell::new(Vec::new()), + running: Cell::new(false), + run: RefCell::new(runner::Run::default()), + state: jsg::RefCell::new(None), + resolver: jsg::RefCell::new(None), + }) + } +} + +/// The string as WTF-8, as C++ JSG converts a string to a `kj::String`: a lone surrogate is kept +/// as its three bytes rather than replaced. +fn wtf8(lock: &mut jsg::Lock<'_>, string: v8::Local<'_, v8::String>) -> Vec { + let mut bytes = vec![0; string.utf8_length(lock)]; + let written = string.write_utf8(lock, &mut bytes, v8::WriteFlags::None); + bytes.truncate(written); + bytes +} + +/// The exception's stack if it has one, or else its string conversion, as WTF-8. +/// +/// # Errors +/// Fails only while execution is terminating; what the conversion throws is caught. +fn describe_exception<'s>( + lock: &mut jsg::Lock<'s>, + exception: v8::Local<'s, v8::Value>, +) -> jsg::Result> { + let description = lock.try_catch(|lock| { + if let Ok(object) = v8::Local::::try_from(exception) { + let stack = object.get(lock, "stack")?; + if let Ok(stack) = v8::Local::::try_from(stack) { + return Ok(wtf8(lock, stack)); + } + } + let string = exception.to_js_string(lock)?; + Ok(wtf8(lock, string)) + })?; + Ok(description + .unwrap_or_else(|_| b"(an exception that can't be converted to a string)".to_vec())) +} + +#[cfg(test)] +#[path = "lib-test.rs"] +mod tests; diff --git a/src/workerd/api/bench-api/options-test.rs b/src/workerd/api/bench-api/options-test.rs new file mode 100644 index 00000000000..fb305338a25 --- /dev/null +++ b/src/workerd/api/bench-api/options-test.rs @@ -0,0 +1,109 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +use super::*; + +fn ns(text: &str) -> jsg::Result { + parse_duration(&BenchDuration::String(text.to_owned()), "minTime") +} + +/// The type and message of the error `result` fails with. +fn message(result: jsg::Result) -> (jsg::ExceptionType, String) { + let Err(err) = result else { + panic!("expected an error"); + }; + let ty = [ + jsg::ExceptionType::TypeError, + jsg::ExceptionType::RangeError, + jsg::ExceptionType::Error, + ] + .into_iter() + .find(|ty| err.name == *ty) + .unwrap(); + (ty, err.message) +} + +#[test] +fn numbers_are_milliseconds() { + let parse = |ms| parse_duration(&BenchDuration::Number(ms), "warmup").unwrap(); + assert_eq!(parse(0.0), 0); + assert_eq!(parse(1.5), 1_500_000); + assert_eq!(parse(250.0), 250_000_000); +} + +#[test] +fn strings_take_a_unit() { + assert_eq!(ns("7ns").unwrap(), 7); + assert_eq!(ns("2us").unwrap(), 2_000); + assert_eq!(ns("2µs").unwrap(), 2_000); + assert_eq!(ns("3ms").unwrap(), 3_000_000); + assert_eq!(ns("3").unwrap(), 3_000_000); + assert_eq!(ns("1.5s").unwrap(), 1_500_000_000); + assert_eq!(ns(".5s").unwrap(), 500_000_000); + assert_eq!(ns("5.s").unwrap(), 5_000_000_000); +} + +#[test] +fn strings_without_a_number_are_type_errors() { + let expected = ( + jsg::ExceptionType::TypeError, + "minTime must be a number of milliseconds or a string like \"500ms\" or \"2s\".".to_owned(), + ); + for text in ["", "ms", ".", "1..2ms", "-1ms", " 1ms"] { + assert_eq!(message(ns(text)), expected, "{text:?}"); + } +} + +#[test] +fn unknown_units_are_type_errors() { + assert_eq!( + message(ns("5min")), + ( + jsg::ExceptionType::TypeError, + "minTime has an unknown unit \"min\"; use \"ns\", \"us\", \"ms\", or \"s\".".to_owned() + ) + ); + // The number ends at the first byte that isn't a digit or a point. + assert_eq!( + message(ns("1e3ms")).1, + "minTime has an unknown unit \"e3ms\"; use \"ns\", \"us\", \"ms\", or \"s\"." + ); + assert_eq!( + message(ns("5 ms")).1, + "minTime has an unknown unit \" ms\"; use \"ns\", \"us\", \"ms\", or \"s\"." + ); +} + +#[test] +fn durations_must_be_non_negative_and_finite() { + let expected = ( + jsg::ExceptionType::RangeError, + "warmup must be a non-negative duration.".to_owned(), + ); + for ms in [-1.0, f64::NAN, f64::INFINITY, 1e12] { + assert_eq!( + message(parse_duration(&BenchDuration::Number(ms), "warmup")), + expected, + "{ms}" + ); + } + let huge = format!("{}s", "9".repeat(400)); + assert_eq!(message(ns(&huge)).0, jsg::ExceptionType::RangeError); +} + +#[test] +fn counts_are_integers_in_range() { + assert_eq!(parse_count(1.0, 10, "samples").unwrap(), 1); + assert_eq!(parse_count(10.0, 10, "samples").unwrap(), 10); + for value in [0.0, 11.0, 1.5, -3.0, f64::NAN, f64::INFINITY] { + assert_eq!( + message(parse_count(value, 10, "samples")), + ( + jsg::ExceptionType::RangeError, + "samples must be an integer from 1 to 10.".to_owned() + ), + "{value}" + ); + } +} diff --git a/src/workerd/api/bench-api/options.rs b/src/workerd/api/bench-api/options.rs new file mode 100644 index 00000000000..56fc6d1604c --- /dev/null +++ b/src/workerd/api/bench-api/options.rs @@ -0,0 +1,120 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +//! The options JavaScript passes to `BenchController.run()`, the options it reads from +//! `BenchController.options`, and the parsing of the budgets they set. + +#![expect( + non_snake_case, + reason = "the fields of the option structs are the property names JavaScript uses" +)] + +use jsg::v8; +use jsg_macros::jsg_oneof; +use jsg_macros::jsg_struct; + +/// A duration: a number of milliseconds, or a string with a unit, as in "500ms" or "2s". +#[jsg_oneof] +#[derive(Debug, Clone)] +pub enum BenchDuration { + Number(f64), + String(String), +} + +/// Options for one case, the third argument of `BenchController.run()`. +#[jsg_struct] +pub struct BenchCaseOptions { + /// Sampling budget: the batch size is calibrated so that all samples take about this long. + pub minTime: Option, + /// How long to call the function before calibrating and sampling, to let V8 optimize it. + pub warmup: Option, + /// The number of batches to time. + pub samples: Option, + /// Calls per batch, instead of calibrating. + pub batch: Option, + /// Called before each batch, untimed. Its result (awaited if it is a promise) is passed to + /// every call of the function in that batch. + pub setup: Option>, + /// Called after each batch with the setup result (undefined without `setup`), untimed, and + /// awaited if it returns a promise. + pub teardown: Option>, + /// Reports the case as skipped instead of running it. + pub skip: Option, +} + +/// `BenchController.options`. +#[jsg_struct(name = "Options")] +pub struct BenchOptions { + /// The case filter given on the command line, if any. + pub filter: Option, + /// Whether `--quick` was given: budgets are short, so results only show that cases run. + pub quick: bool, +} + +/// `duration`, which option `what` set, in nanoseconds. +pub fn parse_duration(duration: &BenchDuration, what: &str) -> jsg::Result { + match duration { + BenchDuration::Number(ms) => duration_to_ns(ms * 1e6, what), + BenchDuration::String(text) => { + let number_end = text + .bytes() + .position(|b| !(b.is_ascii_digit() || b == b'.')) + .unwrap_or(text.len()); + let (number, unit) = text.split_at(number_end); + let number: f64 = number.parse().map_err(|_| { + jsg::Error::new_type_error(format!( + "{what} must be a number of milliseconds or a string like \"500ms\" or \ + \"2s\"." + )) + })?; + let scale = match unit { + "ns" => 1.0, + "us" | "µs" => 1e3, + "ms" | "" => 1e6, + "s" => 1e9, + _ => { + return Err(jsg::Error::new_type_error(format!( + "{what} has an unknown unit \"{unit}\"; use \"ns\", \"us\", \"ms\", or \ + \"s\"." + ))); + } + }; + duration_to_ns(number * scale, what) + } + } +} + +#[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "the duration is checked to be from 0 to 1e18 first" +)] +fn duration_to_ns(ns: f64, what: &str) -> jsg::Result { + if !(0.0..1e18).contains(&ns) { + return Err(jsg::Error::new_range_error(format!( + "{what} must be a non-negative duration." + ))); + } + Ok(ns as u64) +} + +/// `value`, which option `what` set, as an integer from 1 to `max`. +#[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + clippy::cast_precision_loss, + reason = "the value is checked to be an integer from 1 to `max`, compared as a double" +)] +pub fn parse_count(value: f64, max: u64, what: &str) -> jsg::Result { + if !((1.0..=max as f64).contains(&value) && value.fract() == 0.0) { + return Err(jsg::Error::new_range_error(format!( + "{what} must be an integer from 1 to {max}." + ))); + } + Ok(value as u64) +} + +#[cfg(test)] +#[path = "options-test.rs"] +mod tests; diff --git a/src/workerd/api/bench-api/runner.rs b/src/workerd/api/bench-api/runner.rs new file mode 100644 index 00000000000..f863cb480ab --- /dev/null +++ b/src/workerd/api/bench-api/runner.rs @@ -0,0 +1,892 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +//! The runner: after the `bench()` handler has registered its cases, it measures its own +//! overhead (once per thread) and runs the cases, then settles the promise `bench_run()` +//! returned with the group, encoded as a `BenchReport.Group` message in an `ArrayBuffer`. +//! +//! The runner is a state machine in the controller, which promise reactions and the yields +//! between batches advance. Its reactions are registered with [`IoContext::then_or_catch`], with +//! a [`jsg::Rc`] of the controller as their data, so that a reaction that runs in another request +//! fails, as the continuations that C++ `IoContext::addFunctor()` wraps do. Each step that can run +//! JavaScript runs in a [`jsg::Lock::try_catch`]: what a case throws, or a promise of it +//! rejects with, fails the case, and the runner goes on to the next one. What fails the runner +//! itself, such as measuring the overhead, rejects the promise. + +use std::future::Future; +use std::pin::Pin; +use std::task::Context; +use std::task::Poll; + +use bench_capnp::bench_report::case::Status; +use bench_core::CaseResult; +use bench_core::GlobFilter; +use bench_core::GroupResult; +use bench_core::Overhead; +use bench_core::QUICK_MIN_TIME_NS; +use bench_core::QUICK_SAMPLES; +use bench_core::Timing; +use bench_core::clock; +use io_context::IoContext; +use jsg::FromJS; +use jsg::ToJS; +use jsg::v8; + +use crate::BenchController; +use crate::Budget; +use crate::Case; +use crate::MAX_CALLS_PER_BATCH; +use crate::QUICK_WARMUP_NS; +use crate::describe_exception; + +/// A calibrated batch takes at least this long, so that clock resolution and the cost of reading +/// the clocks don't matter. +const MIN_BATCH_NS: u64 = 1_000_000; + +/// Budgets for the cases that measure overhead, which are capped further under `--quick`. +const OVERHEAD_MIN_TIME_NS: u64 = 200_000_000; +const OVERHEAD_WARMUP_NS: u64 = 50_000_000; +const OVERHEAD_SAMPLES: u32 = 20; + +const MIXED_RESULTS: &str = "The function returned a promise from some calls but not from others. \ + It must either always or never return a promise."; + +thread_local! { + /// The overhead is measured once per thread. `workerd bench` runs every group on the same + /// thread, so all groups in a run share one measurement. + static MEASURED_OVERHEAD: std::cell::Cell> = + const { std::cell::Cell::new(None) }; +} + +/// The cases the runner is going through. +#[derive(Debug, Clone, Copy, Default)] +enum Stage { + /// The internal cases, from `begin`, that measure the overhead. + Overhead { begin: usize }, + /// The handler's cases. + #[default] + Cases, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Phase { + Warmup, + Calibrate, + Sample, +} + +/// The case in progress. +#[derive(Debug)] +struct CaseRun { + phase: Phase, + calls: u64, + warmed_up_ns: u64, + /// Calibration grows batches until one takes at least this long. + target_batch_ns: u64, + wall_ns: Vec, + cpu_ns: Vec, + /// The calls of the batch in progress that are still to be made. + remaining: u64, + /// The clocks when the batch in progress started, and then how long it took. + start: Timing, + timing: Timing, +} + +/// The runner's state. +#[derive(Debug, Default)] +pub struct Run { + stage: Stage, + /// The case to run next, or the case in progress, and the end of the stage's cases. + index: usize, + end: usize, + results: Vec, + case: Option, + filter: Option, + overhead: Option, +} + +// Holds no JavaScript handles; its fields are plain data from bench-core. +jsg::jsg_traced_unchecked!(Run); + +/// A reaction of the runner, which gets the controller. +trait Reaction: + Copy + + 'static + + for<'a> Fn( + &mut jsg::Lock<'a>, + &IoContext<'a>, + &jsg::Rc, + v8::Local<'a, v8::Value>, + ) -> jsg::Result> +{ +} + +impl Reaction for F where + F: Copy + + 'static + + for<'a> Fn( + &mut jsg::Lock<'a>, + &IoContext<'a>, + &jsg::Rc, + v8::Local<'a, v8::Value>, + ) -> jsg::Result> +{ +} + +/// A future that is pending once, so that awaiting it yields to the event loop, as +/// `kj::evalLater()` does. +struct YieldOnce(bool); + +impl Future for YieldOnce { + type Output = (); + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { + if self.0 { + return Poll::Ready(()); + } + self.0 = true; + cx.waker().wake_by_ref(); + Poll::Pending + } +} + +/// Starts the `bench()` handler `bench` of `handler`, with `controller`, and returns the promise +/// that the group settles; see the module documentation. +pub fn start<'s>( + lock: &mut jsg::Lock<'s>, + controller: &jsg::Rc, + bench: v8::Local<'s, v8::Function>, + handler: v8::Local<'s, v8::Value>, + env: v8::Local<'s, v8::Value>, + ctx: v8::Local<'s, v8::Value>, +) -> jsg::Result> { + let resolver = v8::PromiseResolver::new(lock)?; + let promise = resolver.promise(); + *controller.get(lock).resolver.borrow_mut(lock) = Some(resolver.to_traced_global(lock)); + + let controller_js = controller.clone(lock).to_js(lock)?; + let returned = lock.try_catch(|lock| { + let returned = bench.call(lock, Some(handler), &[controller_js, env, ctx])?; + Ok(v8::Local::::from(v8::VoidPromise::from_js( + lock, returned, + )?)) + })?; + let returned = match returned { + Ok(returned) => returned, + Err(exception) => v8::Promise::rejected(lock, exception)?, + }; + react_to( + lock, + controller, + returned, + on_handler_fulfilled, + on_handler_rejected, + )?; + Ok(promise) +} + +/// Registers `on_fulfilled` and `on_rejected` on `promise`, to run in the request's `IoContext` +/// with the controller. +fn react_to<'s>( + lock: &mut jsg::Lock<'s>, + this: &jsg::Rc, + promise: v8::Local<'s, v8::Promise>, + on_fulfilled: impl Reaction, + on_rejected: impl Reaction, +) -> jsg::Result<()> { + let data = this.clone(lock); + IoContext::current(lock)?.then_or_catch(lock, promise, data, on_fulfilled, on_rejected)?; + Ok(()) +} + +/// Runs `f`, a step of the runner, for a reaction. What `f` fails with rejects the group's +/// promise; a termination propagates. +fn drive<'a>( + lock: &mut jsg::Lock<'a>, + this: &jsg::Rc, + f: impl FnOnce(&mut jsg::Lock<'a>) -> jsg::Result<()>, +) -> jsg::Result<()> { + if let Err(exception) = lock.try_catch(f)? { + settle(lock, this, Err(exception))?; + } + Ok(()) +} + +/// A promise reaction that runs `f`; see [`drive`]. +fn react<'a>( + lock: &mut jsg::Lock<'a>, + this: &jsg::Rc, + f: impl FnOnce(&mut jsg::Lock<'a>, &jsg::Rc) -> jsg::Result<()>, +) -> jsg::Result> { + drive(lock, this, |lock| f(lock, this))?; + Ok(lock.undefined()) +} + +/// Runs `f`, a step of the case in progress, which returns the case's result once the case has +/// finished. What `f` fails with fails the case. The runner goes on to the next case outside +/// `f`, so that what fails the runner then, such as measuring the overhead, rejects the group's +/// promise rather than failing a case that has finished. +fn case_step<'a>( + lock: &mut jsg::Lock<'a>, + this: &jsg::Rc, + f: impl FnOnce(&mut jsg::Lock<'a>) -> jsg::Result>, +) -> jsg::Result<()> { + let finished = match lock.try_catch(f)? { + Ok(finished) => finished, + Err(exception) => Some(fail_case(lock, this, exception)?), + }; + match finished { + Some(result) => finish_case(lock, this, result), + None => Ok(()), + } +} + +fn on_handler_fulfilled<'a>( + lock: &mut jsg::Lock<'a>, + _context: &IoContext<'a>, + this: &jsg::Rc, + _value: v8::Local<'a, v8::Value>, +) -> jsg::Result> { + react(lock, this, start_cases) +} + +/// The handler threw, or its promise rejected: the group fails with the exception. +fn on_handler_rejected<'a>( + lock: &mut jsg::Lock<'a>, + _context: &IoContext<'a>, + this: &jsg::Rc, + exception: v8::Local<'a, v8::Value>, +) -> jsg::Result> { + react(lock, this, |lock, this| { + let error = describe_exception(lock, exception)?; + settle_group( + lock, + this, + &GroupResult { + error: Some(error), + ..GroupResult::default() + }, + ) + }) +} + +fn on_setup_fulfilled<'a>( + lock: &mut jsg::Lock<'a>, + _context: &IoContext<'a>, + this: &jsg::Rc, + state: v8::Local<'a, v8::Value>, +) -> jsg::Result> { + react(lock, this, |lock, this| { + case_step(lock, this, |lock| start_batch(lock, this, state)) + }) +} + +fn on_call_fulfilled<'a>( + lock: &mut jsg::Lock<'a>, + _context: &IoContext<'a>, + this: &jsg::Rc, + _value: v8::Local<'a, v8::Value>, +) -> jsg::Result> { + react(lock, this, |lock, this| { + case_step(lock, this, |lock| call_batch(lock, this)) + }) +} + +fn on_batch_timed<'a>( + lock: &mut jsg::Lock<'a>, + _context: &IoContext<'a>, + this: &jsg::Rc, + _value: v8::Local<'a, v8::Value>, +) -> jsg::Result> { + react(lock, this, |lock, this| { + case_step(lock, this, |lock| tear_down(lock, this)) + }) +} + +fn on_teardown_fulfilled<'a>( + lock: &mut jsg::Lock<'a>, + _context: &IoContext<'a>, + this: &jsg::Rc, + _value: v8::Local<'a, v8::Value>, +) -> jsg::Result> { + react(lock, this, |lock, this| { + case_step(lock, this, |lock| next_batch(lock, this)) + }) +} + +/// A promise of the case in progress rejected: the case fails with the exception. +fn on_case_rejected<'a>( + lock: &mut jsg::Lock<'a>, + _context: &IoContext<'a>, + this: &jsg::Rc, + exception: v8::Local<'a, v8::Value>, +) -> jsg::Result> { + react(lock, this, |lock, this| { + let result = fail_case(lock, this, exception)?; + finish_case(lock, this, result) + }) +} + +/// Runs the registered cases, after the handler has registered them. +fn start_cases(lock: &mut jsg::Lock<'_>, this: &jsg::Rc) -> jsg::Result<()> { + let controller = this.get(lock); + controller.running.set(true); + let count = controller.cases.borrow().len(); + if count == 0 { + return settle_group( + lock, + this, + &GroupResult { + error: Some(b"bench() did not register any cases.".to_vec()), + ..GroupResult::default() + }, + ); + } + { + let mut run = controller.run.borrow_mut(); + let filter: &[u8] = match controller.case_filter.as_slice() { + b"" => b"*", + filter => filter, + }; + run.filter = Some(GlobFilter::new(filter)); + } + + if let Some(overhead) = MEASURED_OVERHEAD.get() { + controller.run.borrow_mut().overhead = Some(overhead); + return start_stage(lock, this, Stage::Cases, 0, count); + } + + // The internal cases go after the handler's, and are removed once they have run. + // The empty function is a V8 callback that does nothing, so that a call of it costs no + // more than the call itself. + let empty = v8::Function::from_callback(lock, empty_callback)?; + let empty_async = v8::Function::from_callback( + lock, + jsg::function_callback(|lock, args| { + let promise = (|| { + let resolver = v8::PromiseResolver::new(lock)?; + let undefined = lock.undefined(); + resolver.resolve(lock, undefined)?; + jsg::Result::Ok(resolver.promise()) + })(); + match promise { + Ok(promise) => args.set_return_value(promise.into()), + Err(err) => lock.throw_exception(&err), + } + }), + )?; + // `blackBox(undefined)`, called as a method of this controller. + let wrapper = this.clone(lock).to_js(lock)?; + let black_box = v8::Local::::try_from(wrapper) + .map_err(|_| jsg::Error::new_internal_error("the controller's wrapper is not an object"))? + .get(lock, "blackBox")?; + let black_box = v8::Local::::try_from(black_box).map_err(|_| { + jsg::Error::new_internal_error("the controller's blackBox is not a function") + })?; + + let controller = this.get(lock); + let quick = controller.quick; + let budget = Budget { + min_time_ns: if quick { + QUICK_MIN_TIME_NS + } else { + OVERHEAD_MIN_TIME_NS + }, + warmup_ns: if quick { + QUICK_WARMUP_NS + } else { + OVERHEAD_WARMUP_NS + }, + samples: if quick { + QUICK_SAMPLES + } else { + OVERHEAD_SAMPLES + }, + batch: 0, + }; + let added = [ + internal_case(lock, b"(empty)", budget, empty, None), + internal_case(lock, b"(empty async)", budget, empty_async, None), + internal_case(lock, b"(blackBox)", budget, black_box, Some(wrapper)), + ]; + controller.cases.borrow_mut(lock).extend(added); + let end = controller.cases.borrow().len(); + start_stage(lock, this, Stage::Overhead { begin: count }, count, end) +} + +/// A case that measures overhead by calling `func`, with `receiver` as `this` and an undefined +/// argument if there is one. +fn internal_case<'s>( + lock: &mut jsg::Lock<'s>, + name: &[u8], + budget: Budget, + func: v8::Local<'s, v8::Function>, + receiver: Option>, +) -> Case { + Case { + name: name.to_vec(), + func: func.to_traced_global(lock), + receiver: receiver.map(|receiver| receiver.to_traced_global(lock)), + pass_argument: receiver.is_some(), + setup: None, + teardown: None, + options: None, + skip: false, + budget, + internal: true, + returns_promise: std::cell::Cell::new(None), + } +} + +fn start_stage( + lock: &mut jsg::Lock<'_>, + this: &jsg::Rc, + stage: Stage, + index: usize, + end: usize, +) -> jsg::Result<()> { + { + let mut run = this.get(lock).run.borrow_mut(); + run.stage = stage; + run.index = index; + run.end = end; + run.results.clear(); + } + next_case(lock, this) +} + +/// Starts the next case of the stage that the filter selects, or finishes the stage. +fn next_case(lock: &mut jsg::Lock<'_>, this: &jsg::Rc) -> jsg::Result<()> { + let controller = this.get(lock); + loop { + let cases = controller.cases.borrow(); + let mut run = controller.run.borrow_mut(); + while run.index < run.end { + let case = &cases[run.index]; + if case.internal + || run + .filter + .as_ref() + .is_none_or(|filter| filter.matches(&case.name)) + { + break; + } + run.index += 1; + } + if run.index == run.end { + drop((cases, run)); + return finish_stage(lock, this); + } + + let case = &cases[run.index]; + if case.skip { + run.results.push(CaseResult { + name: case.name.clone(), + status: Status::Skipped, + error: None, + iterations_per_sample: 0, + wall_ns: Vec::new(), + cpu_ns: Vec::new(), + returns_promise: false, + }); + run.index += 1; + continue; + } + + let budget = case.budget; + run.case = Some(CaseRun { + phase: if budget.warmup_ns > 0 { + Phase::Warmup + } else if budget.batch > 0 { + Phase::Sample + } else { + Phase::Calibrate + }, + calls: if budget.batch > 0 && budget.warmup_ns == 0 { + budget.batch + } else { + 1 + }, + warmed_up_ns: 0, + target_batch_ns: (budget.min_time_ns / u64::from(budget.samples)).max(MIN_BATCH_NS), + wall_ns: Vec::new(), + cpu_ns: Vec::new(), + remaining: 0, + start: Timing::default(), + timing: Timing::default(), + }); + drop((cases, run)); + return step(lock, this); + } +} + +/// Yields to the event loop, so that pending I/O and timers make progress outside the timed +/// region, then runs the next batch. +fn step(lock: &mut jsg::Lock<'_>, this: &jsg::Rc) -> jsg::Result<()> { + let context = IoContext::current(lock)?; + let this = this.clone(lock); + context.await_io_and_run(YieldOnce(false), move |lock, ()| { + drive(lock, &this, |lock| { + case_step(lock, &this, |lock| run_batch(lock, &this)) + }) + }) +} + +/// Runs the setup of a batch, if the case has one, then the batch. +fn run_batch( + lock: &mut jsg::Lock<'_>, + this: &jsg::Rc, +) -> jsg::Result> { + let controller = this.get(lock); + let (setup, receiver) = { + let cases = controller.cases.borrow(); + let case = &cases[controller.run.borrow().index]; + ( + case.setup.as_ref().map(|setup| setup.as_local(lock)), + case.options.as_ref().map(|options| options.as_local(lock)), + ) + }; + let Some(setup) = setup else { + let undefined = lock.undefined(); + return start_batch(lock, this, undefined); + }; + let state = setup.call(lock, receiver, &[])?; + let state = v8::Promise::resolved(lock, state)?; + react_to(lock, this, state, on_setup_fulfilled, on_case_rejected)?; + Ok(None) +} + +/// Times a batch, whose calls get `state`. +fn start_batch<'s>( + lock: &mut jsg::Lock<'s>, + this: &jsg::Rc, + state: v8::Local<'s, v8::Value>, +) -> jsg::Result> { + let controller = this.get(lock); + *controller.state.borrow_mut(lock) = Some(state.to_traced_global(lock)); + { + let mut run = controller.run.borrow_mut(); + let Some(case) = run.case.as_mut() else { + unreachable!("a batch starts in a case"); + }; + case.remaining = case.calls; + case.start = clock::now(); + } + call_batch(lock, this) +} + +/// The callback of the `(empty)` case, which V8 calls directly. +#[expect( + unsafe_code, + reason = "a V8 function callback, which reads nothing of its arguments" +)] +unsafe extern "C" fn empty_callback(_info: *mut v8::ffi::FunctionCallbackInfo) {} + +/// Makes the rest of the batch's calls. A call that returns a promise is awaited before the +/// next; the batch's time includes the wait. +fn call_batch( + lock: &mut jsg::Lock<'_>, + this: &jsg::Rc, +) -> jsg::Result> { + let controller = this.get(lock); + let undefined = lock.undefined(); + let (func, receiver, argument_count, mut returns_promise) = { + let cases = controller.cases.borrow(); + let case = &cases[controller.run.borrow().index]; + ( + case.func.as_local(lock), + Some( + case.receiver + .as_ref() + .map_or(undefined, |receiver| receiver.as_local(lock)), + ), + usize::from(case.setup.is_some() || case.pass_argument), + case.returns_promise.get(), + ) + }; + let state = controller + .state + .borrow() + .as_ref() + .map_or(undefined, |state| state.as_local(lock)); + let arguments = [state]; + let arguments = &arguments[..argument_count]; + let mut remaining = match &controller.run.borrow().case { + Some(case) => case.remaining, + None => unreachable!("a batch runs in a case"), + }; + + let mut awaiting = false; + let result = (|| -> jsg::Result<()> { + while remaining > 0 { + remaining -= 1; + awaiting = lock.with_handle_scope(|lock, _| -> jsg::Result { + let result = func.call(lock, receiver, arguments)?; + let promise = v8::Local::::try_from(result).ok(); + match returns_promise { + Some(expected) if expected != promise.is_some() => { + return Err(jsg::Error::new_error(MIXED_RESULTS)); + } + _ => returns_promise = Some(promise.is_some()), + } + let Some(promise) = promise else { + return Ok(false); + }; + react_to(lock, this, promise, on_call_fulfilled, on_case_rejected)?; + Ok(true) + })?; + if awaiting { + return Ok(()); + } + } + Ok(()) + })(); + // The clocks are read once the batch is done, not before each wait. + let end = if awaiting { + Timing::default() + } else { + clock::now() + }; + let controller = this.get(lock); + controller.cases.borrow()[controller.run.borrow().index] + .returns_promise + .set(returns_promise); + result?; + { + let mut run = controller.run.borrow_mut(); + let Some(case) = run.case.as_mut() else { + unreachable!("a batch runs in a case"); + }; + case.remaining = remaining; + if awaiting { + return Ok(None); + } + case.timing = end - case.start; + } + + // The teardown and the next batch run in a reaction, as when the batch's result is a promise. + let undefined = lock.undefined(); + let resolved = v8::Promise::resolved(lock, undefined)?; + react_to(lock, this, resolved, on_batch_timed, on_case_rejected)?; + Ok(None) +} + +/// Calls the case's teardown, if it has one, with the batch's state, then goes on. +fn tear_down( + lock: &mut jsg::Lock<'_>, + this: &jsg::Rc, +) -> jsg::Result> { + let controller = this.get(lock); + let undefined = lock.undefined(); + let state = controller + .state + .borrow_mut(lock) + .take() + .map_or(undefined, |state| state.as_local(lock)); + let (teardown, receiver) = { + let cases = controller.cases.borrow(); + let case = &cases[controller.run.borrow().index]; + ( + case.teardown + .as_ref() + .map(|teardown| teardown.as_local(lock)), + case.options.as_ref().map(|options| options.as_local(lock)), + ) + }; + let Some(teardown) = teardown else { + return next_batch(lock, this); + }; + let result = teardown.call(lock, receiver, &[state])?; + let result = v8::Promise::resolved(lock, result)?; + react_to(lock, this, result, on_teardown_fulfilled, on_case_rejected)?; + Ok(None) +} + +/// Advances the case's phase with the batch just timed, then runs the next batch, or returns the +/// case's result once it has all its samples. +#[expect( + clippy::cast_precision_loss, + reason = "samples are per-call times, which the report holds as doubles" +)] +fn next_batch( + lock: &mut jsg::Lock<'_>, + this: &jsg::Rc, +) -> jsg::Result> { + let controller = this.get(lock); + let finished = { + let cases = controller.cases.borrow(); + let mut run = controller.run.borrow_mut(); + let index = run.index; + let case = &cases[index]; + let Some(case_run) = run.case.as_mut() else { + unreachable!("a batch runs in a case"); + }; + let timing = case_run.timing; + let wall_ns = timing.wall_ns.max(0).unsigned_abs(); + let grow = |case_run: &mut CaseRun| { + if wall_ns < case_run.target_batch_ns && case_run.calls < MAX_CALLS_PER_BATCH { + case_run.calls *= 2; + true + } else { + false + } + }; + match case_run.phase { + Phase::Warmup => { + case_run.warmed_up_ns += wall_ns; + if case_run.warmed_up_ns < case.budget.warmup_ns { + grow(case_run); + } else if case.budget.batch > 0 { + case_run.phase = Phase::Sample; + case_run.calls = case.budget.batch; + } else { + case_run.phase = Phase::Calibrate; + } + None + } + Phase::Calibrate => { + if !grow(case_run) { + case_run.phase = Phase::Sample; + } + None + } + Phase::Sample => { + let calls = case_run.calls as f64; + case_run.wall_ns.push(timing.wall_ns as f64 / calls); + case_run.cpu_ns.push(timing.cpu_ns as f64 / calls); + let sampled = case_run.wall_ns.len() == case.budget.samples as usize; + sampled + .then(|| run.case.take()) + .flatten() + .map(|case_run| CaseResult { + name: case.name.clone(), + status: Status::Ok, + error: None, + iterations_per_sample: case_run.calls, + wall_ns: case_run.wall_ns, + cpu_ns: case_run.cpu_ns, + returns_promise: case.returns_promise.get().unwrap_or(false), + }) + } + } + }; + if finished.is_none() { + step(lock, this)?; + } + Ok(finished) +} + +/// The case in progress failed with `exception`: returns its result. +fn fail_case<'s>( + lock: &mut jsg::Lock<'s>, + this: &jsg::Rc, + exception: v8::Local<'s, v8::Value>, +) -> jsg::Result { + let error = describe_exception(lock, exception)?; + let controller = this.get(lock); + controller.state.borrow_mut(lock).take(); + let name = controller.cases.borrow()[controller.run.borrow().index] + .name + .clone(); + controller.run.borrow_mut().case = None; + Ok(CaseResult { + name, + status: Status::Failed, + error: Some(error), + iterations_per_sample: 0, + wall_ns: Vec::new(), + cpu_ns: Vec::new(), + returns_promise: false, + }) +} + +fn finish_case( + lock: &mut jsg::Lock<'_>, + this: &jsg::Rc, + result: CaseResult, +) -> jsg::Result<()> { + { + let mut run = this.get(lock).run.borrow_mut(); + run.results.push(result); + run.index += 1; + } + next_case(lock, this) +} + +fn finish_stage(lock: &mut jsg::Lock<'_>, this: &jsg::Rc) -> jsg::Result<()> { + let controller = this.get(lock); + let (stage, results) = { + let mut run = controller.run.borrow_mut(); + (run.stage, std::mem::take(&mut run.results)) + }; + match stage { + Stage::Overhead { begin } => { + controller.cases.borrow_mut(lock).truncate(begin); + for case in &results { + if case.status != Status::Ok { + return Err(jsg::Error::new_error(format!( + "Measuring the runner's overhead failed: {}", + String::from_utf8_lossy(case.error.as_deref().unwrap_or_default()) + ))); + } + } + let [sync, async_, black_box] = results.as_slice() else { + unreachable!("three internal cases ran"); + }; + debug_assert!(!sync.returns_promise && async_.returns_promise); + let overhead = Overhead { + sync_ns: bench_core::median(&sync.wall_ns), + sync_cpu_ns: bench_core::median(&sync.cpu_ns), + async_ns: bench_core::median(&async_.wall_ns), + async_cpu_ns: bench_core::median(&async_.cpu_ns), + black_box_ns: bench_core::median(&black_box.wall_ns), + }; + MEASURED_OVERHEAD.set(Some(overhead)); + controller.run.borrow_mut().overhead = Some(overhead); + start_stage(lock, this, Stage::Cases, 0, begin) + } + Stage::Cases => { + let overhead = controller.run.borrow().overhead; + settle_group( + lock, + this, + &GroupResult { + error: None, + cases: results, + overhead, + }, + ) + } + } +} + +/// Resolves the group's promise with `group`. +fn settle_group( + lock: &mut jsg::Lock<'_>, + this: &jsg::Rc, + group: &GroupResult, +) -> jsg::Result<()> { + let words = bench_core::encode_group(group) + .map_err(|err| jsg::Error::new_internal_error(err.to_string()))?; + let bytes: Vec = words.iter().flat_map(|word| word.to_ne_bytes()).collect(); + let buffer = v8::ArrayBuffer::new(lock, &bytes); + settle(lock, this, Ok(buffer.into())) +} + +/// Resolves the group's promise with `outcome`'s value, or rejects it with its exception. Does +/// nothing if it has already settled. +fn settle<'s>( + lock: &mut jsg::Lock<'s>, + this: &jsg::Rc, + outcome: Result, v8::Local<'s, v8::Value>>, +) -> jsg::Result<()> { + let Some(resolver) = this.get(lock).resolver.borrow_mut(lock).take() else { + return Ok(()); + }; + let resolver = resolver.as_local(lock); + match outcome { + Ok(value) => resolver.resolve(lock, value), + Err(exception) => resolver.reject(lock, exception), + } +} diff --git a/src/workerd/api/bench-core/BUILD.bazel b/src/workerd/api/bench-core/BUILD.bazel index f87d99faf7b..9e5383ad298 100644 --- a/src/workerd/api/bench-core/BUILD.bazel +++ b/src/workerd/api/bench-core/BUILD.bazel @@ -1,15 +1,13 @@ load("//:build/wd_rust_crate.bzl", "wd_rust_crate") # The parts of `workerd bench` that need no JSG: statistics over a group's samples, written as a -# `BenchReport.Group` (bench.capnp), and the timing of startup groups. With no JSG dependencies, -# both the worker side (api/bench.c++) and the server (workerd-server) can use it. +# `BenchReport.Group` (bench.capnp), the timing of startup groups, and the clocks. With no JSG +# dependencies, both the controller (bench-api) and the server (workerd-server) can use it. wd_rust_crate( name = "bench-core", cxx_bridge_deps = ["@capnp-cpp//src/kj"], cxx_bridge_hdrs = ["glob-filter.h"], - cxx_bridge_src = "ffi.rs", - cxx_bridge_srcs = ["glob_filter.rs"], - cxx_bridge_visibility = ["//visibility:public"], + cxx_bridge_src = "glob_filter.rs", test_deps = ["@crates_vendor//futures"], visibility = ["//visibility:public"], deps = [ @@ -17,5 +15,8 @@ wd_rust_crate( "//src/workerd/io:bench_capnp_rust", "@crates_vendor//capnp", "@crates_vendor//thiserror", - ], + ] + select({ + "@platforms//os:windows": [], + "//conditions:default": ["@crates_vendor//libc"], + }), ) diff --git a/src/workerd/api/bench-core/clock-test.rs b/src/workerd/api/bench-core/clock-test.rs new file mode 100644 index 00000000000..00eeaccf3ff --- /dev/null +++ b/src/workerd/api/bench-core/clock-test.rs @@ -0,0 +1,28 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +use super::*; + +#[test] +fn clocks_advance_with_work() { + let start = now(); + let mut x = 0u64; + while (now() - start).wall_ns < 20_000_000 { + x = std::hint::black_box(x.wrapping_add(1)); + } + let elapsed = now() - start; + assert!(elapsed.wall_ns >= 20_000_000); + // A busy loop on this thread uses CPU time, though the scheduler may run others too. + assert!(elapsed.cpu_ns > 0); +} + +#[test] +fn monotonic_never_goes_back() { + let mut last = now().wall_ns; + for _ in 0..10_000 { + let next = now().wall_ns; + assert!(next >= last); + last = next; + } +} diff --git a/src/workerd/api/bench-core/clock.rs b/src/workerd/api/bench-core/clock.rs new file mode 100644 index 00000000000..b48d413ce65 --- /dev/null +++ b/src/workerd/api/bench-core/clock.rs @@ -0,0 +1,103 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +//! The clocks that `workerd bench` times with: the monotonic clock, as KJ's +//! `systemPreciseMonotonicClock()` reads it, and the calling thread's CPU time. + +#![allow( + unsafe_code, + reason = "reads the clocks through the C library, or through Win32 on Windows" +)] + +use crate::Timing; + +/// Reads both clocks. The difference of two readings times the code between them. +#[must_use] +pub fn now() -> Timing { + Timing { + wall_ns: monotonic_ns(), + cpu_ns: thread_cpu_ns(), + } +} + +#[cfg(unix)] +fn monotonic_ns() -> i64 { + clock_ns(libc::CLOCK_MONOTONIC) +} + +#[cfg(unix)] +fn thread_cpu_ns() -> i64 { + clock_ns(libc::CLOCK_THREAD_CPUTIME_ID) +} + +#[cfg(unix)] +fn clock_ns(clock: libc::clockid_t) -> i64 { + let mut ts = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + // SAFETY: `ts` is a valid, writable timespec. Both clocks exist wherever workerd runs, so the + // call can't fail, as KJ_SYSCALL asserts in C++. + let result = unsafe { libc::clock_gettime(clock, &raw mut ts) }; + debug_assert_eq!(result, 0, "clock_gettime() failed"); + ts.tv_sec * 1_000_000_000 + ts.tv_nsec +} + +/// QueryPerformanceCounter(), which KJ's precise monotonic clock reads on Windows, and so does +/// `Instant`. +#[cfg(windows)] +fn monotonic_ns() -> i64 { + use std::sync::OnceLock; + use std::time::Instant; + static ORIGIN: OnceLock = OnceLock::new(); + let elapsed = ORIGIN.get_or_init(Instant::now).elapsed(); + i64::try_from(elapsed.as_nanos()).unwrap_or(i64::MAX) +} + +/// GetThreadTimes() only advances on scheduler ticks (about 15ms), so with 1ms batches the CPU +/// time samples on Windows are mostly noise. Windows has no precise thread CPU clock. +#[cfg(windows)] +fn thread_cpu_ns() -> i64 { + use std::ffi::c_void; + + #[repr(C)] + #[derive(Default)] + struct FileTime { + low: u32, + high: u32, + } + + #[link(name = "kernel32")] + unsafe extern "system" { + fn GetCurrentThread() -> *mut c_void; + fn GetThreadTimes( + thread: *mut c_void, + creation: *mut FileTime, + exit: *mut FileTime, + kernel: *mut FileTime, + user: *mut FileTime, + ) -> i32; + } + + let (mut creation, mut exit, mut kernel, mut user) = Default::default(); + // SAFETY: GetCurrentThread() returns a pseudo-handle that needs no closing, and the four + // pointers are to valid, writable FILETIMEs. + let ok = unsafe { + GetThreadTimes( + GetCurrentThread(), + &raw mut creation, + &raw mut exit, + &raw mut kernel, + &raw mut user, + ) + }; + debug_assert_ne!(ok, 0, "GetThreadTimes() failed"); + let ticks = |t: &FileTime| (i64::from(t.high) << 32) | i64::from(t.low); + // FILETIME counts 100 ns ticks. + (ticks(&kernel) + ticks(&user)) * 100 +} + +#[cfg(test)] +#[path = "clock-test.rs"] +mod tests; diff --git a/src/workerd/api/bench-core/ffi-test.rs b/src/workerd/api/bench-core/ffi-test.rs deleted file mode 100644 index fe3ec306ea7..00000000000 --- a/src/workerd/api/bench-core/ffi-test.rs +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) 2026 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 - -use bench_capnp::bench_report; - -use super::*; - -/// The group that `report` encodes, read back as C++ reads it. -fn decode(report: &BenchGroupReport) -> capnp::message::Reader { - let words = report.encode().unwrap(); - let bytes: Vec = words.iter().flat_map(|word| word.to_ne_bytes()).collect(); - capnp::serialize::read_message(bytes.as_slice(), capnp::message::ReaderOptions::new()).unwrap() -} - -fn cases( - message: &capnp::message::Reader, -) -> capnp::struct_list::Reader<'_, bench_report::case::Owned> { - message - .get_root::>() - .unwrap() - .get_cases() - .unwrap() -} - -/// Adds a failed case named `name`, without samples. -fn add_failed(report: &mut BenchGroupReport, name: &[u8]) { - report - .add_case(name, Status::Failed as u16, 0, &[], &[], false) - .unwrap(); -} - -#[test] -fn an_empty_case_error_is_set() { - let mut report = new_bench_group_report(); - add_failed(&mut report, b"case"); - report.set_case_error(b""); - - let message = decode(&report); - let case = cases(&message).get(0); - assert!(case.has_error()); - assert_eq!(case.get_error().unwrap().as_bytes(), b""); -} - -#[test] -fn a_case_has_no_error_unless_one_is_set() { - let mut report = new_bench_group_report(); - add_failed(&mut report, b"case"); - - let message = decode(&report); - assert!(!cases(&message).get(0).has_error()); -} - -#[test] -fn a_case_error_goes_to_the_case_added_last() { - let mut report = new_bench_group_report(); - add_failed(&mut report, b"first"); - add_failed(&mut report, b"second"); - report.set_case_error(b"boom"); - - let message = decode(&report); - let cases = cases(&message); - assert!(!cases.get(0).has_error()); - assert_eq!(cases.get(1).get_error().unwrap().as_bytes(), b"boom"); -} - -#[test] -fn a_case_error_before_any_case_is_ignored() { - let mut report = new_bench_group_report(); - report.set_case_error(b"boom"); - add_failed(&mut report, b"case"); - - let message = decode(&report); - assert!(!cases(&message).get(0).has_error()); -} - -#[test] -fn strings_that_arent_utf8_are_written_unchanged() { - // A lone surrogate as WTF-8, and a truncated sequence. - let name = b"case \xed\xa0\x80"; - let error = b"error \xe2\x82"; - let mut report = new_bench_group_report(); - report.set_error(error); - add_failed(&mut report, name); - report.set_case_error(error); - - let message = decode(&report); - let group = message - .get_root::>() - .unwrap(); - assert_eq!(group.get_error().unwrap().as_bytes(), error); - let case = group.get_cases().unwrap().get(0); - assert_eq!(case.get_name().unwrap().as_bytes(), name); - assert_eq!(case.get_error().unwrap().as_bytes(), error); -} - -#[test] -fn an_unknown_status_is_an_error() { - let mut report = new_bench_group_report(); - assert!(report.add_case(b"case", 3, 0, &[], &[], false).is_err()); -} diff --git a/src/workerd/api/bench-core/ffi.rs b/src/workerd/api/bench-core/ffi.rs deleted file mode 100644 index 8fabaec9ff2..00000000000 --- a/src/workerd/api/bench-core/ffi.rs +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (c) 2026 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 - -//! The bridge through which C++ hands a group's results to Rust to encode as a -//! `BenchReport.Group`. - -use bench_capnp::bench_report::case::Status; - -use crate::CaseResult; -use crate::GroupResult; -use crate::Overhead; - -#[cxx::bridge(namespace = "workerd::api")] -#[expect(unsafe_code, reason = "the cxx bridge expands to unsafe FFI glue")] -#[expect(clippy::unnecessary_box_returns, reason = "cxx requires a Box")] -mod bridge { - extern "Rust" { - /// A group's results, collected from C++. - type BenchGroupReport; - - fn new_bench_group_report() -> Box; - - /// Sets the group's error: `bench()` itself failed. Strings are bytes, which needn't be - /// UTF-8, and are written to the report unchanged. - fn set_error(self: &mut BenchGroupReport, error: &[u8]); - - /// Sets the overhead that was subtracted; see `BenchReport.Overhead`. - fn set_overhead( - self: &mut BenchGroupReport, - sync_ns: f64, - sync_cpu_ns: f64, - async_ns: f64, - async_cpu_ns: f64, - black_box_ns: f64, - ); - - /// Adds a case. `status` is a `BenchReport.Case.Status`; `returns_promise` selects the - /// overhead that is subtracted. - fn add_case( - self: &mut BenchGroupReport, - name: &[u8], - status: u16, - iterations_per_sample: u64, - wall_ns: &[f64], - cpu_ns: &[f64], - returns_promise: bool, - ) -> Result<()>; - - /// Sets the error of the case added last, even if `error` is empty: a case has an error - /// exactly when this was called for it, as a C++ `kj::Maybe` that is set. - fn set_case_error(self: &mut BenchGroupReport, error: &[u8]); - - /// The group, as an encoded `BenchReport.Group` message (segment table, then segments) - /// in words. - fn encode(self: &BenchGroupReport) -> Result>; - } -} - -/// A group's results, collected from C++. -pub struct BenchGroupReport(GroupResult); - -#[expect(clippy::unnecessary_box_returns, reason = "cxx requires a Box")] -fn new_bench_group_report() -> Box { - Box::new(BenchGroupReport(GroupResult::default())) -} - -impl BenchGroupReport { - fn set_error(&mut self, error: &[u8]) { - self.0.error = Some(error.to_vec()); - } - - fn set_overhead( - &mut self, - sync_ns: f64, - sync_cpu_ns: f64, - async_ns: f64, - async_cpu_ns: f64, - black_box_ns: f64, - ) { - self.0.overhead = Some(Overhead { - sync_ns, - sync_cpu_ns, - async_ns, - async_cpu_ns, - black_box_ns, - }); - } - - fn add_case( - &mut self, - name: &[u8], - status: u16, - iterations_per_sample: u64, - wall_ns: &[f64], - cpu_ns: &[f64], - returns_promise: bool, - ) -> Result<(), capnp::NotInSchema> { - self.0.cases.push(CaseResult { - name: name.to_vec(), - status: Status::try_from(status)?, - error: None, - iterations_per_sample, - wall_ns: wall_ns.to_vec(), - cpu_ns: cpu_ns.to_vec(), - returns_promise, - }); - Ok(()) - } - - fn set_case_error(&mut self, error: &[u8]) { - if let Some(case) = self.0.cases.last_mut() { - case.error = Some(error.to_vec()); - } - } - - fn encode(&self) -> Result, crate::Error> { - crate::encode_group(&self.0) - } -} - -#[cfg(test)] -#[path = "ffi-test.rs"] -mod tests; diff --git a/src/workerd/api/bench-core/lib.rs b/src/workerd/api/bench-core/lib.rs index 16615c9728a..349db644579 100644 --- a/src/workerd/api/bench-core/lib.rs +++ b/src/workerd/api/bench-core/lib.rs @@ -8,16 +8,18 @@ //! This crate root turns the samples that the runner took for a group's cases into a //! `BenchReport.Group` (bench.capnp), with summary statistics computed after subtracting the //! runner's own overhead and flags for results that can't be trusted. The [`startup`] module -//! times a Worker's startup and reports it the same way, and [`GlobFilter`] is the case filter. +//! times a Worker's startup and reports it the same way, [`clock`] reads the clocks both time +//! with, and [`GlobFilter`] is the case filter. //! //! The group's name is left unset, since the caller knows it. //! -//! Names and errors that come through the C++ bridge are bytes, written to the report's `Text` -//! fields unchanged: C++ strings needn't be valid UTF-8, so a Rust `String` couldn't hold all of -//! them. The [`startup`] module makes its own phase names, and gets a failed start's error as a +//! Names and errors are bytes, written to the report's `Text` fields unchanged: they come from +//! JavaScript strings, which needn't be valid UTF-16, as WTF-8, as C++ JSG converts them to a +//! `kj::String`, so a Rust `String` couldn't hold all of them. +//! The [`startup`] module makes its own phase names, and gets a failed start's error as a //! `String`. -mod ffi; +pub mod clock; mod glob_filter; pub mod startup; @@ -30,15 +32,35 @@ use histogram::Options; pub use crate::glob_filter::GlobFilter; /// The sampling budget, when neither the case nor the command line sets one. -const DEFAULT_MIN_TIME_NS: u64 = 1_000_000_000; +pub const DEFAULT_MIN_TIME_NS: u64 = 1_000_000_000; /// The number of samples, when neither the case nor the command line sets one. -const DEFAULT_SAMPLES: u32 = 50; +pub const DEFAULT_SAMPLES: u32 = 50; /// Under `--quick`, the sampling budget and the number of samples are capped at these. -const QUICK_MIN_TIME_NS: u64 = 10_000_000; -const QUICK_SAMPLES: u32 = 5; +pub const QUICK_MIN_TIME_NS: u64 = 10_000_000; +pub const QUICK_SAMPLES: u32 = 5; -const MAX_SAMPLES: u32 = 1_000_000; +/// The most samples a case can ask for. +pub const MAX_SAMPLES: u32 = 1_000_000; + +/// A reading of the monotonic and thread CPU clocks ([`clock::now`]), or the difference of two, +/// which is how long the code between them took, in nanoseconds. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Timing { + pub wall_ns: i64, + pub cpu_ns: i64, +} + +impl std::ops::Sub for Timing { + type Output = Self; + + fn sub(self, start: Self) -> Self { + Self { + wall_ns: self.wall_ns - start.wall_ns, + cpu_ns: self.cpu_ns - start.cpu_ns, + } + } +} /// Samples are recorded into histograms in picoseconds, up to an hour per call. const HISTOGRAM_HIGHEST_PS: i64 = 3_600_000_000_000_000; diff --git a/src/workerd/api/bench-core/startup.rs b/src/workerd/api/bench-core/startup.rs index d54f68d4769..4b33f4d46aa 100644 --- a/src/workerd/api/bench-core/startup.rs +++ b/src/workerd/api/bench-core/startup.rs @@ -24,6 +24,7 @@ use crate::GroupResult; use crate::MAX_SAMPLES; use crate::QUICK_MIN_TIME_NS; use crate::QUICK_SAMPLES; +use crate::Timing; /// Untimed starts before a startup group's samples, except under `--quick`. const STARTUP_WARMUPS: u32 = 1; @@ -32,13 +33,6 @@ const STARTUP_WARMUPS: u32 = 1; /// that a slow Worker still gets usable statistics. const STARTUP_MIN_SAMPLES: usize = 5; -/// A reading of how long something took on the monotonic and thread CPU clocks, in nanoseconds. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct Timing { - pub wall_ns: i64, - pub cpu_ns: i64, -} - /// How long the phases of starting one Worker took; see `BenchReport.Group.startup` for what each /// covers. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] diff --git a/src/workerd/api/bench-test.c++ b/src/workerd/api/bench-test.c++ deleted file mode 100644 index b6443a5fc71..00000000000 --- a/src/workerd/api/bench-test.c++ +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) 2026 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 - -#include "bench.h" - -#include -#include - -#include - -namespace workerd::api { -namespace { - -// Statistics come from a histogram with three significant figures. -bool near(double actual, double expected) { - return std::abs(actual - expected) <= expected * 0.001 + 0.001; -} - -// fillBenchReport() is a shim over the Rust bench-core crate, whose tests (lib-test.rs) cover the -// statistics. These cover what the shim does: handing the results over and copying the encoded -// group into the report. - -// A case of `sampleCount` samples of `sampleNs`, wall and CPU. -BenchCaseResult makeCase(kj::StringPtr name, size_t sampleCount, double sampleNs) { - BenchCaseResult c{ - .name = kj::str(name), - .iterationsPerSample = 100, - .wallNs = kj::heapArray(sampleCount), - .cpuNs = kj::heapArray(sampleCount), - }; - for (auto& sample: c.wallNs) sample = sampleNs; - for (auto& sample: c.cpuNs) sample = sampleNs; - return c; -} - -KJ_TEST("fillBenchReport copies the group that Rust encodes into the report") { - auto failed = makeCase("fails \xff", 5, 100); - failed.status = bench::BenchReport::Case::Status::FAILED; - failed.error = kj::str(""); - BenchGroupResult result{ - .error = kj::str("bench() threw"), - .cases = kj::arr(makeCase("ok", 5, 100), kj::mv(failed)), - .overhead = - BenchOverhead{ - .syncNs = 10, .syncCpuNs = 8, .asyncNs = 1000, .asyncCpuNs = 900, .blackBoxNs = 2}, - }; - capnp::MallocMessageBuilder message; - auto group = message.initRoot(); - fillBenchReport(result, group); - - auto report = group.asReader(); - KJ_EXPECT(report.getError() == "bench() threw"); - KJ_EXPECT(report.getOverhead().getSyncNs() == 10); - KJ_EXPECT(report.getOverhead().getBlackBoxNs() == 2); - auto cases = report.getCases(); - KJ_ASSERT(cases.size() == 2); - KJ_EXPECT(cases[0].getName() == "ok"); - KJ_EXPECT(!cases[0].hasError()); - KJ_EXPECT(cases[0].getIterationsPerSample() == 100); - KJ_EXPECT(cases[0].getWallNs().getSamples().size() == 5); - KJ_EXPECT(near(cases[0].getWallNs().getMedian(), 90), cases[0].getWallNs().getMedian()); - // Names and errors are copied as bytes, and an empty error is still an error. - KJ_EXPECT(cases[1].getName() == "fails \xff"); - KJ_EXPECT(cases[1].getStatus() == bench::BenchReport::Case::Status::FAILED); - KJ_EXPECT(cases[1].hasError()); - KJ_EXPECT(cases[1].getError() == ""); -} - -KJ_TEST("fillBenchReport writes groups larger than capnp's default traversal limit") { - // 5 cases of MAX_SAMPLES wall and CPU samples are 10M words, past the default limit of 8M - // words for reading a message. - constexpr size_t CASES = 5; - constexpr size_t SAMPLES = 1'000'000; - auto cases = kj::heapArrayBuilder(CASES); - for (size_t i = 0; i < CASES; i++) { - cases.add(makeCase(kj::str("case ", i), SAMPLES, 100)); - } - BenchGroupResult result{.cases = cases.finish()}; - capnp::MallocMessageBuilder message; - auto group = message.initRoot(); - fillBenchReport(result, group); - - auto report = group.asReader(); - KJ_ASSERT(report.getCases().size() == CASES); - for (auto c: report.getCases()) { - KJ_EXPECT(c.getWallNs().getSamples().size() == SAMPLES); - KJ_EXPECT(c.getCpuNs().getSamples().size() == SAMPLES); - } -} - -} // namespace -} // namespace workerd::api diff --git a/src/workerd/api/bench.c++ b/src/workerd/api/bench.c++ deleted file mode 100644 index f2039587ee8..00000000000 --- a/src/workerd/api/bench.c++ +++ /dev/null @@ -1,535 +0,0 @@ -// Copyright (c) 2026 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 - -#include "bench.h" - -#include -#include -#include - -#include - -#include -#include - -#include -#include - -#if _WIN32 -#include -#else -#include -#endif - -namespace workerd::api { - -namespace { - -// TODO(cleanup): DEFAULT_MIN_TIME_NS, DEFAULT_SAMPLES, QUICK_MIN_TIME_NS, QUICK_SAMPLES and -// MAX_SAMPLES are also defined in the bench-core crate (src/workerd/api/bench-core), which -// times startup groups with them. These copies go away when BenchController moves to Rust. - -// Defaults for options that neither the case nor the command line sets. -constexpr uint64_t DEFAULT_MIN_TIME_NS = 1'000'000'000; -constexpr uint64_t DEFAULT_WARMUP_NS = 200'000'000; -constexpr uint32_t DEFAULT_SAMPLES = 50; - -// Under --quick, budgets are capped at these. -constexpr uint64_t QUICK_MIN_TIME_NS = 10'000'000; -constexpr uint64_t QUICK_WARMUP_NS = 2'000'000; -constexpr uint32_t QUICK_SAMPLES = 5; - -// A calibrated batch takes at least this long, so that clock resolution and the cost of reading -// the clocks don't matter. -constexpr uint64_t MIN_BATCH_NS = 1'000'000; - -constexpr uint64_t MAX_CALLS_PER_BATCH = uint64_t{1} << 40; -constexpr uint32_t MAX_SAMPLES = 1'000'000; - -// Budgets for the cases that measure overhead, which are capped further under --quick. -constexpr uint64_t OVERHEAD_MIN_TIME_NS = 200'000'000; -constexpr uint64_t OVERHEAD_WARMUP_NS = 50'000'000; -constexpr uint32_t OVERHEAD_SAMPLES = 20; - -// The overhead is measured once per thread. `workerd bench` runs every group on the same thread, -// so all groups in a run share one measurement. -thread_local kj::Maybe measuredOverhead; - -int64_t monotonicNs() { - return (kj::systemPreciseMonotonicClock().now() - kj::origin()) / kj::NANOSECONDS; -} - -int64_t threadCpuNs() { -#if _WIN32 - // GetThreadTimes() only advances on scheduler ticks (about 15ms), so with 1ms batches the CPU - // time samples on Windows are mostly noise. Windows has no precise thread CPU clock. - FILETIME creation, exit, kernel, user; - KJ_ASSERT(GetThreadTimes(GetCurrentThread(), &creation, &exit, &kernel, &user)); - auto ticks = [](const FILETIME& t) { - return (static_cast(t.dwHighDateTime) << 32) | t.dwLowDateTime; - }; - // FILETIME counts 100 ns ticks. - return (ticks(kernel) + ticks(user)) * 100; -#else - struct timespec ts; - KJ_SYSCALL(clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts)); - return static_cast(ts.tv_sec) * 1'000'000'000 + ts.tv_nsec; -#endif -} - -uint64_t durationToNs(double ns, kj::StringPtr what) { - JSG_REQUIRE(std::isfinite(ns) && ns >= 0 && ns < 1e18, RangeError, what, - " must be a non-negative duration."); - return static_cast(ns); -} - -uint64_t parseDuration(const BenchDuration& duration, kj::StringPtr what) { - KJ_SWITCH_ONEOF(duration) { - KJ_CASE_ONEOF(ms, double) { - return durationToNs(ms * 1e6, what); - } - KJ_CASE_ONEOF(text, kj::String) { - size_t numberEnd = 0; - while (numberEnd < text.size() && - (('0' <= text[numberEnd] && text[numberEnd] <= '9') || text[numberEnd] == '.')) { - ++numberEnd; - } - auto number = - JSG_REQUIRE_NONNULL(kj::str(text.first(numberEnd)).tryParseAs(), TypeError, what, - " must be a number of milliseconds or a string like \"500ms\" or \"2s\"."); - auto unit = text.slice(numberEnd); - double scale; - if (unit == "ns"_kj) { - scale = 1; - } else if (unit == "us"_kj || unit == "µs"_kj) { - scale = 1e3; - } else if (unit == "ms"_kj || unit == ""_kj) { - scale = 1e6; - } else if (unit == "s"_kj) { - scale = 1e9; - } else { - JSG_FAIL_REQUIRE(TypeError, what, " has an unknown unit \"", unit, - "\"; use \"ns\", \"us\", \"ms\", or \"s\"."); - } - return durationToNs(number * scale, what); - } - } - KJ_UNREACHABLE; -} - -uint64_t parseCount(double value, uint64_t max, kj::StringPtr what) { - JSG_REQUIRE(value >= 1 && value <= static_cast(max) && value == std::floor(value), - RangeError, what, " must be an integer from 1 to ", max, "."); - return static_cast(value); -} - -// TODO(cleanup): Same as `median()` in the bench-core crate (src/workerd/api/bench-core), -// which the report uses. Its only remaining user here is the overhead measurement, and it goes -// away when BenchController moves to Rust. -double median(kj::ArrayPtr samples) { - KJ_ASSERT(samples.size() > 0); - auto sorted = kj::heapArray(samples); - std::sort(sorted.begin(), sorted.end()); - auto middle = sorted.size() / 2; - return sorted.size() % 2 == 1 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2; -} - -// A promise for `value`, awaiting it if it is a promise. -jsg::Promise settle(jsg::Lock& js, jsg::Value value) { - if (value.getHandle(js)->IsPromise()) { - return js.toPromise(value.getHandle(js)); - } - return js.resolvedPromise(kj::mv(value)); -} - -} // namespace - -kj::String describeBenchException(jsg::Lock& js, const jsg::Value& exception) { - return js.tryCatch([&]() -> kj::String { - auto value = jsg::JsValue(exception.getHandle(js)); - KJ_IF_SOME(object, value.tryCast()) { - auto stack = object.get(js, "stack"); - if (stack.isString()) { - return stack.toString(js); - } - } - return value.toString(js); - }, [](jsg::Value&&) { return kj::str("(an exception that can't be converted to a string)"); }); -} - -void fillBenchReport(const BenchGroupResult& result, bench::BenchReport::Group::Builder report) { - auto group = new_bench_group_report(); - KJ_IF_SOME(error, result.error) { - group->set_error(error.asBytes().as()); - } - KJ_IF_SOME(o, result.overhead) { - group->set_overhead(o.syncNs, o.syncCpuNs, o.asyncNs, o.asyncCpuNs, o.blackBoxNs); - } - for (auto& c: result.cases) { - group->add_case(c.name.asBytes().as(), static_cast(c.status), - c.iterationsPerSample, c.wallNs.as(), c.cpuNs.as(), c.async); - KJ_IF_SOME(error, c.error) { - group->set_case_error(error.asBytes().as()); - } - } - - auto words = group->encode(); - // A group holds up to MAX_SAMPLES wall and CPU samples per case, which can be more than the - // default traversal limit. - capnp::FlatArrayMessageReader message( - kj::arrayPtr(reinterpret_cast(words.data()), words.size()), - capnp::ReaderOptions{.traversalLimitInWords = kj::maxValue}); - auto encoded = message.getRoot(); - if (encoded.hasError()) { - report.setError(encoded.getError()); - } - if (encoded.hasOverhead()) { - report.setOverhead(encoded.getOverhead()); - } - report.setCases(encoded.getCases()); -} - -BenchTiming BenchTiming::now() { - return {.wallNs = monotonicNs(), .cpuNs = threadCpuNs()}; -} - -struct BenchController::CaseRun { - enum class Phase { WARMUP, CALIBRATE, SAMPLE }; - - size_t index; - Phase phase; - uint64_t calls = 1; - uint64_t warmedUpNs = 0; - // Calibration grows batches until one takes at least this long. - uint64_t targetBatchNs; - kj::Vector wallNs; - kj::Vector cpuNs; -}; - -BenchController::BenchController(bench::BenchParams::Reader params) - : caseFilter(kj::str(params.getCaseFilter())), - quick(params.getQuick()) { - // Only `workerd bench` delivers the bench event; fail closed anywhere else. - KJ_REQUIRE(isBenchMode(), "the bench event is only supported by `workerd bench`"); - - auto defaults = params.getDefaults(); - defaultMinTimeNs = defaults.getMinTimeNs() > 0 ? defaults.getMinTimeNs() : DEFAULT_MIN_TIME_NS; - defaultWarmupNs = defaults.getWarmupNs() > 0 ? defaults.getWarmupNs() : DEFAULT_WARMUP_NS; - defaultSamples = defaults.getSamples() > 0 ? defaults.getSamples() : DEFAULT_SAMPLES; - defaultBatch = defaults.getBatch(); -} - -void BenchController::run(jsg::Lock& js, - kj::String name, - v8::Local fn, - jsg::Optional maybeOptions) { - JSG_REQUIRE(!running, Error, - "BenchController.run() must be called by bench(), before it returns or its promise " - "resolves."); - for (auto& c: cases) { - JSG_REQUIRE(c.name != name, Error, "A case named \"", name, "\" is already registered."); - } - - auto options = kj::mv(maybeOptions).orDefault({}); - Case c{ - .name = kj::mv(name), - .fn = js.v8Ref(fn), - .setup = kj::mv(options.setup), - .teardown = kj::mv(options.teardown), - .skip = options.skip.orDefault(false), - .minTimeNs = defaultMinTimeNs, - .warmupNs = defaultWarmupNs, - .samples = defaultSamples, - .batch = defaultBatch, - }; - KJ_IF_SOME(minTime, options.minTime) { - c.minTimeNs = parseDuration(minTime, "minTime"); - } - KJ_IF_SOME(warmup, options.warmup) { - c.warmupNs = parseDuration(warmup, "warmup"); - } - KJ_IF_SOME(samples, options.samples) { - c.samples = static_cast(parseCount(samples, MAX_SAMPLES, "samples")); - } - KJ_IF_SOME(batch, options.batch) { - c.batch = parseCount(batch, MAX_CALLS_PER_BATCH, "batch"); - } - if (quick) { - c.minTimeNs = kj::min(c.minTimeNs, QUICK_MIN_TIME_NS); - c.warmupNs = kj::min(c.warmupNs, QUICK_WARMUP_NS); - c.samples = kj::min(c.samples, QUICK_SAMPLES); - } - cases.add(kj::mv(c)); -} - -BenchController::Options BenchController::getOptions() { - return { - .filter = - caseFilter == ""_kj || caseFilter == "*"_kj ? kj::none : kj::Maybe(kj::str(caseFilter)), - .quick = quick, - }; -} - -jsg::Promise BenchController::runCases(jsg::Lock& js) { - running = true; - if (cases.empty()) { - return js.resolvedPromise(BenchGroupResult{ - .error = kj::str("bench() did not register any cases."), - }); - } - return measureOverhead(js).then( - js, IoContext::current().addFunctor([self = JSG_THIS](jsg::Lock& js) mutable { - return self->runCasesFrom(js, 0, self->cases.size(), {}); - })); -} - -jsg::Promise BenchController::measureOverhead(jsg::Lock& js) { - KJ_IF_SOME(o, measuredOverhead) { - overhead = o; - return js.resolvedPromise(); - } - - // The internal cases go after the user's, and are removed once they have run. - auto begin = cases.size(); - auto addCase = [&](kj::StringPtr name, v8::Local fn, - kj::Maybe> receiver = kj::none) { - cases.add(Case{ - .name = kj::str(name), - .fn = js.v8Ref(fn), - .receiver = receiver.map([&](v8::Local r) { return js.v8Ref(r); }), - .passArgument = receiver != kj::none, - .skip = false, - .minTimeNs = quick ? QUICK_MIN_TIME_NS : OVERHEAD_MIN_TIME_NS, - .warmupNs = quick ? QUICK_WARMUP_NS : OVERHEAD_WARMUP_NS, - .samples = quick ? QUICK_SAMPLES : OVERHEAD_SAMPLES, - .batch = 0, - .internal = true, - }); - }; - auto context = js.v8Context(); - addCase("(empty)"_kj, - jsg::check(v8::Function::New(context, [](const v8::FunctionCallbackInfo&) {}))); - addCase("(empty async)"_kj, - jsg::check(v8::Function::New(context, [](const v8::FunctionCallbackInfo& info) { - auto isolate = info.GetIsolate(); - auto context = isolate->GetCurrentContext(); - auto resolver = jsg::check(v8::Promise::Resolver::New(context)); - jsg::check(resolver->Resolve(context, v8::Undefined(isolate))); - info.GetReturnValue().Set(resolver->GetPromise()); - }))); - // `blackBox(undefined)`, called as a method of this controller. - auto controller = KJ_ASSERT_NONNULL(JSG_THIS.tryGetHandle(js)); - auto blackBox = jsg::JsObject(controller).get(js, "blackBox"_kj); - KJ_ASSERT(blackBox.isFunction()); - addCase("(blackBox)"_kj, v8::Local(blackBox).As(), - v8::Local(controller)); - - return runCasesFrom(js, begin, cases.size(), {}) - .then(js, - IoContext::current().addFunctor( - [self = JSG_THIS, begin](jsg::Lock& js, BenchGroupResult result) mutable { - self->cases.truncate(begin); - for (auto& c: result.cases) { - JSG_REQUIRE(c.status == bench::BenchReport::Case::Status::OK, Error, - "Measuring the runner's overhead failed: ", c.error.orDefault(kj::str())); - } - KJ_ASSERT(result.cases.size() == 3); - KJ_ASSERT(!result.cases[0].async && result.cases[1].async); - BenchOverhead o{ - .syncNs = median(result.cases[0].wallNs), - .syncCpuNs = median(result.cases[0].cpuNs), - .asyncNs = median(result.cases[1].wallNs), - .asyncCpuNs = median(result.cases[1].cpuNs), - .blackBoxNs = median(result.cases[2].wallNs), - }; - measuredOverhead = o; - self->overhead = o; - })); -} - -jsg::Promise BenchController::runCasesFrom( - jsg::Lock& js, size_t index, size_t end, kj::Vector results) { - kj::GlobFilter filter(caseFilter == ""_kj ? "*"_kj : caseFilter.asPtr()); - while (index < end && !cases[index].internal && !filter.matches(cases[index].name)) { - ++index; - } - if (index == end) { - return js.resolvedPromise( - BenchGroupResult{.cases = results.releaseAsArray(), .overhead = overhead}); - } - - return runCase(js, index).then(js, - IoContext::current().addFunctor([self = JSG_THIS, index, end, results = kj::mv(results)]( - jsg::Lock& js, BenchCaseResult result) mutable { - results.add(kj::mv(result)); - return self->runCasesFrom(js, index + 1, end, kj::mv(results)); - })); -} - -jsg::Promise BenchController::runCase(jsg::Lock& js, size_t index) { - auto& c = cases[index]; - if (c.skip) { - return js.resolvedPromise(BenchCaseResult{ - .name = kj::str(c.name), - .status = bench::BenchReport::Case::Status::SKIPPED, - }); - } - - using Phase = CaseRun::Phase; - auto run = kj::heap(CaseRun{ - .index = index, - .phase = c.warmupNs > 0 ? Phase::WARMUP - : c.batch > 0 ? Phase::SAMPLE - : Phase::CALIBRATE, - .calls = c.batch > 0 && c.warmupNs == 0 ? c.batch : 1, - .targetBatchNs = kj::max(c.minTimeNs / c.samples, MIN_BATCH_NS), - }); - - // Starting from a continuation turns exceptions thrown by the first batch into a rejection. - return js.resolvedPromise() - .then(js, - IoContext::current().addFunctor( - [self = JSG_THIS, run = kj::mv(run)](jsg::Lock& js) mutable { - return self->step(js, kj::mv(run)); - })).catch_(js, [name = kj::str(c.name)](jsg::Lock& js, jsg::Value exception) mutable { - return BenchCaseResult{ - .name = kj::mv(name), - .status = bench::BenchReport::Case::Status::FAILED, - .error = describeBenchException(js, exception), - }; - }); -} - -jsg::Promise BenchController::step(jsg::Lock& js, kj::Own run) { - // Yield to the event loop before each batch, so that pending I/O and timers make progress - // outside the timed region. - auto& context = IoContext::current(); - return context.awaitIo( - js, kj::evalLater([] {}), [self = JSG_THIS, run = kj::mv(run)](jsg::Lock& js) mutable { - auto index = run->index; - auto calls = run->calls; - return self->runBatch(js, index, calls) - .then(js, - IoContext::current().addFunctor( - [self = self.addRef(), run = kj::mv(run)]( - jsg::Lock& js, BenchTiming timing) mutable -> jsg::Promise { - using Phase = CaseRun::Phase; - auto& c = self->cases[run->index]; - auto wallNs = static_cast(kj::max(timing.wallNs, int64_t{0})); - auto grow = [&]() { - if (wallNs < run->targetBatchNs && run->calls < MAX_CALLS_PER_BATCH) { - run->calls *= 2; - return true; - } - return false; - }; - - switch (run->phase) { - case Phase::WARMUP: - run->warmedUpNs += wallNs; - if (run->warmedUpNs < c.warmupNs) { - grow(); - } else if (c.batch > 0) { - run->phase = Phase::SAMPLE; - run->calls = c.batch; - } else { - run->phase = Phase::CALIBRATE; - } - break; - case Phase::CALIBRATE: - if (!grow()) { - run->phase = Phase::SAMPLE; - } - break; - case Phase::SAMPLE: { - auto calls = static_cast(run->calls); - run->wallNs.add(static_cast(timing.wallNs) / calls); - run->cpuNs.add(static_cast(timing.cpuNs) / calls); - if (run->wallNs.size() == c.samples) { - return js.resolvedPromise(BenchCaseResult{ - .name = kj::str(c.name), - .iterationsPerSample = run->calls, - .wallNs = run->wallNs.releaseAsArray(), - .cpuNs = run->cpuNs.releaseAsArray(), - .async = c.returnsPromise.orDefault(false), - }); - } - break; - } - } - return self->step(js, kj::mv(run)); - })); - }); -} - -jsg::Promise BenchController::runBatch(jsg::Lock& js, size_t index, uint64_t calls) { - // Times the batch given the setup result (undefined without `setup`), then runs `teardown`. - auto timeBatch = [self = JSG_THIS, index, calls]( - jsg::Lock& js, jsg::Value state) mutable -> jsg::Promise { - if (self->cases[index].teardown == kj::none) { - return self->callBatch(js, index, kj::mv(state), calls, BenchTiming::now()); - } - auto teardownState = state.addRef(js); - return self->callBatch(js, index, kj::mv(state), calls, BenchTiming::now()) - .then(js, - IoContext::current().addFunctor( - [self = self.addRef(), index, state = kj::mv(teardownState)]( - jsg::Lock& js, BenchTiming timing) mutable { - auto& teardown = KJ_ASSERT_NONNULL(self->cases[index].teardown); - return settle(js, teardown(js, kj::mv(state))).then(js, [timing](jsg::Lock&, jsg::Value) { - return timing; - }); - })); - }; - - KJ_IF_SOME(setup, cases[index].setup) { - return settle(js, setup(js)).then(js, IoContext::current().addFunctor(kj::mv(timeBatch))); - } - return timeBatch(js, js.v8Ref(js.v8Undefined())); -} - -jsg::Promise BenchController::callBatch( - jsg::Lock& js, size_t index, jsg::Value state, uint64_t remaining, BenchTiming start) { - auto& c = cases[index]; - auto isolate = js.v8Isolate; - auto context = js.v8Context(); - auto fn = c.fn.getHandle(js); - v8::Local receiver = js.v8Undefined(); - KJ_IF_SOME(r, c.receiver) { - receiver = r.getHandle(js); - } - v8::Local argument = state.getHandle(js); - int argumentCount = c.setup != kj::none || c.passArgument ? 1 : 0; - - while (remaining > 0) { - v8::HandleScope scope(isolate); - --remaining; - auto result = jsg::check(fn->Call(context, receiver, argumentCount, &argument)); - bool isPromise = result->IsPromise(); - KJ_IF_SOME(expected, c.returnsPromise) { - JSG_REQUIRE(isPromise == expected, Error, - "The function returned a promise from some calls but not from others. It must either " - "always or never return a promise."); - } else { - c.returnsPromise = isPromise; - } - if (isPromise) { - // Await the result before the next call; the batch's time includes the wait. - return js.toPromise(result).then(js, - IoContext::current().addFunctor([self = JSG_THIS, index, state = kj::mv(state), remaining, - start](jsg::Lock& js, jsg::Value) mutable { - return self->callBatch(js, index, kj::mv(state), remaining, start); - })); - } - } - return js.resolvedPromise(BenchTiming::now() - start); -} - -void BenchController::visitForGc(jsg::GcVisitor& visitor) { - for (auto& c: cases) { - visitor.visit(c.fn, c.receiver, c.setup, c.teardown); - } -} - -} // namespace workerd::api diff --git a/src/workerd/api/bench.h b/src/workerd/api/bench.h deleted file mode 100644 index e614fbefecd..00000000000 --- a/src/workerd/api/bench.h +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright (c) 2026 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 - -#pragma once - -// The `bench` handler: `BenchController`, which a Worker's `bench(b, env, ctx)` handler uses to -// register cases, and the runner that times them. Only `workerd bench` dispatches this event. -// -// The runtime runs the timing loop: user code supplies the function to time and never sees a -// high-resolution clock. For each case, the runner calls the function repeatedly to warm up, -// calibrates a batch size, then times `samples` batches, reading the monotonic and thread CPU -// clocks only between batches. Each sample is a batch's time divided by its number of calls. - -#include -#include - -namespace workerd::api { - -// A reading of the monotonic and thread CPU clocks, in nanoseconds. The difference of two -// readings times the code between them. -struct BenchTiming { - int64_t wallNs = 0; - int64_t cpuNs = 0; - - static BenchTiming now(); - BenchTiming operator-(const BenchTiming& other) const { - return {.wallNs = wallNs - other.wallNs, .cpuNs = cpuNs - other.cpuNs}; - } -}; - -// Results of one case, before they are written to a `BenchReport::Case`. -struct BenchCaseResult { - kj::String name; - bench::BenchReport::Case::Status status = bench::BenchReport::Case::Status::OK; - kj::Maybe error; - uint64_t iterationsPerSample = 0; - // Wall and thread CPU time per call, one value per sampled batch, including the runner's - // overhead. - kj::Array wallNs; - kj::Array cpuNs; - // Whether the function returned a promise, which selects the overhead to subtract. - bool async = false; -}; - -// The runner's own cost per call; see `BenchReport.Overhead`. -struct BenchOverhead { - double syncNs; - double syncCpuNs; - double asyncNs; - double asyncCpuNs; - double blackBoxNs; -}; - -// Results of one `bench()` handler. -struct BenchGroupResult { - // Set if `bench()` itself failed. - kj::Maybe error; - kj::Array cases; - // Set once overhead has been measured. - kj::Maybe overhead; -}; - -// The exception's stack if it has one, or else its string conversion. -kj::String describeBenchException(jsg::Lock& js, const jsg::Value& exception); - -// Writes `result` to `report`, computing summary statistics of the samples after subtracting the -// overhead. Doesn't set the group's name, which the caller knows. -void fillBenchReport(const BenchGroupResult& result, bench::BenchReport::Group::Builder report); - -// A duration: a number of milliseconds, or a string with a unit, as in "500ms" or "2s". -using BenchDuration = kj::OneOf; - -// Options for one case, the third argument of `BenchController.run()`. -struct BenchCaseOptions { - // Sampling budget: the batch size is calibrated so that all samples take about this long. - jsg::Optional minTime; - // How long to call the function before calibrating and sampling, to let V8 optimize it. - jsg::Optional warmup; - // The number of batches to time. - jsg::Optional samples; - // Calls per batch, instead of calibrating. - jsg::Optional batch; - // Called before each batch, untimed. Its result (awaited if it is a promise) is passed to every - // call of the function in that batch. - jsg::Optional> setup; - // Called after each batch with the setup result (undefined without `setup`), untimed, and - // awaited if it returns a promise. - jsg::Optional> teardown; - // Reports the case as skipped instead of running it. - jsg::Optional skip; - - JSG_STRUCT(minTime, warmup, samples, batch, setup, teardown, skip); -}; - -// The first argument of a `bench()` handler. -// -// The bench types aren't in the generated TypeScript definitions: only `workerd bench` delivers -// the bench event, so they aren't part of the API that deployed Workers see. Nothing that the -// type generator visits refers to them. -class BenchController final: public jsg::Object { - public: - explicit BenchController(bench::BenchParams::Reader params); - - struct Options { - // The case filter given on the command line, if any. - jsg::Optional filter; - // Whether `--quick` was given: budgets are short, so results only show that cases run. - bool quick; - - JSG_STRUCT(filter, quick); - }; - - // Registers a case. Cases run, in registration order, after `bench()` returns or its promise - // resolves. `fn` may return a promise, which is awaited before the next call. - void run(jsg::Lock& js, - kj::String name, - v8::Local fn, - jsg::Optional options); - - // Returns `value`. Passing a result through it keeps V8 from optimizing away the code that - // computed it, since V8 can't see into the native call. - jsg::JsValue blackBox(jsg::JsValue value) { - return value; - } - - Options getOptions(); - - JSG_RESOURCE_TYPE(BenchController) { - JSG_METHOD(run); - JSG_METHOD(blackBox); - JSG_READONLY_PROTOTYPE_PROPERTY(options, getOptions); - } - - // Runs the registered cases, after the handler has registered them. Called from C++. - jsg::Promise runCases(jsg::Lock& js); - - private: - struct Case { - kj::String name; - jsg::V8Ref fn; - // `this` for calls of `fn`; undefined if none. - kj::Maybe> receiver; - // Whether `fn` gets an argument when there is no `setup`, in which case it is undefined. - bool passArgument = false; - kj::Maybe> setup; - kj::Maybe> teardown; - bool skip; - uint64_t minTimeNs; - uint64_t warmupNs; - uint32_t samples; - // 0 calibrates. - uint64_t batch; - // A case that measures overhead, which the case filter doesn't apply to. - bool internal = false; - // Whether `fn` returns a promise, once it has been called. Every call must agree, since the - // overhead subtracted from the samples depends on it. - kj::Maybe returnsPromise; - }; - - struct CaseRun; - - kj::String caseFilter; - bool quick; - uint64_t defaultMinTimeNs; - uint64_t defaultWarmupNs; - uint32_t defaultSamples; - uint64_t defaultBatch; - - kj::Vector cases; - // Set once the cases start running; registering a case after that is an error. - bool running = false; - kj::Maybe overhead; - - // Measures the overhead, unless this process has already, by running internal cases. - jsg::Promise measureOverhead(jsg::Lock& js); - - // Runs cases[index] through cases[end - 1]. - jsg::Promise runCasesFrom( - jsg::Lock& js, size_t index, size_t end, kj::Vector results); - jsg::Promise runCase(jsg::Lock& js, size_t index); - jsg::Promise step(jsg::Lock& js, kj::Own run); - jsg::Promise runBatch(jsg::Lock& js, size_t index, uint64_t calls); - jsg::Promise callBatch( - jsg::Lock& js, size_t index, jsg::Value state, uint64_t remaining, BenchTiming start); - - void visitForGc(jsg::GcVisitor& visitor); -}; - -#define EW_BENCH_ISOLATE_TYPES \ - api::BenchController, api::BenchController::Options, api::BenchCaseOptions - -} // namespace workerd::api diff --git a/src/workerd/api/global-scope.c++ b/src/workerd/api/global-scope.c++ index 987ecb2a5e2..fb88a7ee515 100644 --- a/src/workerd/api/global-scope.c++ +++ b/src/workerd/api/global-scope.c++ @@ -38,6 +38,8 @@ #include +#include +#include #include namespace workerd::api { @@ -938,30 +940,31 @@ jsg::Promise ServiceWorkerGlobalScope::test( return testHandler(lock, js.alloc(), eh.env.addRef(lock), eh.getCtx()); } -jsg::Promise ServiceWorkerGlobalScope::bench(Worker::Lock& lock, +jsg::Promise> ServiceWorkerGlobalScope::bench(Worker::Lock& lock, kj::Maybe exportedHandler, bench::BenchParams::Reader params) { ExportedHandler& eh = JSG_REQUIRE_NONNULL(exportedHandler, Error, "Benchmarks are not currently supported with Service Workers syntax."); jsg::Lock& js = lock; - auto& typeHandler = lock.getWorker().getIsolate().getApi().getBenchTypeHandler(lock); - auto handlers = JSG_REQUIRE_NONNULL(typeHandler.tryUnwrap(js, eh.self.getHandle(js)), Error, - "Entrypoint does not export a bench() function."); - auto benchHandler = JSG_REQUIRE_NONNULL( - kj::mv(handlers.bench), Error, "Entrypoint does not export a bench() function."); - auto controller = js.alloc(params); - return js - .tryCatch( - [&] { return benchHandler(lock, controller.addRef(), eh.env.addRef(lock), eh.getCtx()); }, - [&](jsg::Value exception) { return js.rejectedPromise(kj::mv(exception)); }) - .then(js, - IoContext::current().addFunctor( - [controller = controller.addRef()]( - jsg::Lock& js) mutable { return controller->runCases(js); }), - [](jsg::Lock& js, jsg::Value exception) { - return js.resolvedPromise(BenchGroupResult{ - .error = describeBenchException(js, exception), - }); + auto& api = lock.getWorker().getIsolate().getApi(); + v8::Local ctx = js.v8Undefined(); + KJ_IF_SOME(c, eh.getCtx()) { + ctx = api.wrapExecutionContext(js, kj::mv(c)); + } + capnp::MallocMessageBuilder paramsMessage; + paramsMessage.setRoot(params); + auto group = api.runBench(js, eh.self.getHandle(js), eh.env.getHandle(js), ctx, + capnp::messageToFlatArray(paramsMessage)); + return js.toPromise(group).then(js, [](jsg::Lock& js, jsg::Value value) { + auto handle = value.getHandle(js); + KJ_ASSERT(handle->IsArrayBuffer(), "the bench runner resolves with an ArrayBuffer"); + auto buffer = handle.As(); + auto bytes = kj::arrayPtr(static_cast(buffer->Data()), buffer->ByteLength()); + KJ_ASSERT(bytes.size() % sizeof(capnp::word) == 0); + // Copied, so that the message is aligned to words. + auto words = kj::heapArray(bytes.size() / sizeof(capnp::word)); + words.asBytes().copyFrom(bytes); + return words; }); } diff --git a/src/workerd/api/global-scope.h b/src/workerd/api/global-scope.h index cef0c10578b..96588bc787d 100644 --- a/src/workerd/api/global-scope.h +++ b/src/workerd/api/global-scope.h @@ -5,7 +5,6 @@ #pragma once #include "basics.h" -#include "bench.h" #include "filesystem.h" #include "http.h" #include "performance.h" @@ -635,20 +634,6 @@ struct ExportedHandler { IsRetryableHandler isFetchRetryable(jsg::Lock& js); }; -// The `bench` handler of an exported object. It isn't a member of ExportedHandler, which is -// unwrapped from the export for every event, reading each of its handlers: reading another name -// there would break exports that reject unknown properties, such as a Proxy. Instead, -// ServiceWorkerGlobalScope::bench() unwraps this from ExportedHandler::self, only when a -// benchmark runs. -struct BenchExportedHandler { - using BenchHandler = jsg::Promise(jsg::Ref controller, - jsg::Value env, - jsg::Optional> ctx); - jsg::LenientOptional> bench; - - JSG_STRUCT(bench); -}; - // V8 private key set on functions marked with retryable() from "cloudflare:durable-objects". // Reading it runs no user code, so a claim can check it before the handler or method runs. inline constexpr auto RETRYABLE_METHOD_PRIVATE_KEY = "cloudflare:durable-objects:retryable"_kjc; @@ -784,9 +769,10 @@ class ServiceWorkerGlobalScope: public WorkerGlobalScope { jsg::Promise test(Worker::Lock& lock, kj::Maybe exportedHandler); // Received bench() (called from C++, not JS). See WorkerInterface::bench(). Runs the handler to - // register cases, then runs them. Failures, of the handler or of a case, are recorded in the - // result rather than rejecting. - jsg::Promise bench(Worker::Lock& lock, + // register cases, then runs them, through Worker::Api::runBench(). Resolves with the group's + // `BenchReport.Group`, without its name, as an encoded message. Failures, of the handler or of + // a case, are recorded in the group rather than rejecting. + jsg::Promise> bench(Worker::Lock& lock, kj::Maybe exportedHandler, bench::BenchParams::Reader params); @@ -1318,10 +1304,9 @@ class ServiceWorkerGlobalScope: public WorkerGlobalScope { #define EW_GLOBAL_SCOPE_ISOLATE_TYPES \ api::WorkerGlobalScope, api::ServiceWorkerGlobalScope, api::TestController, \ - EW_BENCH_ISOLATE_TYPES, api::ExecutionContext, api::ExportedHandler, \ - api::BenchExportedHandler, api::ServiceWorkerGlobalScope::StructuredCloneOptions, \ - api::Navigator, api::AlarmInvocationInfo, api::Immediate, api::Cloudflare, \ - api::CachePurgeError, api::CachePurgeResult, api::CachePurgeOptions, api::CacheContext, \ - api::AccessContext + api::ExecutionContext, api::ExportedHandler, \ + api::ServiceWorkerGlobalScope::StructuredCloneOptions, api::Navigator, \ + api::AlarmInvocationInfo, api::Immediate, api::Cloudflare, api::CachePurgeError, \ + api::CachePurgeResult, api::CachePurgeOptions, api::CacheContext, api::AccessContext // The list of global-scope.h types that are added to worker.c++'s JSG_DECLARE_ISOLATE_TYPE } // namespace workerd::api diff --git a/src/workerd/io/BUILD.bazel b/src/workerd/io/BUILD.bazel index c3e1511cfa5..327b0d02e5e 100644 --- a/src/workerd/io/BUILD.bazel +++ b/src/workerd/io/BUILD.bazel @@ -132,8 +132,6 @@ wd_cc_library( "//src/workerd/api:crypto-crc-impl", "//src/workerd/api:crypto-endianness", "//src/workerd/api:data-url", - "//src/workerd/api/bench-core", - "//src/workerd/api/bench-core:ffi.rs@cxx", "//src/workerd/api/node:exceptions", "//src/workerd/util:abortable", "//src/workerd/util:completion-membrane", diff --git a/src/workerd/io/worker-entrypoint.c++ b/src/workerd/io/worker-entrypoint.c++ index 5af17cd420c..aaa33a41452 100644 --- a/src/workerd/io/worker-entrypoint.c++ +++ b/src/workerd/io/worker-entrypoint.c++ @@ -20,6 +20,7 @@ #include #include +#include #include namespace workerd { @@ -1169,7 +1170,18 @@ kj::Promise WorkerEntrypoint::bench( asPtr(entrypointName), kj::mv(versionInfo), kj::mv(props), context.getActor()), params)); }); - api::fillBenchReport(result, report); + // A group holds up to MAX_SAMPLES wall and CPU samples per case, which can be more than the + // default traversal limit. + capnp::FlatArrayMessageReader message( + result, capnp::ReaderOptions{.traversalLimitInWords = kj::maxValue}); + auto group = message.getRoot(); + if (group.hasError()) { + report.setError(group.getError()); + } + if (group.hasOverhead()) { + report.setOverhead(group.getOverhead()); + } + report.setCases(group.getCases()); } kj::Promise WorkerEntrypoint::test() { diff --git a/src/workerd/io/worker.c++ b/src/workerd/io/worker.c++ index 32e78802e03..cdca1fd65bb 100644 --- a/src/workerd/io/worker.c++ +++ b/src/workerd/io/worker.c++ @@ -530,8 +530,11 @@ jsg::Optional> Worker::Api::getCtxCacheProperty(jsg: return kj::none; } -const jsg::TypeHandler& Worker::Api::getBenchTypeHandler( - jsg::Lock& lock) const { +v8::Local Worker::Api::runBench(jsg::Lock& lock, + v8::Local handler, + v8::Local env, + v8::Local ctx, + kj::ArrayPtr params) const { KJ_UNIMPLEMENTED("bench handlers are only supported under `workerd bench`"); } diff --git a/src/workerd/io/worker.h b/src/workerd/io/worker.h index a4bdbf09b43..966efb4e403 100644 --- a/src/workerd/io/worker.h +++ b/src/workerd/io/worker.h @@ -51,7 +51,6 @@ class ServiceWorkerGlobalScope; struct ExportedHandler; struct CryptoAlgorithm; struct QueueExportedHandler; -struct BenchExportedHandler; class WebSocket; class WebSocketRequestResponsePair; class CacheContext; @@ -713,9 +712,16 @@ class Worker::Api { jsg::Lock& lock) const = 0; virtual const jsg::TypeHandler& getQueueTypeHandler( jsg::Lock& lock) const = 0; - // Only `workerd bench` delivers the bench event, so the default implementation throws. - virtual const jsg::TypeHandler& getBenchTypeHandler( - jsg::Lock& lock) const; + // Runs the `bench()` handler of `handler`, an exported handler object, with `env` and `ctx` + // (undefined if it has none), then the cases it registers: see `bench_run()` in + // api/bench-api/ffi.rs. `params` is an encoded `BenchParams` message. Returns a promise for an + // ArrayBuffer that holds the group's `BenchReport.Group`, without its name, as an encoded + // message. Only `workerd bench` delivers the bench event, so the default implementation throws. + virtual v8::Local runBench(jsg::Lock& lock, + v8::Local handler, + v8::Local env, + v8::Local ctx, + kj::ArrayPtr params) const; // An event listener's callback (api::EventTarget::HandlerFunction). using EventListenerCallback = jsg::Function(jsg::Ref)>; diff --git a/src/workerd/server/BUILD.bazel b/src/workerd/server/BUILD.bazel index 1b603b6b9a7..ed63205ebbd 100644 --- a/src/workerd/server/BUILD.bazel +++ b/src/workerd/server/BUILD.bazel @@ -225,6 +225,8 @@ wd_cc_library( "//src/workerd/api:urlpattern-standard", "//src/workerd/api:worker-loader", "//src/workerd/api:wrapped-binding", + "//src/workerd/api/bench-api", + "//src/workerd/api/bench-api:ffi.rs@cxx", "//src/workerd/api/memory-cache-api", "//src/workerd/api/memory-cache-api:ffi.rs@cxx", "//src/workerd/io:promise-wrapper", diff --git a/src/workerd/server/factory/worker-factory.c++ b/src/workerd/server/factory/worker-factory.c++ index b3efc6f2af6..1479f9b7963 100644 --- a/src/workerd/server/factory/worker-factory.c++ +++ b/src/workerd/server/factory/worker-factory.c++ @@ -5,7 +5,6 @@ #include "worker-factory-impl.h" #include -#include #include #include #include @@ -1703,11 +1702,12 @@ kj::Promise> compileWorker(const WorkerFactory& constFac co_await preloadPython(factory, featureFlags); auto& timing = impl->startupTiming; - auto startTime = api::BenchTiming::now(); + auto startTime = bench_clock_now(); // How long it has been since `start`. - auto since = [](api::BenchTiming start) { - auto elapsed = api::BenchTiming::now() - start; - return StartupPhaseTiming{.wall_ns = elapsed.wallNs, .cpu_ns = elapsed.cpuNs}; + auto since = [](StartupPhaseTiming start) { + auto now = bench_clock_now(); + return StartupPhaseTiming{ + .wall_ns = now.wall_ns - start.wall_ns, .cpu_ns = now.cpu_ns - start.cpu_ns}; }; // The file system roots use their defaults; the config does not expose mount points. @@ -1835,7 +1835,7 @@ kj::Promise> compileWorker(const WorkerFactory& constFac } } - auto isolateStart = api::BenchTiming::now(); + auto isolateStart = bench_clock_now(); auto isolate = makeIsolate(impl->name, inspectorPolicy, kj::mv(snapshotConfig)); timing.isolate = since(isolateStart); KJ_IF_SOME(r, registrar) { @@ -1881,7 +1881,7 @@ kj::Promise> compileWorker(const WorkerFactory& constFac kj::Maybe> ownContent; KJ_IF_SOME(dynamic, impl->dynamicSource) ownContent = kj::mv(dynamic.ownContent); - auto scriptStart = api::BenchTiming::now(); + auto scriptStart = bench_clock_now(); auto script = isolate->newScript(impl->name, workerSource, IsolateObserver::StartType::COLD, SpanParent(nullptr), workerFs.attach(kj::mv(ownContent)), errorReporter, api::pyodide::ArtifactBundler::makeDisabledBundler(), kj::mv(newModuleRegistry)); @@ -1889,7 +1889,7 @@ kj::Promise> compileWorker(const WorkerFactory& constFac // `ctx.exports` is filled in once the validator has found the entrypoints, which needs the // Worker constructed first; the handle is held until then. - auto workerStart = api::BenchTiming::now(); + auto workerStart = bench_clock_now(); auto worker = kj::atomicRefcounted(kj::mv(script), kj::atomicRefcounted(), [&](jsg::Lock& lock, const Worker::Api& api, v8::Local target, v8::Local ctxExports) { diff --git a/src/workerd/server/server-test.c++ b/src/workerd/server/server-test.c++ index 992b6ee0b33..b9a19f4e8a6 100644 --- a/src/workerd/server/server-test.c++ +++ b/src/workerd/server/server-test.c++ @@ -472,7 +472,9 @@ class Server: public kj::PtrTarget { paramsWords.size()) .as()) .attach(reports(server)); - capnp::FlatArrayMessageReader reportMessage(asWords(kj::from(outcome.report))); + // A report can be larger than capnp's default traversal limit. + capnp::FlatArrayMessageReader reportMessage(asWords(kj::from(outcome.report)), + capnp::ReaderOptions{.traversalLimitInWords = kj::maxValue}); report.setGroups(reportMessage.getRoot().getGroups()); co_return outcome.passed; } @@ -7172,6 +7174,49 @@ KJ_TEST("Server: bench command") { } } +KJ_TEST("Server: bench groups can be larger than capnp's default traversal limit") { + setBenchMode(); + KJ_DEFER(unsetBenchModeForTest()); + + // The case's name is 72 MiB, past the default limit of 8M words (64 MiB) for reading a message. + kj::StringPtr config = R"(( + services = [ + ( name = "hello", + worker = ( + compatibilityDate = "2024-01-01", + modules = [ + ( name = "main.js", + esModule = + `export default { + ` bench(b) { b.run("x".repeat(72 << 20), () => {}, {warmup: 0, batch: 1, samples: 1}); } + `} + ) + ] + ) + ), + ] + ))"_kj; + + TestServer test(config); + capnp::MallocMessageBuilder paramsMessage; + capnp::MallocMessageBuilder reportMessage; + auto report = reportMessage.initRoot(); + auto params = paramsMessage.initRoot(); + params.setSkipStartup(true); + KJ_EXPECT_LOG(DBG, "[ BENCH ] hello"); + KJ_EXPECT_LOG(DBG, "[ DONE ] hello ("); + KJ_EXPECT(test.server.bench(v8System, *test.config, params.asReader(), report, "hello", "default") + .wait(test.ws)); + + auto groups = report.getGroups(); + KJ_ASSERT(groups.size() == 1); + KJ_EXPECT(!groups[0].hasError(), groups[0].getError()); + auto cases = groups[0].getCases(); + KJ_ASSERT(cases.size() == 1); + KJ_EXPECT(cases[0].getStatus() == bench::BenchReport::Case::Status::OK, cases[0].getError()); + KJ_EXPECT(cases[0].getName().size() == 72 << 20); +} + // ======================================================================================= KJ_TEST("Server: JS RPC over HTTP connections") { diff --git a/src/workerd/server/server/bridge.rs b/src/workerd/server/server/bridge.rs index 64ad28766bb..5cdd956855a 100644 --- a/src/workerd/server/server/bridge.rs +++ b/src/workerd/server/server/bridge.rs @@ -42,6 +42,7 @@ pub use crate::log::thread_body_run; pub use crate::pyodide::pyodide_bundle_fetch; pub use crate::tasks::SpawnedTask; pub use crate::tasks::task_run; +pub use crate::worker::bench_clock_now; #[cxx::bridge(namespace = "workerd::server")] #[expect( @@ -914,6 +915,11 @@ pub mod ffi { /// holds it. async fn close_in_process_server(server: Box) -> Result<()>; + /// A reading of the monotonic and thread CPU clocks that `workerd bench` times with + /// (`bench_core::clock::now()`): the difference of two readings is how long the code + /// between them took. The factory times the phases of a throwaway start with it. + fn bench_clock_now() -> StartupPhaseTiming; + /// A background task of the server, run by the factory's task set (`factory_spawn`); /// `task_run` is the promise the task set holds. type SpawnedTask; diff --git a/src/workerd/server/server/worker.rs b/src/workerd/server/server/worker.rs index 492862ffa40..e015e0f7318 100644 --- a/src/workerd/server/server/worker.rs +++ b/src/workerd/server/server/worker.rs @@ -1189,9 +1189,18 @@ impl ChannelFactory { } } +/// See `bench_clock_now` in bridge.rs. +pub fn bench_clock_now() -> ffi::StartupPhaseTiming { + let now = bench_core::clock::now(); + ffi::StartupPhaseTiming { + wall_ns: now.wall_ns, + cpu_ns: now.cpu_ns, + } +} + /// The timing of a start, as the factory measured it. fn startup_timing(timing: ffi::WorkerStartupTiming) -> bench_core::startup::StartupTiming { - let phase = |phase: ffi::StartupPhaseTiming| bench_core::startup::Timing { + let phase = |phase: ffi::StartupPhaseTiming| bench_core::Timing { wall_ns: phase.wall_ns, cpu_ns: phase.cpu_ns, }; diff --git a/src/workerd/server/workerd-api.c++ b/src/workerd/server/workerd-api.c++ index 21b95756bd6..f52b75818f7 100644 --- a/src/workerd/server/workerd-api.c++ +++ b/src/workerd/server/workerd-api.c++ @@ -6,6 +6,7 @@ #include "workerd-api-isolate.h" +#include #include #include #include @@ -273,9 +274,18 @@ const jsg::TypeHandler& WorkerdApi::getQueueTypeHandl return kj::downcast(lock).getTypeHandler(); } -const jsg::TypeHandler& WorkerdApi::getBenchTypeHandler( - jsg::Lock& lock) const { - return kj::downcast(lock).getTypeHandler(); +v8::Local WorkerdApi::runBench(jsg::Lock& lock, + v8::Local handler, + v8::Local env, + v8::Local ctx, + kj::ArrayPtr params) const { + static_assert(sizeof(capnp::word) == sizeof(uint64_t)); + auto words = kj::arrayPtr(reinterpret_cast(params.begin()), params.size()); + auto result = jsg::check( + ::workerd::rust::jsg::maybe_local_from_ffi(api::bench_run(lock.v8Isolate, + ::workerd::rust::jsg::to_ffi(kj::mv(handler)), ::workerd::rust::jsg::to_ffi(kj::mv(env)), + ::workerd::rust::jsg::to_ffi(kj::mv(ctx)), words.as()))); + return result.As(); } kj::Maybe&> WorkerdApi:: diff --git a/src/workerd/server/workerd-api.h b/src/workerd/server/workerd-api.h index a7341e6bfe4..10912c07976 100644 --- a/src/workerd/server/workerd-api.h +++ b/src/workerd/server/workerd-api.h @@ -67,8 +67,11 @@ class WorkerdApi final: public Worker::Api { jsg::Lock& lock) const override; const jsg::TypeHandler& getQueueTypeHandler( jsg::Lock& lock) const override; - const jsg::TypeHandler& getBenchTypeHandler( - jsg::Lock& lock) const override; + v8::Local runBench(jsg::Lock& lock, + v8::Local handler, + v8::Local env, + v8::Local ctx, + kj::ArrayPtr params) const override; kj::Maybe&> tryGetEventListenerCallbackTypeHandler( jsg::Lock& lock) const override; jsg::JsObject wrapExecutionContext(