Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions build/rust/test_sharder/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
load("//:build/wd_rust_binary.bzl", "wd_rust_binary")

# Runs one Bazel test shard of a Rust test binary, for wd_rust_test's shard_count
# (//build:wd_rust_test.bzl).
wd_rust_binary(
name = "sharder",
srcs = [
"sharder.rs",
"sharder-test.rs",
],
visibility = ["//visibility:public"],
deps = ["@rules_rust//rust/runfiles"],
)
48 changes: 48 additions & 0 deletions build/rust/test_sharder/sharder-test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// 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::batches;
use super::tests_of_shard;

const LIST: &str = "a::one: test\na::two: test\nb::bench: benchmark\nb::three: test\nc::four: test\n";

#[test]
fn shards_take_every_nth_test() {
assert_eq!(tests_of_shard(LIST, 0, 2), ["a::one", "b::three"]);
assert_eq!(tests_of_shard(LIST, 1, 2), ["a::two", "c::four"]);
}

#[test]
fn every_test_is_in_exactly_one_shard() {
let mut all: Vec<&str> = (0..3).flat_map(|i| tests_of_shard(LIST, i, 3)).collect();
all.sort_unstable();
assert_eq!(all, ["a::one", "a::two", "b::three", "c::four"]);
}

#[test]
fn lines_that_are_not_tests_are_ignored() {
let list = "some output from static initialization\nx: test\n\n";
assert_eq!(tests_of_shard(list, 0, 1), ["x"]);
}

#[test]
fn shards_past_the_last_test_are_empty() {
assert!(tests_of_shard(LIST, 5, 6).is_empty());
}

#[test]
fn batches_stay_within_the_limit() {
assert_eq!(
batches(&["aa", "bb", "cc", "d"], 4),
[vec!["aa", "bb"], vec!["cc", "d"]]
);
}

#[test]
fn a_name_over_the_limit_is_a_batch_of_its_own() {
assert_eq!(
batches(&["a", "too-long", "b"], 4),
[vec!["a"], vec!["too-long"], vec!["b"]]
);
}
152 changes: 152 additions & 0 deletions build/rust/test_sharder/sharder.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
// 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

//! Runs one Bazel test shard of a Rust libtest binary. See `wd_rust_test`'s `shard_count` in
//! `build/wd_rust_test.bzl`.
//!
//! The binary is the runfile whose rlocation path is in `WD_SHARDED_RUST_TEST`. The sharder lists
//! its tests, keeps every `TEST_TOTAL_SHARDS`th one starting at `TEST_SHARD_INDEX`, and runs those
//! by exact name. Its own arguments are passed on to the binary, both when listing (so that a
//! filter narrows the list) and when running. Without `TEST_TOTAL_SHARDS` it runs the binary
//! unchanged.

use std::ffi::OsString;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::process::ExitCode;

/// The bytes of test names given to one run of the binary. Windows limits a command line to 32767
/// UTF-16 units, so a shard with more names than fit runs the binary once per batch.
const MAX_NAME_BYTES_PER_RUN: usize = 16 * 1024;

/// The tests of shard `index` of `total`, from the output of `--list --format=terse`, which has
/// one `<name>: test` line per test, in a stable order.
fn tests_of_shard(list: &str, index: usize, total: usize) -> Vec<&str> {
list.lines()
.filter_map(|line| line.strip_suffix(": test"))
.enumerate()
.filter(|(i, _)| i % total == index)
.map(|(_, name)| name)
.collect()
}

/// Splits `names` into batches whose names add up to at most `max_bytes` each, except that a
/// name longer than that is a batch by itself.
fn batches<'a>(names: &[&'a str], max_bytes: usize) -> Vec<Vec<&'a str>> {
let mut batches: Vec<Vec<&str>> = Vec::new();
let mut bytes = 0;
for &name in names {
match batches.last_mut() {
Some(batch) if bytes + name.len() <= max_bytes => batch.push(name),
_ => {
batches.push(vec![name]);
bytes = 0;
}
}
bytes += name.len();
}
batches
}

/// Reads a non-negative integer from the environment variable `name`, if it is set.
fn env_usize(name: &str) -> Result<Option<usize>, String> {
match std::env::var(name) {
Ok(value) => value
.parse()
.map(Some)
.map_err(|e| format!("{name}={value}: {e}")),
Err(std::env::VarError::NotPresent) => Ok(None),
Err(e) => Err(format!("{name}: {e}")),
}
}

fn test_binary() -> Result<PathBuf, String> {
let rlocation =
std::env::var("WD_SHARDED_RUST_TEST").map_err(|e| format!("WD_SHARDED_RUST_TEST: {e}"))?;
let runfiles = runfiles::Runfiles::create().map_err(|e| format!("runfiles: {e}"))?;
// The path is canonical, so it needs no repository mapping.
runfiles
.rlocation_from(&rlocation, "")
.ok_or_else(|| format!("{rlocation} is not a runfile"))
}

