Files
vectorcraft/xtask/src/shards.rs
T

907 lines
43 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! The gate's shards (`cargo xtask ci shard`, with `GATE_SHARD` of `GATE_SHARDS` set by the shared
//! gate workflow): which workspace crates each shard tests, and the checks that keep the split
//! complete.
//!
//! Each test shard builds and runs the tests of its own crates and what they depend on. The last
//! shard runs the `cargo xtask ci` steps that are not tests. [`GROUPS`] names the crates of the
//! first shards; every other workspace member goes to the [`Group::Rest`] shard, so a new crate is
//! tested without a change here. [`check`] fails when a named crate is not a workspace member or
//! is named twice, when a group is empty, and when a crate's features in its shard differ from
//! its features in `cargo test --workspace`. Cargo resolves features over the packages a command
//! selects, so a feature that only another crate's dev-dependencies turn on is off in a shard
//! without that crate, and the tests behind it do not build.
//!
//! A [`Split`] runs the tests of its crates on several shards in a row ([`Group::Part`]). Each
//! part builds the same tests and runs its share of them: the tests its `pinned` list names, and
//! every other test of the crates by nextest's counted partition (`--partition count:<k>/<n>`
//! with the pinned tests filtered out, so each of them runs once). The doctests and the i18n
//! report run on part 1. A part runs its counted share and then its pinned tests, each with
//! nextest's default thread count, and runs both even when the first fails.
//!
//! A [`Group::Targets`] shard can run a crate's library and binary tests ([`Targets::Units`]) while
//! another shard runs its integration tests ([`Targets::Integration`]), so a shard that already
//! builds that crate's library takes those tests without building the library's test harness. Each
//! list of a shard is its own cargo command, and its doctests run with its library tests.
use std::collections::{BTreeMap, BTreeSet};
use serde_json::Value;
/// What one shard runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Group {
/// Part `k` (1-based) of a split's tests. Parts 1 to n of a split are consecutive shards.
Part(&'static Split, usize),
/// The given test targets of each list of workspace crates (package names). A crate whose
/// [`Targets::Units`] run on one shard has its [`Targets::Integration`] run on another.
Targets(&'static [(Targets, &'static [&'static str])]),
/// The tests of every workspace member no other group names.
Rest,
/// The `cargo xtask ci` steps that are not tests.
Checks,
}
/// The test targets a shard builds and runs for a crate.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Targets {
/// The library, binary and integration tests.
All,
/// The library and binary tests.
Units,
/// The integration tests (`tests/`).
Integration,
}
impl Targets {
/// The target selection `cargo test` and `cargo nextest run` take.
pub fn args(self) -> &'static [&'static str] {
match self {
Targets::All => &["--lib", "--bins", "--tests"],
Targets::Units => &["--lib", "--bins"],
// `--tests` would also take the library's and binaries' test harnesses (every target with `test = true`).
Targets::Integration => &["--test", "*"],
}
}
/// [`Targets::args`] as a shell would take them, for messages.
pub fn shown(self) -> &'static str {
match self {
Targets::All => "--lib --bins --tests",
Targets::Units => "--lib --bins",
Targets::Integration => "--test '*'",
}
}
}
/// Crates whose tests run on several shards, one [`Group::Part`] each.
#[derive(Debug, PartialEq, Eq)]
pub struct Split {
/// The workspace crates (package names).
pub crates: &'static [&'static str],
/// For each part, the full names of the tests it runs outside the counted partition (the
/// slowest ones, spread so that no part waits on all of them). Its length is the part count.
pub pinned: &'static [&'static [&'static str]],
}
impl Split {
/// How many shards the split runs on.
pub fn parts(&self) -> usize {
self.pinned.len()
}
}
/// vectorcraft-ui-egui's tests, on two shards. The pinned tests took 18 to 44 s each in CI
/// run 46267439238.
pub static UI_EGUI: Split = Split {
crates: &["vectorcraft-ui-egui"],
pinned: &[
&[
"panels::actions::tests_edits::every_listed_menu_item_runs_from_the_menu_what_its_step_holds",
"dialogs::revolve::tests::a_3d_row_sets_its_param_previews_and_applies_in_one_step",
"shortcuts::tests::alt_chords_type_special_characters_while_editing_text",
"menus::tests::help_f1_opens_discover_without_a_document",
],
&[
"palette::tests::the_palette_leaves_out_the_commands_a_pick_cannot_run",
"chrome::tests::the_control_bar_leaves_members_out_in_its_priority_order",
],
],
};
/// The shards in order; `test-shards` in `.github/workflows/ci.yml` is its length, and its
/// `shard-members` names each shard's crates. vectorcraft-engine's integration tests run on
/// shard 4, which already builds the engine library for the app crates.
pub const GROUPS: &[Group] = &[
Group::Part(&UI_EGUI, 1),
Group::Part(&UI_EGUI, 2),
Group::Targets(&[(Targets::Units, &["vectorcraft-engine"])]),
Group::Targets(&[
(Targets::All, &["vectorcraft", "vectorcraft-web", "vectorcraft-cli", "vectorcraft-mcp", "xtask"]),
(Targets::Integration, &["vectorcraft-engine"]),
]),
Group::Rest,
Group::Checks,
];
/// A workspace member, as `cargo metadata` gives it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Member {
pub name: String,
/// The package id, which `-p` takes where the name would be ambiguous: craft-libs builds
/// against this repo's geom and pathops by git, so the graph holds a second copy of each.
pub id: String,
pub version: String,
/// Whether `cargo test --doc` can select this package without a warning: it has no library
/// target, or one of `lib`, `rlib` or `proc-macro` kind. Cargo warns for a selected package
/// whose library is only a `cdylib`, `dylib` or `staticlib`.
pub doctests: bool,
}
/// What one shard runs, with its crates resolved; a shard of a [`Split`] carries its part.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Shard {
Tests(Vec<Run>, Option<Part>),
Checks,
}
/// One test run of a shard: the given targets of these crates.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Run {
pub targets: Targets,
pub crates: Vec<Member>,
}
impl Run {
/// A run of every test target of `crates`.
pub fn all(crates: Vec<Member>) -> Run {
Run { targets: Targets::All, crates }
}
}
/// The crates of `runs` whose library is tested there, which run their doctests on that shard.
pub fn unit_crates(runs: &[Run]) -> Vec<Member> {
runs.iter().filter(|r| r.targets != Targets::Integration).flat_map(|r| r.crates.iter().cloned()).collect()
}
/// Part `index` (1-based) of `split`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Part {
pub split: &'static Split,
pub index: usize,
}
impl Part {
/// The arguments `cargo nextest run` takes after the package and target selection, once for
/// each run this part makes: the counted share (`--partition count:<k>/<n>`, with every
/// pinned test filtered out when the split pins any), then the tests this part pins.
/// The counted run passes `--no-tests=pass`. The pinned run keeps nextest's default and
/// fails when no tests match.
pub fn runs(&self) -> Vec<Vec<String>> {
let all: Vec<&str> = self.split.pinned.iter().flat_map(|p| p.iter().copied()).collect();
let mut counted = vec!["--partition".to_owned(), format!("count:{}/{}", self.index, self.split.parts()), "--no-tests=pass".to_owned()];
if !all.is_empty() {
counted.extend(["-E".to_owned(), format!("not ({})", exact(&all))]);
}
let mut runs = vec![counted];
let own = self.split.pinned[self.index - 1];
if !own.is_empty() {
runs.push(vec!["-E".to_owned(), exact(own)]);
}
runs
}
/// The tests this part pins whose full names are absent from
/// `cargo nextest list --message-format json` output. Invalid listings return an error.
pub fn missing_pins(&self, list: &str) -> Result<Vec<&'static str>, String> {
let list: Value = serde_json::from_str(list).map_err(|e| format!("invalid JSON listing: {e}"))?;
let suites = list.get("rust-suites").and_then(Value::as_object).ok_or("JSON listing has no `rust-suites` map")?;
let mut listed = BTreeSet::new();
for (binary, suite) in suites {
let tests =
suite.get("testcases").and_then(Value::as_object).ok_or_else(|| format!("JSON listing has no `testcases` map for `{binary}`"))?;
listed.extend(tests.keys().map(String::as_str));
}
Ok(self.split.pinned[self.index - 1].iter().copied().filter(|p| !listed.contains(p)).collect())
}
/// Whether this part runs the doctests and the i18n report.
pub fn is_first(&self) -> bool {
self.index == 1
}
}
/// A filterset that matches each of `names` exactly.
fn exact(names: &[&str]) -> String {
names.iter().map(|n| format!("test(={n})")).collect::<Vec<_>>().join(" | ")
}
/// The workspace members of `cargo metadata --no-deps` output, in its order.
pub fn members(meta: &Value) -> Result<Vec<Member>, String> {
let ids: BTreeSet<&str> = meta["workspace_members"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
let members: Vec<Member> = meta["packages"]
.as_array()
.into_iter()
.flatten()
.filter(|p| p["id"].as_str().is_some_and(|id| ids.contains(id)))
.map(|p| {
let field = |key: &str| p[key].as_str().map(str::to_owned).ok_or_else(|| format!("cargo metadata: a workspace package has no `{key}`"));
Ok(Member { name: field("name")?, id: field("id")?, version: field("version")?, doctests: has_doctests(p) })
})
.collect::<Result<_, String>>()?;
if members.is_empty() {
return Err("cargo metadata lists no workspace members".into());
}
Ok(members)
}
/// [`Member::doctests`] for the `cargo metadata` package `p`.
fn has_doctests(p: &Value) -> bool {
let kinds = |t: &Value| t["kind"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect::<Vec<_>>();
let libraries: Vec<Vec<String>> = p["targets"]
.as_array()
.into_iter()
.flatten()
.map(kinds)
.filter(|k| k.iter().any(|k| matches!(k.as_str(), "lib" | "rlib" | "dylib" | "cdylib" | "staticlib" | "proc-macro")))
.collect();
libraries.is_empty() || libraries.iter().flatten().any(|k| matches!(k.as_str(), "lib" | "rlib" | "proc-macro"))
}
/// The crates of `crates` that `cargo test --doc` can select (see [`Member::doctests`]).
pub fn with_doctests(crates: &[Member]) -> Vec<Member> {
crates.iter().filter(|m| m.doctests).cloned().collect()
}
/// Each group of `groups` with its crates: a named crate must be a workspace member and named
/// once, or with its [`Targets::Units`] on one shard and its [`Targets::Integration`] on another;
/// there must be exactly one [`Group::Rest`], and no test shard may be empty. A split's parts 1
/// to n must be consecutive shards, with at least two parts, and no test pinned twice.
pub fn assign(groups: &[Group], members: &[Member]) -> Result<Vec<Shard>, String> {
const WHERE: &str = "xtask/src/shards.rs › GROUPS";
let mut named: BTreeMap<&str, Vec<(usize, Targets)>> = BTreeMap::new();
for (i, g) in groups.iter().enumerate() {
let lists: Vec<(Targets, &[&str])> = match g {
Group::Targets(lists) => lists.to_vec(),
Group::Part(split, k) => {
let n = split.parts();
if n < 2 {
return Err(format!("shard {} is a part of a split with {n} part(s), not 2 or more ({WHERE})", i + 1));
}
// Part 1 of the split is shard `first` (0-based) when this shard is part k.
let in_order = (1..=n).contains(k)
&& (i + 1).checked_sub(*k).is_some_and(|first| {
(1..=n).all(|p| matches!(groups.get(first + p - 1), Some(Group::Part(s, q)) if *s == *split && *q == p))
});
if !in_order {
return Err(format!("shard {} is part {k} of a split whose {n} parts are not shards 1 to {n} in a row ({WHERE})", i + 1));
}
if *k > 1 {
continue;
}
let mut pinned = BTreeSet::new();
for name in split.pinned.iter().flat_map(|p| p.iter()) {
if !pinned.insert(*name) {
return Err(format!("`{name}` is pinned to two parts of shard {}'s split ({WHERE})", i + 1));
}
}
vec![(Targets::All, split.crates)]
}
Group::Rest | Group::Checks => continue,
};
if lists.iter().all(|(_, names)| names.is_empty()) {
return Err(format!("shard {} names no crates ({WHERE})", i + 1));
}
for (targets, names) in lists {
for name in names {
if !members.iter().any(|m| m.name == *name) {
return Err(format!("shard {} names `{name}`, which is not a workspace member ({WHERE})", i + 1));
}
let entries = named.entry(name).or_default();
// The one allowed second entry: the other half of a crate split into units and integration tests.
let halves =
|a: Targets, b: Targets| matches!((a, b), (Targets::Units, Targets::Integration) | (Targets::Integration, Targets::Units));
match entries.as_slice() {
[] => {}
[(first, t)] if halves(*t, targets) && *first != i => {}
[(first, _), ..] => return Err(format!("`{name}` is in shard {} and shard {} ({WHERE})", first + 1, i + 1)),
}
entries.push((i, targets));
}
}
}
for (name, entries) in &named {
if let [(i, t)] = entries.as_slice()
&& *t != Targets::All
{
let other = if *t == Targets::Units { "integration" } else { "library and binary" };
return Err(format!("shard {} runs part of `{name}`'s tests, and no shard runs its {other} tests ({WHERE})", i + 1));
}
}
let rests = groups.iter().filter(|g| **g == Group::Rest).count();
if rests != 1 {
return Err(format!("{rests} shards take the remaining crates, not 1 ({WHERE})"));
}
let pick = |f: &dyn Fn(&Member) -> bool| members.iter().filter(|m| f(m)).cloned().collect::<Vec<_>>();
groups
.iter()
.enumerate()
.map(|(i, g)| match g {
Group::Targets(lists) => Ok(Shard::Tests(
lists
.iter()
.filter(|(_, names)| !names.is_empty())
.map(|(targets, names)| Run { targets: *targets, crates: pick(&|m| names.contains(&m.name.as_str())) })
.collect(),
None,
)),
Group::Part(split, index) => {
Ok(Shard::Tests(vec![Run::all(pick(&|m| split.crates.contains(&m.name.as_str())))], Some(Part { split, index: *index })))
}
Group::Rest => {
let rest = pick(&|m| !named.contains_key(m.name.as_str()));
if rest.is_empty() {
return Err(format!("shard {} takes the remaining crates, and there are none ({WHERE})", i + 1));
}
Ok(Shard::Tests(vec![Run::all(rest)], None))
}
Group::Checks => Ok(Shard::Checks),
})
.collect()
}
/// The features `cargo tree -e normal,dev,build --prefix none -f '{p}|{f}'` shows for each of
/// `members`, by name; a crate the tree holds twice (once for the host, say) has two entries.
/// Other copies of a member's name (craft-libs' git copies of geom and pathops) are not members.
pub fn tree_features(tree: &str, members: &[Member]) -> BTreeMap<String, BTreeSet<String>> {
let mut found: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
for line in tree.lines() {
let line = line.trim_end();
let line = line.strip_suffix(" (*)").unwrap_or(line);
let Some((package, features)) = line.split_once('|') else { continue };
let Some(m) =
members.iter().find(|m| package.strip_prefix(&format!("{} v{} (", m.name, m.version)).is_some_and(|source| !source.contains("://")))
else {
continue;
};
let mut features: Vec<&str> = features.split(',').map(str::trim).filter(|f| !f.is_empty()).collect();
features.sort_unstable();
found.entry(m.name.clone()).or_default().insert(features.join(","));
}
found
}
/// One line for each crate of `shard` whose features in `alone` (the shard's tree) differ from
/// `workspace` (the whole workspace's tree).
pub fn feature_differences(
shard: usize,
crates: &[Member],
workspace: &BTreeMap<String, BTreeSet<String>>,
alone: &BTreeMap<String, BTreeSet<String>>,
) -> Vec<String> {
let show = |set: Option<&BTreeSet<String>>| match set {
None => "absent".to_owned(),
Some(set) => set.iter().map(|f| format!("[{f}]")).collect::<Vec<_>>().join(" "),
};
crates
.iter()
.filter(|m| workspace.get(&m.name) != alone.get(&m.name))
.map(|m| {
format!("{}: features {} in shard {shard}, {} with the whole workspace", m.name, show(alone.get(&m.name)), show(workspace.get(&m.name)))
})
.collect()
}
/// `cargo tree` with the features of each package, for `select` (`--workspace` or `-p` ids).
fn tree(select: &[String]) -> Result<String, String> {
let mut c = crate::cargo();
// Without `--color never`, CARGO_TERM_COLOR=always (as the gate sets it) colors the ` (*)` marks.
c.args(["tree", "--color", "never", "-e", "normal,dev,build", "--prefix", "none", "-f", "{p}|{f}"]).args(select);
let out = c.output().map_err(|e| format!("cargo tree: failed to spawn: {e}"))?;
if !out.status.success() {
return Err(format!("cargo tree {}: exited with {}:\n{}", select.join(" "), out.status, String::from_utf8_lossy(&out.stderr)));
}
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}
/// `-p <id>` for each crate.
pub fn select(crates: &[Member]) -> Vec<String> {
crates.iter().flat_map(|m| ["-p".to_owned(), m.id.clone()]).collect()
}
/// The package names of `crates`, for messages.
pub fn names(crates: &[Member]) -> String {
crates.iter().map(|m| m.name.as_str()).collect::<Vec<_>>().join(", ")
}
/// The crates of `runs` for messages, each run's targets after its crates unless it runs all of them.
pub fn describe(runs: &[Run]) -> String {
runs.iter()
.map(|r| match r.targets {
Targets::All => names(&r.crates),
t => format!("{} ({})", names(&r.crates), t.shown()),
})
.collect::<Vec<_>>()
.join(", ")
}
/// The shards of this workspace, after the checks in [`assign`] and [`feature_differences`].
pub fn check() -> Result<Vec<Shard>, String> {
// The shared gate runs only the shards that test a crate a pull request reaches, by these
// lines, so a mismatch fails every shard instead of one test that selection may skip.
workflow_members(include_str!("../../.github/workflows/ci.yml"))?;
let members = members(&crate::metadata()?)?;
let shards = assign(GROUPS, &members)?;
let workspace = tree_features(&tree(&["--workspace".to_owned()])?, &members);
let mut differences = Vec::new();
for (i, shard) in shards.iter().enumerate() {
// Each run is its own cargo command, so cargo resolves features over that run's crates.
if let Shard::Tests(runs, _) = shard {
for r in runs {
let alone = tree_features(&tree(&select(&r.crates))?, &members);
differences.extend(feature_differences(i + 1, &r.crates, &workspace, &alone));
}
}
}
if !differences.is_empty() {
return Err(format!(
"{} crate(s) build with other features in their shard than in `cargo test --workspace`, so some of their tests \
would build differently or not at all (turn the feature on in the crate's own dev-dependencies, or move the crate \
to the shard of the crate that turns it on):\n {}",
differences.len(),
differences.join("\n ")
));
}
Ok(shards)
}
/// The lines of the `shard-members: |` block in `workflow`, trimmed.
fn shard_members(workflow: &str) -> Vec<&str> {
let mut lines = workflow.lines().skip_while(|l| l.trim() != "shard-members: |");
let Some(key) = lines.next() else { return Vec::new() };
let indent = |l: &str| l.len() - l.trim_start().len();
lines.take_while(|l| !l.trim().is_empty() && indent(l) > indent(key)).map(str::trim).collect()
}
/// Checks that `workflow`'s `shard-members` block names each shard's crates as [`GROUPS`] does.
fn workflow_members(workflow: &str) -> Result<(), String> {
let expected: Vec<String> = GROUPS
.iter()
.map(|g| match g {
Group::Part(split, _) => split.crates.join(" "),
// The selection names each crate on one line only, so a shard that runs a crate's
// integration tests leaves it off its line and relies on a crate there that
// depends on it (checked in the tests).
Group::Targets(lists) => {
lists.iter().filter(|(t, _)| *t != Targets::Integration).flat_map(|(_, c)| c.iter().copied()).collect::<Vec<_>>().join(" ")
}
Group::Rest => "(rest)".to_owned(),
Group::Checks => "(always)".to_owned(),
})
.collect();
let found = shard_members(workflow);
if found != expected {
return Err(format!(
"shard-members in .github/workflows/ci.yml does not match xtask/src/shards.rs › GROUPS:\n found: {found:?}\n expected: {expected:?}"
));
}
Ok(())
}
/// `cargo xtask shards`: prints each shard's crates after [`check`], and returns the shards.
pub fn run() -> Result<Vec<Shard>, String> {
let shards = check()?;
for (i, shard) in shards.iter().enumerate() {
match shard {
Shard::Tests(runs, part) => {
let share = part.map(|p| format!(", part {} of {}", p.index, p.split.parts())).unwrap_or_default();
println!("shard {}/{}: tests of {}{share}", i + 1, shards.len(), describe(runs))
}
Shard::Checks => println!("shard {}/{}: the other ci steps", i + 1, shards.len()),
}
}
println!("OK: every workspace member is tested on one shard, with the features `cargo test --workspace` gives it.");
Ok(shards)
}
/// The shard `cargo xtask ci warm` builds alone, as an index into [`GROUPS`], from the gate's
/// `GATE_SHARD` and `GATE_SHARDS`: `None` (every shard) when neither is set. Setting only one,
/// a value that is not a number, a count other than the number of shards, or a shard out of range
/// is an error.
pub fn warm_only(shard: Option<&str>, count: Option<&str>) -> Result<Option<usize>, String> {
let (shard, count) = match (shard, count) {
(None, None) => return Ok(None),
(Some(shard), Some(count)) => (shard, count),
_ => return Err("ci warm: GATE_SHARD and GATE_SHARDS are set together or not at all".into()),
};
let number =
|key: &str, value: &str| -> Result<usize, String> { value.trim().parse().map_err(|_| format!("ci warm: {key} is `{value}`, not a number")) };
let (shard, count) = (number("GATE_SHARD", shard)?, number("GATE_SHARDS", count)?);
if count != GROUPS.len() {
return Err(format!(
"ci warm: GATE_SHARDS is {count}, and xtask/src/shards.rs has {} shards (test-shards in .github/workflows/ci.yml)",
GROUPS.len()
));
}
if !(1..=count).contains(&shard) {
return Err(format!("ci warm: GATE_SHARD is {shard}, not 1 to {count}"));
}
Ok(Some(shard - 1))
}
/// What `cargo xtask ci warm` builds of `shards`: the indices of the test shards whose tests it
/// builds, and whether it runs the checks shard's builds. With `only` (from [`warm_only`]) it
/// builds that shard alone, and without it every shard. A split's later parts build nothing: they
/// build the same tests as part 1, whose leg puts them in the cache.
pub fn warm_plan(shards: &[Shard], only: Option<usize>) -> (Vec<usize>, bool) {
let mut tests = Vec::new();
let mut checks = false;
for (i, shard) in shards.iter().enumerate() {
if only.is_some_and(|k| k != i) {
continue;
}
match shard {
Shard::Checks => checks = true,
Shard::Tests(_, part) if part.is_some_and(|p| !p.is_first()) => {}
Shard::Tests(..) => tests.push(i),
}
}
(tests, checks)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn warm_builds_every_shard_unless_the_gate_names_one() {
let n = GROUPS.len().to_string();
assert_eq!(warm_only(None, None), Ok(None));
assert_eq!(warm_only(Some("1"), Some(&n)), Ok(Some(0)));
assert_eq!(warm_only(Some(&n), Some(&n)), Ok(Some(GROUPS.len() - 1)));
for (shard, count) in [(Some("1"), None), (None, Some(n.as_str())), (Some("0"), Some(n.as_str())), (Some("x"), Some(n.as_str()))] {
assert!(warm_only(shard, count).is_err(), "{shard:?} of {count:?}");
}
let past = (GROUPS.len() + 1).to_string();
assert!(warm_only(Some(&past), Some(&n)).is_err());
assert!(warm_only(Some("1"), Some(&past)).is_err());
}
#[test]
fn warm_builds_each_shard_of_the_plan() {
let ws = [m("a"), m("b")];
let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest, Group::Checks], &ws).unwrap();
assert_eq!(warm_plan(&shards, None), (vec![0, 2], true));
assert_eq!(warm_plan(&shards, Some(0)), (vec![0], false));
assert_eq!(warm_plan(&shards, Some(1)), (vec![], false));
assert_eq!(warm_plan(&shards, Some(2)), (vec![2], false));
assert_eq!(warm_plan(&shards, Some(3)), (vec![], true));
// The real plan: every leg the gate names builds its own shard (a split's later part
// builds nothing), and the legs together, like a full warm, build every crate's tests
// once and the checks.
let real = assign(GROUPS, &members(&crate::metadata().unwrap()).unwrap()).unwrap();
let mut owned: Vec<&str> = real.iter().flat_map(owners).map(|(name, _)| name).collect();
owned.sort_unstable();
let (mut legs, mut leg_checks) = (Vec::new(), 0);
for i in 0..GROUPS.len() {
let n = GROUPS.len().to_string();
let only = warm_only(Some(&(i + 1).to_string()), Some(&n)).unwrap();
let (tests, checks) = warm_plan(&real, only);
let want = match &real[i] {
Shard::Checks => (vec![], true),
Shard::Tests(_, Some(p)) if !p.is_first() => (vec![], false),
Shard::Tests(..) => (vec![i], false),
};
assert_eq!((tests.clone(), checks), want, "shard {}", i + 1);
legs.extend(tests);
leg_checks += usize::from(checks);
}
let (tests, checks) = warm_plan(&real, None);
assert!(checks);
assert_eq!(leg_checks, 1);
assert_eq!(tests, legs);
let mut built: Vec<&str> = tests.iter().flat_map(|&i| crates(&real[i])).collect();
built.sort_unstable();
assert_eq!(built, owned);
}
fn m(name: &str) -> Member {
Member { name: name.into(), id: format!("path+file:///w/{name}#0.1.0"), version: "0.1.0".into(), doctests: true }
}
#[test]
fn the_doc_tests_leave_out_only_packages_whose_library_cargo_cannot_doc_test() {
let package = |kinds: &[&str]| serde_json::json!({ "targets": [{ "kind": kinds }, { "kind": ["bin"] }] });
assert!(has_doctests(&package(&["lib"])));
assert!(has_doctests(&package(&["rlib"])));
assert!(has_doctests(&package(&["proc-macro"])));
assert!(has_doctests(&package(&["cdylib", "rlib"])));
assert!(has_doctests(&package(&["bin"])));
assert!(has_doctests(&serde_json::json!({ "targets": [] })));
assert!(!has_doctests(&package(&["cdylib"])));
assert!(!has_doctests(&package(&["dylib"])));
assert!(!has_doctests(&package(&["staticlib"])));
let mut cdylib = m("cdylib");
cdylib.doctests = false;
assert_eq!(with_doctests(&[m("a"), cdylib, m("b")]).iter().map(|m| m.name.as_str()).collect::<Vec<_>>(), ["a", "b"]);
}
fn crates(shard: &Shard) -> Vec<&str> {
match shard {
Shard::Tests(runs, _) => runs.iter().flat_map(|r| r.crates.iter().map(|m| m.name.as_str())).collect(),
Shard::Checks => Vec::new(),
}
}
/// Each crate a shard tests from the start, with the targets it runs: a part after the first
/// runs a share of the same tests, so it is counted with part 1.
fn owners(shard: &Shard) -> Vec<(&str, Targets)> {
match shard {
Shard::Tests(_, Some(p)) if !p.is_first() => Vec::new(),
Shard::Tests(runs, _) => runs.iter().flat_map(|r| r.crates.iter().map(|m| (m.name.as_str(), r.targets))).collect(),
Shard::Checks => Vec::new(),
}
}
/// The tests (binary ids and full names, in the order nextest lists them) that one `cargo nextest run` with
/// `args` from [`Part::runs`] runs, as nextest selects them: the `-E` filterset (`test(=…)`
/// terms joined by `|`, or `not (…)` of them) first, then `--partition count:<k>/<n>`, which
/// keeps the i-th (0-based) test the filter left in each binary when `i % n` is `k - 1`.
fn selected<'a>(args: &[String], tests: &[(&'a str, &'a str)]) -> Vec<(&'a str, &'a str)> {
let value = |flag: &str| args.iter().position(|a| a == flag).map(|i| args[i + 1].as_str());
let filtered: Vec<(&str, &str)> = match value("-E") {
None => tests.to_vec(),
Some(expr) => {
let (negated, body) = expr.strip_prefix("not (").and_then(|e| e.strip_suffix(')')).map_or((false, expr), |b| (true, b));
let names: Vec<&str> = body.split(" | ").map(|t| t.strip_prefix("test(=").and_then(|t| t.strip_suffix(')')).unwrap()).collect();
tests.iter().copied().filter(|(_, t)| names.contains(t) != negated).collect()
}
};
match value("--partition") {
None => filtered,
Some(p) => {
let (k, n) = p.strip_prefix("count:").and_then(|p| p.split_once('/')).unwrap();
let (k, n): (usize, usize) = (k.parse().unwrap(), n.parse().unwrap());
let mut counts = BTreeMap::new();
filtered
.into_iter()
.filter(|(binary, _)| {
let count = counts.entry(*binary).or_insert(0);
let selected = *count % n == k - 1;
*count += 1;
selected
})
.collect()
}
}
}
/// The tests each part of `split` runs, over all of its runs.
fn share<'a>(split: &'static Split, tests: &[(&'a str, &'a str)]) -> Vec<Vec<(&'a str, &'a str)>> {
(1..=split.parts()).map(|index| Part { split, index }.runs().iter().flat_map(|args| selected(args, tests)).collect()).collect()
}
static SPLIT: Split = Split { crates: &["a"], pinned: &[&["a::slow1", "a::slow3"], &["a::slow2"]] };
#[test]
fn a_split_runs_on_its_parts_in_a_row() {
let ws = [m("a"), m("b")];
let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest, Group::Checks], &ws).unwrap();
assert_eq!(shards.iter().map(crates).collect::<Vec<_>>(), [vec!["a"], vec!["a"], vec!["b"], vec![]]);
assert_eq!(shards[1], Shard::Tests(vec![Run::all(vec![m("a")])], Some(Part { split: &SPLIT, index: 2 })));
let apart = assign(&[Group::Part(&SPLIT, 1), Group::Rest, Group::Part(&SPLIT, 2)], &ws).unwrap_err();
assert!(apart.contains("not shards 1 to 2 in a row"), "{apart}");
let missing = assign(&[Group::Part(&SPLIT, 2), Group::Rest], &ws).unwrap_err();
assert!(missing.contains("shard 1 is part 2"), "{missing}");
let twice = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), ALL_A, Group::Rest], &ws).unwrap_err();
assert!(twice.contains("`a` is in shard 1 and shard 3"), "{twice}");
const ONE: Split = Split { crates: &["a"], pinned: &[&[]] };
assert!(assign(&[Group::Part(&ONE, 1), Group::Rest], &ws).unwrap_err().contains("not 2 or more"));
const DOUBLE: Split = Split { crates: &["a"], pinned: &[&["a::t"], &["a::t"]] };
assert!(assign(&[Group::Part(&DOUBLE, 1), Group::Part(&DOUBLE, 2), Group::Rest], &ws).unwrap_err().contains("pinned to two parts"));
}
#[test]
fn every_test_of_a_split_runs_on_exactly_one_part() {
let tests = [
("a::lib", "a::t1"),
("a::lib", "a::slow1"),
("a::lib", "a::t2"),
("a::lib", "a::t3"),
("a::bin/a", "a::slow2"),
("a::bin/a", "a::t4"),
("a::bin/a", "a::t5"),
("a::bin/a", "a::slow3"),
];
let parts = share(&SPLIT, &tests);
assert_eq!(
parts,
[
vec![("a::lib", "a::t1"), ("a::lib", "a::t3"), ("a::bin/a", "a::t4"), ("a::lib", "a::slow1"), ("a::bin/a", "a::slow3")],
vec![("a::lib", "a::t2"), ("a::bin/a", "a::t5"), ("a::bin/a", "a::slow2")],
]
);
let mut all = parts.concat();
all.sort_unstable();
let mut want = tests.to_vec();
want.sort_unstable();
assert_eq!(all, want);
let (one, two) = (Part { split: &SPLIT, index: 1 }, Part { split: &SPLIT, index: 2 });
assert_eq!(
one.runs(),
[
vec![
"--partition".to_owned(),
"count:1/2".to_owned(),
"--no-tests=pass".to_owned(),
"-E".to_owned(),
"not (test(=a::slow1) | test(=a::slow3) | test(=a::slow2))".to_owned(),
],
vec!["-E".to_owned(), "test(=a::slow1) | test(=a::slow3)".to_owned()],
]
);
assert!(one.is_first() && !two.is_first());
let list = r#"{"rust-suites":{"a::lib":{"testcases":{"a::t1":{},"a::slow1":{}}},"a::bin/a":{"testcases":{"a::slow2":{}}}}}"#;
assert_eq!(one.missing_pins(list).unwrap(), ["a::slow3"]);
assert!(two.missing_pins(list).unwrap().is_empty());
assert!(one.missing_pins("invalid JSON").is_err());
assert!(one.missing_pins("{}").is_err());
assert!(one.missing_pins(r#"{"rust-suites":{"a::lib":{}}}"#).is_err());
// A split that pins nothing passes no filterset, which nextest would reject as `not ()`.
static BARE: Split = Split { crates: &["a"], pinned: &[&[], &[]] };
assert_eq!(Part { split: &BARE, index: 2 }.runs(), [vec!["--partition".to_owned(), "count:2/2".to_owned(), "--no-tests=pass".to_owned()]]);
assert_eq!(share(&BARE, &tests).concat().len(), tests.len());
}
#[test]
fn the_rest_shard_takes_every_crate_no_group_names() {
let ws = [m("a"), m("b"), m("c"), m("d")];
let shards = assign(&[Group::Targets(&[(Targets::All, &["c"])]), Group::Rest, Group::Checks], &ws).unwrap();
assert_eq!(shards.iter().map(crates).collect::<Vec<_>>(), [vec!["c"], vec!["a", "b", "d"], vec![]]);
assert_eq!(shards[2], Shard::Checks);
}
/// Every test target of `a`.
const ALL_A: Group = Group::Targets(&[(Targets::All, &["a"])]);
const UNITS: (Targets, &[&str]) = (Targets::Units, &["a"]);
const INTEGRATION: (Targets, &[&str]) = (Targets::Integration, &["a"]);
#[test]
fn a_crate_s_units_and_integration_tests_run_on_two_shards() {
let ws = [m("a"), m("b"), m("c")];
let shards =
assign(&[Group::Targets(&[UNITS]), Group::Targets(&[(Targets::All, &["b"]), INTEGRATION]), Group::Rest, Group::Checks], &ws).unwrap();
assert_eq!(shards[0], Shard::Tests(vec![Run { targets: Targets::Units, crates: vec![m("a")] }], None));
assert_eq!(shards[1], Shard::Tests(vec![Run::all(vec![m("b")]), Run { targets: Targets::Integration, crates: vec![m("a")] }], None));
assert_eq!(crates(&shards[2]), ["c"]);
assert_eq!(
unit_crates(match &shards[1] {
Shard::Tests(r, _) => r,
Shard::Checks => panic!("shard 2 is a test shard"),
}),
[m("b")]
);
let half = assign(&[Group::Targets(&[UNITS]), Group::Rest], &ws).unwrap_err();
assert!(half.contains("no shard runs its integration tests"), "{half}");
let other_half = assign(&[Group::Targets(&[INTEGRATION]), Group::Rest], &ws).unwrap_err();
assert!(other_half.contains("no shard runs its library and binary tests"), "{other_half}");
let with_all = assign(&[ALL_A, Group::Targets(&[INTEGRATION]), Group::Rest], &ws).unwrap_err();
assert!(with_all.contains("`a` is in shard 1 and shard 2"), "{with_all}");
let same_shard = assign(&[Group::Targets(&[UNITS, INTEGRATION]), Group::Rest], &ws).unwrap_err();
assert!(same_shard.contains("`a` is in shard 1 and shard 1"), "{same_shard}");
let units_twice = assign(&[Group::Targets(&[UNITS]), Group::Targets(&[UNITS]), Group::Rest], &ws).unwrap_err();
assert!(units_twice.contains("`a` is in shard 1 and shard 2"), "{units_twice}");
let third =
assign(&[Group::Targets(&[UNITS]), Group::Targets(&[INTEGRATION]), Group::Targets(&[INTEGRATION]), Group::Rest], &ws).unwrap_err();
assert!(third.contains("`a` is in shard 1 and shard 3"), "{third}");
}
#[test]
fn a_crate_named_twice_or_unknown_fails() {
let ws = [m("a"), m("b")];
let twice = assign(&[ALL_A, ALL_A, Group::Rest], &ws).unwrap_err();
assert!(twice.contains("`a` is in shard 1 and shard 2"), "{twice}");
let unknown = assign(&[Group::Targets(&[(Targets::All, &["z"])]), Group::Rest], &ws).unwrap_err();
assert!(unknown.contains("`z`, which is not a workspace member"), "{unknown}");
}
#[test]
fn empty_groups_and_a_missing_or_second_rest_fail() {
let ws = [m("a"), m("b")];
assert!(assign(&[Group::Targets(&[(Targets::All, &[])]), Group::Rest], &ws).unwrap_err().contains("names no crates"));
assert!(assign(&[Group::Targets(&[(Targets::All, &["a", "b"])]), Group::Rest], &ws).unwrap_err().contains("there are none"));
assert!(assign(&[ALL_A], &ws).unwrap_err().contains("0 shards take the remaining crates"));
assert!(assign(&[Group::Rest, Group::Rest], &ws).unwrap_err().contains("2 shards take the remaining crates"));
}
#[test]
fn every_workspace_member_is_tested_on_exactly_one_shard() {
let ws = members(&crate::metadata().unwrap()).unwrap();
let shards = assign(GROUPS, &ws).unwrap();
let mut tested: BTreeMap<&str, Vec<Targets>> = BTreeMap::new();
for (name, targets) in shards.iter().flat_map(owners) {
tested.entry(name).or_default().push(targets);
}
for targets in tested.values_mut() {
targets.sort_unstable();
}
let mut all: Vec<&str> = ws.iter().map(|m| m.name.as_str()).collect();
all.sort_unstable();
assert_eq!(tested.keys().copied().collect::<Vec<_>>(), all);
for (name, targets) in &tested {
assert!(
*targets == [Targets::All] || *targets == [Targets::Units, Targets::Integration],
"`{name}` runs {targets:?}, not each test target once"
);
}
assert_eq!(shards.iter().filter(|s| **s == Shard::Checks).count(), 1);
}
#[test]
fn the_workspace_doc_tests_skip_the_cdylib_thumbnail_handler() {
let ws = members(&crate::metadata().unwrap()).unwrap();
let doctests = |name: &str| ws.iter().find(|m| m.name == name).map(|m| m.doctests);
assert_eq!(doctests("vectorcraft-thumbnail-handler"), Some(false));
assert_eq!(doctests("vectorcraft-geom"), Some(true));
assert_eq!(doctests("vectorcraft-cli"), Some(true));
}
#[test]
fn a_feature_only_another_shard_turns_on_is_a_difference() {
let ws = [m("lib"), m("geom")];
let workspace = "\
lib v0.1.0 (/w/lib)|default,synth
geom v0.1.0 (/w/geom)|
geom v0.18.0 (https://github.com/x/y?rev=1#1)|old
lib v0.1.0 (/w/lib)|default,synth (*)
";
let alone = "\
lib v0.1.0 (/w/lib)|default
geom v0.1.0 (/w/geom)|
";
let workspace = tree_features(workspace, &ws);
assert_eq!(workspace["lib"], BTreeSet::from(["default,synth".to_owned()]));
assert_eq!(workspace["geom"], BTreeSet::from([String::new()]));
let alone = tree_features(alone, &ws);
assert_eq!(feature_differences(4, &ws, &workspace, &alone), ["lib: features [default] in shard 4, [default,synth] with the whole workspace"]);
assert!(feature_differences(4, &ws, &workspace, &workspace).is_empty());
assert_eq!(
feature_differences(4, &[m("lib")], &workspace, &BTreeMap::new()),
["lib: features absent in shard 4, [default,synth] with the whole workspace"]
);
}
#[test]
fn ci_names_the_crates_of_every_shard_for_test_selection() {
assert_eq!(workflow_members(include_str!("../../.github/workflows/ci.yml")), Ok(()));
assert!(workflow_members(" shard-members: |\n a b\n (rest)\n next: 1\n").is_err());
let meta = crate::metadata().unwrap();
let deps: BTreeMap<&str, Vec<&str>> = meta["packages"]
.as_array()
.unwrap()
.iter()
.map(|p| (p["name"].as_str().unwrap(), p["dependencies"].as_array().unwrap().iter().map(|d| d["name"].as_str().unwrap()).collect()))
.collect();
let reaches = |from: &str, to: &str| {
let (mut seen, mut stack) = (BTreeSet::new(), vec![from]);
while let Some(c) = stack.pop() {
if c == to {
return true;
}
if seen.insert(c) {
stack.extend(deps.get(c).into_iter().flatten().copied());
}
}
false
};
for g in GROUPS {
let Group::Targets(lists) = g else { continue };
let named: Vec<&str> = lists.iter().filter(|(t, _)| *t != Targets::Integration).flat_map(|(_, c)| c.iter().copied()).collect();
for crate_ in lists.iter().filter(|(t, _)| *t == Targets::Integration).flat_map(|(_, c)| c.iter().copied()) {
assert!(named.iter().any(|n| reaches(n, crate_)), "no crate on the shard of `{crate_}`'s integration tests depends on it");
}
}
assert_eq!(shard_members(" shard-members: |\n a b\n (rest)\n next: 1\n"), ["a b", "(rest)"]);
assert!(shard_members("test-shards: 6\n").is_empty());
}
}