Repository navigation
Shard jsg-test's Rust tests between Bazel test shards #8856
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"], | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"]] | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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()); | ||
| 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; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.