/// Runs `binary` with `args` and returns its exit code, or 1 if a signal ended it.
fn run(binary: &Path, args: &[OsString]) -> Result<u8, String> {
let status = Command::new(binary)
.args(args)
.status()
.map_err(|e| format!("running {}: {e}", binary.display()))?;
match status.code() {
Some(0) => Ok(0),
Some(code) => Ok(u8::try_from(code).unwrap_or(1).max(1)),
None => {
eprintln!("{} ended with {status}", binary.display());
Ok(1)
}
}
}

fn run_shard() -> Result<u8, String> {
let binary = test_binary()?;
let args: Vec<OsString> = std::env::args_os().skip(1).collect();

// Tells Bazel that this test shards, which it checks when TEST_TOTAL_SHARDS > 1.
if let Some(status_file) = std::env::var_os("TEST_SHARD_STATUS_FILE") {
std::fs::write(&status_file, b"").map_err(|e| format!("TEST_SHARD_STATUS_FILE: {e}"))?;
}
let total = env_usize("TEST_TOTAL_SHARDS")?.unwrap_or(1);
let index = env_usize("TEST_SHARD_INDEX")?.unwrap_or(0);
if total <= 1 {
return run(&binary, &args);
}
if index >= total {
return Err(format!(
"TEST_SHARD_INDEX={index} with TEST_TOTAL_SHARDS={total}"
));
}

let listing = Command::new(&binary)
.args(&args)
.args(["--list", "--format=terse"])
.output()
.map_err(|e| format!("listing the tests of {}: {e}", binary.display()))?;
if !listing.status.success() {
eprint!("{}", String::from_utf8_lossy(&listing.stderr));
return Err(format!("listing the tests failed with {}", listing.status));
}
let list = String::from_utf8(listing.stdout).map_err(|e| format!("test list: {e}"))?;
let names = tests_of_shard(&list, index, total);
// Without a name the binary would run every test.
if names.is_empty() {
println!("shard {index} of {total} has no tests");
return Ok(0);
}

let mut result = 0;
for batch in batches(&names, MAX_NAME_BYTES_PER_RUN) {
let mut batch_args = args.clone();
batch_args.push("--exact".into());
Comment thread
danlapid marked this conversation as resolved.
Resolved
batch_args.extend(batch.into_iter().map(OsString::from));
let code = run(&binary, &batch_args)?;
if result == 0 {
result = code;
}
}
Ok(result)
}

fn main() -> ExitCode {
match run_shard() {
Ok(code) => ExitCode::from(code),
Err(message) => {
eprintln!("sharder: {message}");
ExitCode::FAILURE
}
}
}

#[cfg(test)]
#[path = "sharder-test.rs"]
mod tests;
10 changes: 7 additions & 3 deletions build/wd_rust_crate.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ def wd_rust_crate(
test_proc_macro_deps = [],
test_compile_data = [],
test_size = "medium",
test_shard_count = None,
cxx_bridge_deps = [],
cxx_bridge_hdrs = None,
cxx_bridge_tags = [],
Expand Down Expand Up @@ -103,8 +104,10 @@ def wd_rust_crate(
test_proc_macro_deps: test-only proc_macro dependencies.
test_compile_data: files the unit tests read at compile time (include_str!, include_bytes!),
such as test vectors. Like the *-test.rs files, they are inputs of <name>_test only.
test_size: Bazel test size (default "medium"); affects test timeout. Use "large" for
crates with many subtests, since RUST_TEST_THREADS=1 forces serial execution.
test_size: Bazel test size (default "medium"); affects test timeout.
test_shard_count: the number of shards to split the unit tests between, for crates
whose many tests together take long, since RUST_TEST_THREADS=1 runs them serially.
See wd_rust_test.
cxx_bridge_deps: either a flat dependency list applied to every bridge source, or a dict of
bridge source => dependency list.
cxx_bridge_hdrs: headers the bridges include!(); defaults to every .h file in the package.
Expand Down Expand Up @@ -193,6 +196,7 @@ def wd_rust_crate(
crate = ":" + name,
env = test_env,
size = test_size,
shard_count = test_shard_count,
tags = test_tags,
crate_features = crate_features,
rustc_env = rustc_env,
Expand All @@ -211,7 +215,7 @@ def wd_rust_crate(
if len(test_proc_macro_deps) > 0:
rust_unpretty(
name = name + "_test@expand",
deps = [":" + name + "_test"],
deps = [":" + name + ("_test@unsharded" if test_shard_count else "_test")],
tags = ["manual", "off-by-default"],
testonly = True,
)
107 changes: 97 additions & 10 deletions build/wd_rust_test.bzl
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
load("@rules_rust//rust:defs.bzl", "rust_test")
load("@rules_rust//rust:defs.bzl", "rust_clippy_aspect", "rust_test", "rustfmt_aspect")
load("//:build/test_attrs.bzl", "test_attrs")

def split_rust_test_srcs(srcs):
Expand All @@ -12,24 +12,111 @@ def split_rust_test_srcs(srcs):
test_srcs = [src for src in srcs if src.endswith("-test.rs")]
return [src for src in srcs if src not in test_srcs], test_srcs

def _sharded_rust_test_impl(ctx):
test = ctx.attr.test
sharder = ctx.executable._sharder

# A test's executable must be its own output.
name = ctx.label.name
if sharder.extension:
name += "." + sharder.extension
executable = ctx.actions.declare_file(name)
ctx.actions.symlink(output = executable, target_file = sharder, is_executable = True)

runfiles = ctx.runfiles(files = [ctx.executable.test])
runfiles = runfiles.merge_all([
test[DefaultInfo].default_runfiles,
ctx.attr._sharder[DefaultInfo].default_runfiles,
])
rlocation = ctx.expand_location("$(rlocationpath {})".format(test.label), [test])

# The lint aspects that --config=lint applies are not run on targets that already have their
# output groups, so this one stands for the test it runs.
output_groups = test[OutputGroupInfo] if OutputGroupInfo in test else struct()
lint_checks = {
group: getattr(output_groups, group)
for group in ["clippy_checks", "rustfmt_checks"]
if hasattr(output_groups, group)
}
return [
DefaultInfo(executable = executable, runfiles = runfiles),
RunEnvironmentInfo(environment = ctx.attr.env | {"WD_SHARDED_RUST_TEST": rlocation}),
Comment thread
danlapid marked this conversation as resolved.
Resolved
OutputGroupInfo(**lint_checks),
]

_sharded_rust_test = rule(
implementation = _sharded_rust_test_impl,
test = True,
attrs = {
# The rust_test to shard. It is a manual target, which `bazel build //...` does not lint,
# so its lint checks become this target's.
"test": attr.label(
mandatory = True,
executable = True,
cfg = "target",
aspects = [rust_clippy_aspect, rustfmt_aspect],
),
"env": attr.string_dict(),
"_sharder": attr.label(
default = "//build/rust/test_sharder:sharder",
executable = True,
cfg = "target",
),
},
)

def wd_rust_test(
name,
env = {},
link_deps = [],
tags = [],
shard_count = None,
size = "medium",
target_compatible_with = None,
exec_properties = {},
**kwargs):
"""Defines a Rust test.

Args:
name: the test's name.
env: additional environment variables of the test.
link_deps: C/C++ libraries to link with the test.
tags: the test's tags.
shard_count: the number of Bazel test shards to split the test cases between, each run
in its own process. The cases of one shard still run serially. Shard a test whose
cases together take too long but can run in separate processes. The rust_test is then
`<name>@unsharded`, run through //build/rust/test_sharder.
size: the test's size.
target_compatible_with: platform constraints of the test.
exec_properties: the test's own exec_properties; see test_attrs.
**kwargs: further rust_test attributes.
"""
env = {
"RUST_BACKTRACE": "1",
# Rust's test runner captures stderr by default, which makes debugging tests difficult.
"RUST_TEST_NOCAPTURE": "1",
# Rust tests in this repository are often heavyweight or rely on process-global state.
"RUST_TEST_THREADS": "1",
} | env
attrs = test_attrs(tags + ["no-coverage"], size, target_compatible_with, exec_properties)
test_name = name
if shard_count:
test_name = name + "@unsharded"
_sharded_rust_test(
name = name,
test = ":" + test_name,
env = env,
shard_count = shard_count,
size = size,
**attrs
)

# Run through the sharded test only, not on its own as well.
attrs = attrs | {"tags": attrs["tags"] + ["manual"]}

rust_test(
name = name,
env = {
"RUST_BACKTRACE": "1",
# Rust's test runner captures stderr by default, which makes debugging tests difficult.
"RUST_TEST_NOCAPTURE": "1",
# Rust tests in this repository are often heavyweight or rely on process-global state.
"RUST_TEST_THREADS": "1",
} | env,
name = test_name,
env = env,
experimental_use_cc_common_link = 1,
# linkopts_default limits linker parallelism to avoid resource exhaustion.
link_deps = link_deps + [
Expand All @@ -38,5 +125,5 @@ def wd_rust_test(
],
malloc = "//src/workerd/server:malloc",
size = size,
**(kwargs | test_attrs(tags + ["no-coverage"], size, target_compatible_with, exec_properties))
**(kwargs | attrs)
)
3 changes: 3 additions & 0 deletions docs/reference/rust-review-checklist.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,9 @@ some violations, and the README says which. Reviewers flag these:
These test the C++ side of the FFI bridge.
- **Inline `#[cfg(test)]` modules**: standard Rust unit tests for pure-Rust logic.
- All test targets run with `RUST_BACKTRACE=1` and `RUST_TEST_THREADS=1` (serial execution).
A crate whose tests together take long splits them between Bazel test shards with
`test_shard_count` (`wd_rust_crate`) or `shard_count` (`wd_rust_test`), each a process of its
own, rather than taking a larger test size.

### Review Checklist

Expand Down
Loading
Loading