From 9e46dce65b94a62b23e6d5ac62e419d7282c99dd Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Mon, 26 Oct 2026 10:59:05 -0500 Subject: [PATCH 01/40] feat(xtask): #3058 cargo xtask test runs every test binary under the CI caps `cargo xtask test [-p PKG]... [--keep-going] [--doc] [-- ARGS]` runs the tests alone the way ci does: it takes the machine-wide CI slot, gets ci's caps (build jobs by available RAM, at most 4 test threads, line-table debuginfo), builds every workspace test target once (the same artifacts as ci's test step) and runs each test binary, or the -p packages', with ARGS. It stops at the first failing binary unless --keep-going (alias --no-fail-fast), which runs them all and names each that failed; --doc adds the doctests; LIGHTCRAFT_NEXTEST=1 runs them under cargo nextest with the packages as a filter expression. The caps no longer key on argv[1] == "ci": ci and test opt in with use_ci_caps(), and apply_ci_caps() sets them on every cargo and test binary they start. ci --quick's runner moves into xtask/src/test.rs and shares run_binary (the one place a test binary starts) with test; its directly-run test binaries now get the same RUST_TEST_THREADS as ci's cargo runs (jobs by RAM, at most 4) instead of min(CPUs, 4). Co-Authored-By: Claude Opus 5.5 --- README.md | 9 + docs/architecture.md | 9 + xtask/src/ci.rs | 77 ++------ xtask/src/main.rs | 78 +++++--- xtask/src/test.rs | 434 +++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 526 insertions(+), 81 deletions(-) create mode 100644 xtask/src/test.rs diff --git a/README.md b/README.md index a3e49813607..4d78c13ad84 100644 --- a/README.md +++ b/README.md @@ -407,6 +407,7 @@ cargo xtask web --serve # the same app in the br cargo run --release -p lightcraft-cli -- render photo.jpg -o out.jpg --set light.exposure=0.5 cargo xtask ci # fmt, clippy, HEIF, tests, parity, layers, assets, WASM cargo xtask ci --quick # only what your branch's changes can break (minutes) +cargo xtask test -p lightcraft-raw --keep-going # tests only, with ci's caps; every failing test binary ``` `cargo xtask ci --quick` compares with the merge base of `origin/main` (`--base REF` for another) @@ -427,6 +428,14 @@ unchanged. Explicit `CARGO_PROFILE_DEV_DEBUG`, `CARGO_BUILD_JOBS`, `RUST_TEST_TH `cargo test`; `LIGHTCRAFT_NEXTEST=1` runs them under [cargo-nextest](https://nexte.st) instead (one process per test, slower here because each regenerates the demo scenes). Ordinary development commands keep their own settings. +To run tests without the rest of `ci`, use `cargo xtask test` rather than `cargo test --workspace`, +which runs one test per CPU in every test binary (on a 16-core machine the UI tests alone run out of +memory) and takes no CI slot. It has `ci`'s caps and waits for its slot, builds every test target +once (the same build as `ci`'s, so neither rebuilds the other) and runs each test binary, or those +of the `-p PKG` packages, with whatever follows `--` (`cargo xtask test -p lightcraft-ui-egui -- +i18n::`). It stops at the first failing binary, as `ci` does; `--keep-going` runs them all and +names each that failed. `--doc` adds the doctests; `LIGHTCRAFT_NEXTEST=1` applies here too. + **Release builds on memory-constrained machines:** [#1196](https://github.com/storytold/lightcraft/issues/1196) reports Arch/AUR release-link OOM kills on a 16 GB machine when the desktop and CLI build concurrently with full debug information, thin LTO and one codegen unit. The CI defaults above do not apply to diff --git a/docs/architecture.md b/docs/architecture.md index 9437896b2d9..65d90506753 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -73,6 +73,14 @@ module per file (`cargo test -p --test it ::`); a test that chan whole process (a global allocator, closing the GPU) keeps a binary of its own in `tests/`. The WASM build is one `cargo check --target wasm32-unknown-unknown --keep-going` over the wasm-safe crates. +`ci`'s resource caps (build jobs by available RAM, at most 4 test threads, line-table debuginfo) and +its one-run-per-machine slot (`xtask/src/ci_lock.rs`) also cover `cargo xtask test [-p PKG]… +[--keep-going] [--doc] [-- ARGS]` (`xtask/src/test.rs`), the way to run the tests alone: subcommands +opt into the caps with `use_ci_caps`. It builds every workspace test target once, as `ci` does, and +runs each test binary, or the `-p` packages' binaries, itself (`test::run_binary`, which `ci --quick` +uses too); `--keep-going` runs every binary and names each that failed instead of stopping at the +first. + `ci` also probes the machine: OS, CPUs, RAM, the GPU adapters of each backend (from the ignored `gpu_probe` test of `lightcraft-gpu`, run after the workspace tests so it reuses their build; xtask has no wgpu), the corpus and `CRAFT_FONTS_DIR`. Tests @@ -87,6 +95,7 @@ the `lightcraft-gpu` tests once per backend with a hardware adapter (`LIGHTCRAFT | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | Quality gates: `cargo xtask test` runs the tests with `ci`'s caps and slot, and can keep going past a failing binary | | 2026-10-23 | minor | Quality gates: one integration-test binary per crate, doctests apart, nextest on request, one WASM check | | 2026-10-11 | minor | Quality gates: the CI machine probe, visible skips (`testkit`) and `target/ci/report.json` | | 2026-10-10 | major | Created from the code (crate sizes, layers, data model, rendering, control, gates) | diff --git a/xtask/src/ci.rs b/xtask/src/ci.rs index f5aa147a2dd..a3d97c20c7c 100644 --- a/xtask/src/ci.rs +++ b/xtask/src/ci.rs @@ -1,7 +1,7 @@ use super::layers::cmd_layers; use super::raw_samples::RAW_SAMPLES; use super::wasm::{cmd_wasm, cmd_wasm_for}; -use super::{Command, Path, PathBuf, USAGE, assets, cargo, ci_lock, ci_quick, ci_report, metadata, parity, root, roots, run}; +use super::{Command, PathBuf, USAGE, assets, cargo, ci_lock, ci_quick, ci_report, metadata, parity, root, roots, run, test, use_ci_caps}; /// CI build jobs: one per 1.5 GB of RAM available when CI starts, at most one per CPU, 4 when it /// is unknown. With line-table debuginfo, 4 jobs measured about 3 GB of RAM in use and 2 jobs @@ -63,7 +63,7 @@ pub(crate) fn total_ram_gb() -> Option { const TEST_TARGETS: [&str; 3] = ["--lib", "--bins", "--tests"]; /// `args` followed by [`TEST_TARGETS`]. -fn with_test_targets<'a>(args: &[&'a str]) -> Vec<&'a str> { +pub(crate) fn with_test_targets<'a>(args: &[&'a str]) -> Vec<&'a str> { args.iter().copied().chain(TEST_TARGETS).collect() } @@ -72,7 +72,7 @@ fn with_test_targets<'a>(args: &[&'a str]) -> Vec<&'a str> { /// are cached per process: libtest runs a binary's tests in one process and generates each scene /// once, while nextest's process per test regenerates them (measured: the ui-egui tests take about /// 30 min under nextest, under 5 min under cargo test). -fn nextest() -> bool { +pub(crate) fn nextest() -> bool { static FOUND: std::sync::OnceLock = std::sync::OnceLock::new(); *FOUND.get_or_init(|| { if std::env::var_os("LIGHTCRAFT_NEXTEST").is_none_or(|v| v != "1") { @@ -108,60 +108,6 @@ fn doctests() -> (Command, String) { (c, "cargo test --no-fail-fast --workspace --doc".to_owned()) } -/// `ci --quick`'s tests: build every workspace test target, then run only the test binaries of -/// `packages`. Building with `-p` instead would resolve features per selection: different -/// artifacts from `ci`'s workspace build, so it would recompile ~130 crates. Doc tests are left to -/// the full `ci`. -fn test_selected(root: &Path, packages: &std::collections::BTreeSet, skip_log: &Path) -> Result<(), String> { - let manifests: std::collections::BTreeMap = metadata()?["packages"] - .as_array() - .into_iter() - .flatten() - .filter_map(|p| Some((p["manifest_path"].as_str()?.to_owned(), p["name"].as_str()?.to_owned()))) - .filter(|(_, name)| packages.contains(name)) - .collect(); - let what = "cargo test --workspace --no-run --lib --bins --tests"; - eprintln!("$ {what} (then the test binaries of {})", packages.iter().map(String::as_str).collect::>().join(", ")); - let out = cargo() - .args(with_test_targets(&["test", "--workspace", "--no-run", "--message-format=json-render-diagnostics"])) - .stderr(std::process::Stdio::inherit()) - .output() - .map_err(|e| format!("{what}: failed to spawn: {e}"))?; - if !out.status.success() { - return Err(format!("{what}: exited with {}", out.status)); - } - let mut binaries = Vec::new(); - for line in String::from_utf8_lossy(&out.stdout).lines() { - let Ok(msg) = serde_json::from_str::(line) else { continue }; - if msg["reason"] != "compiler-artifact" || msg["profile"]["test"] != true { - continue; - } - let (Some(exe), Some(manifest)) = (msg["executable"].as_str(), msg["manifest_path"].as_str()) else { continue }; - if let Some(name) = manifests.get(manifest) { - binaries.push((name.clone(), manifest.to_owned(), exe.to_owned())); - } - } - if binaries.is_empty() { - println!("no test binaries in {}", packages.iter().map(String::as_str).collect::>().join(", ")); - return Ok(()); - } - let mut failed = Vec::new(); - for (name, manifest, exe) in &binaries { - let dir = Path::new(manifest).parent().unwrap_or(root); - let mut c = Command::new(exe); - c.current_dir(dir).env("CARGO_MANIFEST_DIR", dir).env("CARGO_PKG_NAME", name).env(ci_report::SKIP_LOG_ENV, skip_log); - if std::env::var_os("RUST_TEST_THREADS").is_none() { - // as the cargo runs of ci (`cargo()`): more threads make the frame-budget tests flaky - c.env("RUST_TEST_THREADS", std::thread::available_parallelism().map_or(4, |n| n.get()).min(4).to_string()); - } - let file = Path::new(exe).file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default(); - if run(c, &format!("{name}: {file}")).is_err() { - failed.push(format!("{name} ({file})")); - } - } - if failed.is_empty() { Ok(()) } else { Err(format!("tests failed in {}", failed.join(", "))) } -} - /// The test that prints the messages each language lacks (shown in English); it always passes. const TRANSLATION_GAPS_TEST: &str = "i18n::tests::translation_gaps_report"; @@ -211,6 +157,7 @@ pub(crate) fn cmd_ci(args: &[&str]) -> Result<(), String> { if base.is_some() && !quick { return Err("ci: --base only applies to --quick".into()); } + use_ci_caps(); let root = root(); let command = std::iter::once("cargo xtask ci").chain(args.iter().copied()).collect::>().join(" "); // held until ci returns: one run at a time per machine (ci_lock.rs) @@ -294,7 +241,7 @@ pub(crate) fn cmd_ci(args: &[&str]) -> Result<(), String> { ( "test", Box::new(|| match &plan { - Some(p) if !p.workspace_wide => test_selected(&root, &p.packages, &ci_report::skip_log(&root, "test")), + Some(p) if !p.workspace_wide => test::selected(&root, &p.packages, &ci_report::skip_log(&root, "test")), _ => test(tests(&with_test_targets(&["--workspace"])), "test").and_then(|()| test(doctests(), "test")), }), ), @@ -458,4 +405,18 @@ mod ci_jobs_tests { assert_eq!(ci_jobs(None, 32), 4, "unknown RAM keeps the old default"); assert_eq!(ci_jobs(None, 2), 2); } + + #[test] + fn caps_cover_build_and_test_threads_and_yield_to_explicit_settings() { + let caps = crate::ci_caps(); + let keys: Vec<&str> = caps.iter().map(|(k, _)| *k).collect(); + assert_eq!(keys, ["CARGO_PROFILE_DEV_DEBUG", "CARGO_BUILD_JOBS", "RUST_TEST_THREADS", "NEXTEST_TEST_THREADS"]); + for (key, value) in caps.iter().filter(|(k, _)| k.ends_with("TEST_THREADS")) { + let n: usize = value.parse().unwrap(); + assert!((1..=4).contains(&n), "{key}={value}"); + } + let set = crate::caps_to_set(caps, |key| key == "RUST_TEST_THREADS"); + assert_eq!(set.iter().map(|(k, _)| *k).collect::>(), ["CARGO_PROFILE_DEV_DEBUG", "CARGO_BUILD_JOBS", "NEXTEST_TEST_THREADS"]); + assert!(crate::caps_to_set(caps, |_| true).is_empty()); + } } diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 33b236b56d9..a92d9a5cde2 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -15,6 +15,7 @@ mod layers; mod parity; mod roots; mod stats; +mod test; mod version; mod web; @@ -63,6 +64,13 @@ commands: break: clippy, the changed packages' tests, and heif / parity / wasm when they apply. One ci runs at a time per machine; others wait (LIGHTCRAFT_CI_SLOTS=N for N at once, LIGHTCRAFT_CI_LOCK=off to skip the lock) + test [-p PKG]... [--keep-going] [--doc] [-- ARGS] + the workspace's tests (or PKG's) with ci's caps (build jobs by free RAM, at most 4 test + threads, line-table debuginfo) in ci's machine-wide slot, instead of `cargo test`: + builds every test target once, then runs each test binary with ARGS (a filter, + --exact, --skip, --nocapture); stops at the first failing binary unless --keep-going + (alias --no-fail-fast), which runs them all and names each that failed; --doc runs the + doctests after them. LIGHTCRAFT_NEXTEST=1 runs the tests under cargo nextest corpus [--download] show where test corpora live; --download fetches PngSuite and CC0 raw samples (raw.pixls.us) into corpus/ and checks their sha256 stats [--exact] count tests and lines per crate (--exact: ask the test harness via `-- --list`) @@ -87,6 +95,7 @@ fn main() -> ExitCode { Some("wasm") => cmd_wasm(), Some("web") => web::run(&rest), Some("ci") => cmd_ci(&rest), + Some("test") => test::run(&rest), Some("corpus") => cmd_corpus(rest.contains(&"--download")), Some("stats") => stats::run(&root(), rest.contains(&"--exact")), Some("raw-frame") => cmd_raw_frame(&rest), @@ -139,32 +148,55 @@ fn workspace_root(runtime_manifest_dir: Option, compile_time_manifest_d pub fn cargo() -> Command { let mut c = Command::new(std::env::var("CARGO").unwrap_or_else(|_| "cargo".into())); c.current_dir(root()); - // Full Windows debuginfo plus one linker per CPU can exhaust RAM before any - // tests run. Scope these overridable defaults to CI, including parity/WASM - // subprocesses, without changing ordinary developer builds or GPU coverage. - if std::env::args().nth(1).as_deref() == Some("ci") { - static JOBS: std::sync::OnceLock<(String, String)> = std::sync::OnceLock::new(); - let (build, threads) = JOBS.get_or_init(|| { - let ram_mb = available_ram_mb().or_else(|| total_ram_gb().map(|gb| gb.saturating_mul(1024) / 2)); - let jobs = ci_jobs(ram_mb, std::thread::available_parallelism().map_or(4, |n| n.get())); - // More test threads barely shorten CI (a few heavy tests dominate) but make the - // wall-clock frame-budget tests flaky on a loaded machine. - (jobs.to_string(), jobs.min(4).to_string()) - }); - for (key, value) in [ - ("CARGO_PROFILE_DEV_DEBUG", "line-tables-only"), - ("CARGO_BUILD_JOBS", build.as_str()), - ("RUST_TEST_THREADS", threads.as_str()), - ("NEXTEST_TEST_THREADS", threads.as_str()), - ] { - if std::env::var_os(key).is_none() { - c.env(key, value); - } - } - } + apply_ci_caps(&mut c); c } +/// Whether this run gives the cargo and test processes it starts CI's resource caps +/// ([`apply_ci_caps`]). Off until a subcommand opts in with [`use_ci_caps`]. +static CI_CAPS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Opt this run into CI's resource caps: the subcommands that build and run the test suite (`ci`, +/// `test`) call it first, so every cargo and test binary they start, including parity and WASM +/// subprocesses, gets them. Ordinary developer builds keep their own settings. +fn use_ci_caps() { + CI_CAPS.store(true, std::sync::atomic::Ordering::Relaxed); +} + +/// The environment defaults of a capped run, worked out once: line-table debuginfo, build jobs by +/// available RAM ([`ci_jobs`]) and test threads at most 4. +fn ci_caps() -> &'static [(&'static str, String); 4] { + static CAPS: std::sync::OnceLock<[(&'static str, String); 4]> = std::sync::OnceLock::new(); + CAPS.get_or_init(|| { + let ram_mb = available_ram_mb().or_else(|| total_ram_gb().map(|gb| gb.saturating_mul(1024) / 2)); + let jobs = ci_jobs(ram_mb, std::thread::available_parallelism().map_or(4, |n| n.get())); + // More test threads barely shorten CI (a few heavy tests dominate) but make the + // wall-clock frame-budget tests flaky on a loaded machine. + let threads = jobs.min(4).to_string(); + [ + ("CARGO_PROFILE_DEV_DEBUG", "line-tables-only".to_owned()), + ("CARGO_BUILD_JOBS", jobs.to_string()), + ("RUST_TEST_THREADS", threads.clone()), + ("NEXTEST_TEST_THREADS", threads), + ] + }) +} + +/// The caps `c` gets: each of `caps` the environment doesn't set itself (`is_set`), so an explicit +/// setting always wins. +fn caps_to_set<'a>(caps: &'a [(&'static str, String)], is_set: impl Fn(&str) -> bool) -> Vec<(&'static str, &'a str)> { + caps.iter().filter(|(key, _)| !is_set(key)).map(|(key, value)| (*key, value.as_str())).collect() +} + +/// Give `c` CI's resource caps when this run opted in ([`use_ci_caps`]). Full Windows debuginfo +/// plus one linker per CPU can exhaust RAM before any tests run, and one test thread per CPU +/// can exhaust it while they run (#3057). +fn apply_ci_caps(c: &mut Command) { + if CI_CAPS.load(std::sync::atomic::Ordering::Relaxed) { + c.envs(caps_to_set(ci_caps(), |key| std::env::var_os(key).is_some())); + } +} + pub fn run(mut cmd: Command, what: &str) -> Result<(), String> { eprintln!("$ {what}"); let status = cmd.status().map_err(|e| format!("{what}: failed to spawn: {e}"))?; diff --git a/xtask/src/test.rs b/xtask/src/test.rs new file mode 100644 index 00000000000..0659af1ea22 --- /dev/null +++ b/xtask/src/test.rs @@ -0,0 +1,434 @@ +//! `cargo xtask test [-p PKG]… [--keep-going] [--doc] [-- ARGS]`: the workspace tests, or some +//! packages' tests, under the same caps as `ci` and in its machine-wide slot. +//! +//! Plain `cargo test --workspace` runs one test per CPU in every test binary and takes no CI slot: +//! on a 16-core machine the ui-egui tests alone then run out of memory (#3057). This runs them the +//! way `ci` does: build jobs by available RAM, at most 4 test threads, line-table debuginfo +//! ([`super::use_ci_caps`]), one run per machine ([`ci_lock`]). +//! +//! It builds every workspace test target once (`cargo test --workspace --no-run`, the same +//! artifacts as `ci`'s test step, so nothing rebuilds between them) and then runs each test binary +//! itself ([`run_binary`]), passing it `ARGS` (a filter, `--exact`, `--skip`, `--nocapture`, …). +//! It stops at the first failing binary, as `ci` does; `--keep-going` runs every binary and names +//! each that failed. `--doc` runs the doctests after them. With `LIGHTCRAFT_NEXTEST=1` (and +//! cargo-nextest installed) the binaries run under `cargo nextest run` instead, as in `ci`. +//! +//! `ci --quick` runs the changed packages' tests through the same functions ([`selected`]). + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; +use std::process::Command; + +use crate::ci_lock; + +/// What `cargo xtask test` was asked to run. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Args<'a> { + /// `-p` packages; empty for the whole workspace. + pub packages: BTreeSet, + /// Run every test binary and report all that failed, rather than stop at the first. + pub keep_going: bool, + /// Run the doctests too, after the test binaries. + pub doc: bool, + /// What follows `--`, passed to every test binary (and the doctests). + pub test_args: Vec<&'a str>, +} + +/// Parse the arguments after `cargo xtask test`. +pub fn parse<'a>(args: &[&'a str]) -> Result, String> { + let mut parsed = Args::default(); + let mut it = args.iter().copied(); + while let Some(arg) = it.next() { + match arg { + "--" => { + parsed.test_args = it.by_ref().collect(); + } + // `--no-fail-fast` is cargo's name for it + "--keep-going" | "--no-fail-fast" => parsed.keep_going = true, + "--doc" => parsed.doc = true, + "-p" | "--package" => { + let Some(pkg) = it.next().filter(|p| !p.is_empty() && !p.starts_with('-')) else { + return Err(format!("test: {arg} needs a package name")); + }; + parsed.packages.insert(pkg.to_owned()); + } + _ => match arg.strip_prefix("--package=").or_else(|| arg.strip_prefix("-p")).map(|p| p.trim_start_matches('=')).filter(|p| !p.is_empty()) + { + Some(pkg) => { + parsed.packages.insert(pkg.to_owned()); + } + None => return Err(format!("test: unknown option `{arg}` (test arguments go after `--`)")), + }, + } + } + Ok(parsed) +} + +/// A workspace package: its name and whether it has a library (so doctests). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Package { + pub name: String, + pub lib: bool, +} + +/// The workspace packages in `metadata` (`cargo metadata --no-deps`) by manifest path, or only +/// those in `only` (an error names any that aren't workspace packages). +pub fn packages(metadata: &serde_json::Value, only: &BTreeSet) -> Result, String> { + let all: BTreeMap = metadata["packages"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| { + let lib = p["targets"] + .as_array() + .into_iter() + .flatten() + .any(|t| t["kind"].as_array().into_iter().flatten().any(|k| matches!(k.as_str(), Some("lib" | "rlib" | "proc-macro")))); + Some((p["manifest_path"].as_str()?.to_owned(), Package { name: p["name"].as_str()?.to_owned(), lib })) + }) + .collect(); + let names: BTreeSet<&str> = all.values().map(|p| p.name.as_str()).collect(); + let unknown: Vec<&str> = only.iter().map(String::as_str).filter(|p| !names.contains(p)).collect(); + if !unknown.is_empty() { + return Err(format!( + "test: not a workspace package: {} (packages: {})", + unknown.join(", "), + names.into_iter().collect::>().join(", ") + )); + } + Ok(all.into_iter().filter(|(_, p)| only.is_empty() || only.contains(&p.name)).collect()) +} + +/// A test binary cargo built: its package, the package's manifest and the executable. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Binary { + pub package: String, + pub manifest: String, + pub exe: String, +} + +impl Binary { + /// `package (file)`, how the log and the summary name it. + pub fn label(&self) -> String { + let file = Path::new(&self.exe).file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default(); + format!("{} ({file})", self.package) + } +} + +/// The test binaries of `packages` among the artifacts in cargo's JSON messages (`stdout` of a +/// `--message-format=json` build), by package and file name. +pub fn binaries(stdout: &str, packages: &BTreeMap) -> Vec { + let mut found: Vec = stdout + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .filter(|msg| msg["reason"] == "compiler-artifact" && msg["profile"]["test"] == true) + .filter_map(|msg| { + let (exe, manifest) = (msg["executable"].as_str()?, msg["manifest_path"].as_str()?); + let package = packages.get(manifest)?; + Some(Binary { package: package.name.clone(), manifest: manifest.to_owned(), exe: exe.to_owned() }) + }) + .collect(); + found.sort_by(|a, b| (&a.package, &a.exe).cmp(&(&b.package, &b.exe))); + found.dedup(); + found +} + +/// Build every workspace test target once and return the test binaries of `packages`. Building +/// with `-p` instead would resolve features per selection: different artifacts from `ci`'s +/// workspace build, so it would recompile ~130 crates. +pub fn build(packages: &BTreeMap, whole_workspace: bool) -> Result, String> { + let what = "cargo test --workspace --no-run --lib --bins --tests"; + let then = if whole_workspace { "every test binary".to_owned() } else { format!("the test binaries of {}", names(packages.values())) }; + eprintln!("$ {what} (then {then})"); + let out = super::cargo() + .args(crate::ci::with_test_targets(&["test", "--workspace", "--no-run", "--message-format=json-render-diagnostics"])) + .stderr(std::process::Stdio::inherit()) + .output() + .map_err(|e| format!("{what}: failed to spawn: {e}"))?; + if !out.status.success() { + return Err(format!("{what}: exited with {}", out.status)); + } + Ok(binaries(&String::from_utf8_lossy(&out.stdout), packages)) +} + +fn names<'a>(packages: impl Iterator) -> String { + packages.map(|p| p.name.as_str()).collect::>().join(", ") +} + +/// Run one test binary as `cargo test` would (from its package's directory, with its +/// `CARGO_MANIFEST_DIR` and `CARGO_PKG_NAME`) under CI's caps, with `args`; skips the tests record +/// go to `skip_log`. The one place `test` and `ci --quick` start a test binary and wait for it. +pub fn run_binary(root: &Path, binary: &Binary, args: &[&str], skip_log: Option<&Path>) -> Result<(), String> { + let dir = Path::new(&binary.manifest).parent().unwrap_or(root); + let mut c = Command::new(&binary.exe); + c.current_dir(dir).env("CARGO_MANIFEST_DIR", dir).env("CARGO_PKG_NAME", &binary.package).args(args); + if let Some(log) = skip_log { + c.env(crate::ci_report::SKIP_LOG_ENV, log); + } + super::apply_ci_caps(&mut c); + let shown = std::iter::once(binary.label()).chain(args.iter().map(|a| (*a).to_owned())).collect::>().join(" "); + super::run(c, &shown) +} + +/// The outcome of running a list of test binaries. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Outcome { + pub passed: usize, + /// The labels of the binaries that failed. + pub failed: Vec, + /// Binaries not run: the run stopped at the first failure. + pub not_run: usize, +} + +/// Run `binaries` in order with `run_one`; stop at the first failure unless `keep_going`. +pub fn run_all(binaries: &[Binary], keep_going: bool, mut run_one: impl FnMut(&Binary) -> Result<(), String>) -> Outcome { + let mut outcome = Outcome::default(); + for (i, binary) in binaries.iter().enumerate() { + if run_one(binary).is_ok() { + outcome.passed += 1; + continue; + } + outcome.failed.push(binary.label()); + if !keep_going { + outcome.not_run = binaries.len().saturating_sub(i + 1); + break; + } + } + outcome +} + +/// `ci --quick`'s tests: the test binaries of `packages`, every one of them (each failure named). +/// Doctests are left to the full `ci`. +pub fn selected(root: &Path, packages: &BTreeSet, skip_log: &Path) -> Result<(), String> { + let packages = self::packages(&super::metadata()?, packages)?; + let binaries = build(&packages, false)?; + if binaries.is_empty() { + println!("no test binaries in {}", names(packages.values())); + return Ok(()); + } + let outcome = run_all(&binaries, true, |b| run_binary(root, b, &[], Some(skip_log))); + if outcome.failed.is_empty() { Ok(()) } else { Err(format!("tests failed in {}", outcome.failed.join(", "))) } +} + +/// The `cargo nextest run` arguments for `args`: the workspace build, the `-p` packages as a +/// filter expression (so the build is still the workspace's), `--no-fail-fast` for `--keep-going`. +pub fn nextest_args<'a>(args: &Args<'a>) -> Vec { + let mut v: Vec = crate::ci::with_test_targets(&["--workspace"]).into_iter().map(str::to_owned).collect(); + if !args.packages.is_empty() { + let filter = args.packages.iter().map(|p| format!("package(={p})")).collect::>().join(" | "); + v.extend(["-E".to_owned(), filter]); + } + if args.keep_going { + v.push("--no-fail-fast".to_owned()); + } + if !args.test_args.is_empty() { + v.push("--".to_owned()); + v.extend(args.test_args.iter().map(|a| (*a).to_owned())); + } + v +} + +/// The `cargo test --doc` arguments for `args`: the workspace's doctests, or those of the `-p` +/// packages that have a library (`None` when none has). +pub fn doc_args<'a>(args: &Args<'a>, packages: &BTreeMap) -> Option> { + let mut v = vec!["test".to_owned(), "--doc".to_owned()]; + if args.packages.is_empty() { + v.push("--workspace".to_owned()); + } else { + let libs: Vec<&Package> = packages.values().filter(|p| p.lib).collect(); + if libs.is_empty() { + return None; + } + for p in libs { + v.extend(["-p".to_owned(), p.name.clone()]); + } + } + if !args.test_args.is_empty() { + v.push("--".to_owned()); + v.extend(args.test_args.iter().map(|a| (*a).to_owned())); + } + Some(v) +} + +/// `cargo xtask test`. +pub fn run(raw: &[&str]) -> Result<(), String> { + let args = parse(raw)?; + super::use_ci_caps(); + let root = super::root(); + let command = std::iter::once("cargo xtask test").chain(raw.iter().copied()).collect::>().join(" "); + // held until the run ends: one ci or test run at a time per machine (ci_lock.rs) + let _slot = ci_lock::acquire(&root, &command)?; + let packages = packages(&super::metadata()?, &args.packages)?; + let mut failed = Vec::new(); + let mut summary = Vec::new(); + if crate::ci::nextest() { + let nextest = nextest_args(&args); + let mut c = super::cargo(); + c.args(["nextest", "run"]).args(&nextest); + if super::run(c, &format!("cargo nextest run {}", nextest.join(" "))).is_err() { + failed.push("cargo nextest run".to_owned()); + } + } else { + let binaries = build(&packages, args.packages.is_empty())?; + if binaries.is_empty() { + println!("no test binaries in {}", names(packages.values())); + } + let outcome = run_all(&binaries, args.keep_going, |b| run_binary(&root, b, &args.test_args, None)); + summary.push(format!("{} of {} test binaries passed", outcome.passed, binaries.len())); + if outcome.not_run > 0 { + summary.push(format!("{} not run after the first failure (--keep-going runs them)", outcome.not_run)); + } + failed.extend(outcome.failed); + } + if args.doc && !failed.is_empty() && !args.keep_going { + summary.push("doctests not run after the failure".to_owned()); + } else if args.doc { + match doc_args(&args, &packages) { + Some(doc) => { + let mut c = super::cargo(); + c.args(&doc); + if super::run(c, &format!("cargo {}", doc.join(" "))).is_err() { + failed.push("doctests".to_owned()); + } + } + None => println!("no doctests: none of {} has a library", names(packages.values())), + } + } + println!("\ntest summary: {}", if summary.is_empty() { "done".to_owned() } else { summary.join("; ") }); + if failed.is_empty() { + println!(" all passed"); + return Ok(()); + } + for f in &failed { + println!(" FAIL {f}"); + } + Err(format!("tests failed in {}", failed.join(", "))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_packages_keep_going_doc_and_test_args() { + let a = parse(&[ + "-p", + "lightcraft-geom", + "--package", + "xtask", + "--package=lightcraft-raw", + "-plightcraft-color", + "--keep-going", + "--doc", + "--", + "foo::", + "--exact", + ]) + .unwrap(); + assert_eq!(a.packages.iter().map(String::as_str).collect::>(), ["lightcraft-color", "lightcraft-geom", "lightcraft-raw", "xtask"]); + assert!(a.keep_going && a.doc); + assert_eq!(a.test_args, ["foo::", "--exact"]); + assert_eq!(parse(&[]).unwrap(), Args::default(), "no arguments: every package, fail fast, no doctests"); + assert!(parse(&["--no-fail-fast"]).unwrap().keep_going, "cargo's name for it"); + assert_eq!(parse(&["--", "--keep-going", "-p"]).unwrap().test_args, ["--keep-going", "-p"], "after `--` everything is the binaries'"); + } + + #[test] + fn rejects_unknown_options_and_a_missing_package() { + assert!(parse(&["--workspace"]).unwrap_err().contains("unknown option `--workspace`")); + assert!(parse(&["foo"]).unwrap_err().contains("after `--`"), "a bare filter must follow `--`"); + assert!(parse(&["-p"]).unwrap_err().contains("needs a package name")); + assert!(parse(&["-p", "--doc"]).unwrap_err().contains("needs a package name")); + assert!(parse(&["--package="]).is_err()); + assert!(parse(&["-p="]).is_err()); + } + + fn metadata() -> serde_json::Value { + serde_json::json!({"packages": [ + {"name": "a", "manifest_path": "/w/a/Cargo.toml", "targets": [{"kind": ["lib"]}, {"kind": ["test"]}]}, + {"name": "b", "manifest_path": "/w/b/Cargo.toml", "targets": [{"kind": ["bin"]}]}, + {"name": "c", "manifest_path": "/w/c/Cargo.toml", "targets": [{"kind": ["proc-macro"]}]}, + ]}) + } + + #[test] + fn selects_workspace_packages_and_names_unknown_ones() { + let all = packages(&metadata(), &BTreeSet::new()).unwrap(); + assert_eq!(all.len(), 3); + assert_eq!(all["/w/b/Cargo.toml"], Package { name: "b".into(), lib: false }); + assert!(all["/w/c/Cargo.toml"].lib, "a proc-macro crate has doctests"); + let only = packages(&metadata(), &["b".to_owned()].into()).unwrap(); + assert_eq!(only.keys().collect::>(), ["/w/b/Cargo.toml"]); + let err = packages(&metadata(), &["a".to_owned(), "nope".to_owned()].into()).unwrap_err(); + assert!(err.contains("not a workspace package: nope") && err.contains("packages: a, b, c"), "{err}"); + } + + #[test] + fn finds_the_test_binaries_of_the_selected_packages() { + let sel = packages(&metadata(), &["a".to_owned()].into()).unwrap(); + let stdout = [ + r#"{"reason":"compiler-artifact","profile":{"test":true},"manifest_path":"/w/a/Cargo.toml","executable":"/t/debug/deps/it-2"}"#, + r#"{"reason":"compiler-artifact","profile":{"test":false},"manifest_path":"/w/a/Cargo.toml","executable":null}"#, + r#"{"reason":"compiler-artifact","profile":{"test":true},"manifest_path":"/w/b/Cargo.toml","executable":"/t/debug/deps/b-1"}"#, + r#"{"reason":"build-finished","success":true}"#, + "not json", + r#"{"reason":"compiler-artifact","profile":{"test":true},"manifest_path":"/w/a/Cargo.toml","executable":"/t/debug/deps/a-1"}"#, + ] + .join("\n"); + let found = binaries(&stdout, &sel); + assert_eq!(found.iter().map(Binary::label).collect::>(), ["a (a-1)", "a (it-2)"]); + assert_eq!(found.first().map(|b| b.manifest.as_str()), Some("/w/a/Cargo.toml")); + } + + fn bins(names: &[&str]) -> Vec { + names.iter().map(|n| Binary { package: (*n).to_owned(), manifest: format!("/w/{n}/Cargo.toml"), exe: format!("/t/{n}-0") }).collect() + } + + #[test] + fn keep_going_runs_every_binary_and_names_each_failure() { + let binaries = bins(&["a", "b", "c", "d"]); + let fail = |b: &Binary| if b.package == "b" || b.package == "d" { Err("exit 101".to_owned()) } else { Ok(()) }; + let mut ran = Vec::new(); + let outcome = run_all(&binaries, true, |b| { + ran.push(b.package.clone()); + fail(b) + }); + assert_eq!(ran, ["a", "b", "c", "d"]); + assert_eq!(outcome, Outcome { passed: 2, failed: vec!["b (b-0)".into(), "d (d-0)".into()], not_run: 0 }); + } + + #[test] + fn without_keep_going_the_first_failure_stops_the_run() { + let binaries = bins(&["a", "b", "c", "d"]); + let mut ran = Vec::new(); + let outcome = run_all(&binaries, false, |b| { + ran.push(b.package.clone()); + if b.package == "b" { Err("exit 101".to_owned()) } else { Ok(()) } + }); + assert_eq!(ran, ["a", "b"]); + assert_eq!(outcome, Outcome { passed: 1, failed: vec!["b (b-0)".into()], not_run: 2 }); + assert_eq!(run_all(&binaries, false, |_| Ok(())), Outcome { passed: 4, failed: vec![], not_run: 0 }); + } + + #[test] + fn nextest_keeps_the_workspace_build_and_filters_packages() { + let all = parse(&[]).unwrap(); + assert_eq!(nextest_args(&all), ["--workspace", "--lib", "--bins", "--tests"]); + let some = parse(&["-p", "b", "-p", "a", "--keep-going", "--", "foo"]).unwrap(); + assert_eq!( + nextest_args(&some), + ["--workspace", "--lib", "--bins", "--tests", "-E", "package(=a) | package(=b)", "--no-fail-fast", "--", "foo"] + ); + } + + #[test] + fn doctests_cover_the_workspace_or_the_selected_libraries() { + let all = packages(&metadata(), &BTreeSet::new()).unwrap(); + assert_eq!(doc_args(&parse(&["--doc"]).unwrap(), &all).unwrap(), ["test", "--doc", "--workspace"]); + let args = parse(&["-p", "a", "-p", "b", "--doc", "--", "x"]).unwrap(); + let sel = packages(&metadata(), &args.packages).unwrap(); + assert_eq!(doc_args(&args, &sel).unwrap(), ["test", "--doc", "-p", "a", "--", "x"], "b has no library"); + let bin_only = parse(&["-p", "b"]).unwrap(); + assert_eq!(doc_args(&bin_only, &packages(&metadata(), &bin_only.packages).unwrap()), None); + } +} From 6b6bbd32355bb8f8fe9a724ba6b9a7105f3ba0e2 Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Mon, 26 Oct 2026 11:43:05 -0500 Subject: [PATCH 02/40] fix(xtask): #3058 keep going through doctests, keep ci --quick's threads, report how a binary ended - `--keep-going --doc` passes `--no-fail-fast` to `cargo test --doc`, so one package's failing doctests don't stop the next package's. - ci --quick's directly-run test binaries keep their previous default, RUST_TEST_THREADS = min(CPUs, 4) and nothing else (run_binary's Caps::QuickCi); cargo xtask test gets all of ci's caps (Caps::Ci, RAM-aware threads). - run_binary keeps how each binary ended (exit status, the signal that killed it, with a hint for SIGKILL from the out-of-memory killer, or why it didn't start), and the test summary prints it next to each failing binary. Co-Authored-By: Claude Opus 5.5 --- xtask/src/test.rs | 118 +++++++++++++++++++++++++++++++++++++--------- 1 file changed, 96 insertions(+), 22 deletions(-) diff --git a/xtask/src/test.rs b/xtask/src/test.rs index 0659af1ea22..dde8e9de643 100644 --- a/xtask/src/test.rs +++ b/xtask/src/test.rs @@ -155,27 +155,61 @@ fn names<'a>(packages: impl Iterator) -> String { packages.map(|p| p.name.as_str()).collect::>().join(", ") } +/// The resource limits a test binary run directly gets, where the environment doesn't set them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Caps { + /// `cargo xtask test`: all of CI's caps ([`super::apply_ci_caps`]), so `RUST_TEST_THREADS` is + /// the RAM-aware `min(build jobs by available RAM, 4)` that `ci`'s cargo runs get. + Ci, + /// `ci --quick`: only `RUST_TEST_THREADS = min(CPUs, 4)`, its default before `test` existed. + QuickCi, +} + /// Run one test binary as `cargo test` would (from its package's directory, with its -/// `CARGO_MANIFEST_DIR` and `CARGO_PKG_NAME`) under CI's caps, with `args`; skips the tests record +/// `CARGO_MANIFEST_DIR` and `CARGO_PKG_NAME`) under `caps`, with `args`; skips the tests record /// go to `skip_log`. The one place `test` and `ci --quick` start a test binary and wait for it. -pub fn run_binary(root: &Path, binary: &Binary, args: &[&str], skip_log: Option<&Path>) -> Result<(), String> { +/// The error says how it ended: its exit status, the signal that killed it, or why it didn't start. +pub fn run_binary(root: &Path, binary: &Binary, args: &[&str], skip_log: Option<&Path>, caps: Caps) -> Result<(), String> { let dir = Path::new(&binary.manifest).parent().unwrap_or(root); let mut c = Command::new(&binary.exe); c.current_dir(dir).env("CARGO_MANIFEST_DIR", dir).env("CARGO_PKG_NAME", &binary.package).args(args); if let Some(log) = skip_log { c.env(crate::ci_report::SKIP_LOG_ENV, log); } - super::apply_ci_caps(&mut c); + match caps { + Caps::Ci => super::apply_ci_caps(&mut c), + Caps::QuickCi => { + if std::env::var_os("RUST_TEST_THREADS").is_none() { + // as the cargo runs of ci (`cargo()`): more threads make the frame-budget tests flaky + c.env("RUST_TEST_THREADS", std::thread::available_parallelism().map_or(4, |n| n.get()).min(4).to_string()); + } + } + } let shown = std::iter::once(binary.label()).chain(args.iter().map(|a| (*a).to_owned())).collect::>().join(" "); - super::run(c, &shown) + eprintln!("$ {shown}"); + let status = c.status().map_err(|e| format!("failed to start: {e}"))?; + if status.success() { Ok(()) } else { Err(describe(status)) } +} + +/// How a process that failed ended: `exit status: 101`, or on Unix the signal that killed it +/// (`signal: 9 (SIGKILL)`), with a hint for SIGKILL, which is what the out-of-memory killer sends. +pub fn describe(status: std::process::ExitStatus) -> String { + #[cfg(unix)] + { + use std::os::unix::process::ExitStatusExt; + if status.signal() == Some(9) { + return format!("{status}: killed, maybe for running out of memory"); + } + } + status.to_string() } /// The outcome of running a list of test binaries. #[derive(Debug, Default, PartialEq, Eq)] pub struct Outcome { pub passed: usize, - /// The labels of the binaries that failed. - pub failed: Vec, + /// The labels of the binaries that failed, each with how it ended. + pub failed: Vec<(String, String)>, /// Binaries not run: the run stopped at the first failure. pub not_run: usize, } @@ -184,11 +218,11 @@ pub struct Outcome { pub fn run_all(binaries: &[Binary], keep_going: bool, mut run_one: impl FnMut(&Binary) -> Result<(), String>) -> Outcome { let mut outcome = Outcome::default(); for (i, binary) in binaries.iter().enumerate() { - if run_one(binary).is_ok() { + let Err(error) = run_one(binary) else { outcome.passed += 1; continue; - } - outcome.failed.push(binary.label()); + }; + outcome.failed.push((binary.label(), error)); if !keep_going { outcome.not_run = binaries.len().saturating_sub(i + 1); break; @@ -206,8 +240,12 @@ pub fn selected(root: &Path, packages: &BTreeSet, skip_log: &Path) -> Re println!("no test binaries in {}", names(packages.values())); return Ok(()); } - let outcome = run_all(&binaries, true, |b| run_binary(root, b, &[], Some(skip_log))); - if outcome.failed.is_empty() { Ok(()) } else { Err(format!("tests failed in {}", outcome.failed.join(", "))) } + let outcome = run_all(&binaries, true, |b| run_binary(root, b, &[], Some(skip_log), Caps::QuickCi)); + if outcome.failed.is_empty() { + Ok(()) + } else { + Err(format!("tests failed in {}", outcome.failed.iter().map(|(label, _)| label.as_str()).collect::>().join(", "))) + } } /// The `cargo nextest run` arguments for `args`: the workspace build, the `-p` packages as a @@ -229,7 +267,8 @@ pub fn nextest_args<'a>(args: &Args<'a>) -> Vec { } /// The `cargo test --doc` arguments for `args`: the workspace's doctests, or those of the `-p` -/// packages that have a library (`None` when none has). +/// packages that have a library (`None` when none has); `--no-fail-fast` for `--keep-going`, so a +/// package's failing doctests don't stop the next package's. pub fn doc_args<'a>(args: &Args<'a>, packages: &BTreeMap) -> Option> { let mut v = vec!["test".to_owned(), "--doc".to_owned()]; if args.packages.is_empty() { @@ -243,6 +282,9 @@ pub fn doc_args<'a>(args: &Args<'a>, packages: &BTreeMap) -> Op v.extend(["-p".to_owned(), p.name.clone()]); } } + if args.keep_going { + v.push("--no-fail-fast".to_owned()); + } if !args.test_args.is_empty() { v.push("--".to_owned()); v.extend(args.test_args.iter().map(|a| (*a).to_owned())); @@ -265,15 +307,15 @@ pub fn run(raw: &[&str]) -> Result<(), String> { let nextest = nextest_args(&args); let mut c = super::cargo(); c.args(["nextest", "run"]).args(&nextest); - if super::run(c, &format!("cargo nextest run {}", nextest.join(" "))).is_err() { - failed.push("cargo nextest run".to_owned()); + if let Err(e) = super::run(c, &format!("cargo nextest run {}", nextest.join(" "))) { + failed.push(("cargo nextest run".to_owned(), e)); } } else { let binaries = build(&packages, args.packages.is_empty())?; if binaries.is_empty() { println!("no test binaries in {}", names(packages.values())); } - let outcome = run_all(&binaries, args.keep_going, |b| run_binary(&root, b, &args.test_args, None)); + let outcome = run_all(&binaries, args.keep_going, |b| run_binary(&root, b, &args.test_args, None, Caps::Ci)); summary.push(format!("{} of {} test binaries passed", outcome.passed, binaries.len())); if outcome.not_run > 0 { summary.push(format!("{} not run after the first failure (--keep-going runs them)", outcome.not_run)); @@ -287,8 +329,8 @@ pub fn run(raw: &[&str]) -> Result<(), String> { Some(doc) => { let mut c = super::cargo(); c.args(&doc); - if super::run(c, &format!("cargo {}", doc.join(" "))).is_err() { - failed.push("doctests".to_owned()); + if let Err(e) = super::run(c, &format!("cargo {}", doc.join(" "))) { + failed.push(("doctests".to_owned(), e)); } } None => println!("no doctests: none of {} has a library", names(packages.values())), @@ -299,10 +341,10 @@ pub fn run(raw: &[&str]) -> Result<(), String> { println!(" all passed"); return Ok(()); } - for f in &failed { - println!(" FAIL {f}"); + for (label, error) in &failed { + println!(" FAIL {label}: {error}"); } - Err(format!("tests failed in {}", failed.join(", "))) + Err(format!("tests failed in {}", failed.iter().map(|(label, _)| label.as_str()).collect::>().join(", "))) } #[cfg(test)] @@ -394,7 +436,8 @@ mod tests { fail(b) }); assert_eq!(ran, ["a", "b", "c", "d"]); - assert_eq!(outcome, Outcome { passed: 2, failed: vec!["b (b-0)".into(), "d (d-0)".into()], not_run: 0 }); + let failed = vec![("b (b-0)".into(), "exit 101".into()), ("d (d-0)".into(), "exit 101".into())]; + assert_eq!(outcome, Outcome { passed: 2, failed, not_run: 0 }); } #[test] @@ -406,7 +449,7 @@ mod tests { if b.package == "b" { Err("exit 101".to_owned()) } else { Ok(()) } }); assert_eq!(ran, ["a", "b"]); - assert_eq!(outcome, Outcome { passed: 1, failed: vec!["b (b-0)".into()], not_run: 2 }); + assert_eq!(outcome, Outcome { passed: 1, failed: vec![("b (b-0)".into(), "exit 101".into())], not_run: 2 }); assert_eq!(run_all(&binaries, false, |_| Ok(())), Outcome { passed: 4, failed: vec![], not_run: 0 }); } @@ -428,7 +471,38 @@ mod tests { let args = parse(&["-p", "a", "-p", "b", "--doc", "--", "x"]).unwrap(); let sel = packages(&metadata(), &args.packages).unwrap(); assert_eq!(doc_args(&args, &sel).unwrap(), ["test", "--doc", "-p", "a", "--", "x"], "b has no library"); + let keep_going = parse(&["-p", "a", "--doc", "--keep-going", "--", "x"]).unwrap(); + assert_eq!(doc_args(&keep_going, &sel).unwrap(), ["test", "--doc", "-p", "a", "--no-fail-fast", "--", "x"], "cargo's flag, before `--`"); + assert_eq!(doc_args(&parse(&["--keep-going"]).unwrap(), &all).unwrap(), ["test", "--doc", "--workspace", "--no-fail-fast"]); let bin_only = parse(&["-p", "b"]).unwrap(); assert_eq!(doc_args(&bin_only, &packages(&metadata(), &bin_only.packages).unwrap()), None); } + + #[cfg(unix)] + #[test] + fn a_failure_says_how_the_binary_ended() { + use std::os::unix::process::ExitStatusExt; + // wait(2) statuses: an exit code in the high byte, a terminating signal in the low bits + assert_eq!(describe(std::process::ExitStatus::from_raw(101 << 8)), "exit status: 101"); + let killed = describe(std::process::ExitStatus::from_raw(9)); + assert!(killed.contains("SIGKILL") && killed.contains("out of memory"), "{killed}"); + assert!(describe(std::process::ExitStatus::from_raw(11)).contains("SIGSEGV")); + } + + #[test] + fn a_binary_that_cannot_start_reports_why() { + let missing = Binary { package: "a".into(), manifest: "/nonexistent/a/Cargo.toml".into(), exe: "/nonexistent/a/target/a-0".into() }; + let err = run_binary(Path::new("/nonexistent"), &missing, &[], None, Caps::QuickCi).unwrap_err(); + assert!(err.starts_with("failed to start:"), "{err}"); + } + + #[cfg(unix)] + #[test] + fn a_failing_binary_reports_its_exit_status() { + let binary = Binary { package: "sh".into(), manifest: "/Cargo.toml".into(), exe: "/bin/sh".into() }; + let err = run_binary(Path::new("/"), &binary, &["-c", "exit 3"], None, Caps::QuickCi).unwrap_err(); + assert_eq!(err, "exit status: 3"); + let err = run_binary(Path::new("/"), &binary, &["-c", "kill -9 $$"], None, Caps::QuickCi).unwrap_err(); + assert!(err.contains("SIGKILL"), "{err}"); + } } From 48b774f42211b764155d2c6c7bfb1b952c372704 Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Fri, 30 Oct 2026 13:01:56 -0500 Subject: [PATCH 03/40] fix(xtask): #3058 under nextest, --test-threads and --nocapture go before its `--` `cargo xtask test -- --test-threads=1` with LIGHTCRAFT_NEXTEST=1 passed the option after nextest's `--`, where nextest takes only filters, --exact, --skip, --ignored and --include-ignored, and refused it. nextest_args now makes --test-threads N (or =N) and --nocapture nextest's runner options and rejects any other option with a message naming it, before the run takes its slot. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 ++- xtask/src/main.rs | 1 + xtask/src/test.rs | 71 +++++++++++++++++++++++++++++++++++++++++------ 3 files changed, 67 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 4d78c13ad84..9ed648d13d2 100644 --- a/README.md +++ b/README.md @@ -434,7 +434,9 @@ memory) and takes no CI slot. It has `ci`'s caps and waits for its slot, builds once (the same build as `ci`'s, so neither rebuilds the other) and runs each test binary, or those of the `-p PKG` packages, with whatever follows `--` (`cargo xtask test -p lightcraft-ui-egui -- i18n::`). It stops at the first failing binary, as `ci` does; `--keep-going` runs them all and -names each that failed. `--doc` adds the doctests; `LIGHTCRAFT_NEXTEST=1` applies here too. +names each that failed. `--doc` adds the doctests; `LIGHTCRAFT_NEXTEST=1` applies here too, where +`--test-threads N` and `--nocapture` become nextest's own options and only filters, `--exact`, +`--skip`, `--ignored` and `--include-ignored` may follow `--`. **Release builds on memory-constrained machines:** [#1196](https://github.com/storytold/lightcraft/issues/1196) reports Arch/AUR release-link OOM kills on a 16 GB machine when the desktop and CLI build concurrently diff --git a/xtask/src/main.rs b/xtask/src/main.rs index a92d9a5cde2..59c0d61f5f7 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -71,6 +71,7 @@ commands: --exact, --skip, --nocapture); stops at the first failing binary unless --keep-going (alias --no-fail-fast), which runs them all and names each that failed; --doc runs the doctests after them. LIGHTCRAFT_NEXTEST=1 runs the tests under cargo nextest + (--test-threads N and --nocapture become its options; ARGS are its filters) corpus [--download] show where test corpora live; --download fetches PngSuite and CC0 raw samples (raw.pixls.us) into corpus/ and checks their sha256 stats [--exact] count tests and lines per crate (--exact: ask the test harness via `-- --list`) diff --git a/xtask/src/test.rs b/xtask/src/test.rs index dde8e9de643..d4a3062ab70 100644 --- a/xtask/src/test.rs +++ b/xtask/src/test.rs @@ -250,7 +250,12 @@ pub fn selected(root: &Path, packages: &BTreeSet, skip_log: &Path) -> Re /// The `cargo nextest run` arguments for `args`: the workspace build, the `-p` packages as a /// filter expression (so the build is still the workspace's), `--no-fail-fast` for `--keep-going`. -pub fn nextest_args<'a>(args: &Args<'a>) -> Vec { +/// +/// Nextest doesn't hand `ARGS` to the test binaries: after its `--` it takes only filters, +/// `--exact`, `--skip NAME`, `--ignored` and `--include-ignored`. `--test-threads N` (or `=N`) and +/// `--nocapture` become its runner options before `--`; any other option is an error naming it, +/// rather than nextest's own refusal after the slot was taken. +pub fn nextest_args<'a>(args: &Args<'a>) -> Result, String> { let mut v: Vec = crate::ci::with_test_targets(&["--workspace"]).into_iter().map(str::to_owned).collect(); if !args.packages.is_empty() { let filter = args.packages.iter().map(|p| format!("package(={p})")).collect::>().join(" | "); @@ -259,11 +264,45 @@ pub fn nextest_args<'a>(args: &Args<'a>) -> Vec { if args.keep_going { v.push("--no-fail-fast".to_owned()); } - if !args.test_args.is_empty() { + let mut filters = Vec::new(); + let mut it = args.test_args.iter().copied(); + while let Some(arg) = it.next() { + match arg { + "--" => { + // nextest reads what follows its own `--` as filters too, `-`-prefixed or not + filters.push(arg.to_owned()); + filters.extend(it.by_ref().map(str::to_owned)); + } + "--exact" | "--ignored" | "--include-ignored" => filters.push(arg.to_owned()), + "--skip" => { + let Some(name) = it.next() else { + return Err("test: --skip needs a test name".to_owned()); + }; + filters.extend([arg.to_owned(), name.to_owned()]); + } + "--nocapture" | "--no-capture" => v.push("--no-capture".to_owned()), + "--test-threads" => { + let Some(n) = it.next() else { + return Err("test: --test-threads needs a number".to_owned()); + }; + v.extend(["--test-threads".to_owned(), n.to_owned()]); + } + _ if arg.starts_with("--test-threads=") => { + v.extend(["--test-threads".to_owned(), arg.trim_start_matches("--test-threads=").to_owned()]); + } + _ if arg.starts_with('-') => { + return Err(format!( + "test: `{arg}` can't reach the tests under nextest (LIGHTCRAFT_NEXTEST=1), which takes filters, --exact, --skip, --ignored, --include-ignored, --nocapture and --test-threads" + )); + } + _ => filters.push(arg.to_owned()), + } + } + if !filters.is_empty() { v.push("--".to_owned()); - v.extend(args.test_args.iter().map(|a| (*a).to_owned())); + v.extend(filters); } - v + Ok(v) } /// The `cargo test --doc` arguments for `args`: the workspace's doctests, or those of the `-p` @@ -297,14 +336,14 @@ pub fn run(raw: &[&str]) -> Result<(), String> { let args = parse(raw)?; super::use_ci_caps(); let root = super::root(); + let nextest = if crate::ci::nextest() { Some(nextest_args(&args)?) } else { None }; let command = std::iter::once("cargo xtask test").chain(raw.iter().copied()).collect::>().join(" "); // held until the run ends: one ci or test run at a time per machine (ci_lock.rs) let _slot = ci_lock::acquire(&root, &command)?; let packages = packages(&super::metadata()?, &args.packages)?; let mut failed = Vec::new(); let mut summary = Vec::new(); - if crate::ci::nextest() { - let nextest = nextest_args(&args); + if let Some(nextest) = nextest { let mut c = super::cargo(); c.args(["nextest", "run"]).args(&nextest); if let Err(e) = super::run(c, &format!("cargo nextest run {}", nextest.join(" "))) { @@ -456,14 +495,30 @@ mod tests { #[test] fn nextest_keeps_the_workspace_build_and_filters_packages() { let all = parse(&[]).unwrap(); - assert_eq!(nextest_args(&all), ["--workspace", "--lib", "--bins", "--tests"]); + assert_eq!(nextest_args(&all).unwrap(), ["--workspace", "--lib", "--bins", "--tests"]); let some = parse(&["-p", "b", "-p", "a", "--keep-going", "--", "foo"]).unwrap(); assert_eq!( - nextest_args(&some), + nextest_args(&some).unwrap(), ["--workspace", "--lib", "--bins", "--tests", "-E", "package(=a) | package(=b)", "--no-fail-fast", "--", "foo"] ); } + #[test] + fn nextest_takes_test_threads_and_nocapture_before_its_separator() { + let targets = ["--workspace", "--lib", "--bins", "--tests"]; + let nextest = |a: &[&str]| nextest_args(&parse(a).unwrap()).map(|v| v[targets.len()..].to_vec()); + assert_eq!(nextest(&["--", "--test-threads=1"]).unwrap(), ["--test-threads", "1"], "a runner option, not a filter"); + assert_eq!( + nextest(&["--", "foo", "--test-threads", "2", "--nocapture", "--exact", "--skip", "bar", "--ignored"]).unwrap(), + ["--test-threads", "2", "--no-capture", "--", "foo", "--exact", "--skip", "bar", "--ignored"] + ); + assert_eq!(nextest(&["--", "--include-ignored", "--", "-odd"]).unwrap(), ["--", "--include-ignored", "--", "-odd"]); + let err = nextest(&["--", "--show-output"]).unwrap_err(); + assert!(err.contains("`--show-output`") && err.contains("--test-threads"), "{err}"); + assert!(nextest(&["--", "--test-threads"]).unwrap_err().contains("needs a number")); + assert!(nextest(&["--", "--skip"]).unwrap_err().contains("needs a test name")); + } + #[test] fn doctests_cover_the_workspace_or_the_selected_libraries() { let all = packages(&metadata(), &BTreeSet::new()).unwrap(); From 3b8ef15c1a3b0796f4e0f7762a986d89f062e0bf Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Tue, 3 Nov 2026 00:05:26 -0600 Subject: [PATCH 04/40] docs(xtask): #3058 the test help says a CARGO_BUILD_JOBS or RUST_TEST_THREADS you set wins Co-Authored-By: Claude Opus 5.5 --- xtask/src/main.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 59c0d61f5f7..6fd2feb2825 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -66,7 +66,8 @@ commands: LIGHTCRAFT_CI_LOCK=off to skip the lock) test [-p PKG]... [--keep-going] [--doc] [-- ARGS] the workspace's tests (or PKG's) with ci's caps (build jobs by free RAM, at most 4 test - threads, line-table debuginfo) in ci's machine-wide slot, instead of `cargo test`: + threads, line-table debuginfo; a CARGO_BUILD_JOBS or RUST_TEST_THREADS you set wins) + in ci's machine-wide slot, instead of `cargo test`: builds every test target once, then runs each test binary with ARGS (a filter, --exact, --skip, --nocapture); stops at the first failing binary unless --keep-going (alias --no-fail-fast), which runs them all and names each that failed; --doc runs the From 6cd47f5db44184d792a46729850818bc47520c4b Mon Sep 17 00:00:00 2001 From: THEtheChad <880190+THEtheChad@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:09:51 -0600 Subject: [PATCH 05/40] Issue #3058: ci's test step runs every binary since #3791; xtask test's docs stop saying it stops at the first --- README.md | 4 ++-- xtask/src/test.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 9ed648d13d2..118e9338896 100644 --- a/README.md +++ b/README.md @@ -433,8 +433,8 @@ which runs one test per CPU in every test binary (on a 16-core machine the UI te memory) and takes no CI slot. It has `ci`'s caps and waits for its slot, builds every test target once (the same build as `ci`'s, so neither rebuilds the other) and runs each test binary, or those of the `-p PKG` packages, with whatever follows `--` (`cargo xtask test -p lightcraft-ui-egui -- -i18n::`). It stops at the first failing binary, as `ci` does; `--keep-going` runs them all and -names each that failed. `--doc` adds the doctests; `LIGHTCRAFT_NEXTEST=1` applies here too, where +i18n::`). It stops at the first failing binary; `--keep-going` runs them all and names each that +failed, as `ci`'s test step does. `--doc` adds the doctests; `LIGHTCRAFT_NEXTEST=1` applies here too, where `--test-threads N` and `--nocapture` become nextest's own options and only filters, `--exact`, `--skip`, `--ignored` and `--include-ignored` may follow `--`. diff --git a/xtask/src/test.rs b/xtask/src/test.rs index d4a3062ab70..e24785db9d1 100644 --- a/xtask/src/test.rs +++ b/xtask/src/test.rs @@ -9,8 +9,8 @@ //! It builds every workspace test target once (`cargo test --workspace --no-run`, the same //! artifacts as `ci`'s test step, so nothing rebuilds between them) and then runs each test binary //! itself ([`run_binary`]), passing it `ARGS` (a filter, `--exact`, `--skip`, `--nocapture`, …). -//! It stops at the first failing binary, as `ci` does; `--keep-going` runs every binary and names -//! each that failed. `--doc` runs the doctests after them. With `LIGHTCRAFT_NEXTEST=1` (and +//! It stops at the first failing binary; `--keep-going` runs every binary and names each that +//! failed, as `ci`'s test step does (`--no-fail-fast`). `--doc` runs the doctests after them. With `LIGHTCRAFT_NEXTEST=1` (and //! cargo-nextest installed) the binaries run under `cargo nextest run` instead, as in `ci`. //! //! `ci --quick` runs the changed packages' tests through the same functions ([`selected`]). From 0c2a49ac33d92277bbb91877057ee0f1029be26b Mon Sep 17 00:00:00 2001 From: THEtheChad <880190+THEtheChad@users.noreply.github.com> Date: Mon, 9 Nov 2026 10:46:23 -0600 Subject: [PATCH 06/40] Issue #3058: the Quick start line says what --keep-going does --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 118e9338896..620de9d8989 100644 --- a/README.md +++ b/README.md @@ -407,7 +407,7 @@ cargo xtask web --serve # the same app in the br cargo run --release -p lightcraft-cli -- render photo.jpg -o out.jpg --set light.exposure=0.5 cargo xtask ci # fmt, clippy, HEIF, tests, parity, layers, assets, WASM cargo xtask ci --quick # only what your branch's changes can break (minutes) -cargo xtask test -p lightcraft-raw --keep-going # tests only, with ci's caps; every failing test binary +cargo xtask test -p lightcraft-raw --keep-going # tests only, with ci's caps; runs every binary, names each that failed ``` `cargo xtask ci --quick` compares with the merge base of `origin/main` (`--base REF` for another) From fe076d64d8b34bdd643a1b4d481de43f65561c78 Mon Sep 17 00:00:00 2001 From: THEtheChad <880190+THEtheChad@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:55:29 -0600 Subject: [PATCH 07/40] Issue #3058: the CI caps go on only once the CI slot is held `cargo xtask test` under LIGHTCRAFT_NEXTEST=1 probed for nextest with the caps already on, before waiting for the slot. The probe's capped `cargo` took ci_caps' RAM snapshot while another run might still hold the slot, so this run's build jobs and test threads counted that run's memory as used. use_ci_caps now takes the held slot, so neither `ci` nor `test` can turn the caps on, or take the snapshot, before the slot is held. Co-Authored-By: Claude Opus 5.5 --- xtask/src/ci.rs | 4 ++-- xtask/src/main.rs | 10 +++++++--- xtask/src/test.rs | 5 +++-- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/xtask/src/ci.rs b/xtask/src/ci.rs index a3d97c20c7c..ee8968a5eec 100644 --- a/xtask/src/ci.rs +++ b/xtask/src/ci.rs @@ -157,11 +157,11 @@ pub(crate) fn cmd_ci(args: &[&str]) -> Result<(), String> { if base.is_some() && !quick { return Err("ci: --base only applies to --quick".into()); } - use_ci_caps(); let root = root(); let command = std::iter::once("cargo xtask ci").chain(args.iter().copied()).collect::>().join(" "); // held until ci returns: one run at a time per machine (ci_lock.rs) - let _slot = ci_lock::acquire(&root, &command)?; + let slot = ci_lock::acquire(&root, &command)?; + use_ci_caps(&slot); let plan = if quick { let (base, files) = ci_quick::changed_files(&root, base)?; let plan = ci_quick::plan(&files, &ci_quick::packages(&root, &metadata()?), base); diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 6fd2feb2825..bd797b8f227 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -159,9 +159,13 @@ pub fn cargo() -> Command { static CI_CAPS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// Opt this run into CI's resource caps: the subcommands that build and run the test suite (`ci`, -/// `test`) call it first, so every cargo and test binary they start, including parity and WASM -/// subprocesses, gets them. Ordinary developer builds keep their own settings. -fn use_ci_caps() { +/// `test`) call it once they hold the CI slot, so every cargo and test binary they start, including +/// parity and WASM subprocesses, gets them. Ordinary developer builds keep their own settings. +/// +/// It takes the slot so it can't run before the slot is held: the first capped command takes the +/// RAM snapshot behind [`ci_caps`], and a snapshot taken while another run still holds the slot +/// counts that run's memory as used, shrinking this run's jobs and threads for its whole length. +fn use_ci_caps(_slot: &Option) { CI_CAPS.store(true, std::sync::atomic::Ordering::Relaxed); } diff --git a/xtask/src/test.rs b/xtask/src/test.rs index e24785db9d1..6bf6dbc609d 100644 --- a/xtask/src/test.rs +++ b/xtask/src/test.rs @@ -334,12 +334,13 @@ pub fn doc_args<'a>(args: &Args<'a>, packages: &BTreeMap) -> Op /// `cargo xtask test`. pub fn run(raw: &[&str]) -> Result<(), String> { let args = parse(raw)?; - super::use_ci_caps(); let root = super::root(); + // probed before the caps are on, so the probe doesn't take their RAM snapshot (use_ci_caps) let nextest = if crate::ci::nextest() { Some(nextest_args(&args)?) } else { None }; let command = std::iter::once("cargo xtask test").chain(raw.iter().copied()).collect::>().join(" "); // held until the run ends: one ci or test run at a time per machine (ci_lock.rs) - let _slot = ci_lock::acquire(&root, &command)?; + let slot = ci_lock::acquire(&root, &command)?; + super::use_ci_caps(&slot); let packages = packages(&super::metadata()?, &args.packages)?; let mut failed = Vec::new(); let mut summary = Vec::new(); From 11e753a15f5e40c2a921dfca2324fd5a4eac3ab7 Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Mon, 26 Oct 2026 12:03:47 -0500 Subject: [PATCH 08/40] build(cargo): #3059 plain cargo test runs at most 4 tests at once libtest runs one test per CPU by default; on a 16-core machine the ui-egui lib tests then ran out of memory. `.cargo/config.toml` now sets RUST_TEST_THREADS=4 in [env] with force = false, so an explicit value still wins, and `.config/nextest.toml` sets test-threads = 4 for plain `cargo nextest run`. `cargo xtask` runs under the same config, so it would inherit the default and skip ci's RAM-aware value, which can be lower. [env] also sets LIGHTCRAFT_TEST_THREADS_DEFAULT to the same value; xtask's `caller_sets` treats a RUST_TEST_THREADS equal to it as unset, for both the ci caps and `ci --quick`'s test binaries. An explicit 4 looks like the default, which is harmless: the caps only ever lower it. Co-Authored-By: Claude Opus 5.5 --- .cargo/config.toml | 10 ++++++++++ .config/nextest.toml | 5 +++++ README.md | 11 ++++++++--- docs/architecture.md | 9 +++++++++ xtask/src/ci.rs | 43 +++++++++++++++++++++++++++++++++++++++++++ xtask/src/main.rs | 24 +++++++++++++++++++++++- xtask/src/test.rs | 10 ++++++---- 7 files changed, 104 insertions(+), 8 deletions(-) create mode 100644 .config/nextest.toml diff --git a/.cargo/config.toml b/.cargo/config.toml index 35049cbcb13..dd3f07df33a 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,2 +1,12 @@ [alias] xtask = "run --package xtask --" + +# Plain `cargo test` runs at most 4 tests at once in each test binary, as `cargo xtask ci` does: +# libtest's default of one per CPU ran the UI tests out of memory on a 16-core machine (#3059). +# A RUST_TEST_THREADS already in the environment wins (`force = false`). +# `cargo xtask` runs under this config too: the marker beside it holds the value set here, so xtask +# can tell this default from a caller's setting and size `ci`'s test threads by available RAM. Keep +# the two values equal (`xtask` tests it). +[env] +RUST_TEST_THREADS = { value = "4", force = false } +LIGHTCRAFT_TEST_THREADS_DEFAULT = { value = "4", force = true } diff --git a/.config/nextest.toml b/.config/nextest.toml new file mode 100644 index 00000000000..2615c88a76d --- /dev/null +++ b/.config/nextest.toml @@ -0,0 +1,5 @@ +# Plain `cargo nextest run` runs at most 4 tests at once, as plain `cargo test` does +# (`.cargo/config.toml`, #3059). NEXTEST_TEST_THREADS or `--test-threads` wins; `cargo xtask ci` +# and `cargo xtask test` set it from available RAM. +[profile.default] +test-threads = 4 diff --git a/README.md b/README.md index 620de9d8989..12c11126a8a 100644 --- a/README.md +++ b/README.md @@ -424,13 +424,18 @@ available when it starts (at most one per CPU; 4 if memory can't be read), so an builds with fewer. Test threads follow, capped at 4. Full-debuginfo linkers, one per CPU, otherwise exhaust RAM before any test runs. GPU coverage is unchanged. Explicit `CARGO_PROFILE_DEV_DEBUG`, `CARGO_BUILD_JOBS`, `RUST_TEST_THREADS` and -`NEXTEST_TEST_THREADS` settings override these defaults. The tests run under +`NEXTEST_TEST_THREADS` settings override these defaults. Outside `ci`, `.cargo/config.toml` limits +plain `cargo test` to 4 tests at once in each test binary (`RUST_TEST_THREADS=4` unless the +environment sets it; libtest's own default is one per CPU), and `.config/nextest.toml` does the same +for `cargo nextest run`. `cargo xtask` inherits that default but doesn't count it as an explicit +setting: a marker beside it (`LIGHTCRAFT_TEST_THREADS_DEFAULT`) tells it apart, so `ci` still +lowers the threads on a machine short of RAM. The tests run under `cargo test`; `LIGHTCRAFT_NEXTEST=1` runs them under [cargo-nextest](https://nexte.st) instead (one process per test, slower here because each regenerates the demo scenes). Ordinary development commands keep their own settings. To run tests without the rest of `ci`, use `cargo xtask test` rather than `cargo test --workspace`, -which runs one test per CPU in every test binary (on a 16-core machine the UI tests alone run out of -memory) and takes no CI slot. It has `ci`'s caps and waits for its slot, builds every test target +which gets none of `ci`'s RAM-aware caps (only the 4-thread default above) and takes no CI slot. +It has `ci`'s caps and waits for its slot, builds every test target once (the same build as `ci`'s, so neither rebuilds the other) and runs each test binary, or those of the `-p PKG` packages, with whatever follows `--` (`cargo xtask test -p lightcraft-ui-egui -- i18n::`). It stops at the first failing binary; `--keep-going` runs them all and names each that diff --git a/docs/architecture.md b/docs/architecture.md index 65d90506753..81cf3d0b9a0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -81,6 +81,14 @@ runs each test binary, or the `-p` packages' binaries, itself (`test::run_binary uses too); `--keep-going` runs every binary and names each that failed instead of stopping at the first. +Outside `ci`, `.cargo/config.toml`'s `[env]` limits plain `cargo test` to 4 tests at once per test +binary (`RUST_TEST_THREADS = { value = "4", force = false }`, so a value already in the environment +wins), and `.config/nextest.toml` sets `test-threads = 4` for `cargo nextest run`. `cargo xtask` runs +under that config too, so `[env]` also sets a marker, `LIGHTCRAFT_TEST_THREADS_DEFAULT`, to the same +value: a `RUST_TEST_THREADS` equal to it counts as unset (`caller_sets` in `xtask/src/main.rs`) and the +caps replace it with the RAM-aware value, while any other value is the caller's and wins. A caller who +sets 4 explicitly looks like the default; the caps only ever lower it. + `ci` also probes the machine: OS, CPUs, RAM, the GPU adapters of each backend (from the ignored `gpu_probe` test of `lightcraft-gpu`, run after the workspace tests so it reuses their build; xtask has no wgpu), the corpus and `CRAFT_FONTS_DIR`. Tests @@ -95,6 +103,7 @@ the `lightcraft-gpu` tests once per backend with a hardware adapter (`LIGHTCRAFT | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | Quality gates: plain `cargo test` (and `cargo nextest run`) runs at most 4 tests at once; xtask tells that default from a caller's `RUST_TEST_THREADS` | | 2026-10-26 | minor | Quality gates: `cargo xtask test` runs the tests with `ci`'s caps and slot, and can keep going past a failing binary | | 2026-10-23 | minor | Quality gates: one integration-test binary per crate, doctests apart, nextest on request, one WASM check | | 2026-10-11 | minor | Quality gates: the CI machine probe, visible skips (`testkit`) and `target/ci/report.json` | diff --git a/xtask/src/ci.rs b/xtask/src/ci.rs index ee8968a5eec..3b43df6573f 100644 --- a/xtask/src/ci.rs +++ b/xtask/src/ci.rs @@ -419,4 +419,47 @@ mod ci_jobs_tests { assert_eq!(set.iter().map(|(k, _)| *k).collect::>(), ["CARGO_PROFILE_DEV_DEBUG", "CARGO_BUILD_JOBS", "NEXTEST_TEST_THREADS"]); assert!(crate::caps_to_set(caps, |_| true).is_empty()); } + + /// An environment of `vars` for [`crate::set_by_caller`]. + fn env(vars: &[(&str, &str)]) -> impl Fn(&str) -> Option { + let vars: Vec<(String, String)> = vars.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(); + move |key| vars.iter().find(|(k, _)| k == key).map(|(_, v)| v.into()) + } + + #[test] + fn the_config_test_threads_default_is_not_a_callers_setting() { + use crate::set_by_caller; + const MARKER: &str = crate::TEST_THREADS_DEFAULT_MARKER; + let threads = "RUST_TEST_THREADS"; + assert!(!set_by_caller(threads, env(&[])), "unset, outside cargo"); + assert!(!set_by_caller(threads, env(&[(MARKER, "4")])), "unset (no RUST_TEST_THREADS at all)"); + assert!(!set_by_caller(threads, env(&[(threads, "4"), (MARKER, "4")])), "the config default: ci sizes it by RAM"); + assert!(set_by_caller(threads, env(&[(threads, "9"), (MARKER, "4")])), "RUST_TEST_THREADS=9 cargo xtask ci"); + assert!(set_by_caller(threads, env(&[(threads, "2"), (MARKER, "4")])), "a lower explicit value wins too"); + assert!(set_by_caller(threads, env(&[(threads, "4")])), "no marker: xtask run outside cargo, the value is the caller's"); + assert!(set_by_caller(threads, env(&[(threads, "")])), "set, even if empty"); + // the marker only speaks for RUST_TEST_THREADS + assert!(set_by_caller("NEXTEST_TEST_THREADS", env(&[("NEXTEST_TEST_THREADS", "4"), (MARKER, "4")]))); + assert!(set_by_caller("CARGO_BUILD_JOBS", env(&[("CARGO_BUILD_JOBS", "4"), (MARKER, "4")]))); + assert!(!set_by_caller("CARGO_BUILD_JOBS", env(&[(MARKER, "4")]))); + } + + /// The quoted `value` of the `key = { value = "…", … }` line in `.cargo/config.toml`'s `[env]`. + fn config_env(config: &str, key: &str) -> Option<(String, String)> { + let line = config.lines().find(|l| l.split('=').next().is_some_and(|k| k.trim() == key))?; + let value = line.split("value = \"").nth(1)?.split('"').next()?.to_owned(); + Some((value, line.to_owned())) + } + + #[test] + fn the_cargo_config_sets_the_test_threads_default_and_its_marker_to_one_value() { + let config = std::fs::read_to_string(super::root().join(".cargo/config.toml")).unwrap(); + let (threads, line) = config_env(&config, "RUST_TEST_THREADS").expect("RUST_TEST_THREADS in [env]"); + assert!(line.contains("force = false"), "an explicit RUST_TEST_THREADS must win: {line}"); + let (marker, _) = config_env(&config, crate::TEST_THREADS_DEFAULT_MARKER).expect("the marker in [env]"); + assert_eq!(threads, marker, "xtask tells the default apart by this marker"); + let n: usize = threads.parse().unwrap(); + assert!((1..=4).contains(&n), "{n}"); + assert!(config.contains("[env]")); + } } diff --git a/xtask/src/main.rs b/xtask/src/main.rs index bd797b8f227..2978f2330a9 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -194,12 +194,34 @@ fn caps_to_set<'a>(caps: &'a [(&'static str, String)], is_set: impl Fn(&str) -> caps.iter().filter(|(key, _)| !is_set(key)).map(|(key, value)| (*key, value.as_str())).collect() } +/// The variable `.cargo/config.toml` sets beside its `RUST_TEST_THREADS` default, to the same +/// value (#3059). `cargo xtask` runs under that config, so it inherits the default like any cargo +/// run; the marker tells it apart from a caller's own setting. +const TEST_THREADS_DEFAULT_MARKER: &str = "LIGHTCRAFT_TEST_THREADS_DEFAULT"; + +/// Whether the caller set `key` in the environment (`get` reads it), rather than leaving it unset +/// or to the `RUST_TEST_THREADS` default of `.cargo/config.toml`: that one counts as unset when it +/// equals the marker [`TEST_THREADS_DEFAULT_MARKER`] holds. A caller who sets the same value (4) +/// can't be told apart and is treated as the default; the caps only ever lower it (`ci`'s test +/// threads are at most 4), so they still never get more threads than they asked for. +fn set_by_caller(key: &str, get: impl Fn(&str) -> Option) -> bool { + let Some(value) = get(key) else { + return false; + }; + !(key == "RUST_TEST_THREADS" && get(TEST_THREADS_DEFAULT_MARKER).is_some_and(|default| default == value)) +} + +/// [`set_by_caller`] for this process's environment. +pub fn caller_sets(key: &str) -> bool { + set_by_caller(key, |k| std::env::var_os(k)) +} + /// Give `c` CI's resource caps when this run opted in ([`use_ci_caps`]). Full Windows debuginfo /// plus one linker per CPU can exhaust RAM before any tests run, and one test thread per CPU /// can exhaust it while they run (#3057). fn apply_ci_caps(c: &mut Command) { if CI_CAPS.load(std::sync::atomic::Ordering::Relaxed) { - c.envs(caps_to_set(ci_caps(), |key| std::env::var_os(key).is_some())); + c.envs(caps_to_set(ci_caps(), caller_sets)); } } diff --git a/xtask/src/test.rs b/xtask/src/test.rs index 6bf6dbc609d..27ca0a1f260 100644 --- a/xtask/src/test.rs +++ b/xtask/src/test.rs @@ -1,8 +1,9 @@ //! `cargo xtask test [-p PKG]… [--keep-going] [--doc] [-- ARGS]`: the workspace tests, or some //! packages' tests, under the same caps as `ci` and in its machine-wide slot. //! -//! Plain `cargo test --workspace` runs one test per CPU in every test binary and takes no CI slot: -//! on a 16-core machine the ui-egui tests alone then run out of memory (#3057). This runs them the +//! Plain `cargo test --workspace` takes no CI slot and gets only `.cargo/config.toml`'s 4 test +//! threads per binary (libtest's own default, one per CPU, ran the ui-egui tests alone out of memory +//! on a 16-core machine, #3057, #3059), not `ci`'s RAM-aware caps. This runs them the //! way `ci` does: build jobs by available RAM, at most 4 test threads, line-table debuginfo //! ([`super::use_ci_caps`]), one run per machine ([`ci_lock`]). //! @@ -155,7 +156,8 @@ fn names<'a>(packages: impl Iterator) -> String { packages.map(|p| p.name.as_str()).collect::>().join(", ") } -/// The resource limits a test binary run directly gets, where the environment doesn't set them. +/// The resource limits a test binary run directly gets, where the caller doesn't set them +/// ([`super::caller_sets`]: `.cargo/config.toml`'s `RUST_TEST_THREADS` default doesn't count). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Caps { /// `cargo xtask test`: all of CI's caps ([`super::apply_ci_caps`]), so `RUST_TEST_THREADS` is @@ -179,7 +181,7 @@ pub fn run_binary(root: &Path, binary: &Binary, args: &[&str], skip_log: Option< match caps { Caps::Ci => super::apply_ci_caps(&mut c), Caps::QuickCi => { - if std::env::var_os("RUST_TEST_THREADS").is_none() { + if !super::caller_sets("RUST_TEST_THREADS") { // as the cargo runs of ci (`cargo()`): more threads make the frame-budget tests flaky c.env("RUST_TEST_THREADS", std::thread::available_parallelism().map_or(4, |n| n.get()).min(4).to_string()); } From fa3cdbcc2fab82d01e70196498c825056c795d69 Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Mon, 26 Oct 2026 12:41:40 -0500 Subject: [PATCH 09/40] fix(xtask): #3059 state exactly when an explicit RUST_TEST_THREADS wins An explicit RUST_TEST_THREADS=4 equals the .cargo/config.toml default and its marker, so ci and xtask test may lower it to their RAM-aware value. The README, docs/architecture.md and the doc comments now say so: any other explicit value wins as-is, and 4 may be lowered, never raised. A regression test pins the resulting thread count with an injected cap: explicit 9 and 2 kept, the default and an explicit 4 lowered to the cap, and 4 kept when there is no marker. Co-Authored-By: Claude Opus 5.5 --- README.md | 6 ++++-- docs/architecture.md | 5 +++-- xtask/src/ci.rs | 26 ++++++++++++++++++++++++++ xtask/src/main.rs | 18 +++++++++++------- 4 files changed, 44 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 12c11126a8a..af4332b2ca9 100644 --- a/README.md +++ b/README.md @@ -428,8 +428,10 @@ unchanged. Explicit `CARGO_PROFILE_DEV_DEBUG`, `CARGO_BUILD_JOBS`, `RUST_TEST_TH plain `cargo test` to 4 tests at once in each test binary (`RUST_TEST_THREADS=4` unless the environment sets it; libtest's own default is one per CPU), and `.config/nextest.toml` does the same for `cargo nextest run`. `cargo xtask` inherits that default but doesn't count it as an explicit -setting: a marker beside it (`LIGHTCRAFT_TEST_THREADS_DEFAULT`) tells it apart, so `ci` still -lowers the threads on a machine short of RAM. The tests run under +setting (a marker beside it, `LIGHTCRAFT_TEST_THREADS_DEFAULT`, tells it apart), so `ci` still +lowers the threads on a machine short of RAM. An explicit `RUST_TEST_THREADS` other than 4 wins +as-is; an explicit 4 can't be told apart from the default, so `ci` and `cargo xtask test` may lower +it to their RAM-aware value (never raise it). The tests run under `cargo test`; `LIGHTCRAFT_NEXTEST=1` runs them under [cargo-nextest](https://nexte.st) instead (one process per test, slower here because each regenerates the demo scenes). Ordinary development commands keep their own settings. diff --git a/docs/architecture.md b/docs/architecture.md index 81cf3d0b9a0..9e29536a876 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -86,8 +86,9 @@ binary (`RUST_TEST_THREADS = { value = "4", force = false }`, so a value already wins), and `.config/nextest.toml` sets `test-threads = 4` for `cargo nextest run`. `cargo xtask` runs under that config too, so `[env]` also sets a marker, `LIGHTCRAFT_TEST_THREADS_DEFAULT`, to the same value: a `RUST_TEST_THREADS` equal to it counts as unset (`caller_sets` in `xtask/src/main.rs`) and the -caps replace it with the RAM-aware value, while any other value is the caller's and wins. A caller who -sets 4 explicitly looks like the default; the caps only ever lower it. +caps replace it with the RAM-aware value, while any other value is the caller's and wins as-is. An +explicit `RUST_TEST_THREADS=4` can't be told apart from the default, so `ci` and `xtask test` may +lower it to their RAM-aware value (never raise it). `ci` also probes the machine: OS, CPUs, RAM, the GPU adapters of each backend (from the ignored `gpu_probe` test of `lightcraft-gpu`, run after the workspace tests so it reuses their build; xtask diff --git a/xtask/src/ci.rs b/xtask/src/ci.rs index 3b43df6573f..91da280b475 100644 --- a/xtask/src/ci.rs +++ b/xtask/src/ci.rs @@ -444,6 +444,32 @@ mod ci_jobs_tests { assert!(!set_by_caller("CARGO_BUILD_JOBS", env(&[(MARKER, "4")]))); } + /// The `RUST_TEST_THREADS` a capped run's test binaries get in environment `vars` when `ci`'s + /// RAM-aware value is `cap`: the cap where the caller didn't set it, else the environment's. + fn test_threads(vars: &[(&str, &str)], cap: &str) -> String { + let caps = [("RUST_TEST_THREADS", cap.to_owned())]; + let get = env(vars); + let set = crate::caps_to_set(&caps, |key| crate::set_by_caller(key, &get)); + match set.first() { + Some((_, value)) => (*value).to_owned(), + None => get("RUST_TEST_THREADS").unwrap().into_string().unwrap(), + } + } + + #[test] + fn an_explicit_test_thread_count_wins_except_one_equal_to_the_config_default() { + const MARKER: &str = crate::TEST_THREADS_DEFAULT_MARKER; + let threads = "RUST_TEST_THREADS"; + assert_eq!(test_threads(&[(threads, "9"), (MARKER, "4")], "2"), "9", "explicit 9 is kept"); + assert_eq!(test_threads(&[(threads, "2"), (MARKER, "4")], "3"), "2", "explicit 2 is kept"); + assert_eq!(test_threads(&[(threads, "4"), (MARKER, "4")], "2"), "2", "the config default yields to the RAM-aware cap"); + // An explicit RUST_TEST_THREADS=4 looks the same as the config default (documented): it + // may be lowered, never raised. + assert_eq!(test_threads(&[(threads, "4"), (MARKER, "4")], "2"), "2", "explicit 4 under cargo is lowered like the default"); + assert_eq!(test_threads(&[(threads, "4")], "2"), "4", "no marker (xtask run outside cargo): 4 is the caller's"); + assert_eq!(test_threads(&[(MARKER, "4")], "3"), "3", "unset: the cap"); + } + /// The quoted `value` of the `key = { value = "…", … }` line in `.cargo/config.toml`'s `[env]`. fn config_env(config: &str, key: &str) -> Option<(String, String)> { let line = config.lines().find(|l| l.split('=').next().is_some_and(|k| k.trim() == key))?; diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 2978f2330a9..fead32ba24a 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -188,8 +188,9 @@ fn ci_caps() -> &'static [(&'static str, String); 4] { }) } -/// The caps `c` gets: each of `caps` the environment doesn't set itself (`is_set`), so an explicit -/// setting always wins. +/// The caps `c` gets: each of `caps` the environment doesn't set itself (`is_set`, normally +/// [`caller_sets`]), so a caller's setting wins; see [`set_by_caller`] for an explicit +/// `RUST_TEST_THREADS=4`. fn caps_to_set<'a>(caps: &'a [(&'static str, String)], is_set: impl Fn(&str) -> bool) -> Vec<(&'static str, &'a str)> { caps.iter().filter(|(key, _)| !is_set(key)).map(|(key, value)| (*key, value.as_str())).collect() } @@ -201,9 +202,10 @@ const TEST_THREADS_DEFAULT_MARKER: &str = "LIGHTCRAFT_TEST_THREADS_DEFAULT"; /// Whether the caller set `key` in the environment (`get` reads it), rather than leaving it unset /// or to the `RUST_TEST_THREADS` default of `.cargo/config.toml`: that one counts as unset when it -/// equals the marker [`TEST_THREADS_DEFAULT_MARKER`] holds. A caller who sets the same value (4) -/// can't be told apart and is treated as the default; the caps only ever lower it (`ci`'s test -/// threads are at most 4), so they still never get more threads than they asked for. +/// equals the marker [`TEST_THREADS_DEFAULT_MARKER`] holds. So an explicit value other than the +/// default (4) wins as-is, but an explicit `RUST_TEST_THREADS=4` can't be told apart from the +/// default: `ci` and `xtask test` may lower it to their RAM-aware value (never raise it, as that is +/// at most 4). Without the marker (xtask run outside cargo) every value is the caller's. fn set_by_caller(key: &str, get: impl Fn(&str) -> Option) -> bool { let Some(value) = get(key) else { return false; @@ -211,14 +213,16 @@ fn set_by_caller(key: &str, get: impl Fn(&str) -> Option) -> !(key == "RUST_TEST_THREADS" && get(TEST_THREADS_DEFAULT_MARKER).is_some_and(|default| default == value)) } -/// [`set_by_caller`] for this process's environment. +/// [`set_by_caller`] for this process's environment (an explicit `RUST_TEST_THREADS=4` counts as +/// the config default). pub fn caller_sets(key: &str) -> bool { set_by_caller(key, |k| std::env::var_os(k)) } /// Give `c` CI's resource caps when this run opted in ([`use_ci_caps`]). Full Windows debuginfo /// plus one linker per CPU can exhaust RAM before any tests run, and one test thread per CPU -/// can exhaust it while they run (#3057). +/// can exhaust it while they run (#3057). A caller's setting wins ([`caller_sets`]), except that an +/// explicit `RUST_TEST_THREADS=4` looks like the config default and may be lowered. fn apply_ci_caps(c: &mut Command) { if CI_CAPS.load(std::sync::atomic::Ordering::Relaxed) { c.envs(caps_to_set(ci_caps(), caller_sets)); From 9ef72f59b49409d9af7c94dea418c5a84b60cf3b Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Thu, 29 Oct 2026 23:58:35 -0500 Subject: [PATCH 10/40] fix(xtask): #3059 ci --quick's test binaries get the RAM-aware test threads too ci --quick ran each test binary with RUST_TEST_THREADS = min(CPUs, 4), ignoring available RAM, though cmd_ci had opted into CI's caps: on a machine with many CPUs and little free memory it still ran 4 tests at once (#3057). run_binary now always applies CI's caps, as `cargo xtask test` already did, and the Caps choice is gone. Co-Authored-By: Claude Opus 5.5 --- xtask/src/test.rs | 42 +++++++++++++----------------------------- 1 file changed, 13 insertions(+), 29 deletions(-) diff --git a/xtask/src/test.rs b/xtask/src/test.rs index 27ca0a1f260..09eae7c01c8 100644 --- a/xtask/src/test.rs +++ b/xtask/src/test.rs @@ -156,37 +156,21 @@ fn names<'a>(packages: impl Iterator) -> String { packages.map(|p| p.name.as_str()).collect::>().join(", ") } -/// The resource limits a test binary run directly gets, where the caller doesn't set them -/// ([`super::caller_sets`]: `.cargo/config.toml`'s `RUST_TEST_THREADS` default doesn't count). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Caps { - /// `cargo xtask test`: all of CI's caps ([`super::apply_ci_caps`]), so `RUST_TEST_THREADS` is - /// the RAM-aware `min(build jobs by available RAM, 4)` that `ci`'s cargo runs get. - Ci, - /// `ci --quick`: only `RUST_TEST_THREADS = min(CPUs, 4)`, its default before `test` existed. - QuickCi, -} - /// Run one test binary as `cargo test` would (from its package's directory, with its -/// `CARGO_MANIFEST_DIR` and `CARGO_PKG_NAME`) under `caps`, with `args`; skips the tests record -/// go to `skip_log`. The one place `test` and `ci --quick` start a test binary and wait for it. -/// The error says how it ended: its exit status, the signal that killed it, or why it didn't start. -pub fn run_binary(root: &Path, binary: &Binary, args: &[&str], skip_log: Option<&Path>, caps: Caps) -> Result<(), String> { +/// `CARGO_MANIFEST_DIR` and `CARGO_PKG_NAME`) under CI's caps ([`super::apply_ci_caps`]: where the +/// caller doesn't set it, `RUST_TEST_THREADS` is the RAM-aware `min(build jobs by available RAM, 4)` +/// of `ci`'s cargo runs; `.cargo/config.toml`'s default doesn't count, [`super::caller_sets`]), with +/// `args`; skips the tests record go to `skip_log`. The one place `test` and `ci --quick` start a +/// test binary and wait for it. The error says how it ended: its exit status, the signal that killed +/// it, or why it didn't start. +pub fn run_binary(root: &Path, binary: &Binary, args: &[&str], skip_log: Option<&Path>) -> Result<(), String> { let dir = Path::new(&binary.manifest).parent().unwrap_or(root); let mut c = Command::new(&binary.exe); c.current_dir(dir).env("CARGO_MANIFEST_DIR", dir).env("CARGO_PKG_NAME", &binary.package).args(args); if let Some(log) = skip_log { c.env(crate::ci_report::SKIP_LOG_ENV, log); } - match caps { - Caps::Ci => super::apply_ci_caps(&mut c), - Caps::QuickCi => { - if !super::caller_sets("RUST_TEST_THREADS") { - // as the cargo runs of ci (`cargo()`): more threads make the frame-budget tests flaky - c.env("RUST_TEST_THREADS", std::thread::available_parallelism().map_or(4, |n| n.get()).min(4).to_string()); - } - } - } + super::apply_ci_caps(&mut c); let shown = std::iter::once(binary.label()).chain(args.iter().map(|a| (*a).to_owned())).collect::>().join(" "); eprintln!("$ {shown}"); let status = c.status().map_err(|e| format!("failed to start: {e}"))?; @@ -242,7 +226,7 @@ pub fn selected(root: &Path, packages: &BTreeSet, skip_log: &Path) -> Re println!("no test binaries in {}", names(packages.values())); return Ok(()); } - let outcome = run_all(&binaries, true, |b| run_binary(root, b, &[], Some(skip_log), Caps::QuickCi)); + let outcome = run_all(&binaries, true, |b| run_binary(root, b, &[], Some(skip_log))); if outcome.failed.is_empty() { Ok(()) } else { @@ -357,7 +341,7 @@ pub fn run(raw: &[&str]) -> Result<(), String> { if binaries.is_empty() { println!("no test binaries in {}", names(packages.values())); } - let outcome = run_all(&binaries, args.keep_going, |b| run_binary(&root, b, &args.test_args, None, Caps::Ci)); + let outcome = run_all(&binaries, args.keep_going, |b| run_binary(&root, b, &args.test_args, None)); summary.push(format!("{} of {} test binaries passed", outcome.passed, binaries.len())); if outcome.not_run > 0 { summary.push(format!("{} not run after the first failure (--keep-going runs them)", outcome.not_run)); @@ -550,7 +534,7 @@ mod tests { #[test] fn a_binary_that_cannot_start_reports_why() { let missing = Binary { package: "a".into(), manifest: "/nonexistent/a/Cargo.toml".into(), exe: "/nonexistent/a/target/a-0".into() }; - let err = run_binary(Path::new("/nonexistent"), &missing, &[], None, Caps::QuickCi).unwrap_err(); + let err = run_binary(Path::new("/nonexistent"), &missing, &[], None).unwrap_err(); assert!(err.starts_with("failed to start:"), "{err}"); } @@ -558,9 +542,9 @@ mod tests { #[test] fn a_failing_binary_reports_its_exit_status() { let binary = Binary { package: "sh".into(), manifest: "/Cargo.toml".into(), exe: "/bin/sh".into() }; - let err = run_binary(Path::new("/"), &binary, &["-c", "exit 3"], None, Caps::QuickCi).unwrap_err(); + let err = run_binary(Path::new("/"), &binary, &["-c", "exit 3"], None).unwrap_err(); assert_eq!(err, "exit status: 3"); - let err = run_binary(Path::new("/"), &binary, &["-c", "kill -9 $$"], None, Caps::QuickCi).unwrap_err(); + let err = run_binary(Path::new("/"), &binary, &["-c", "kill -9 $$"], None).unwrap_err(); assert!(err.contains("SIGKILL"), "{err}"); } } From 53d0028cbdd5999a88a12918a5d55fe51bd2d08c Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Tue, 3 Nov 2026 00:05:43 -0600 Subject: [PATCH 11/40] test(xtask): #3059 the config check reads RUST_TEST_THREADS and its marker only from [env]; the test help names the explicit-4 case Co-Authored-By: Claude Opus 5.5 --- xtask/src/ci.rs | 20 +++++++++++++++++++- xtask/src/main.rs | 3 ++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/xtask/src/ci.rs b/xtask/src/ci.rs index 91da280b475..452c94d3931 100644 --- a/xtask/src/ci.rs +++ b/xtask/src/ci.rs @@ -472,11 +472,29 @@ mod ci_jobs_tests { /// The quoted `value` of the `key = { value = "…", … }` line in `.cargo/config.toml`'s `[env]`. fn config_env(config: &str, key: &str) -> Option<(String, String)> { - let line = config.lines().find(|l| l.split('=').next().is_some_and(|k| k.trim() == key))?; + // only inside `[env]`: the same key in another table isn't an environment default + let mut in_env = false; + let line = config.lines().find(|l| { + if l.trim_start().starts_with('[') { + in_env = l.trim() == "[env]"; + return false; + } + in_env && l.split('=').next().is_some_and(|k| k.trim() == key) + })?; let value = line.split("value = \"").nth(1)?.split('"').next()?.to_owned(); Some((value, line.to_owned())) } + #[test] + fn config_env_reads_only_the_env_table() { + let k = "RUST_TEST_THREADS"; + let line = |v: &str| format!("{k} = {{ value = \"{v}\", force = false }}"); + assert_eq!(config_env(&format!("[env]\n{}\n", line("4")), k).map(|(v, _)| v).as_deref(), Some("4")); + assert_eq!(config_env(&format!("[build]\n{}\n[env]\n", line("4")), k), None, "another table's key"); + assert_eq!(config_env(&format!("[env]\n[alias]\n{}\n", line("4")), k), None, "after [env] ends"); + assert_eq!(config_env(&format!("{}\n[env]\nX = 1\n", line("4")), k), None, "before any table"); + } + #[test] fn the_cargo_config_sets_the_test_threads_default_and_its_marker_to_one_value() { let config = std::fs::read_to_string(super::root().join(".cargo/config.toml")).unwrap(); diff --git a/xtask/src/main.rs b/xtask/src/main.rs index fead32ba24a..fccfa7b38fe 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -66,7 +66,8 @@ commands: LIGHTCRAFT_CI_LOCK=off to skip the lock) test [-p PKG]... [--keep-going] [--doc] [-- ARGS] the workspace's tests (or PKG's) with ci's caps (build jobs by free RAM, at most 4 test - threads, line-table debuginfo; a CARGO_BUILD_JOBS or RUST_TEST_THREADS you set wins) + threads, line-table debuginfo; a CARGO_BUILD_JOBS or RUST_TEST_THREADS you set wins, + but RUST_TEST_THREADS=4 can't be told from .cargo/config.toml's default) in ci's machine-wide slot, instead of `cargo test`: builds every test target once, then runs each test binary with ARGS (a filter, --exact, --skip, --nocapture); stops at the first failing binary unless --keep-going From 2b3021e945f81e84b8c68b7641666d4ba9723711 Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Tue, 3 Nov 2026 00:36:06 -0600 Subject: [PATCH 12/40] test(xtask): #3059 the config check also requires the marker to be forced Co-Authored-By: Claude Opus 5.5 --- xtask/src/ci.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/xtask/src/ci.rs b/xtask/src/ci.rs index 452c94d3931..d79f52e9fd5 100644 --- a/xtask/src/ci.rs +++ b/xtask/src/ci.rs @@ -500,7 +500,9 @@ mod ci_jobs_tests { let config = std::fs::read_to_string(super::root().join(".cargo/config.toml")).unwrap(); let (threads, line) = config_env(&config, "RUST_TEST_THREADS").expect("RUST_TEST_THREADS in [env]"); assert!(line.contains("force = false"), "an explicit RUST_TEST_THREADS must win: {line}"); - let (marker, _) = config_env(&config, crate::TEST_THREADS_DEFAULT_MARKER).expect("the marker in [env]"); + let (marker, marker_line) = config_env(&config, crate::TEST_THREADS_DEFAULT_MARKER).expect("the marker in [env]"); + // forced, so an inherited marker can't make a caller's equal value look like the default + assert!(marker_line.contains("force = true"), "cargo must overwrite an inherited marker: {marker_line}"); assert_eq!(threads, marker, "xtask tells the default apart by this marker"); let n: usize = threads.parse().unwrap(); assert!((1..=4).contains(&n), "{n}"); From 36b38a111b0dc155f2684098d4ed44873196fd13 Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Mon, 26 Oct 2026 13:42:54 -0500 Subject: [PATCH 13/40] feat(xtask): #3060 bound each test binary's run and the wait for the CI slot A hung test binary held `ci` and `cargo xtask test`, and with them the machine-wide CI slot, forever; a run waiting for the slot waited forever too. - Each test binary gets LIGHTCRAFT_TEST_BINARY_TIMEOUT minutes (default 30; 0/off for none; fractions allowed; a bad value is an error before the run takes its slot). xtask/src/deadline.rs streams the output through, reads libtest's lines on the way, and on timeout kills the binary with every process it started and reports `timed out after N min: ` with the tests still running (the "has been running for over 60 seconds" warnings, or the test a single-threaded run started) and those that never reported a result (from `--list`). - test::run_binary (cargo xtask test, ci --quick) times a binary from its start. The cargo test runs of the full ci (test and heif steps, doctests, the GPU backend runs) are timed per binary from cargo's `Running` / `Doc-tests` line; the build before them isn't bounded. Under nextest, .config/nextest.toml's slow-timeout kills a test after 30 minutes. - The kill walks the process tree (`ps`: SIGSTOP, then SIGKILL; `taskkill /T` on Windows) rather than signalling a process group of its own: a child in its own group would no longer get the terminal's Ctrl-C and would outlive an interrupted xtask. - The CI slot wait gives up after LIGHTCRAFT_CI_LOCK_WAIT minutes (default 120, several full runs) with an error naming the holder and how to wait longer. Co-Authored-By: Claude Opus 5.5 --- .config/nextest.toml | 3 + README.md | 9 +- docs/architecture.md | 14 + xtask/src/ci.rs | 20 +- xtask/src/ci_lock.rs | 76 ++++- xtask/src/deadline.rs | 756 ++++++++++++++++++++++++++++++++++++++++++ xtask/src/main.rs | 16 +- xtask/src/test.rs | 44 ++- 8 files changed, 905 insertions(+), 33 deletions(-) create mode 100644 xtask/src/deadline.rs diff --git a/.config/nextest.toml b/.config/nextest.toml index 2615c88a76d..951b5bb5279 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -3,3 +3,6 @@ # and `cargo xtask test` set it from available RAM. [profile.default] test-threads = 4 +# A test still running after 30 minutes is killed (`cargo xtask` gives each test binary under +# `cargo test` the same limit, LIGHTCRAFT_TEST_BINARY_TIMEOUT, #3060). +slow-timeout = { period = "60s", terminate-after = 30 } diff --git a/README.md b/README.md index af4332b2ca9..f253c101507 100644 --- a/README.md +++ b/README.md @@ -416,7 +416,14 @@ the wasm check when the changes touch them; a change to `Cargo.toml`, `Cargo.loc config tests everything. GitHub runs the full `cargo xtask ci` on every pull request (`.github/workflows/ci.yml`). Only one `ci` runs at a time per machine: a second one, from another worktree say, waits for the first and names it, since several at once take longer in total than in -turn. `LIGHTCRAFT_CI_SLOTS=2` allows two; `LIGHTCRAFT_CI_LOCK=off` skips the lock. +turn. `LIGHTCRAFT_CI_SLOTS=2` allows two; `LIGHTCRAFT_CI_LOCK=off` skips the lock. The wait +gives up after `LIGHTCRAFT_CI_LOCK_WAIT` minutes (default 120; `0` waits as long as it takes) and +names the run holding the slot. Nothing a run waits on is unbounded either: each test binary may run +for `LIGHTCRAFT_TEST_BINARY_TIMEOUT` minutes (default 30, timed from cargo's `Running` line for it; +`0` for no limit). One that runs longer, a test hung on a GPU device say, is killed with every +process it started, and the run reports it as `timed out after 30 min` with the tests still running +and those that never reported a result. Under `LIGHTCRAFT_NEXTEST=1`, `.config/nextest.toml` kills a +test after 30 minutes instead. CI defaults to line-table debug information and one build job per 1.5 GB of RAM available when it starts (at most one per CPU; 4 if memory can't be read), so an diff --git a/docs/architecture.md b/docs/architecture.md index 9e29536a876..b42b386dc56 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -81,6 +81,19 @@ runs each test binary, or the `-p` packages' binaries, itself (`test::run_binary uses too); `--keep-going` runs every binary and names each that failed instead of stopping at the first. +Nothing these runs wait on is unbounded (`xtask/src/deadline.rs`, #3060). Stable libtest has no +per-test timeout, so each test binary gets `LIGHTCRAFT_TEST_BINARY_TIMEOUT` minutes (default 30; `0` +for none): timed from its start when xtask runs it (`test::run_binary`), and from cargo's `Running` / +`Doc-tests` line for it when `cargo test` runs it (the full `ci`'s test and HEIF steps; the build +before isn't bounded). The output streams through and is read for libtest's lines; on timeout the +binary and every process it started are killed (frozen, then SIGKILL, by walking the process tree: +the child stays in xtask's process group so Ctrl-C still reaches it; `taskkill /T` on Windows), and +the run reports `timed out after N min: ` with the tests still running (libtest's "has been +running for over 60 seconds" warnings, or the test a single-threaded run started) and those that +never reported a result (`--list`). Under nextest, `.config/nextest.toml`'s `slow-timeout` kills a test +after 30 minutes instead. The wait for the CI slot gives up after `LIGHTCRAFT_CI_LOCK_WAIT` minutes +(default 120, several full runs; `0` for no limit) with an error naming the run that holds it. + Outside `ci`, `.cargo/config.toml`'s `[env]` limits plain `cargo test` to 4 tests at once per test binary (`RUST_TEST_THREADS = { value = "4", force = false }`, so a value already in the environment wins), and `.config/nextest.toml` sets `test-threads = 4` for `cargo nextest run`. `cargo xtask` runs @@ -104,6 +117,7 @@ the `lightcraft-gpu` tests once per backend with a hardware adapter (`LIGHTCRAFT | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | Quality gates: each test binary's run (`LIGHTCRAFT_TEST_BINARY_TIMEOUT`) and the wait for the CI slot (`LIGHTCRAFT_CI_LOCK_WAIT`) have a time limit | | 2026-10-26 | minor | Quality gates: plain `cargo test` (and `cargo nextest run`) runs at most 4 tests at once; xtask tells that default from a caller's `RUST_TEST_THREADS` | | 2026-10-26 | minor | Quality gates: `cargo xtask test` runs the tests with `ci`'s caps and slot, and can keep going past a failing binary | | 2026-10-23 | minor | Quality gates: one integration-test binary per crate, doctests apart, nextest on request, one WASM check | diff --git a/xtask/src/ci.rs b/xtask/src/ci.rs index 5be97c4f690..2a9ee24187e 100644 --- a/xtask/src/ci.rs +++ b/xtask/src/ci.rs @@ -1,7 +1,9 @@ use super::layers::cmd_layers; use super::raw_samples::RAW_SAMPLES; use super::wasm::{cmd_wasm, cmd_wasm_for}; -use super::{Command, PathBuf, USAGE, assets, cargo, ci_lock, ci_quick, ci_report, metadata, parity, root, roots, run, test, use_ci_caps}; +use super::{ + Command, PathBuf, USAGE, assets, cargo, ci_lock, ci_quick, ci_report, deadline, metadata, parity, root, roots, run, run_tests, test, use_ci_caps, +}; /// CI build jobs: one per 1.5 GB of RAM available when CI starts, at most one per CPU, 4 when it /// is unknown. With line-table debuginfo, 4 jobs measured about 3 GB of RAM in use and 2 jobs @@ -114,7 +116,7 @@ const TRANSLATION_GAPS_TEST: &str = "i18n::tests::translation_gaps_report"; /// Print the translation gaps report into the log: [`TRANSLATION_GAPS_TEST`] of lightcraft-ui-egui, /// run from the test binary the test step built (found with `--no-run` and the step's own /// arguments, so nothing rebuilds). A report that can't run is a note, never a failed step. -fn translation_gaps() { +fn translation_gaps(limit: Option) { eprintln!("\n=== ci: translation gaps ==="); let mut c = cargo(); c.args(["test", "--no-run", "--message-format=json"]).args(with_test_targets(&["--workspace"])); @@ -134,7 +136,9 @@ fn translation_gaps() { let ran = binary.and_then(|binary| { let mut c = Command::new(&binary); c.args(["--exact", TRANSLATION_GAPS_TEST, "--nocapture", "--quiet"]); - run(c, &format!("{} --exact {TRANSLATION_GAPS_TEST} --nocapture --quiet", binary.display())) + let what = format!("{} --exact {TRANSLATION_GAPS_TEST} --nocapture --quiet", binary.display()); + eprintln!("$ {what}"); + deadline::run_test_binary(c, "lightcraft-ui-egui (translation gaps)", limit).map_err(|e| format!("{what}: {e}")) }); if let Err(e) = ran { eprintln!("note: the translation gaps report did not run: {e}"); @@ -157,6 +161,8 @@ pub(crate) fn cmd_ci(args: &[&str]) -> Result<(), String> { if base.is_some() && !quick { return Err("ci: --base only applies to --quick".into()); } + // each test binary's time limit (deadline.rs); a bad value fails before the run waits for its slot + let limit = deadline::test_binary_timeout()?; let root = root(); let command = std::iter::once("cargo xtask ci").chain(args.iter().copied()).collect::>().join(" "); // held until ci returns: one run at a time per machine (ci_lock.rs) @@ -182,7 +188,7 @@ pub(crate) fn cmd_ci(args: &[&str]) -> Result<(), String> { // target/ci/skips-.jsonl: a file, so it works the same under nextest and cargo test let test = |(mut c, what): (Command, String), step: &str| { c.env(ci_report::SKIP_LOG_ENV, ci_report::skip_log(&root, step)); - run(c, &what) + run_tests(c, &what, limit) }; let gpu = std::cell::RefCell::new(serde_json::Value::Null); let hardware_runs = std::cell::RefCell::new(Vec::new()); @@ -241,7 +247,7 @@ pub(crate) fn cmd_ci(args: &[&str]) -> Result<(), String> { ( "test", Box::new(|| match &plan { - Some(p) if !p.workspace_wide => test::selected(&root, &p.packages, &ci_report::skip_log(&root, "test")), + Some(p) if !p.workspace_wide => test::selected(&root, &p.packages, &ci_report::skip_log(&root, "test"), limit), _ => test(tests(&with_test_targets(&["--workspace"])), "test").and_then(|()| test(doctests(), "test")), }), ), @@ -263,7 +269,7 @@ pub(crate) fn cmd_ci(args: &[&str]) -> Result<(), String> { let (mut c, what) = tests(&with_test_targets(&["-p", "lightcraft-gpu", "--features", "denoise"])); c.env("LIGHTCRAFT_GPU_BACKEND", &backend).env(ci_report::SKIP_LOG_ENV, ci_report::skip_log(&root, &step)); let t = std::time::Instant::now(); - let ok = run(c, &format!("LIGHTCRAFT_GPU_BACKEND={backend} {what}")).is_ok(); + let ok = run_tests(c, &format!("LIGHTCRAFT_GPU_BACKEND={backend} {what}"), limit).is_ok(); hardware_runs.borrow_mut().push(serde_json::json!({ "backend": backend, "adapter": adapter, @@ -302,7 +308,7 @@ pub(crate) fn cmd_ci(args: &[&str]) -> Result<(), String> { if *name == "test" && plan.is_none() { // right after the workspace tests, before parity and wasm build other feature sets probe(); - translation_gaps(); + translation_gaps(limit); } if let Err(e) = r { failure = Some((*name, e)); diff --git a/xtask/src/ci_lock.rs b/xtask/src/ci_lock.rs index 70c90b043bb..0042285cd53 100644 --- a/xtask/src/ci_lock.rs +++ b/xtask/src/ci_lock.rs @@ -9,6 +9,11 @@ //! - `LIGHTCRAFT_CI_SLOTS=N`: N runs at once (1–64). //! - `LIGHTCRAFT_CI_LOCK=off`: no lock (e.g. a CI runner that only ever runs one job). //! - `LIGHTCRAFT_CI_LOCK=`: keep the lock files there instead. +//! - `LIGHTCRAFT_CI_LOCK_WAIT=MIN`: give up after waiting MIN minutes for a slot (default +//! [`DEFAULT_WAIT_MIN`]; `0` or `off` waits as long as it takes), with an error naming the run +//! that holds it (#3060). A full `ci` takes about 15 minutes on a 16-core machine, and a hung test +//! binary can't hold a slot past its own limit any more ([`crate::deadline`]), so two hours is +//! several runs ahead in the queue; a wait longer than that means something is stuck. use std::fs::{File, OpenOptions, TryLockError}; use std::io::Write; @@ -17,6 +22,11 @@ use std::time::{Duration, Instant}; const POLL: Duration = Duration::from_secs(2); +/// How long to wait for a slot, in minutes. +pub const WAIT_ENV: &str = "LIGHTCRAFT_CI_LOCK_WAIT"; +/// The default of [`WAIT_ENV`]. +pub const DEFAULT_WAIT_MIN: u64 = 120; + /// A held CI slot; dropping it releases the slot. pub struct Held { _file: File, @@ -108,25 +118,44 @@ pub fn acquire(root: &Path, command: &str) -> Result, String> { let Some(dir) = lock_dir() else { return Ok(None); }; - let slots = slots(); + let wait = crate::deadline::minutes_from_env(WAIT_ENV, DEFAULT_WAIT_MIN)?; let owner = format!("pid {} in {}: {command}", std::process::id(), root.display()); - if let Some(held) = try_acquire(&dir, slots, &owner)? { + wait_for_slot(&dir, slots(), &owner, wait, POLL) +} + +/// Take a slot of `slots` in `dir`, polling every `poll` for at most `wait` (`None`: no limit). +fn wait_for_slot(dir: &Path, slots: usize, owner: &str, wait: Option, poll: Duration) -> Result, String> { + if let Some(held) = try_acquire(dir, slots, owner)? { return Ok(Some(held)); } let waiting = Instant::now(); - eprintln!("=== ci: waiting for another CI run to finish ({slots} at a time; LIGHTCRAFT_CI_SLOTS changes it) ==="); - for h in holders(&dir, slots) { + let limit = wait.map_or_else(|| "no time limit".to_owned(), |w| format!("for up to {}", crate::deadline::show(w))); + eprintln!("=== ci: waiting for another CI run to finish ({slots} at a time; LIGHTCRAFT_CI_SLOTS changes it), {limit} ({WAIT_ENV}) ==="); + for h in holders(dir, slots) { eprintln!(" running: {h}"); } loop { - std::thread::sleep(POLL); - if let Some(held) = try_acquire(&dir, slots, &owner)? { + std::thread::sleep(poll); + if let Some(held) = try_acquire(dir, slots, owner)? { eprintln!("=== ci: waited {:.0} s for a CI slot ===", waiting.elapsed().as_secs_f64()); return Ok(Some(held)); } + if let Some(wait) = wait.filter(|w| waiting.elapsed() >= *w) { + return Err(gave_up(wait, &holders(dir, slots))); + } } } +/// The error when the wait for a slot ran out: who holds the slots, and what to do. +fn gave_up(wait: Duration, holders: &[String]) -> String { + let held_by = if holders.is_empty() { "a run that didn't record itself".to_owned() } else { holders.join("; ") }; + format!( + "ci lock: gave up after waiting {} for a CI slot, held by: {held_by}. If that run is stuck, end it; \ + {WAIT_ENV}= waits longer (0 for as long as it takes), LIGHTCRAFT_CI_SLOTS=2 runs beside it", + crate::deadline::show(wait) + ) +} + #[cfg(test)] mod tests { use super::*; @@ -149,6 +178,41 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn the_wait_for_a_held_slot_ends_with_the_holder_named() { + let dir = scratch("wait"); + let _held = try_acquire(&dir, 1, "pid 1 in /w: cargo xtask ci").unwrap().expect("free slot"); + let t = Instant::now(); + let err = wait_for_slot(&dir, 1, "second", Some(Duration::from_millis(300)), Duration::from_millis(20)).err().expect("gave up"); + assert!(t.elapsed() >= Duration::from_millis(300) && t.elapsed() < Duration::from_secs(10), "{:?}", t.elapsed()); + assert!(err.contains("gave up after waiting 300 ms") && err.contains("held by: pid 1 in /w: cargo xtask ci"), "{err}"); + assert!(err.contains("LIGHTCRAFT_CI_LOCK_WAIT="), "says how to wait longer: {err}"); + assert_eq!(holders(&dir, 1), ["pid 1 in /w: cargo xtask ci"], "giving up leaves the holder alone"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_slot_freed_within_the_wait_is_taken() { + let dir = scratch("freed"); + let held = try_acquire(&dir, 1, "first").unwrap().expect("free slot"); + let release = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(200)); + drop(held); + }); + let got = wait_for_slot(&dir, 1, "second", Some(Duration::from_secs(30)), Duration::from_millis(20)).unwrap(); + assert!(got.is_some()); + assert_eq!(holders(&dir, 1), ["second"]); + release.join().unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn giving_up_names_an_unrecorded_holder_too() { + assert!( + gave_up(Duration::from_secs(7200), &[]).contains("gave up after waiting 120 min for a CI slot, held by: a run that didn't record itself") + ); + } + #[test] fn more_slots_admit_more_runs() { let dir = scratch("two"); diff --git a/xtask/src/deadline.rs b/xtask/src/deadline.rs new file mode 100644 index 00000000000..9d28113b6af --- /dev/null +++ b/xtask/src/deadline.rs @@ -0,0 +1,756 @@ +//! Time limits for the test processes `cargo xtask` waits on (#3060). +//! +//! Stable libtest has no per-test timeout, so a test that hangs (a GPU device that never answers, +//! a deadlock) used to hang `ci` and `cargo xtask test` with it, and with them the machine-wide CI +//! slot ([`crate::ci_lock`]) that every other run on the machine waits for. Here the process that +//! starts the tests bounds them: each test binary gets [`TEST_BINARY_TIMEOUT_ENV`] minutes +//! ([`DEFAULT_TEST_BINARY_TIMEOUT_MIN`] by default; `0` or `off` for no limit). +//! +//! - A test binary xtask starts itself ([`run_test_binary`]: `cargo xtask test`, `ci --quick`) is +//! timed from its start. +//! - A `cargo test` run ([`run_cargo_tests`]: the full `ci`'s test and heif steps, doctests) is timed +//! per test binary, from the `Running` (or `Doc-tests`) line cargo prints as it starts each one; +//! the build before the first one isn't bounded. Under `cargo nextest run` (no such lines) nextest's +//! own `slow-timeout` in `.config/nextest.toml` ends a hung test instead. +//! +//! The output streams through as it arrives, and is read on the way for libtest's lines: `running N +//! tests`, `test NAME ... ok` as each test finishes, and `test NAME has been running for over 60 +//! seconds`. On timeout the binary and every process it started are killed (on Unix: frozen with +//! SIGSTOP so nothing more forks, then SIGKILL; on Windows `taskkill /T /F`), and the report names the +//! binary, the tests still running (those warned about and not finished, or the one a single-threaded +//! run printed `test NAME ... ` for) and the tests that never reported a result (from `--list`). +//! +//! The child stays in xtask's process group rather than one of its own, so Ctrl-C in the terminal +//! still reaches the test binaries as before; that's why the kill walks the process tree (`ps`) +//! rather than signalling a group. + +use std::collections::BTreeSet; +use std::io::{IsTerminal, Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, ExitStatus, Stdio}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError, mpsc}; +use std::time::{Duration, Instant}; + +/// The limit, in minutes, on each test binary's run. +pub const TEST_BINARY_TIMEOUT_ENV: &str = "LIGHTCRAFT_TEST_BINARY_TIMEOUT"; +/// The default of [`TEST_BINARY_TIMEOUT_ENV`]: the slowest binary, the ui-egui library tests, takes +/// about 5 minutes here under `ci`'s caps. +pub const DEFAULT_TEST_BINARY_TIMEOUT_MIN: u64 = 30; +/// The longest limit a variable may set (a week); `0` or `off` means none. +const MAX_MINUTES: f64 = 7.0 * 24.0 * 60.0; +/// How often the wait checks the child and the clock. +const TICK: Duration = Duration::from_millis(50); +/// How long, after the child ends, to wait for its output pipes to close (a process it started +/// that outlives it may hold them open). +const DRAIN: Duration = Duration::from_secs(5); +/// How long the `--list` run of a timed-out binary may take (it runs no tests: milliseconds). +const LIST_LIMIT: Duration = Duration::from_secs(15); +/// The longest line of output parsed for test names; longer ones stream through unparsed. +const MAX_LINE: usize = 64 * 1024; +/// How many never-finished tests the timeout report names. +const NAMED: usize = 20; + +/// A time limit in minutes from `value` (the variable `var`'s), `default_min` when it's unset or +/// blank. `Ok(None)` is no limit (`0`, `off`, `none`, `never`). Fractions are allowed (`0.5`); a +/// value that isn't a number of minutes from 0 to a week is an error naming the variable. +pub fn parse_minutes(var: &str, value: Option<&str>, default_min: u64) -> Result, String> { + let Some(v) = value.map(str::trim).filter(|v| !v.is_empty()) else { + return Ok(Some(Duration::from_secs(default_min.saturating_mul(60)))); + }; + if matches!(v.to_ascii_lowercase().as_str(), "off" | "none" | "never") { + return Ok(None); + } + let bad = || format!("{var}={v}: not a number of minutes (e.g. 30 or 0.5; 0 or off for no limit; at most {MAX_MINUTES} = a week)"); + let minutes: f64 = v.parse().map_err(|_| bad())?; + if !minutes.is_finite() || minutes < 0.0 || minutes > MAX_MINUTES { + return Err(bad()); + } + if minutes <= 0.0 { + return Ok(None); + } + Duration::try_from_secs_f64(minutes * 60.0).map(Some).map_err(|_| bad()) +} + +/// [`parse_minutes`] for the environment variable `var` (one that isn't Unicode is an error). +pub fn minutes_from_env(var: &str, default_min: u64) -> Result, String> { + let value = match std::env::var(var) { + Ok(v) => Some(v), + Err(std::env::VarError::NotPresent) => None, + Err(std::env::VarError::NotUnicode(v)) => return Err(format!("{var}={}: not a number of minutes", v.to_string_lossy())), + }; + parse_minutes(var, value.as_deref(), default_min) +} + +/// The per-binary test limit from [`TEST_BINARY_TIMEOUT_ENV`]. +pub fn test_binary_timeout() -> Result, String> { + minutes_from_env(TEST_BINARY_TIMEOUT_ENV, DEFAULT_TEST_BINARY_TIMEOUT_MIN) +} + +/// `30 min`, `1.5 min`, `20 s`, `300 ms`: a limit as the reports show it. +pub fn show(limit: Duration) -> String { + let secs = limit.as_secs_f64(); + let minutes = secs / 60.0; + if secs >= 60.0 && (minutes * 10.0).fract().abs() < 1e-6 { + format!("{} min", (minutes * 10.0).round() / 10.0) + } else if secs >= 1.0 { + format!("{} s", (secs * 10.0).round() / 10.0) + } else { + format!("{} ms", limit.as_millis()) + } +} + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// `line` without ANSI escape sequences (cargo's and libtest's colours). +fn strip_ansi(line: &str) -> String { + let mut out = String::with_capacity(line.len()); + let mut chars = line.chars(); + while let Some(c) = chars.next() { + if c != '\u{1b}' { + out.push(c); + continue; + } + // CSI: ESC [ parameters… final byte in @..~; anything else: drop the ESC and the next char + if chars.next() == Some('[') { + for c in chars.by_ref() { + if ('@'..='~').contains(&c) { + break; + } + } + } + } + out +} + +/// What a test run's output said so far: the test binary cargo started last and, from libtest's +/// lines, how many tests it runs, which finished and which ran long. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Progress { + /// The test binary cargo started last, as its `Running` / `Doc-tests` line names it. + pub binary: Option, + /// That binary's executable (the path in the `Running` line's parentheses). + pub exe: Option, + /// `running N tests`. + pub total: Option, + /// The tests that reported a result (`test NAME ... ok`, `FAILED`, `ignored`). + pub finished: BTreeSet, + /// The tests libtest said had been running for over 60 seconds, in that order. + pub slow: Vec, + /// The unfinished last line of stdout: `test NAME ... ` while a single-threaded run runs NAME. + pub pending: String, +} + +impl Progress { + /// Read one whole line of output. True when it is cargo starting a test binary. + pub fn line(&mut self, raw: &str) -> bool { + let clean = strip_ansi(raw); + let line = clean.trim_end(); + let text = line.trim_start(); + // cargo right-aligns its status word, so its lines start with spaces + let cargo_status = line.starts_with(' '); + if let Some(rest) = text.strip_prefix("Running ").filter(|_| cargo_status) { + let exe = rest.strip_suffix(')').and_then(|r| r.rsplit_once(" (")).map(|(_, path)| PathBuf::from(path)); + self.start_binary(rest.to_owned(), exe); + return true; + } + if let Some(rest) = text.strip_prefix("Doc-tests ").filter(|_| cargo_status) { + self.start_binary(format!("doctests of {rest}"), None); + return true; + } + if let Some(rest) = text.strip_prefix("running ") { + let mut words = rest.split_whitespace(); + if let (Some(n), Some("test" | "tests"), None) = (words.next().and_then(|n| n.parse().ok()), words.next(), words.next()) { + self.reset(); + self.total = Some(n); + } + return false; + } + if let Some(rest) = text.strip_prefix("test ") { + if let Some((name, _result)) = rest.split_once(" ... ") { + self.finished.insert(name.to_owned()); + } else if let Some((name, _)) = rest.split_once(" has been running for over ") + && !self.slow.iter().any(|s| s == name) + { + self.slow.push(name.to_owned()); + } + } + false + } + + /// Cargo started a test binary. The test lines stay until its `running N tests`: cargo's line + /// comes on stderr and the binary's on stdout, read by two threads, so the first lines of the + /// new binary can be read before cargo's. + fn start_binary(&mut self, name: String, exe: Option) { + self.binary = Some(name); + self.exe = exe; + } + + fn reset(&mut self) { + self.total = None; + self.finished.clear(); + self.slow.clear(); + self.pending.clear(); + } + + /// The tests still running: warned about as slow and not finished, then the one a + /// single-threaded run started last. + pub fn running(&self) -> Vec { + let mut running: Vec = self.slow.iter().filter(|s| !self.finished.contains(*s)).cloned().collect(); + let pending = strip_ansi(&self.pending); + let started = pending.trim().strip_prefix("test ").and_then(|p| p.strip_suffix(" ...")).filter(|n| !n.contains(" ... ")); + if let Some(name) = started.filter(|n| !self.finished.contains(*n) && !running.iter().any(|r| r == n)) { + running.push(name.to_owned()); + } + running + } +} + +/// When a run's time limit starts. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Clock { + /// When the process starts: a test binary run directly. + Start, + /// At each test binary cargo starts (its `Running` / `Doc-tests` line): the limit is per binary, + /// and the build before the first isn't bounded. + EachBinary, +} + +/// How a watched run ended. +#[derive(Debug)] +pub enum Ended { + Exited(ExitStatus), + /// Out of time: killed, with what its output said by then. + TimedOut(Progress), +} + +struct Watch { + progress: Progress, + /// When the current limit started, `None` while it doesn't run. + since: Option, +} + +/// Run `cmd` with its output streamed through and read for libtest's lines, until it exits or +/// `limit` runs out (timed as `clock` says); then kill it and every process it started. +pub fn watch(mut cmd: Command, limit: Duration, clock: Clock) -> Result { + cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); + let mut child = cmd.spawn().map_err(|e| format!("failed to start: {e}"))?; + let state = Arc::new(Mutex::new(Watch { progress: Progress::default(), since: (clock == Clock::Start).then(Instant::now) })); + let (done_tx, done_rx) = mpsc::channel(); + let mut readers = 0; + let pipes: [(Option>, bool); 2] = [ + (child.stdout.take().map(|s| Box::new(s) as Box), true), + (child.stderr.take().map(|s| Box::new(s) as Box), false), + ]; + for (pipe, is_stdout) in pipes { + let Some(pipe) = pipe else { continue }; + let (state, done) = (Arc::clone(&state), done_tx.clone()); + let spawned = std::thread::Builder::new().name("xtask-output".into()).spawn(move || { + pump(pipe, is_stdout, clock, &state); + let _ = done.send(()); + }); + if let Err(e) = spawned { + kill_tree(&mut child); + return Err(format!("could not start a thread to read its output: {e}")); + } + readers += 1; + } + drop(done_tx); + let drain = |readers: usize| { + let until = Instant::now() + DRAIN; + for _ in 0..readers { + if done_rx.recv_timeout(until.saturating_duration_since(Instant::now())).is_err() { + break; + } + } + }; + loop { + match child.try_wait() { + Ok(Some(status)) => { + drain(readers); + return Ok(Ended::Exited(status)); + } + Ok(None) => {} + Err(e) => { + kill_tree(&mut child); + return Err(format!("waiting for it failed: {e}")); + } + } + if lock(&state).since.is_some_and(|since| since.elapsed() >= limit) { + kill_tree(&mut child); + drain(readers); + return Ok(Ended::TimedOut(lock(&state).progress.clone())); + } + std::thread::sleep(TICK); + } +} + +/// Copy `pipe` to xtask's stdout or stderr as it arrives, feeding whole lines to the progress. +fn pump(mut pipe: Box, is_stdout: bool, clock: Clock, state: &Mutex) { + let mut buf = [0u8; 8192]; + let mut line: Vec = Vec::new(); + let mut overlong = false; + loop { + let n = match pipe.read(&mut buf) { + Ok(0) => break, + Ok(n) => n, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, + Err(_) => break, + }; + let chunk = buf.get(..n).unwrap_or_default(); + if is_stdout { + let mut out = std::io::stdout().lock(); + let _ = out.write_all(chunk).and_then(|()| out.flush()); + } else { + let mut err = std::io::stderr().lock(); + let _ = err.write_all(chunk).and_then(|()| err.flush()); + } + let mut watch = lock(state); + for piece in chunk.split_inclusive(|b| *b == b'\n') { + if !overlong { + line.extend_from_slice(piece); + } + if line.len() > MAX_LINE { + line.clear(); + overlong = true; + } + if piece.ends_with(b"\n") { + if !overlong && watch.progress.line(&String::from_utf8_lossy(&line)) && clock == Clock::EachBinary { + watch.since = Some(Instant::now()); + } + line.clear(); + overlong = false; + } + } + if is_stdout { + watch.progress.pending = String::from_utf8_lossy(&line).into_owned(); + } + } +} + +/// Kill `child` and every process it started, and reap it. +pub fn kill_tree(child: &mut Child) { + #[cfg(unix)] + { + // freeze the tree first so nothing forks while it is collected, then kill it all + let mut seen: BTreeSet = BTreeSet::from([child.id()]); + let mut fresh: Vec = vec![child.id()]; + for _ in 0..8 { + signal("STOP", &fresh); + fresh = descendants(child.id()).into_iter().filter(|p| !seen.contains(p)).collect(); + if fresh.is_empty() { + break; + } + seen.extend(&fresh); + } + signal("KILL", &seen.iter().copied().collect::>()); + } + #[cfg(windows)] + { + let _ = Command::new("taskkill").args(["/PID", &child.id().to_string(), "/T", "/F"]).stdout(Stdio::null()).stderr(Stdio::null()).status(); + } + let _ = child.kill(); + let _ = child.wait(); +} + +#[cfg(unix)] +fn signal(name: &str, pids: &[u32]) { + if pids.is_empty() { + return; + } + let _ = Command::new("kill").arg(format!("-{name}")).args(pids.iter().map(u32::to_string)).stdout(Stdio::null()).stderr(Stdio::null()).status(); +} + +/// The processes descended from `root`, from `ps`'s pid / parent pid table (empty if `ps` fails). +#[cfg(unix)] +fn descendants(root: u32) -> Vec { + let Ok(out) = Command::new("ps").args(["-A", "-o", "pid=", "-o", "ppid="]).stderr(Stdio::null()).output() else { + return Vec::new(); + }; + descendants_in(&String::from_utf8_lossy(&out.stdout), root) +} + +/// The descendants of `root` in a `pid ppid` table, one process per line. +#[cfg_attr(not(unix), allow(dead_code))] +fn descendants_in(table: &str, root: u32) -> Vec { + let pairs: Vec<(u32, u32)> = table + .lines() + .filter_map(|l| { + let mut w = l.split_whitespace(); + Some((w.next()?.parse().ok()?, w.next()?.parse().ok()?)) + }) + .collect(); + let mut found: BTreeSet = BTreeSet::new(); + let mut frontier = vec![root]; + while let Some(parent) = frontier.pop() { + for (pid, _) in pairs.iter().filter(|(pid, ppid)| *ppid == parent && *pid != root) { + if found.insert(*pid) { + frontier.push(*pid); + } + } + } + found.into_iter().collect() +} + +/// A copy of `cmd`: its program, arguments, directory and environment changes. +fn copy_command(cmd: &Command) -> Command { + let mut c = Command::new(cmd.get_program()); + c.args(cmd.get_args()); + if let Some(dir) = cmd.get_current_dir() { + c.current_dir(dir); + } + for (key, value) in cmd.get_envs() { + match value { + Some(v) => c.env(key, v), + None => c.env_remove(key), + }; + } + c +} + +/// The tests a test binary would run, from `c` (the binary with its arguments) plus `--list`; +/// `None` when that fails or takes over [`LIST_LIMIT`]. +fn list_tests(mut c: Command) -> Option> { + c.arg("--list").stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()); + let mut child = c.spawn().ok()?; + let Some(mut stdout) = child.stdout.take() else { + kill_tree(&mut child); + return None; + }; + let (tx, rx) = mpsc::channel(); + let reader = std::thread::Builder::new().spawn(move || { + let mut text = String::new(); + let _ = stdout.read_to_string(&mut text); + let _ = tx.send(text); + }); + let text = reader.ok().and_then(|_| rx.recv_timeout(LIST_LIMIT).ok()); + let Some(text) = text else { + kill_tree(&mut child); + return None; + }; + let status = child.wait().ok()?; + status.success().then(|| text.lines().filter_map(|l| l.strip_suffix(": test")).map(str::to_owned).collect()) +} + +/// What to tell about a test binary that ran out of `limit`: the lines to print and the one-line +/// error. `listed` is every test it would run (`--list`), when known. +pub fn report(limit: Duration, binary: &str, progress: &Progress, listed: Option<&[String]>) -> (Vec, String) { + let running = progress.running(); + let mut lines = vec![format!("timed out after {}: {binary}; killed it and the processes it started", show(limit))]; + if running.is_empty() { + lines.push(" no test was reported as running (libtest warns about a test after 60 s)".to_owned()); + } else { + lines.push(format!(" still running: {}", running.join(", "))); + } + let never: Option> = listed.map(|all| all.iter().filter(|t| !progress.finished.contains(*t) && !running.contains(t)).collect()); + match (never, progress.total) { + (Some(never), _) if !never.is_empty() => { + let shown: Vec<&str> = never.iter().take(NAMED).map(|s| s.as_str()).collect(); + let more = never.len().saturating_sub(NAMED); + let more = if more > 0 { format!(" and {more} more") } else { String::new() }; + lines.push(format!( + " no result from {} other test(s) of {} (not started, or started less than 60 s before): {}{more}", + never.len(), + listed.map_or(0, <[String]>::len), + shown.join(", ") + )); + } + (None, Some(total)) => { + lines.push(format!(" {} of {total} test(s) had finished", progress.finished.len().min(total))); + } + _ => {} + } + lines.push(format!(" {TEST_BINARY_TIMEOUT_ENV}= changes the limit (0 for none)")); + let still = if running.is_empty() { String::new() } else { format!(" (still running: {})", running.join(", ")) }; + (lines, format!("timed out after {}{still}", show(limit))) +} + +fn print(lines: &[String]) { + let mut err = std::io::stderr().lock(); + if !lines.is_empty() { + // the killed binary's last line may have no end (`test NAME ... `) + let _ = writeln!(err); + } + for line in lines { + let _ = writeln!(err, "{line}"); + } +} + +/// Whether `cmd`'s arguments already choose libtest's colours. +fn sets_color(cmd: &Command) -> bool { + cmd.get_args().any(|a| a.to_str().is_some_and(|a| a == "--color" || a.starts_with("--color="))) +} + +/// Run a test binary (`cmd`, already given its arguments) under `limit` (`None`: no limit, and the +/// output isn't piped). The error says how it ended: its exit status, the signal that killed it, +/// that it ran out of time (and the tests still running), or why it didn't start. +pub fn run_test_binary(cmd: Command, label: &str, limit: Option) -> Result<(), String> { + let mut lines = Vec::new(); + let result = test_binary(cmd, label, limit, &mut lines); + print(&lines); + result +} + +/// [`run_test_binary`], with the timeout report added to `shown` rather than printed. +fn test_binary(mut cmd: Command, label: &str, limit: Option, shown: &mut Vec) -> Result<(), String> { + let Some(limit) = limit else { + let status = cmd.status().map_err(|e| format!("failed to start: {e}"))?; + return if status.success() { Ok(()) } else { Err(crate::test::describe(status)) }; + }; + let lister = copy_command(&cmd); + // its stdout is a pipe now: keep libtest's colours when ours is a terminal + if std::io::stdout().is_terminal() && !sets_color(&cmd) { + cmd.args(["--color", "always"]); + } + match watch(cmd, limit, Clock::Start)? { + Ended::Exited(status) if status.success() => Ok(()), + Ended::Exited(status) => Err(crate::test::describe(status)), + Ended::TimedOut(progress) => { + let listed = list_tests(lister); + let (lines, error) = report(limit, label, &progress, listed.as_deref()); + shown.extend(lines); + Err(error) + } + } +} + +/// Run `cmd`, a `cargo test` (or `cargo nextest run`) command, with each test binary it starts +/// under `limit` ([`Clock::EachBinary`]; `None`: no limit, and the output isn't piped). +pub fn run_cargo_tests(cmd: Command, limit: Option) -> Result<(), String> { + let mut lines = Vec::new(); + let result = cargo_tests(cmd, limit, &mut lines); + print(&lines); + result +} + +/// [`run_cargo_tests`], with the timeout report added to `shown` rather than printed. +fn cargo_tests(mut cmd: Command, limit: Option, shown: &mut Vec) -> Result<(), String> { + let Some(limit) = limit else { + let status = cmd.status().map_err(|e| format!("failed to spawn: {e}"))?; + return if status.success() { Ok(()) } else { Err(format!("exited with {status}")) }; + }; + // cargo's stderr is a pipe now: keep its colours when ours is a terminal + if std::io::stderr().is_terminal() && std::env::var_os("CARGO_TERM_COLOR").is_none() { + cmd.env("CARGO_TERM_COLOR", "always"); + } + let dir = cmd.get_current_dir().map(Path::to_path_buf); + match watch(cmd, limit, Clock::EachBinary)? { + Ended::Exited(status) if status.success() => Ok(()), + Ended::Exited(status) => Err(format!("exited with {status}")), + Ended::TimedOut(progress) => { + let listed = progress.exe.as_ref().and_then(|exe| { + let exe = match &dir { + Some(dir) if exe.is_relative() => dir.join(exe), + _ => exe.clone(), + }; + list_tests(Command::new(exe)) + }); + let binary = progress.binary.clone().unwrap_or_else(|| "a test binary".to_owned()); + let (lines, error) = report(limit, &binary, &progress, listed.as_deref()); + shown.extend(lines); + Err(format!("{error}: {binary}")) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const MIN: Duration = Duration::from_secs(60); + + #[test] + fn limits_parse_as_minutes_and_hostile_values_are_errors() { + let p = |v: Option<&str>| parse_minutes("V", v, 30); + assert_eq!(p(None), Ok(Some(MIN * 30)), "unset: the default"); + assert_eq!(p(Some(" ")), Ok(Some(MIN * 30)), "blank: the default"); + assert_eq!(p(Some("45")), Ok(Some(MIN * 45))); + assert_eq!(p(Some(" 0.5 ")), Ok(Some(Duration::from_secs(30)))); + assert_eq!(p(Some("1e1")), Ok(Some(MIN * 10))); + for none in ["0", "0.0", "-0", "off", "OFF", "none", "never"] { + assert_eq!(p(Some(none)), Ok(None), "{none}"); + } + for bad in ["-1", "abc", "30m", "NaN", "inf", "-inf", "1e300", "10081", "18446744073709551616"] { + let err = p(Some(bad)).unwrap_err(); + assert!(err.starts_with(&format!("V={bad}:")) && err.contains("0 or off for no limit"), "{err}"); + } + assert_eq!(p(Some("10080")), Ok(Some(MIN * 10080)), "a week is allowed"); + assert_eq!(parse_minutes("V", None, u64::MAX), Ok(Some(Duration::from_secs(u64::MAX))), "saturates"); + } + + #[test] + fn limits_show_in_minutes_seconds_or_milliseconds() { + assert_eq!(show(MIN * 30), "30 min"); + assert_eq!(show(Duration::from_secs(90)), "1.5 min"); + assert_eq!(show(Duration::from_secs(20)), "20 s"); + assert_eq!(show(Duration::from_secs(61)), "61 s"); + assert_eq!(show(Duration::from_millis(1200)), "1.2 s"); + assert_eq!(show(Duration::from_millis(300)), "300 ms"); + } + + #[test] + fn reads_libtest_and_cargo_lines() { + let mut p = Progress::default(); + assert!(p.line(" Running unittests src/lib.rs (target/debug/deps/geom-1a2b)\n")); + assert_eq!(p.binary.as_deref(), Some("unittests src/lib.rs (target/debug/deps/geom-1a2b)")); + assert_eq!(p.exe, Some(PathBuf::from("target/debug/deps/geom-1a2b"))); + assert!(!p.line("running 4 tests")); + assert_eq!(p.total, Some(4)); + p.line("test a::one ... ok"); + p.line("test a::two ... \u{1b}[31mFAILED\u{1b}[0m"); + p.line("test a::three has been running for over 60 seconds"); + p.line("test a::four has been running for over 60 seconds"); + p.line("test a::four ... ok"); + p.line("test result: FAILED. 2 passed; 1 failed"); + p.line("Running is not cargo's when it starts the line"); + assert_eq!(p.finished.iter().map(String::as_str).collect::>(), ["a::four", "a::one", "a::two"]); + assert_eq!(p.running(), ["a::three"], "warned about and not finished"); + assert!(p.line("\u{1b}[1m\u{1b}[92m Doc-tests\u{1b}[0m lightcraft_geom"), "coloured, as with CARGO_TERM_COLOR=always"); + assert_eq!(p.binary.as_deref(), Some("doctests of lightcraft_geom")); + assert_eq!(p.exe, None); + assert_eq!(p.total, Some(4), "the test lines stay until the new binary's own `running` line"); + p.line("running 1 test"); + assert_eq!((p.total, p.finished.len(), p.running().len()), (Some(1), 0, 0), "which starts afresh"); + p.pending = "test src/lib.rs - f (line 3) ... ".to_owned(); + assert_eq!(p.running(), ["src/lib.rs - f (line 3)"], "a single-threaded run prints the name as the test starts"); + } + + #[test] + fn finds_every_descendant_in_a_process_table() { + let table = " 1 0\n 10 1\n 11 10\n 12 11\n 13 10\n 20 1\n 21 20\n junk\n 14 12"; + assert_eq!(descendants_in(table, 10), [11, 12, 13, 14]); + assert!(descendants_in(table, 99).is_empty()); + assert_eq!(descendants_in("5 6\n6 5", 5), [6], "a cycle ends"); + } + + #[test] + fn the_report_names_the_binary_the_running_tests_and_the_rest() { + let mut p = Progress::default(); + for l in ["running 4 tests", "test a ... ok", "test b has been running for over 60 seconds"] { + p.line(l); + } + let listed: Vec = ["a", "b", "c", "d"].map(String::from).to_vec(); + let (lines, error) = report(MIN * 30, "geom (geom-1)", &p, Some(&listed)); + assert_eq!(error, "timed out after 30 min (still running: b)"); + let text = lines.join("\n"); + assert!(text.starts_with("timed out after 30 min: geom (geom-1); killed it"), "{text}"); + assert!(text.contains("still running: b") && text.contains("no result from 2 other test(s) of 4") && text.contains(": c, d"), "{text}"); + assert!(text.contains(TEST_BINARY_TIMEOUT_ENV), "says how to change the limit: {text}"); + let (lines, _) = report(MIN, "x", &p, None); + assert!(lines.join("\n").contains("1 of 4 test(s) had finished"), "without --list: {lines:?}"); + let many: Vec = (0..30).map(|i| format!("t{i}")).collect(); + let (lines, _) = report(MIN, "x", &Progress::default(), Some(&many)); + let text = lines.join("\n"); + assert!(text.contains("no test was reported as running") && text.contains("t19 and 10 more") && !text.contains("t20"), "{text}"); + } + + /// Whether process `pid` is gone (or a zombie no one has reaped yet). + #[cfg(unix)] + fn gone(pid: &str) -> bool { + let out = Command::new("ps").args(["-o", "stat=", "-p", pid]).output().unwrap(); + let stat = String::from_utf8_lossy(&out.stdout); + stat.trim().is_empty() || stat.trim().starts_with('Z') + } + + #[cfg(unix)] + fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("xtask-deadline-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[cfg(unix)] + fn wait_gone(pid: &str) -> bool { + let until = Instant::now() + Duration::from_secs(10); + while Instant::now() < until { + if gone(pid) { + return true; + } + std::thread::sleep(Duration::from_millis(50)); + } + false + } + + #[cfg(unix)] + #[test] + fn a_hung_binary_is_killed_with_the_processes_it_started_and_named() { + let dir = scratch("hung"); + let pidfile = dir.join("grandchild.pid"); + // a "test binary" that reports one test, warns about another, starts a grandchild and hangs; + // `sh -c SCRIPT --list` (how the report lists the tests) sets $0 to `--list` + let script = format!( + "case \"$0\" in --list) printf 'a: test\\nb: test\\nc: test\\n\\n3 tests, 0 benchmarks\\n'; exit;; esac; \ + printf 'running 3 tests\\ntest a ... ok\\ntest b has been running for over 60 seconds\\n'; \ + sleep 300 & echo $! > '{}'; wait", + pidfile.display() + ); + let mut cmd = Command::new("/bin/sh"); + cmd.args(["-c", &script]); + let t = Instant::now(); + let mut shown = Vec::new(); + let err = test_binary(cmd, "fake (sh)", Some(Duration::from_secs(2)), &mut shown).unwrap_err(); + assert!(t.elapsed() < Duration::from_secs(14), "the limit ended it, and --list answered: {:?}", t.elapsed()); + assert_eq!(err, "timed out after 2 s (still running: b)"); + let shown = shown.join("\n"); + assert!(shown.starts_with("timed out after 2 s: fake (sh); killed it"), "{shown}"); + assert!(shown.contains("no result from 1 other test(s) of 3") && shown.ends_with("(0 for none)"), "c, from --list: {shown}"); + let grandchild = std::fs::read_to_string(&pidfile).unwrap(); + assert!(wait_gone(grandchild.trim()), "the sleep it started was killed too"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[cfg(unix)] + #[test] + fn a_binary_that_ends_in_time_passes_or_fails_as_before() { + let sh = |script: &str| { + let mut c = Command::new("/bin/sh"); + c.args(["-c", script]); + run_test_binary(c, "fake (sh)", Some(MIN)) + }; + assert_eq!(sh("echo running 0 tests"), Ok(())); + assert_eq!(sh("exit 3"), Err("exit status: 3".to_owned())); + assert!(sh("kill -9 $$").unwrap_err().contains("SIGKILL")); + } + + #[cfg(unix)] + #[test] + fn under_cargo_each_binary_gets_the_limit_and_the_build_does_not_count() { + // the "build" outlasts the limit, then each "binary" finishes in time + let script = "sleep 1; \ + echo ' Running unittests src/lib.rs (target/debug/deps/a-1)' >&2; echo 'running 1 test'; echo 'test x ... ok'; \ + echo ' Running tests/it/main.rs (target/debug/deps/it-2)' >&2; echo 'running 0 tests'"; + let mut c = Command::new("/bin/sh"); + c.args(["-c", script]); + assert_eq!(run_cargo_tests(c, Some(Duration::from_millis(500))), Ok(())); + + let dir = scratch("cargo"); + let pidfile = dir.join("binary.pid"); + let script = format!( + "echo ' Running tests/it/main.rs (target/debug/deps/it-2)' >&2; \ + sh -c 'echo running 2 tests; printf \"test slow ... \"; sleep 300' & echo $! > '{}'; wait", + pidfile.display() + ); + let mut c = Command::new("/bin/sh"); + c.args(["-c", &script]); + let mut shown = Vec::new(); + let err = cargo_tests(c, Some(Duration::from_secs(2)), &mut shown).unwrap_err(); + assert!(shown.first().is_some_and(|l| l.starts_with("timed out after 2 s: tests/it/main.rs")), "{shown:?}"); + assert_eq!(err, "timed out after 2 s (still running: slow): tests/it/main.rs (target/debug/deps/it-2)"); + let binary = std::fs::read_to_string(&pidfile).unwrap(); + assert!(wait_gone(binary.trim()), "the test binary cargo started was killed too"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[cfg(unix)] + #[test] + fn no_limit_runs_as_before() { + let mut c = Command::new("/bin/sh"); + c.args(["-c", "exit 0"]); + assert_eq!(run_cargo_tests(c, None), Ok(())); + let mut c = Command::new("/bin/sh"); + c.args(["-c", "exit 4"]); + assert_eq!(run_test_binary(c, "fake", None), Err("exit status: 4".to_owned())); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index fccfa7b38fe..202a262c488 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -10,6 +10,7 @@ mod bench; mod ci_lock; mod ci_quick; mod ci_report; +mod deadline; mod ico; mod layers; mod parity; @@ -63,7 +64,10 @@ commands: --quick: only what the changes since the merge base with origin/main (or REF) can break: clippy, the changed packages' tests, and heif / parity / wasm when they apply. One ci runs at a time per machine; others wait (LIGHTCRAFT_CI_SLOTS=N for N at once, - LIGHTCRAFT_CI_LOCK=off to skip the lock) + LIGHTCRAFT_CI_LOCK=off to skip the lock) for up to LIGHTCRAFT_CI_LOCK_WAIT minutes + (default 120; 0: no limit). Each test binary may run LIGHTCRAFT_TEST_BINARY_TIMEOUT + minutes (default 30; 0: no limit); one that runs longer is killed with the processes + it started and reported with the tests still running test [-p PKG]... [--keep-going] [--doc] [-- ARGS] the workspace's tests (or PKG's) with ci's caps (build jobs by free RAM, at most 4 test threads, line-table debuginfo; a CARGO_BUILD_JOBS or RUST_TEST_THREADS you set wins, @@ -73,7 +77,8 @@ commands: --exact, --skip, --nocapture); stops at the first failing binary unless --keep-going (alias --no-fail-fast), which runs them all and names each that failed; --doc runs the doctests after them. LIGHTCRAFT_NEXTEST=1 runs the tests under cargo nextest - (--test-threads N and --nocapture become its options; ARGS are its filters) + (--test-threads N and --nocapture become its options; ARGS are its filters). + Same slot wait and per-binary time limit as ci corpus [--download] show where test corpora live; --download fetches PngSuite and CC0 raw samples (raw.pixls.us) into corpus/ and checks their sha256 stats [--exact] count tests and lines per crate (--exact: ask the test harness via `-- --list`) @@ -230,6 +235,13 @@ fn apply_ci_caps(c: &mut Command) { } } +/// [`run`] for a command that runs test binaries (`cargo test`, `cargo nextest run`): each test +/// binary it starts may run for `limit` ([`deadline::run_cargo_tests`]; `None`: no limit). +pub fn run_tests(cmd: Command, what: &str, limit: Option) -> Result<(), String> { + eprintln!("$ {what}"); + deadline::run_cargo_tests(cmd, limit).map_err(|e| format!("{what}: {e}")) +} + pub fn run(mut cmd: Command, what: &str) -> Result<(), String> { eprintln!("$ {what}"); let status = cmd.status().map_err(|e| format!("{what}: failed to spawn: {e}"))?; diff --git a/xtask/src/test.rs b/xtask/src/test.rs index 09eae7c01c8..d58d1025c5c 100644 --- a/xtask/src/test.rs +++ b/xtask/src/test.rs @@ -14,13 +14,16 @@ //! failed, as `ci`'s test step does (`--no-fail-fast`). `--doc` runs the doctests after them. With `LIGHTCRAFT_NEXTEST=1` (and //! cargo-nextest installed) the binaries run under `cargo nextest run` instead, as in `ci`. //! -//! `ci --quick` runs the changed packages' tests through the same functions ([`selected`]). +//! `ci --quick` runs the changed packages' tests through the same functions ([`selected`]). Each +//! test binary gets `LIGHTCRAFT_TEST_BINARY_TIMEOUT` minutes (30 by default; [`deadline`]): one that +//! runs longer is killed, with the processes it started, and reported with the tests still running. use std::collections::{BTreeMap, BTreeSet}; use std::path::Path; use std::process::Command; +use std::time::Duration; -use crate::ci_lock; +use crate::{ci_lock, deadline}; /// What `cargo xtask test` was asked to run. #[derive(Debug, Default, PartialEq, Eq)] @@ -161,9 +164,11 @@ fn names<'a>(packages: impl Iterator) -> String { /// caller doesn't set it, `RUST_TEST_THREADS` is the RAM-aware `min(build jobs by available RAM, 4)` /// of `ci`'s cargo runs; `.cargo/config.toml`'s default doesn't count, [`super::caller_sets`]), with /// `args`; skips the tests record go to `skip_log`. The one place `test` and `ci --quick` start a -/// test binary and wait for it. The error says how it ended: its exit status, the signal that killed -/// it, or why it didn't start. -pub fn run_binary(root: &Path, binary: &Binary, args: &[&str], skip_log: Option<&Path>) -> Result<(), String> { +/// test binary and wait for it, for at most `limit` ([`deadline::run_test_binary`]; +/// [`deadline::test_binary_timeout`] gives it). The error says how it ended: its exit status, the +/// signal that killed it, that it ran out of time (and which tests were still running), or why it +/// didn't start. +pub fn run_binary(root: &Path, binary: &Binary, args: &[&str], skip_log: Option<&Path>, limit: Option) -> Result<(), String> { let dir = Path::new(&binary.manifest).parent().unwrap_or(root); let mut c = Command::new(&binary.exe); c.current_dir(dir).env("CARGO_MANIFEST_DIR", dir).env("CARGO_PKG_NAME", &binary.package).args(args); @@ -173,8 +178,7 @@ pub fn run_binary(root: &Path, binary: &Binary, args: &[&str], skip_log: Option< super::apply_ci_caps(&mut c); let shown = std::iter::once(binary.label()).chain(args.iter().map(|a| (*a).to_owned())).collect::>().join(" "); eprintln!("$ {shown}"); - let status = c.status().map_err(|e| format!("failed to start: {e}"))?; - if status.success() { Ok(()) } else { Err(describe(status)) } + deadline::run_test_binary(c, &binary.label(), limit) } /// How a process that failed ended: `exit status: 101`, or on Unix the signal that killed it @@ -219,14 +223,14 @@ pub fn run_all(binaries: &[Binary], keep_going: bool, mut run_one: impl FnMut(&B /// `ci --quick`'s tests: the test binaries of `packages`, every one of them (each failure named). /// Doctests are left to the full `ci`. -pub fn selected(root: &Path, packages: &BTreeSet, skip_log: &Path) -> Result<(), String> { +pub fn selected(root: &Path, packages: &BTreeSet, skip_log: &Path, limit: Option) -> Result<(), String> { let packages = self::packages(&super::metadata()?, packages)?; let binaries = build(&packages, false)?; if binaries.is_empty() { println!("no test binaries in {}", names(packages.values())); return Ok(()); } - let outcome = run_all(&binaries, true, |b| run_binary(root, b, &[], Some(skip_log))); + let outcome = run_all(&binaries, true, |b| run_binary(root, b, &[], Some(skip_log), limit)); if outcome.failed.is_empty() { Ok(()) } else { @@ -320,6 +324,8 @@ pub fn doc_args<'a>(args: &Args<'a>, packages: &BTreeMap) -> Op /// `cargo xtask test`. pub fn run(raw: &[&str]) -> Result<(), String> { let args = parse(raw)?; + // a bad limit is an error before the run waits for its slot + let limit = deadline::test_binary_timeout()?; let root = super::root(); // probed before the caps are on, so the probe doesn't take their RAM snapshot (use_ci_caps) let nextest = if crate::ci::nextest() { Some(nextest_args(&args)?) } else { None }; @@ -333,7 +339,7 @@ pub fn run(raw: &[&str]) -> Result<(), String> { if let Some(nextest) = nextest { let mut c = super::cargo(); c.args(["nextest", "run"]).args(&nextest); - if let Err(e) = super::run(c, &format!("cargo nextest run {}", nextest.join(" "))) { + if let Err(e) = super::run_tests(c, &format!("cargo nextest run {}", nextest.join(" ")), limit) { failed.push(("cargo nextest run".to_owned(), e)); } } else { @@ -341,7 +347,7 @@ pub fn run(raw: &[&str]) -> Result<(), String> { if binaries.is_empty() { println!("no test binaries in {}", names(packages.values())); } - let outcome = run_all(&binaries, args.keep_going, |b| run_binary(&root, b, &args.test_args, None)); + let outcome = run_all(&binaries, args.keep_going, |b| run_binary(&root, b, &args.test_args, None, limit)); summary.push(format!("{} of {} test binaries passed", outcome.passed, binaries.len())); if outcome.not_run > 0 { summary.push(format!("{} not run after the first failure (--keep-going runs them)", outcome.not_run)); @@ -355,7 +361,7 @@ pub fn run(raw: &[&str]) -> Result<(), String> { Some(doc) => { let mut c = super::cargo(); c.args(&doc); - if let Err(e) = super::run(c, &format!("cargo {}", doc.join(" "))) { + if let Err(e) = super::run_tests(c, &format!("cargo {}", doc.join(" ")), limit) { failed.push(("doctests".to_owned(), e)); } } @@ -534,7 +540,9 @@ mod tests { #[test] fn a_binary_that_cannot_start_reports_why() { let missing = Binary { package: "a".into(), manifest: "/nonexistent/a/Cargo.toml".into(), exe: "/nonexistent/a/target/a-0".into() }; - let err = run_binary(Path::new("/nonexistent"), &missing, &[], None).unwrap_err(); + let err = run_binary(Path::new("/nonexistent"), &missing, &[], None, None).unwrap_err(); + assert!(err.starts_with("failed to start:"), "{err}"); + let err = run_binary(Path::new("/nonexistent"), &missing, &[], None, Some(Duration::from_secs(60))).unwrap_err(); assert!(err.starts_with("failed to start:"), "{err}"); } @@ -542,9 +550,11 @@ mod tests { #[test] fn a_failing_binary_reports_its_exit_status() { let binary = Binary { package: "sh".into(), manifest: "/Cargo.toml".into(), exe: "/bin/sh".into() }; - let err = run_binary(Path::new("/"), &binary, &["-c", "exit 3"], None).unwrap_err(); - assert_eq!(err, "exit status: 3"); - let err = run_binary(Path::new("/"), &binary, &["-c", "kill -9 $$"], None).unwrap_err(); - assert!(err.contains("SIGKILL"), "{err}"); + for limit in [None, Some(Duration::from_secs(60))] { + let err = run_binary(Path::new("/"), &binary, &["-c", "exit 3"], None, limit).unwrap_err(); + assert_eq!(err, "exit status: 3"); + let err = run_binary(Path::new("/"), &binary, &["-c", "kill -9 $$"], None, limit).unwrap_err(); + assert!(err.contains("SIGKILL"), "{err}"); + } } } From f206ea8b41c650754833718c8299d037d53124d3 Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Mon, 26 Oct 2026 14:40:37 -0500 Subject: [PATCH 14/40] fix(xtask): #3060 make the per-binary clock, the kill and the --list run hold up Review round 1: - A quiet cargo (`-q`, CARGO_TERM_QUIET=true or term.quiet in its config) prints no `Running` lines, so the per-binary clock never started. The cargo test runs xtask watches now run loud (CARGO_TERM_QUIET=false, cargo's own `-q` / `--quiet` dropped; the test binaries' after `--` stay), and a binary's own `running N tests` line starts the clock too. - The `--list` run of a timed-out binary had a bound on reading its output but none on its exit: one deadline now covers both, and a run past it is killed like the binary. - Walking the process tree missed processes that outlived their parent. Every watched process gets an environment variable of its own (LIGHTCRAFT_XTASK_RUN__) that its descendants inherit; the kill finds them by it (/proc/*/environ on Linux, `ps eww` elsewhere) besides the current tree, and the report says how many it killed, names any still alive, and says when it couldn't look. - A single-threaded --nocapture run's `test NAME ... ` counted as a result. Only libtest's results (ok, FAILED, ignored[, why], bench:, ok/FAILED with a time) finish a test, on its line or on a later line of their own; the started test is kept across its output. - What is kept of a child's output is bounded: test names per binary by a byte budget, `--list` output to 16 MiB; the report says when a list was cut. Co-Authored-By: Claude Opus 5.5 --- README.md | 3 +- docs/architecture.md | 19 +- xtask/src/deadline.rs | 765 ++++++++++++++++++++++++++++++++++-------- 3 files changed, 634 insertions(+), 153 deletions(-) diff --git a/README.md b/README.md index f253c101507..97bd226dd3b 100644 --- a/README.md +++ b/README.md @@ -421,7 +421,8 @@ gives up after `LIGHTCRAFT_CI_LOCK_WAIT` minutes (default 120; `0` waits as long names the run holding the slot. Nothing a run waits on is unbounded either: each test binary may run for `LIGHTCRAFT_TEST_BINARY_TIMEOUT` minutes (default 30, timed from cargo's `Running` line for it; `0` for no limit). One that runs longer, a test hung on a GPU device say, is killed with every -process it started, and the run reports it as `timed out after 30 min` with the tests still running +process it started (found by an environment variable they inherit, so those that outlived their +parent too), and the run reports it as `timed out after 30 min` with the tests still running and those that never reported a result. Under `LIGHTCRAFT_NEXTEST=1`, `.config/nextest.toml` kills a test after 30 minutes instead. diff --git a/docs/architecture.md b/docs/architecture.md index b42b386dc56..b2ee7670713 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -84,13 +84,18 @@ first. Nothing these runs wait on is unbounded (`xtask/src/deadline.rs`, #3060). Stable libtest has no per-test timeout, so each test binary gets `LIGHTCRAFT_TEST_BINARY_TIMEOUT` minutes (default 30; `0` for none): timed from its start when xtask runs it (`test::run_binary`), and from cargo's `Running` / -`Doc-tests` line for it when `cargo test` runs it (the full `ci`'s test and HEIF steps; the build -before isn't bounded). The output streams through and is read for libtest's lines; on timeout the -binary and every process it started are killed (frozen, then SIGKILL, by walking the process tree: -the child stays in xtask's process group so Ctrl-C still reaches it; `taskkill /T` on Windows), and -the run reports `timed out after N min: ` with the tests still running (libtest's "has been -running for over 60 seconds" warnings, or the test a single-threaded run started) and those that -never reported a result (`--list`). Under nextest, `.config/nextest.toml`'s `slow-timeout` kills a test +`Doc-tests` line for it, and again from its own `running N tests` line, when `cargo test` runs it (the +full `ci`'s test and HEIF steps; the build before isn't bounded; cargo runs with +`CARGO_TERM_QUIET=false` and without `-q` so it prints those lines). The output streams through and is +read for libtest's lines, keeping a bounded amount. On timeout the binary and every process it started +are killed: each watched process gets an environment variable of its own +(`LIGHTCRAFT_XTASK_RUN__`) that its descendants inherit, so the kill also finds those that +outlived their parent (`/proc/*/environ` on Linux, `ps eww` elsewhere, plus the current process tree), +freezes them with SIGSTOP and then kills them (`taskkill /T` on Windows). The child stays in xtask's +process group, so Ctrl-C still reaches it. The run reports `timed out after N min: `, what +the kill found, the tests still running (libtest's "has been running for over 60 seconds" warnings, +or the test a single-threaded run started) and those that never reported a result (`--list`, itself +bounded in time and size). Under nextest, `.config/nextest.toml`'s `slow-timeout` kills a test after 30 minutes instead. The wait for the CI slot gives up after `LIGHTCRAFT_CI_LOCK_WAIT` minutes (default 120, several full runs; `0` for no limit) with an error naming the run that holds it. diff --git a/xtask/src/deadline.rs b/xtask/src/deadline.rs index 9d28113b6af..9807a5dd1bf 100644 --- a/xtask/src/deadline.rs +++ b/xtask/src/deadline.rs @@ -9,25 +9,33 @@ //! - A test binary xtask starts itself ([`run_test_binary`]: `cargo xtask test`, `ci --quick`) is //! timed from its start. //! - A `cargo test` run ([`run_cargo_tests`]: the full `ci`'s test and heif steps, doctests) is timed -//! per test binary, from the `Running` (or `Doc-tests`) line cargo prints as it starts each one; -//! the build before the first one isn't bounded. Under `cargo nextest run` (no such lines) nextest's -//! own `slow-timeout` in `.config/nextest.toml` ends a hung test instead. +//! per test binary, from the `Running` (or `Doc-tests`) line cargo prints as it starts each one, +//! and again from the binary's own `running N tests` line; the build before the first one isn't +//! bounded. Cargo runs loud for this (`CARGO_TERM_QUIET=false`, no `-q`): a quiet cargo prints no +//! `Running` lines. Under `cargo nextest run` (no such lines) nextest's own `slow-timeout` in +//! `.config/nextest.toml` ends a hung test instead. //! //! The output streams through as it arrives, and is read on the way for libtest's lines: `running N -//! tests`, `test NAME ... ok` as each test finishes, and `test NAME has been running for over 60 -//! seconds`. On timeout the binary and every process it started are killed (on Unix: frozen with -//! SIGSTOP so nothing more forks, then SIGKILL; on Windows `taskkill /T /F`), and the report names the -//! binary, the tests still running (those warned about and not finished, or the one a single-threaded -//! run printed `test NAME ... ` for) and the tests that never reported a result (from `--list`). +//! tests`, `test NAME ... ok` as each test finishes (or `test NAME ... ` as it starts, when one runs +//! at a time), and `test NAME has been running for over 60 seconds`. What is kept of it is bounded +//! ([`MAX_LINE`], [`NAME_BUDGET`]). On timeout the binary and every process it started are killed, +//! and the report names the binary, the tests still running and the tests that never reported a +//! result (from `--list`, itself bounded in time and size). //! -//! The child stays in xtask's process group rather than one of its own, so Ctrl-C in the terminal -//! still reaches the test binaries as before; that's why the kill walks the process tree (`ps`) -//! rather than signalling a group. +//! Containment: every process xtask watches gets an environment variable of its own +//! ([`Marker`], `LIGHTCRAFT_XTASK_RUN__=1`) that everything it starts inherits, so on Unix +//! the kill finds them all, including those that outlived their parent and were reparented, from +//! `/proc/*/environ` on Linux or `ps eww` elsewhere, besides the binary's current descendants. They +//! are frozen with SIGSTOP until no new one turns up, then killed with SIGKILL; the report says how +//! many and names any still alive. Only a process that clears its environment escapes. On Windows +//! `taskkill /T /F` ends the process tree. The child stays in xtask's process group rather than one +//! of its own, so Ctrl-C in the terminal still reaches the test binaries as before. use std::collections::BTreeSet; use std::io::{IsTerminal, Read, Write}; use std::path::{Path, PathBuf}; use std::process::{Child, Command, ExitStatus, Stdio}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError, mpsc}; use std::time::{Duration, Instant}; @@ -38,15 +46,19 @@ pub const TEST_BINARY_TIMEOUT_ENV: &str = "LIGHTCRAFT_TEST_BINARY_TIMEOUT"; pub const DEFAULT_TEST_BINARY_TIMEOUT_MIN: u64 = 30; /// The longest limit a variable may set (a week); `0` or `off` means none. const MAX_MINUTES: f64 = 7.0 * 24.0 * 60.0; -/// How often the wait checks the child and the clock. +/// How often the waits check the child and the clock. const TICK: Duration = Duration::from_millis(50); /// How long, after the child ends, to wait for its output pipes to close (a process it started /// that outlives it may hold them open). const DRAIN: Duration = Duration::from_secs(5); -/// How long the `--list` run of a timed-out binary may take (it runs no tests: milliseconds). +/// How long the `--list` run of a timed-out binary may take, start to exit (it runs no tests). const LIST_LIMIT: Duration = Duration::from_secs(15); +/// The most `--list` output read; the rest is cut. +const LIST_MAX_BYTES: usize = 16 << 20; /// The longest line of output parsed for test names; longer ones stream through unparsed. const MAX_LINE: usize = 64 * 1024; +/// The bytes of test names one [`Names`] keeps (finished, slow or listed tests of one binary). +const NAME_BUDGET: usize = 8 << 20; /// How many never-finished tests the timeout report names. const NAMED: usize = 20; @@ -86,7 +98,7 @@ pub fn test_binary_timeout() -> Result, String> { minutes_from_env(TEST_BINARY_TIMEOUT_ENV, DEFAULT_TEST_BINARY_TIMEOUT_MIN) } -/// `30 min`, `1.5 min`, `20 s`, `300 ms`: a limit as the reports show it. +/// `30 min`, `1.5 min`, `20 s`, `1.2 s`, `300 ms`: a limit as the reports show it. pub fn show(limit: Duration) -> String { let secs = limit.as_secs_f64(); let minutes = secs / 60.0; @@ -124,6 +136,126 @@ fn strip_ansi(line: &str) -> String { out } +/// Splits output into lines as it arrives, dropping (not parsing) lines over [`MAX_LINE`]. +#[derive(Default)] +struct Lines { + buf: Vec, + overlong: bool, +} + +impl Lines { + /// Feed `chunk`; `each` gets every whole line it completes. + fn feed(&mut self, chunk: &[u8], mut each: impl FnMut(&str)) { + for piece in chunk.split_inclusive(|b| *b == b'\n') { + if !self.overlong { + self.buf.extend_from_slice(piece); + if self.buf.len() > MAX_LINE { + self.buf.clear(); + self.overlong = true; + } + } + if piece.ends_with(b"\n") { + if !self.overlong { + each(&String::from_utf8_lossy(&self.buf)); + } + self.buf.clear(); + self.overlong = false; + } + } + } + + /// The line begun and not yet ended. + fn rest(&self) -> String { + String::from_utf8_lossy(&self.buf).into_owned() + } +} + +/// Test names in the order first seen, without repeats, up to [`NAME_BUDGET`] bytes; past that +/// they are dropped and [`Names::cut`] says so. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Names { + order: Vec, + index: BTreeSet, + bytes: usize, + budget: usize, + /// Some names were dropped for the budget. + pub cut: bool, +} + +impl Default for Names { + fn default() -> Self { + Self::with_budget(NAME_BUDGET) + } +} + +impl Names { + fn with_budget(budget: usize) -> Self { + Self { order: Vec::new(), index: BTreeSet::new(), bytes: 0, budget, cut: false } + } + + fn insert(&mut self, name: &str) { + if self.index.contains(name) { + return; + } + // kept twice (order and index) + let cost = name.len().saturating_mul(2); + if self.bytes.saturating_add(cost) > self.budget { + self.cut = true; + return; + } + self.bytes += cost; + self.order.push(name.to_owned()); + self.index.insert(name.to_owned()); + } + + fn contains(&self, name: &str) -> bool { + self.index.contains(name) + } + + fn len(&self) -> usize { + self.order.len() + } + + fn iter(&self) -> impl Iterator { + self.order.iter().map(String::as_str) + } + + fn clear(&mut self) { + *self = Self::with_budget(self.budget); + } +} + +/// Whether `result`, what follows `test NAME ... `, is one of libtest's results. +fn is_result(result: &str) -> bool { + let r = result.trim(); + matches!(r, "ok" | "FAILED" | "ignored") + || r.starts_with("ignored, ") + || r.starts_with("bench:") + || r.starts_with("ok <") + || r.starts_with("FAILED <") + || r.starts_with("FAILED (") +} + +/// `test NAME ... REST` (REST may be empty: a test a single-threaded run just started): the name +/// and the rest. +fn test_line(text: &str) -> Option<(&str, &str)> { + let rest = text.strip_prefix("test ")?; + if let Some((name, result)) = rest.split_once(" ... ") { + return Some((name, result)); + } + rest.trim_end().strip_suffix(" ...").map(|name| (name, "")) +} + +/// What a line of output meant for the clock. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Event { + /// Cargo started a test binary (`Running`, `Doc-tests`). + Binary, + /// A test binary started its tests (`running N tests`). + Tests, + Other, +} + /// What a test run's output said so far: the test binary cargo started last and, from libtest's /// lines, how many tests it runs, which finished and which ran long. #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -134,17 +266,20 @@ pub struct Progress { pub exe: Option, /// `running N tests`. pub total: Option, - /// The tests that reported a result (`test NAME ... ok`, `FAILED`, `ignored`). - pub finished: BTreeSet, + /// The tests that reported a result (`test NAME ... ok`, `FAILED`, `ignored`, `bench:`). + pub finished: Names, /// The tests libtest said had been running for over 60 seconds, in that order. - pub slow: Vec, + pub slow: Names, + /// The test a single-threaded run started (`test NAME ... `) and has no result for yet; the + /// test's own output may come between. + pub active: Option, /// The unfinished last line of stdout: `test NAME ... ` while a single-threaded run runs NAME. pub pending: String, } impl Progress { - /// Read one whole line of output. True when it is cargo starting a test binary. - pub fn line(&mut self, raw: &str) -> bool { + /// Read one whole line of output. + pub fn line(&mut self, raw: &str) -> Event { let clean = strip_ansi(raw); let line = clean.trim_end(); let text = line.trim_start(); @@ -153,30 +288,48 @@ impl Progress { if let Some(rest) = text.strip_prefix("Running ").filter(|_| cargo_status) { let exe = rest.strip_suffix(')').and_then(|r| r.rsplit_once(" (")).map(|(_, path)| PathBuf::from(path)); self.start_binary(rest.to_owned(), exe); - return true; + return Event::Binary; } if let Some(rest) = text.strip_prefix("Doc-tests ").filter(|_| cargo_status) { self.start_binary(format!("doctests of {rest}"), None); - return true; + return Event::Binary; } if let Some(rest) = text.strip_prefix("running ") { let mut words = rest.split_whitespace(); if let (Some(n), Some("test" | "tests"), None) = (words.next().and_then(|n| n.parse().ok()), words.next(), words.next()) { self.reset(); self.total = Some(n); + return Event::Tests; } - return false; - } - if let Some(rest) = text.strip_prefix("test ") { - if let Some((name, _result)) = rest.split_once(" ... ") { - self.finished.insert(name.to_owned()); - } else if let Some((name, _)) = rest.split_once(" has been running for over ") - && !self.slow.iter().any(|s| s == name) - { - self.slow.push(name.to_owned()); + return Event::Other; + } + if let Some((name, result)) = test_line(text) { + if is_result(result) { + self.finish(name); + } else { + // started; what follows is the test's own output (single-threaded, --nocapture) + self.active = Some(name.to_owned()); } + return Event::Other; + } + if let Some((name, _)) = text.strip_prefix("test ").and_then(|r| r.split_once(" has been running for over ")) { + self.slow.insert(name); + return Event::Other; + } + // the result of the active test, after its output + if is_result(text) + && let Some(name) = self.active.take() + { + self.finished.insert(&name); + } + Event::Other + } + + fn finish(&mut self, name: &str) { + self.finished.insert(name); + if self.active.as_deref() == Some(name) { + self.active = None; } - false } /// Cargo started a test binary. The test lines stay until its `running N tests`: cargo's line @@ -191,17 +344,20 @@ impl Progress { self.total = None; self.finished.clear(); self.slow.clear(); + self.active = None; self.pending.clear(); } /// The tests still running: warned about as slow and not finished, then the one a /// single-threaded run started last. pub fn running(&self) -> Vec { - let mut running: Vec = self.slow.iter().filter(|s| !self.finished.contains(*s)).cloned().collect(); + let mut running: Vec = self.slow.iter().filter(|s| !self.finished.contains(s)).map(str::to_owned).collect(); let pending = strip_ansi(&self.pending); - let started = pending.trim().strip_prefix("test ").and_then(|p| p.strip_suffix(" ...")).filter(|n| !n.contains(" ... ")); - if let Some(name) = started.filter(|n| !self.finished.contains(*n) && !running.iter().any(|r| r == n)) { - running.push(name.to_owned()); + let started = test_line(pending.trim_start()).filter(|(_, result)| !is_result(result)).map(|(name, _)| name); + for name in [self.active.as_deref(), started].into_iter().flatten() { + if !self.finished.contains(name) && !running.iter().any(|r| r == name) { + running.push(name.to_owned()); + } } running } @@ -212,17 +368,37 @@ impl Progress { pub enum Clock { /// When the process starts: a test binary run directly. Start, - /// At each test binary cargo starts (its `Running` / `Doc-tests` line): the limit is per binary, - /// and the build before the first isn't bounded. + /// At each test binary cargo starts (its `Running` / `Doc-tests` line, and its own `running N + /// tests` line): the limit is per binary, and the build before the first isn't bounded. EachBinary, } +/// The environment variable that marks every process one watched run starts (see the module +/// docs): its name is unique to this xtask process and run, so nested runs keep each other's. +pub struct Marker { + key: String, +} + +impl Marker { + fn new() -> Self { + static RUNS: AtomicU64 = AtomicU64::new(0); + Self { key: format!("LIGHTCRAFT_XTASK_RUN_{}_{}", std::process::id(), RUNS.fetch_add(1, Ordering::Relaxed)) } + } +} + +/// Spawn `cmd` with a fresh [`Marker`]. +fn spawn_marked(cmd: &mut Command) -> std::io::Result<(Child, Marker)> { + let marker = Marker::new(); + cmd.env(&marker.key, "1"); + Ok((cmd.spawn()?, marker)) +} + /// How a watched run ended. #[derive(Debug)] pub enum Ended { Exited(ExitStatus), - /// Out of time: killed, with what its output said by then. - TimedOut(Progress), + /// Out of time: killed (what the kill did), with what its output said by then. + TimedOut(Box, String), } struct Watch { @@ -235,7 +411,7 @@ struct Watch { /// `limit` runs out (timed as `clock` says); then kill it and every process it started. pub fn watch(mut cmd: Command, limit: Duration, clock: Clock) -> Result { cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); - let mut child = cmd.spawn().map_err(|e| format!("failed to start: {e}"))?; + let (mut child, marker) = spawn_marked(&mut cmd).map_err(|e| format!("failed to start: {e}"))?; let state = Arc::new(Mutex::new(Watch { progress: Progress::default(), since: (clock == Clock::Start).then(Instant::now) })); let (done_tx, done_rx) = mpsc::channel(); let mut readers = 0; @@ -251,7 +427,7 @@ pub fn watch(mut cmd: Command, limit: Duration, clock: Clock) -> Result Result {} Err(e) => { - kill_tree(&mut child); + kill_marked(&mut child, &marker); return Err(format!("waiting for it failed: {e}")); } } if lock(&state).since.is_some_and(|since| since.elapsed() >= limit) { - kill_tree(&mut child); + let killed = kill_marked(&mut child, &marker); drain(readers); - return Ok(Ended::TimedOut(lock(&state).progress.clone())); + return Ok(Ended::TimedOut(Box::new(lock(&state).progress.clone()), killed)); } std::thread::sleep(TICK); } @@ -289,8 +465,7 @@ pub fn watch(mut cmd: Command, limit: Duration, clock: Clock) -> Result, is_stdout: bool, clock: Clock, state: &Mutex) { let mut buf = [0u8; 8192]; - let mut line: Vec = Vec::new(); - let mut overlong = false; + let mut lines = Lines::default(); loop { let n = match pipe.read(&mut buf) { Ok(0) => break, @@ -307,51 +482,84 @@ fn pump(mut pipe: Box, is_stdout: bool, clock: Clock, state: &M let _ = err.write_all(chunk).and_then(|()| err.flush()); } let mut watch = lock(state); - for piece in chunk.split_inclusive(|b| *b == b'\n') { - if !overlong { - line.extend_from_slice(piece); - } - if line.len() > MAX_LINE { - line.clear(); - overlong = true; - } - if piece.ends_with(b"\n") { - if !overlong && watch.progress.line(&String::from_utf8_lossy(&line)) && clock == Clock::EachBinary { - watch.since = Some(Instant::now()); - } - line.clear(); - overlong = false; + lines.feed(chunk, |line| { + let event = watch.progress.line(line); + if clock == Clock::EachBinary && event != Event::Other { + watch.since = Some(Instant::now()); } - } + }); if is_stdout { - watch.progress.pending = String::from_utf8_lossy(&line).into_owned(); + watch.progress.pending = lines.rest(); } } } -/// Kill `child` and every process it started, and reap it. -pub fn kill_tree(child: &mut Child) { - #[cfg(unix)] - { - // freeze the tree first so nothing forks while it is collected, then kill it all - let mut seen: BTreeSet = BTreeSet::from([child.id()]); - let mut fresh: Vec = vec![child.id()]; - for _ in 0..8 { - signal("STOP", &fresh); - fresh = descendants(child.id()).into_iter().filter(|p| !seen.contains(p)).collect(); - if fresh.is_empty() { - break; - } - seen.extend(&fresh); +/// Kill `child`, every process it started and every process carrying its `marker`, reap it, and +/// say what was done. +pub fn kill_marked(child: &mut Child, marker: &Marker) -> String { + let note = kill_all(child, marker); + let _ = child.kill(); + let _ = child.wait(); + note +} + +#[cfg(unix)] +fn kill_all(child: &Child, marker: &Marker) -> String { + let me = std::process::id(); + // freeze everything found so nothing forks while the rest is collected, then kill it all + let mut seen: BTreeSet = BTreeSet::from([child.id()]); + let mut fresh: Vec = vec![child.id()]; + let mut marker_seen = true; + for _ in 0..16 { + signal("STOP", &fresh); + let mut found = descendants(child.id()); + match marked(&marker.key) { + Some(pids) => found.extend(pids), + None => marker_seen = false, + } + fresh = found.into_iter().filter(|p| *p != me && !seen.contains(p)).collect::>().into_iter().collect(); + if fresh.is_empty() { + break; } - signal("KILL", &seen.iter().copied().collect::>()); + seen.extend(&fresh); } - #[cfg(windows)] - { - let _ = Command::new("taskkill").args(["/PID", &child.id().to_string(), "/T", "/F"]).stdout(Stdio::null()).stderr(Stdio::null()).status(); + signal("KILL", &seen.iter().copied().collect::>()); + let others = seen.len().saturating_sub(1); + if !marker_seen { + return format!( + "killed it and {others} process(es) it started that were still its descendants; ones that outlived their parent \ + could not be looked for (no /proc or ps eww) and may still run" + ); } - let _ = child.kill(); - let _ = child.wait(); + // a killed process leaves the list once its parent (or init) reaps it + let until = Instant::now() + Duration::from_secs(2); + let mut alive = marked(&marker.key).unwrap_or_default(); + while !alive.is_empty() && Instant::now() < until { + std::thread::sleep(TICK); + alive = marked(&marker.key).unwrap_or_default(); + } + alive.retain(|p| *p != me && *p != child.id()); + let mut note = if others == 0 { + "killed it; it had started no other process (looked for by the run's environment marker)".to_owned() + } else { + format!("killed it and the {others} process(es) it started (found by the run's environment marker, reparented ones too)") + }; + if !alive.is_empty() { + let pids: Vec = alive.iter().map(u32::to_string).collect(); + note.push_str(&format!("; still alive after the kill: pid {} (they carry {})", pids.join(", "), marker.key)); + } + note +} + +#[cfg(windows)] +fn kill_all(child: &Child, _marker: &Marker) -> String { + let _ = Command::new("taskkill").args(["/PID", &child.id().to_string(), "/T", "/F"]).stdout(Stdio::null()).stderr(Stdio::null()).status(); + "killed it and its process tree (taskkill /T); processes that outlived their parent may still run".to_owned() +} + +#[cfg(not(any(unix, windows)))] +fn kill_all(_child: &Child, _marker: &Marker) -> String { + "killed it; processes it started may still run".to_owned() } #[cfg(unix)] @@ -393,6 +601,39 @@ fn descendants_in(table: &str, root: u32) -> Vec { found.into_iter().collect() } +/// The processes whose environment holds `key` (this user's; zombies have none), or `None` when +/// they can't be looked for. +#[cfg(unix)] +fn marked(key: &str) -> Option> { + let entry = format!("{key}="); + if let Ok(dir) = std::fs::read_dir("/proc") + && Path::new("/proc/self/environ").exists() + { + let pids = dir + .filter_map(Result::ok) + .filter_map(|e| e.file_name().to_str()?.parse::().ok()) + .filter(|pid| { + // another user's process can't be read: it isn't ours + std::fs::read(format!("/proc/{pid}/environ")).is_ok_and(|env| env.split(|b| *b == 0).any(|var| var.starts_with(entry.as_bytes()))) + }) + .collect(); + return Some(pids); + } + // macOS, BSD: `ps eww` appends each process's environment to its command line + let out = Command::new("ps").args(["eww", "-A", "-o", "pid=", "-o", "command="]).stderr(Stdio::null()).output().ok()?; + if !out.status.success() { + return None; + } + Some(marked_in(&String::from_utf8_lossy(&out.stdout), key)) +} + +/// The pids in `ps eww -o pid= -o command=` output whose environment holds `key`. +#[cfg_attr(not(unix), allow(dead_code))] +fn marked_in(table: &str, key: &str) -> Vec { + let entry = format!(" {key}="); + table.lines().filter(|l| l.contains(&entry)).filter_map(|l| l.split_whitespace().next()?.parse().ok()).collect() +} + /// A copy of `cmd`: its program, arguments, directory and environment changes. fn copy_command(cmd: &Command) -> Command { let mut c = Command::new(cmd.get_program()); @@ -409,50 +650,114 @@ fn copy_command(cmd: &Command) -> Command { c } +/// The tests a test binary would run (`--list`), as far as they were read. +#[derive(Debug)] +pub struct Listed { + pub names: Names, + /// The output passed [`LIST_MAX_BYTES`] or the names their budget: the list is incomplete. + pub cut: bool, +} + /// The tests a test binary would run, from `c` (the binary with its arguments) plus `--list`; -/// `None` when that fails or takes over [`LIST_LIMIT`]. -fn list_tests(mut c: Command) -> Option> { +/// `None` when that fails or takes over `limit` from start to exit (then it is killed, with what +/// it started). At most `max_bytes` of its output are read. +fn list_tests(mut c: Command, limit: Duration, max_bytes: usize) -> Option { c.arg("--list").stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()); - let mut child = c.spawn().ok()?; + let until = Instant::now() + limit; + let (mut child, marker) = spawn_marked(&mut c).ok()?; let Some(mut stdout) = child.stdout.take() else { - kill_tree(&mut child); + kill_marked(&mut child, &marker); return None; }; let (tx, rx) = mpsc::channel(); - let reader = std::thread::Builder::new().spawn(move || { - let mut text = String::new(); - let _ = stdout.read_to_string(&mut text); - let _ = tx.send(text); + let reader = std::thread::Builder::new().name("xtask-list".into()).spawn(move || { + let (mut names, mut lines, mut read, mut buf) = (Names::default(), Lines::default(), 0usize, [0u8; 8192]); + let mut cut = false; + loop { + let n = match stdout.read(&mut buf) { + Ok(0) => break, + Ok(n) => n, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, + Err(_) => break, + }; + let room = max_bytes.saturating_sub(read); + let chunk = buf.get(..n.min(room)).unwrap_or_default(); + read = read.saturating_add(chunk.len()); + lines.feed(chunk, |line| { + if let Some(name) = line.trim_end().strip_suffix(": test") { + names.insert(name); + } + }); + if n > room { + cut = true; + break; + } + } + let cut = cut || names.cut; + let _ = tx.send(Listed { names, cut }); }); - let text = reader.ok().and_then(|_| rx.recv_timeout(LIST_LIMIT).ok()); - let Some(text) = text else { - kill_tree(&mut child); + if reader.is_err() { + kill_marked(&mut child, &marker); return None; - }; - let status = child.wait().ok()?; - status.success().then(|| text.lines().filter_map(|l| l.strip_suffix(": test")).map(str::to_owned).collect()) + } + let (mut status, mut listed) = (None, None); + loop { + if status.is_none() { + match child.try_wait() { + Ok(s) => status = s, + Err(_) => break, + } + } + if listed.is_none() { + match rx.try_recv() { + Ok(l) => listed = Some(l), + Err(mpsc::TryRecvError::Empty) => {} + Err(mpsc::TryRecvError::Disconnected) => break, + } + } + match (status, listed.as_ref()) { + // read as much as it may: whatever more it writes (or how the cut pipe ends it) doesn't matter + (status, Some(l)) if l.cut => { + if status.is_none() { + kill_marked(&mut child, &marker); + } + return listed; + } + (Some(s), Some(_)) => return listed.filter(|_| s.success()), + _ => {} + } + if Instant::now() >= until { + break; + } + std::thread::sleep(TICK); + } + if status.is_none() { + kill_marked(&mut child, &marker); + } + None } /// What to tell about a test binary that ran out of `limit`: the lines to print and the one-line -/// error. `listed` is every test it would run (`--list`), when known. -pub fn report(limit: Duration, binary: &str, progress: &Progress, listed: Option<&[String]>) -> (Vec, String) { +/// error. `listed` is every test it would run (`--list`), when known; `killed` what the kill did. +pub fn report(limit: Duration, binary: &str, progress: &Progress, listed: Option<&Listed>, killed: &str) -> (Vec, String) { let running = progress.running(); - let mut lines = vec![format!("timed out after {}: {binary}; killed it and the processes it started", show(limit))]; + let mut lines = vec![format!("timed out after {}: {binary}", show(limit)), format!(" {killed}")]; if running.is_empty() { lines.push(" no test was reported as running (libtest warns about a test after 60 s)".to_owned()); } else { lines.push(format!(" still running: {}", running.join(", "))); } - let never: Option> = listed.map(|all| all.iter().filter(|t| !progress.finished.contains(*t) && !running.contains(t)).collect()); + let never: Option> = + listed.map(|l| l.names.iter().filter(|t| !progress.finished.contains(t) && !running.iter().any(|r| r.as_str() == *t)).collect()); match (never, progress.total) { (Some(never), _) if !never.is_empty() => { - let shown: Vec<&str> = never.iter().take(NAMED).map(|s| s.as_str()).collect(); + let shown: Vec<&str> = never.iter().take(NAMED).copied().collect(); let more = never.len().saturating_sub(NAMED); let more = if more > 0 { format!(" and {more} more") } else { String::new() }; lines.push(format!( " no result from {} other test(s) of {} (not started, or started less than 60 s before): {}{more}", never.len(), - listed.map_or(0, <[String]>::len), + listed.map_or(0, |l| l.names.len()), shown.join(", ") )); } @@ -461,6 +766,9 @@ pub fn report(limit: Duration, binary: &str, progress: &Progress, listed: Option } _ => {} } + if listed.is_some_and(|l| l.cut) || progress.finished.cut || progress.slow.cut { + lines.push(" (the output named more tests than xtask keeps, so these lists may be incomplete)".to_owned()); + } lines.push(format!(" {TEST_BINARY_TIMEOUT_ENV}= changes the limit (0 for none)")); let still = if running.is_empty() { String::new() } else { format!(" (still running: {})", running.join(", ")) }; (lines, format!("timed out after {}{still}", show(limit))) @@ -506,15 +814,42 @@ fn test_binary(mut cmd: Command, label: &str, limit: Option, shown: &m match watch(cmd, limit, Clock::Start)? { Ended::Exited(status) if status.success() => Ok(()), Ended::Exited(status) => Err(crate::test::describe(status)), - Ended::TimedOut(progress) => { - let listed = list_tests(lister); - let (lines, error) = report(limit, label, &progress, listed.as_deref()); + Ended::TimedOut(progress, killed) => { + let listed = list_tests(lister, LIST_LIMIT, LIST_MAX_BYTES); + let (lines, error) = report(limit, label, &progress, listed.as_ref(), &killed); shown.extend(lines); Err(error) } } } +/// `cmd`, a cargo command, made to print the `Running` lines the per-binary clock starts from: no +/// `-q` / `--quiet` among cargo's own arguments (those before `--`), and `CARGO_TERM_QUIET=false` +/// over any quiet setting in the environment or cargo's config. +fn loud(cmd: &Command) -> Command { + let mut c = Command::new(cmd.get_program()); + let mut cargos = true; + for arg in cmd.get_args() { + if arg == "--" { + cargos = false; + } + if !(cargos && (arg == "-q" || arg == "--quiet")) { + c.arg(arg); + } + } + if let Some(dir) = cmd.get_current_dir() { + c.current_dir(dir); + } + for (key, value) in cmd.get_envs() { + match value { + Some(v) => c.env(key, v), + None => c.env_remove(key), + }; + } + c.env("CARGO_TERM_QUIET", "false"); + c +} + /// Run `cmd`, a `cargo test` (or `cargo nextest run`) command, with each test binary it starts /// under `limit` ([`Clock::EachBinary`]; `None`: no limit, and the output isn't piped). pub fn run_cargo_tests(cmd: Command, limit: Option) -> Result<(), String> { @@ -525,11 +860,13 @@ pub fn run_cargo_tests(cmd: Command, limit: Option) -> Result<(), Stri } /// [`run_cargo_tests`], with the timeout report added to `shown` rather than printed. -fn cargo_tests(mut cmd: Command, limit: Option, shown: &mut Vec) -> Result<(), String> { +fn cargo_tests(cmd: Command, limit: Option, shown: &mut Vec) -> Result<(), String> { + let mut cmd = cmd; let Some(limit) = limit else { let status = cmd.status().map_err(|e| format!("failed to spawn: {e}"))?; return if status.success() { Ok(()) } else { Err(format!("exited with {status}")) }; }; + let mut cmd = loud(&cmd); // cargo's stderr is a pipe now: keep its colours when ours is a terminal if std::io::stderr().is_terminal() && std::env::var_os("CARGO_TERM_COLOR").is_none() { cmd.env("CARGO_TERM_COLOR", "always"); @@ -538,16 +875,16 @@ fn cargo_tests(mut cmd: Command, limit: Option, shown: &mut Vec Ok(()), Ended::Exited(status) => Err(format!("exited with {status}")), - Ended::TimedOut(progress) => { + Ended::TimedOut(progress, killed) => { let listed = progress.exe.as_ref().and_then(|exe| { let exe = match &dir { Some(dir) if exe.is_relative() => dir.join(exe), _ => exe.clone(), }; - list_tests(Command::new(exe)) + list_tests(Command::new(exe), LIST_LIMIT, LIST_MAX_BYTES) }); let binary = progress.binary.clone().unwrap_or_else(|| "a test binary".to_owned()); - let (lines, error) = report(limit, &binary, &progress, listed.as_deref()); + let (lines, error) = report(limit, &binary, &progress, listed.as_ref(), &killed); shown.extend(lines); Err(format!("{error}: {binary}")) } @@ -592,10 +929,10 @@ mod tests { #[test] fn reads_libtest_and_cargo_lines() { let mut p = Progress::default(); - assert!(p.line(" Running unittests src/lib.rs (target/debug/deps/geom-1a2b)\n")); + assert_eq!(p.line(" Running unittests src/lib.rs (target/debug/deps/geom-1a2b)\n"), Event::Binary); assert_eq!(p.binary.as_deref(), Some("unittests src/lib.rs (target/debug/deps/geom-1a2b)")); assert_eq!(p.exe, Some(PathBuf::from("target/debug/deps/geom-1a2b"))); - assert!(!p.line("running 4 tests")); + assert_eq!(p.line("running 4 tests"), Event::Tests); assert_eq!(p.total, Some(4)); p.line("test a::one ... ok"); p.line("test a::two ... \u{1b}[31mFAILED\u{1b}[0m"); @@ -603,10 +940,10 @@ mod tests { p.line("test a::four has been running for over 60 seconds"); p.line("test a::four ... ok"); p.line("test result: FAILED. 2 passed; 1 failed"); - p.line("Running is not cargo's when it starts the line"); - assert_eq!(p.finished.iter().map(String::as_str).collect::>(), ["a::four", "a::one", "a::two"]); + assert_eq!(p.line("Running is not cargo's when it starts the line"), Event::Other); + assert_eq!(p.finished.iter().collect::>(), BTreeSet::from(["a::four", "a::one", "a::two"])); assert_eq!(p.running(), ["a::three"], "warned about and not finished"); - assert!(p.line("\u{1b}[1m\u{1b}[92m Doc-tests\u{1b}[0m lightcraft_geom"), "coloured, as with CARGO_TERM_COLOR=always"); + assert_eq!(p.line("\u{1b}[1m\u{1b}[92m Doc-tests\u{1b}[0m lightcraft_geom"), Event::Binary, "coloured, as with CARGO_TERM_COLOR=always"); assert_eq!(p.binary.as_deref(), Some("doctests of lightcraft_geom")); assert_eq!(p.exe, None); assert_eq!(p.total, Some(4), "the test lines stay until the new binary's own `running` line"); @@ -616,6 +953,52 @@ mod tests { assert_eq!(p.running(), ["src/lib.rs - f (line 3)"], "a single-threaded run prints the name as the test starts"); } + #[test] + fn only_libtest_results_finish_a_test_and_its_output_between_does_not() { + let mut p = Progress::default(); + p.line("running 5 tests"); + // single-threaded --nocapture: the test's output follows its name on the same line + p.line("test a::hang ... connecting to server"); + p.line("still connecting"); + p.line("test a::hang has been running for over 60 seconds"); + assert!(!p.finished.contains("a::hang")); + assert_eq!(p.running(), ["a::hang"]); + // the result on a line of its own, after the output + p.line("ok"); + assert!(p.finished.contains("a::hang") && p.running().is_empty()); + p.line("test b ... "); + p.line("log line"); + p.line("FAILED"); + p.line("test c ... ignored, needs a GPU"); + p.line("test d ... bench: 1,234 ns/iter (+/- 56)"); + p.line("test e ... ok <0.003s>"); + assert_eq!(p.finished.iter().collect::>(), ["a::hang", "b", "c", "d", "e"]); + p.line("ok"); + assert_eq!(p.finished.len(), 5, "a stray result with no test running is nobody's"); + for not_a_result in ["okay", "ok then", "FAILED to connect", "ignoredx"] { + assert!(!is_result(not_a_result), "{not_a_result}"); + } + } + + #[test] + fn what_is_kept_of_the_output_is_bounded() { + let mut names = Names::with_budget(100); + for i in 0..100 { + names.insert(&format!("test_{i:03}")); + } + assert!(names.cut && names.len() == 6, "{} names kept (16 bytes each)", names.len()); + names.insert("test_000"); + assert_eq!(names.len(), 6, "no repeats"); + let mut lines = Lines::default(); + let mut seen = Vec::new(); + let long = vec![b'x'; MAX_LINE + 10]; + lines.feed(&long, |l| seen.push(l.len())); + assert!(lines.rest().is_empty(), "an overlong line isn't kept"); + lines.feed(b"xx\nshort\npart", |l| seen.push(l.len())); + assert_eq!(seen, [6], "the overlong line is skipped to its end; `short` is read"); + assert_eq!(lines.rest(), "part"); + } + #[test] fn finds_every_descendant_in_a_process_table() { let table = " 1 0\n 10 1\n 11 10\n 12 11\n 13 10\n 20 1\n 21 20\n junk\n 14 12"; @@ -624,25 +1007,51 @@ mod tests { assert_eq!(descendants_in("5 6\n6 5", 5), [6], "a cycle ends"); } + #[test] + fn finds_marked_processes_in_ps_eww_output() { + let table = " 10 /bin/sleep 600 HOME=/h LIGHTCRAFT_XTASK_RUN_7_1=1 PATH=/bin\n 11 sh -c x LIGHTCRAFT_XTASK_RUN_7_10=1\n\ + 12 vim LIGHTCRAFT_XTASK_RUN_7_1=1\n bad LIGHTCRAFT_XTASK_RUN_7_1=1"; + assert_eq!(marked_in(table, "LIGHTCRAFT_XTASK_RUN_7_1"), [10, 12]); + } + #[test] fn the_report_names_the_binary_the_running_tests_and_the_rest() { let mut p = Progress::default(); for l in ["running 4 tests", "test a ... ok", "test b has been running for over 60 seconds"] { p.line(l); } - let listed: Vec = ["a", "b", "c", "d"].map(String::from).to_vec(); - let (lines, error) = report(MIN * 30, "geom (geom-1)", &p, Some(&listed)); + let mut names = Names::default(); + for n in ["a", "b", "c", "d"] { + names.insert(n); + } + let listed = Listed { names, cut: false }; + let (lines, error) = report(MIN * 30, "geom (geom-1)", &p, Some(&listed), "killed it"); assert_eq!(error, "timed out after 30 min (still running: b)"); let text = lines.join("\n"); - assert!(text.starts_with("timed out after 30 min: geom (geom-1); killed it"), "{text}"); + assert!(text.starts_with("timed out after 30 min: geom (geom-1)\n killed it\n"), "{text}"); assert!(text.contains("still running: b") && text.contains("no result from 2 other test(s) of 4") && text.contains(": c, d"), "{text}"); - assert!(text.contains(TEST_BINARY_TIMEOUT_ENV), "says how to change the limit: {text}"); - let (lines, _) = report(MIN, "x", &p, None); + assert!(text.contains(TEST_BINARY_TIMEOUT_ENV) && !text.contains("incomplete"), "{text}"); + let (lines, _) = report(MIN, "x", &p, None, ""); assert!(lines.join("\n").contains("1 of 4 test(s) had finished"), "without --list: {lines:?}"); - let many: Vec = (0..30).map(|i| format!("t{i}")).collect(); - let (lines, _) = report(MIN, "x", &Progress::default(), Some(&many)); + let mut names = Names::default(); + for i in 0..30 { + names.insert(&format!("t{i}")); + } + let (lines, _) = report(MIN, "x", &Progress::default(), Some(&Listed { names, cut: true }), ""); let text = lines.join("\n"); assert!(text.contains("no test was reported as running") && text.contains("t19 and 10 more") && !text.contains("t20"), "{text}"); + assert!(text.contains("may be incomplete"), "a cut list says so: {text}"); + } + + #[test] + fn loud_cargo_drops_quiet_flags_before_the_separator_and_overrides_the_config() { + let mut c = Command::new("cargo"); + c.args(["test", "-q", "--workspace", "--quiet", "--", "-q", "--quiet"]).env("CARGO_TERM_QUIET", "true").env("X", "1"); + let l = loud(&c); + assert_eq!(l.get_args().collect::>(), ["test", "--workspace", "--", "-q", "--quiet"], "the test binaries' -q stays"); + let envs: Vec<_> = l.get_envs().collect(); + assert!(envs.contains(&(std::ffi::OsStr::new("CARGO_TERM_QUIET"), Some(std::ffi::OsStr::new("false")))), "{envs:?}"); + assert!(envs.contains(&(std::ffi::OsStr::new("X"), Some(std::ffi::OsStr::new("1"))))); } /// Whether process `pid` is gone (or a zombie no one has reaped yet). @@ -673,6 +1082,13 @@ mod tests { false } + #[cfg(unix)] + fn sh(script: &str) -> Command { + let mut c = Command::new("/bin/sh"); + c.args(["-c", script]); + c + } + #[cfg(unix)] #[test] fn a_hung_binary_is_killed_with_the_processes_it_started_and_named() { @@ -686,32 +1102,81 @@ mod tests { sleep 300 & echo $! > '{}'; wait", pidfile.display() ); - let mut cmd = Command::new("/bin/sh"); - cmd.args(["-c", &script]); let t = Instant::now(); let mut shown = Vec::new(); - let err = test_binary(cmd, "fake (sh)", Some(Duration::from_secs(2)), &mut shown).unwrap_err(); + let err = test_binary(sh(&script), "fake (sh)", Some(Duration::from_secs(2)), &mut shown).unwrap_err(); assert!(t.elapsed() < Duration::from_secs(14), "the limit ended it, and --list answered: {:?}", t.elapsed()); assert_eq!(err, "timed out after 2 s (still running: b)"); let shown = shown.join("\n"); - assert!(shown.starts_with("timed out after 2 s: fake (sh); killed it"), "{shown}"); + assert!(shown.starts_with("timed out after 2 s: fake (sh)\n killed it and the 1 process(es) it started"), "{shown}"); assert!(shown.contains("no result from 1 other test(s) of 3") && shown.ends_with("(0 for none)"), "c, from --list: {shown}"); let grandchild = std::fs::read_to_string(&pidfile).unwrap(); assert!(wait_gone(grandchild.trim()), "the sleep it started was killed too"); let _ = std::fs::remove_dir_all(&dir); } + #[cfg(target_os = "linux")] + #[test] + fn a_process_that_outlived_its_parent_is_killed_too() { + let dir = scratch("orphan"); + let pidfile = dir.join("orphan.pid"); + // the subshell starts a sleep and exits: the sleep is reparented, no longer a descendant + let script = format!("case \"$0\" in --list) exit;; esac; (sleep 300 & echo $! > '{}'); sleep 300", pidfile.display()); + let mut shown = Vec::new(); + let err = test_binary(sh(&script), "fake (sh)", Some(Duration::from_secs(1)), &mut shown).unwrap_err(); + assert!(err.starts_with("timed out after 1 s"), "{err}"); + let orphan = std::fs::read_to_string(&pidfile).unwrap(); + assert!(wait_gone(orphan.trim()), "the reparented sleep was found by its marker and killed: {shown:?}"); + let killed = shown.get(1).cloned().unwrap_or_default(); + assert!(killed.contains("2 process(es)") && killed.contains("reparented ones too") && !killed.contains("still alive"), "{killed}"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[cfg(target_os = "linux")] + #[test] + fn a_binary_that_started_nothing_is_reported_as_such() { + let mut shown = Vec::new(); + let script = "case \"$0\" in --list) exit;; esac; exec sleep 300"; + assert!(test_binary(sh(script), "fake", Some(Duration::from_millis(500)), &mut shown).is_err()); + assert_eq!( + shown.get(1).map(String::as_str), + Some(" killed it; it had started no other process (looked for by the run's environment marker)") + ); + } + + #[cfg(unix)] + #[test] + fn a_list_run_that_hangs_is_bounded_and_killed() { + let dir = scratch("list"); + let pidfile = dir.join("list.pid"); + // closes its stdout, so the output is done, but never exits + let script = format!("exec >&-; sleep 300 & echo $! > '{}'; wait", pidfile.display()); + let t = Instant::now(); + assert!(list_tests(sh(&script), Duration::from_secs(1), LIST_MAX_BYTES).is_none()); + assert!(t.elapsed() < Duration::from_secs(10), "{:?}", t.elapsed()); + let pid = std::fs::read_to_string(&pidfile).unwrap(); + assert!(wait_gone(pid.trim()), "what it started was killed"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[cfg(unix)] + #[test] + fn a_list_run_is_read_only_so_far() { + let listed = list_tests(sh("i=0; while [ $i -lt 1000 ]; do echo \"t$i: test\"; i=$((i+1)); done"), MIN, 1000).unwrap(); + assert!(listed.cut && listed.names.len() > 50 && listed.names.len() < 200, "{} names", listed.names.len()); + assert_eq!(listed.names.iter().next(), Some("t0")); + let listed = list_tests(sh("echo 'a: test'; echo 'b: bench'; echo; echo '1 test, 1 benchmark'"), MIN, LIST_MAX_BYTES).unwrap(); + assert_eq!((listed.names.iter().collect::>(), listed.cut), (vec!["a"], false)); + assert!(list_tests(sh("echo 'a: test'; exit 1"), MIN, LIST_MAX_BYTES).is_none(), "a failed --list lists nothing"); + } + #[cfg(unix)] #[test] fn a_binary_that_ends_in_time_passes_or_fails_as_before() { - let sh = |script: &str| { - let mut c = Command::new("/bin/sh"); - c.args(["-c", script]); - run_test_binary(c, "fake (sh)", Some(MIN)) - }; - assert_eq!(sh("echo running 0 tests"), Ok(())); - assert_eq!(sh("exit 3"), Err("exit status: 3".to_owned())); - assert!(sh("kill -9 $$").unwrap_err().contains("SIGKILL")); + let run = |script: &str| run_test_binary(sh(script), "fake (sh)", Some(MIN)); + assert_eq!(run("echo running 0 tests"), Ok(())); + assert_eq!(run("exit 3"), Err("exit status: 3".to_owned())); + assert!(run("kill -9 $$").unwrap_err().contains("SIGKILL")); } #[cfg(unix)] @@ -721,9 +1186,7 @@ mod tests { let script = "sleep 1; \ echo ' Running unittests src/lib.rs (target/debug/deps/a-1)' >&2; echo 'running 1 test'; echo 'test x ... ok'; \ echo ' Running tests/it/main.rs (target/debug/deps/it-2)' >&2; echo 'running 0 tests'"; - let mut c = Command::new("/bin/sh"); - c.args(["-c", script]); - assert_eq!(run_cargo_tests(c, Some(Duration::from_millis(500))), Ok(())); + assert_eq!(run_cargo_tests(sh(script), Some(Duration::from_millis(500))), Ok(())); let dir = scratch("cargo"); let pidfile = dir.join("binary.pid"); @@ -732,10 +1195,8 @@ mod tests { sh -c 'echo running 2 tests; printf \"test slow ... \"; sleep 300' & echo $! > '{}'; wait", pidfile.display() ); - let mut c = Command::new("/bin/sh"); - c.args(["-c", &script]); let mut shown = Vec::new(); - let err = cargo_tests(c, Some(Duration::from_secs(2)), &mut shown).unwrap_err(); + let err = cargo_tests(sh(&script), Some(Duration::from_secs(2)), &mut shown).unwrap_err(); assert!(shown.first().is_some_and(|l| l.starts_with("timed out after 2 s: tests/it/main.rs")), "{shown:?}"); assert_eq!(err, "timed out after 2 s (still running: slow): tests/it/main.rs (target/debug/deps/it-2)"); let binary = std::fs::read_to_string(&pidfile).unwrap(); @@ -743,14 +1204,28 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[cfg(unix)] + #[test] + fn a_quiet_cargo_configuration_still_starts_the_clock() { + // a "cargo" that prints no Running line when quiet (-q or CARGO_TERM_QUIET=true), then + // starts a binary that hangs before it prints anything + let script = "quiet=; for a in \"$@\"; do [ \"$a\" = -q ] && quiet=1; done; [ \"$CARGO_TERM_QUIET\" = true ] && quiet=1; \ + [ -z \"$quiet\" ] && echo ' Running tests/it/main.rs (target/debug/deps/it-2)' >&2; sleep 300"; + let mut c = sh(script); + c.args(["cargo", "test", "-q"]).env("CARGO_TERM_QUIET", "true"); + let t = Instant::now(); + let err = cargo_tests(c, Some(Duration::from_secs(1)), &mut Vec::new()).unwrap_err(); + assert!(t.elapsed() < Duration::from_secs(10) && err.starts_with("timed out after 1 s"), "{err} after {:?}", t.elapsed()); + + // and without any Running line at all, the binary's own `running N tests` starts it + let err = cargo_tests(sh("echo 'running 1 test'; sleep 300"), Some(Duration::from_secs(1)), &mut Vec::new()).unwrap_err(); + assert_eq!(err, "timed out after 1 s: a test binary"); + } + #[cfg(unix)] #[test] fn no_limit_runs_as_before() { - let mut c = Command::new("/bin/sh"); - c.args(["-c", "exit 0"]); - assert_eq!(run_cargo_tests(c, None), Ok(())); - let mut c = Command::new("/bin/sh"); - c.args(["-c", "exit 4"]); - assert_eq!(run_test_binary(c, "fake", None), Err("exit status: 4".to_owned())); + assert_eq!(run_cargo_tests(sh("exit 0"), None), Ok(())); + assert_eq!(run_test_binary(sh("exit 4"), "fake", None), Err("exit status: 4".to_owned())); } } From 7c6902fcdf52c4f09b57f83cf56f64ee47354fef Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Mon, 26 Oct 2026 15:48:12 -0500 Subject: [PATCH 15/40] fix(xtask): #3060 signal only processes xtask started, and bound the GPU probe MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review round 2: - The macOS/BSD `ps eww` lookup matched marker text anywhere in a command line or another variable's value. It is gone: on Linux a process is marked only by the exact NUL-separated `KEY=1` entry in its /proc//environ, of a process of this user (unreadable ones are skipped); elsewhere only the process tree is signalled, and the report says that processes which outlived their parent can't be found there. - The tree is frozen level by level: a process is signalled only once its parent is stopped (so its pid can't be freed and reused meanwhile), and killed leaves first. - The marker was pid plus a counter starting at 0, so an earlier xtask's leftovers with the same pid carried it. It is now LIGHTCRAFT_XTASK_RUN___, the nonce drawn once per process from std's randomly seeded hasher, the pid and the time. - The GPU probe ran `cargo test … gpu_probe` with an unbounded output(): it now runs captured under the same watch (each test binary bounded by 5 minutes, or the test limit when shorter; stdout and stderr kept bounded), and the GPU probe and the translation gaps report are skipped once a test binary timed out in the run. - A --list run that exited left what it started running (a process holding its output): its marked processes are killed once it's done, without signalling its reaped pid. Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +- docs/architecture.md | 15 +- xtask/src/ci.rs | 39 ++- xtask/src/deadline.rs | 537 ++++++++++++++++++++++++++++++------------ 4 files changed, 426 insertions(+), 171 deletions(-) diff --git a/README.md b/README.md index 97bd226dd3b..d724f9f4735 100644 --- a/README.md +++ b/README.md @@ -421,10 +421,10 @@ gives up after `LIGHTCRAFT_CI_LOCK_WAIT` minutes (default 120; `0` waits as long names the run holding the slot. Nothing a run waits on is unbounded either: each test binary may run for `LIGHTCRAFT_TEST_BINARY_TIMEOUT` minutes (default 30, timed from cargo's `Running` line for it; `0` for no limit). One that runs longer, a test hung on a GPU device say, is killed with every -process it started (found by an environment variable they inherit, so those that outlived their -parent too), and the run reports it as `timed out after 30 min` with the tests still running +process it started (on Linux found by an environment variable they inherit, so those that outlived +their parent too), and the run reports it as `timed out after 30 min` with the tests still running and those that never reported a result. Under `LIGHTCRAFT_NEXTEST=1`, `.config/nextest.toml` kills a -test after 30 minutes instead. +test after 30 minutes instead. After a timeout, `ci` skips its GPU probe and translation gaps report. CI defaults to line-table debug information and one build job per 1.5 GB of RAM available when it starts (at most one per CPU; 4 if memory can't be read), so an diff --git a/docs/architecture.md b/docs/architecture.md index b2ee7670713..1022a48f10f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -88,11 +88,13 @@ for none): timed from its start when xtask runs it (`test::run_binary`), and fro full `ci`'s test and HEIF steps; the build before isn't bounded; cargo runs with `CARGO_TERM_QUIET=false` and without `-q` so it prints those lines). The output streams through and is read for libtest's lines, keeping a bounded amount. On timeout the binary and every process it started -are killed: each watched process gets an environment variable of its own -(`LIGHTCRAFT_XTASK_RUN__`) that its descendants inherit, so the kill also finds those that -outlived their parent (`/proc/*/environ` on Linux, `ps eww` elsewhere, plus the current process tree), -freezes them with SIGSTOP and then kills them (`taskkill /T` on Windows). The child stays in xtask's -process group, so Ctrl-C still reaches it. The run reports `timed out after N min: `, what +are killed, and no process xtask didn't start: the binary and its process tree (a process only once +its parent is frozen, so its pid can't be reused meanwhile), and on Linux every process whose +`/proc//environ` holds the run's exact marker entry (`LIGHTCRAFT_XTASK_RUN___=1`, +inherited by all it starts; the nonce is random per xtask process), which finds those that outlived +their parent. They are frozen with SIGSTOP, then killed (`taskkill /T` on Windows; elsewhere the +report says reparented ones can't be found). The child stays in xtask's process group, so Ctrl-C +still reaches it. The run reports `timed out after N min: `, what the kill found, the tests still running (libtest's "has been running for over 60 seconds" warnings, or the test a single-threaded run started) and those that never reported a result (`--list`, itself bounded in time and size). Under nextest, `.config/nextest.toml`'s `slow-timeout` kills a test @@ -109,7 +111,8 @@ explicit `RUST_TEST_THREADS=4` can't be told apart from the default, so `ci` and lower it to their RAM-aware value (never raise it). `ci` also probes the machine: OS, CPUs, RAM, the GPU adapters of each backend (from the ignored -`gpu_probe` test of `lightcraft-gpu`, run after the workspace tests so it reuses their build; xtask +`gpu_probe` test of `lightcraft-gpu`, run after the workspace tests so it reuses their build, each +test binary it starts bounded by 5 minutes, and skipped once a test binary timed out; xtask has no wgpu), the corpus and `CRAFT_FONTS_DIR`. Tests that need what is missing call `lightcraft_testkit::skip!(need, reason)`, which appends a JSON line to the file `LIGHTCRAFT_SKIP_LOG` names. The run ends with the machine and the skips by need and reason, diff --git a/xtask/src/ci.rs b/xtask/src/ci.rs index 2a9ee24187e..69b314d5ebb 100644 --- a/xtask/src/ci.rs +++ b/xtask/src/ci.rs @@ -117,6 +117,10 @@ const TRANSLATION_GAPS_TEST: &str = "i18n::tests::translation_gaps_report"; /// run from the test binary the test step built (found with `--no-run` and the step's own /// arguments, so nothing rebuilds). A report that can't run is a note, never a failed step. fn translation_gaps(limit: Option) { + if deadline::any_timed_out() { + eprintln!("\nnote: the translation gaps report is skipped: a test binary timed out in this run"); + return; + } eprintln!("\n=== ci: translation gaps ==="); let mut c = cargo(); c.args(["test", "--no-run", "--message-format=json"]).args(with_test_targets(&["--workspace"])); @@ -195,10 +199,14 @@ pub(crate) fn cmd_ci(args: &[&str]) -> Result<(), String> { // What this machine offers the GPU tests, once, after the workspace tests (whose build the // probe reuses). Never fails the run: the report says what went wrong. let probe = || { + if gpu.borrow().is_null() && deadline::any_timed_out() { + eprintln!("\nnote: the GPU probe is skipped: a test binary timed out, and what hung it would hang the probe too"); + *gpu.borrow_mut() = serde_json::json!({"error": "not probed: a test binary timed out in this run"}); + } if gpu.borrow().is_null() { eprintln!("\n=== ci: GPU probe ==="); let t = std::time::Instant::now(); - let mut found = ci_report::gpu(probe_gpu, hardware); + let mut found = ci_report::gpu(|backend| probe_gpu(backend, limit), hardware); found["seconds"] = serde_json::json!(t.elapsed().as_secs_f64()); *gpu.borrow_mut() = found; } @@ -378,22 +386,27 @@ pub(crate) fn cmd_ci(args: &[&str]) -> Result<(), String> { /// backend's adapters. `--workspace`, like the test step, so its build is reused (every crate's `it` /// binary starts; only lightcraft-gpu's has the test). Its stdout, or why /// it failed (a driver that crashes while it is enumerated, issue #136, ends up here, not in xtask). -fn probe_gpu(backend: Option<&str>) -> Result { +/// Run the GPU probe test (on `backend`, or the pipeline's choice) and return its output. Each +/// test binary it starts may run for [`deadline::probe_limit`] of the test binaries' `limit`: the +/// probe initialises the GPU, which is what hangs when a display server stops answering. Not run +/// once a test binary has timed out in this xtask run. +fn probe_gpu(backend: Option<&str>, limit: Option) -> Result { + let name = format!("gpu_probe {}", backend.map(|b| format!("{b} ")).unwrap_or_default()); + if deadline::any_timed_out() { + return Err(format!("{name}not run: a test binary timed out earlier in this run")); + } let mut c = cargo(); c.args(["test", "-q", "--workspace", "--test", "it", "--", "--ignored", "--exact", "gpu_probe::gpu_probe", "--nocapture"]); c.env("LIGHTCRAFT_GPU_PROBE", backend.unwrap_or("")); - let out = c.output().map_err(|e| format!("gpu_probe: {e}"))?; - if !out.status.success() { - let err = String::from_utf8_lossy(&out.stderr); - let tail: Vec<&str> = err.lines().rev().filter(|l| !l.trim().is_empty()).take(3).collect(); - return Err(format!( - "gpu_probe {}exited with {}: {}", - backend.map(|b| format!("{b} ")).unwrap_or_default(), - out.status, - tail.into_iter().rev().collect::>().join(" / ") - )); + let out = deadline::capture_cargo(&c, deadline::probe_limit(limit)).map_err(|e| format!("gpu_probe: {e}"))?; + match out.status { + Ok(status) if status.success() => Ok(out.stdout), + Ok(status) => { + let tail: Vec<&str> = out.stderr_tail.iter().map(String::as_str).filter(|l| !l.trim().is_empty()).rev().take(3).collect(); + Err(format!("{name}exited with {status}: {}", tail.into_iter().rev().collect::>().join(" / "))) + } + Err(timed_out) => Err(format!("{name}{timed_out}")), } - Ok(String::from_utf8_lossy(&out.stdout).into_owned()) } #[cfg(test)] diff --git a/xtask/src/deadline.rs b/xtask/src/deadline.rs index 9807a5dd1bf..39259ffe003 100644 --- a/xtask/src/deadline.rs +++ b/xtask/src/deadline.rs @@ -22,22 +22,31 @@ //! and the report names the binary, the tests still running and the tests that never reported a //! result (from `--list`, itself bounded in time and size). //! -//! Containment: every process xtask watches gets an environment variable of its own -//! ([`Marker`], `LIGHTCRAFT_XTASK_RUN__=1`) that everything it starts inherits, so on Unix -//! the kill finds them all, including those that outlived their parent and were reparented, from -//! `/proc/*/environ` on Linux or `ps eww` elsewhere, besides the binary's current descendants. They -//! are frozen with SIGSTOP until no new one turns up, then killed with SIGKILL; the report says how -//! many and names any still alive. Only a process that clears its environment escapes. On Windows -//! `taskkill /T /F` ends the process tree. The child stays in xtask's process group rather than one -//! of its own, so Ctrl-C in the terminal still reaches the test binaries as before. +//! Containment, and never a process xtask didn't start: every process xtask watches gets an +//! environment variable of its own ([`Marker`], `LIGHTCRAFT_XTASK_RUN___=1`, the +//! nonce random per xtask process so an earlier xtask with the same pid had another) that +//! everything it starts inherits. On timeout the binary (while unreaped, so its pid is its own) and +//! its process tree are frozen with SIGSTOP level by level, a process only once its parent is +//! stopped and so can't reap it and free its pid; on Linux also every process of this user whose +//! `/proc//environ` holds the exact entry, which finds those that outlived their parent. Once +//! no new one turns up they are killed with SIGKILL; the report says how many, names any still +//! alive, and says when the OS doesn't allow looking for the reparented ones (Unix other than +//! Linux: only the tree; Windows: `taskkill /T /F`). Only a process that clears its environment +//! escapes. The child stays in xtask's process group rather than one of its own, so Ctrl-C in the +//! terminal still reaches the test binaries as before. +//! +//! A timeout also turns off the optional probes after it in the same run ([`any_timed_out`]): the +//! GPU probe, which runs bounded too ([`capture_cargo`], [`probe_limit`]), and the translation +//! gaps report. use std::collections::BTreeSet; +use std::hash::{BuildHasher, Hasher}; use std::io::{IsTerminal, Read, Write}; use std::path::{Path, PathBuf}; use std::process::{Child, Command, ExitStatus, Stdio}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex, MutexGuard, PoisonError, mpsc}; -use std::time::{Duration, Instant}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, mpsc}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; /// The limit, in minutes, on each test binary's run. pub const TEST_BINARY_TIMEOUT_ENV: &str = "LIGHTCRAFT_TEST_BINARY_TIMEOUT"; @@ -374,25 +383,60 @@ pub enum Clock { } /// The environment variable that marks every process one watched run starts (see the module -/// docs): its name is unique to this xtask process and run, so nested runs keep each other's. +/// docs). Its name holds xtask's pid, a random number drawn once per xtask process and a run +/// counter, so it is this run's alone: nested runs keep each other's, and the leftovers of an +/// earlier xtask that had the same pid carry a different one. pub struct Marker { key: String, } +/// The value every marker has; a process is marked only by the exact entry `KEY=1`. +const MARK_VALUE: &str = "1"; + +/// A number drawn once per xtask process: std's randomly seeded hasher, fed the pid and the time. +fn process_nonce() -> u64 { + static NONCE: OnceLock = OnceLock::new(); + *NONCE.get_or_init(|| { + let mut h = std::collections::hash_map::RandomState::new().build_hasher(); + h.write_u32(std::process::id()); + h.write_u128(SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)); + h.finish() + }) +} + impl Marker { fn new() -> Self { static RUNS: AtomicU64 = AtomicU64::new(0); - Self { key: format!("LIGHTCRAFT_XTASK_RUN_{}_{}", std::process::id(), RUNS.fetch_add(1, Ordering::Relaxed)) } + Self::with(std::process::id(), process_nonce(), RUNS.fetch_add(1, Ordering::Relaxed)) + } + + fn with(pid: u32, nonce: u64, run: u64) -> Self { + Self { key: format!("LIGHTCRAFT_XTASK_RUN_{pid}_{nonce:016x}_{run}") } + } + + /// The exact environment entry that marks the run's processes. + #[cfg_attr(not(unix), allow(dead_code))] + fn entry(&self) -> String { + format!("{}={MARK_VALUE}", self.key) } } /// Spawn `cmd` with a fresh [`Marker`]. fn spawn_marked(cmd: &mut Command) -> std::io::Result<(Child, Marker)> { let marker = Marker::new(); - cmd.env(&marker.key, "1"); + cmd.env(&marker.key, MARK_VALUE); Ok((cmd.spawn()?, marker)) } +/// Set when a watched run runs out of time: the optional probes after it (the GPU probe, the +/// translation gaps report) are skipped, as what hung the tests would hang them too. +static TIMED_OUT: AtomicBool = AtomicBool::new(false); + +/// Whether a watched run in this xtask process ran out of time. +pub fn any_timed_out() -> bool { + TIMED_OUT.load(Ordering::Relaxed) +} + /// How a watched run ended. #[derive(Debug)] pub enum Ended { @@ -401,18 +445,47 @@ pub enum Ended { TimedOut(Box, String), } +/// Where a watched run's output goes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Output { + /// Through to xtask's stdout and stderr, as it arrives. + Stream, + /// Kept: stdout up to [`CAPTURE_MAX`] bytes, the last [`STDERR_TAIL`] lines of stderr. + Capture, +} + +/// The most stdout a captured run keeps. +const CAPTURE_MAX: usize = 1 << 20; +/// How many of the last stderr lines a captured run keeps. +const STDERR_TAIL: usize = 20; + +/// A watched run: how it ended and, when captured, its output. +#[derive(Debug)] +pub struct Watched { + pub ended: Ended, + pub stdout: String, + pub stderr_tail: Vec, +} + struct Watch { progress: Progress, /// When the current limit started, `None` while it doesn't run. since: Option, + stdout: Vec, + stderr_tail: std::collections::VecDeque, } -/// Run `cmd` with its output streamed through and read for libtest's lines, until it exits or -/// `limit` runs out (timed as `clock` says); then kill it and every process it started. -pub fn watch(mut cmd: Command, limit: Duration, clock: Clock) -> Result { +/// Run `cmd` with its output streamed through (or captured) and read for libtest's lines, until it +/// exits or `limit` runs out (timed as `clock` says); then kill it and every process it started. +pub fn watch(mut cmd: Command, limit: Duration, clock: Clock, output: Output) -> Result { cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); let (mut child, marker) = spawn_marked(&mut cmd).map_err(|e| format!("failed to start: {e}"))?; - let state = Arc::new(Mutex::new(Watch { progress: Progress::default(), since: (clock == Clock::Start).then(Instant::now) })); + let state = Arc::new(Mutex::new(Watch { + progress: Progress::default(), + since: (clock == Clock::Start).then(Instant::now), + stdout: Vec::new(), + stderr_tail: std::collections::VecDeque::new(), + })); let (done_tx, done_rx) = mpsc::channel(); let mut readers = 0; let pipes: [(Option>, bool); 2] = [ @@ -423,11 +496,11 @@ pub fn watch(mut cmd: Command, limit: Duration, clock: Clock) -> Result Result { drain(readers); - return Ok(Ended::Exited(status)); + return Ok(finish(Ended::Exited(status))); } Ok(None) => {} Err(e) => { - kill_marked(&mut child, &marker); + kill_run(Some(&mut child), &marker); return Err(format!("waiting for it failed: {e}")); } } if lock(&state).since.is_some_and(|since| since.elapsed() >= limit) { - let killed = kill_marked(&mut child, &marker); + TIMED_OUT.store(true, Ordering::Relaxed); + // not reaped yet (try_wait said it runs): its pid is still its own + let killed = kill_run(Some(&mut child), &marker); drain(readers); - return Ok(Ended::TimedOut(Box::new(lock(&state).progress.clone()), killed)); + let progress = Box::new(lock(&state).progress.clone()); + return Ok(finish(Ended::TimedOut(progress, killed))); } std::thread::sleep(TICK); } } -/// Copy `pipe` to xtask's stdout or stderr as it arrives, feeding whole lines to the progress. -fn pump(mut pipe: Box, is_stdout: bool, clock: Clock, state: &Mutex) { +/// Copy `pipe` to xtask's stdout or stderr as it arrives (or keep it, bounded), feeding whole lines +/// to the progress. +fn pump(mut pipe: Box, is_stdout: bool, clock: Clock, output: Output, state: &Mutex) { let mut buf = [0u8; 8192]; let mut lines = Lines::default(); loop { @@ -474,19 +556,33 @@ fn pump(mut pipe: Box, is_stdout: bool, clock: Clock, state: &M Err(_) => break, }; let chunk = buf.get(..n).unwrap_or_default(); - if is_stdout { - let mut out = std::io::stdout().lock(); - let _ = out.write_all(chunk).and_then(|()| out.flush()); - } else { - let mut err = std::io::stderr().lock(); - let _ = err.write_all(chunk).and_then(|()| err.flush()); - } let mut watch = lock(state); + match (output, is_stdout) { + (Output::Stream, true) => { + let mut out = std::io::stdout().lock(); + let _ = out.write_all(chunk).and_then(|()| out.flush()); + } + (Output::Stream, false) => { + let mut err = std::io::stderr().lock(); + let _ = err.write_all(chunk).and_then(|()| err.flush()); + } + (Output::Capture, true) => { + let room = CAPTURE_MAX.saturating_sub(watch.stdout.len()); + watch.stdout.extend_from_slice(chunk.get(..room.min(chunk.len())).unwrap_or_default()); + } + (Output::Capture, false) => {} + } lines.feed(chunk, |line| { let event = watch.progress.line(line); if clock == Clock::EachBinary && event != Event::Other { watch.since = Some(Instant::now()); } + if output == Output::Capture && !is_stdout { + if watch.stderr_tail.len() >= STDERR_TAIL { + watch.stderr_tail.pop_front(); + } + watch.stderr_tail.push_back(line.trim_end().to_owned()); + } }); if is_stdout { watch.progress.pending = lines.rest(); @@ -494,55 +590,82 @@ fn pump(mut pipe: Box, is_stdout: bool, clock: Clock, state: &M } } -/// Kill `child`, every process it started and every process carrying its `marker`, reap it, and -/// say what was done. -pub fn kill_marked(child: &mut Child, marker: &Marker) -> String { - let note = kill_all(child, marker); - let _ = child.kill(); - let _ = child.wait(); +/// Kill everything a run started, reap its direct child, and say what was done. +/// +/// `child` is the run's direct child while it hasn't been reaped (so its pid is still its own): +/// it and its process tree are signalled, plus every process carrying the run's `marker`. `None` +/// once it has been reaped: then only processes carrying the marker are, never the old pid, which +/// may belong to another process by now. +fn kill_run(child: Option<&mut Child>, marker: &Marker) -> String { + let root = child.as_ref().map(|c| c.id()); + let note = kill_all(root, marker); + if let Some(child) = child { + let _ = child.kill(); + let _ = child.wait(); + } note } +/// Whether this OS lets xtask find a run's processes by their marker (Linux: `/proc/*/environ`). +#[cfg_attr(not(unix), allow(dead_code))] +fn can_find_marked() -> bool { + cfg!(target_os = "linux") && Path::new("/proc/self/environ").exists() +} + +/// Freeze and kill `root` (unreaped) and what it started (see [`kill_run`]); what was done. +/// +/// Only processes xtask started are signalled. One found through the process tree is signalled only +/// once its parent is stopped: a stopped parent can't reap it, so its pid can't pass to another +/// process meanwhile. One found by its marker carries this run's exact entry, which nothing else +/// has. Everything found is frozen with SIGSTOP until no new one turns up, then killed with +/// SIGKILL, the last found first. #[cfg(unix)] -fn kill_all(child: &Child, marker: &Marker) -> String { +fn kill_all(root: Option, marker: &Marker) -> String { let me = std::process::id(); - // freeze everything found so nothing forks while the rest is collected, then kill it all - let mut seen: BTreeSet = BTreeSet::from([child.id()]); - let mut fresh: Vec = vec![child.id()]; - let mut marker_seen = true; - for _ in 0..16 { + let entry = marker.entry(); + let by_marker = can_find_marked(); + let mut order: Vec = Vec::new(); + let mut stopped: BTreeSet = BTreeSet::new(); + let mut fresh: Vec = root.into_iter().collect(); + for _ in 0..64 { signal("STOP", &fresh); - let mut found = descendants(child.id()); - match marked(&marker.key) { - Some(pids) => found.extend(pids), - None => marker_seen = false, + stopped.extend(&fresh); + order.extend(&fresh); + let mut found = children_of(&process_table(), &stopped); + if by_marker { + found.extend(marked(&entry)); } - fresh = found.into_iter().filter(|p| *p != me && !seen.contains(p)).collect::>().into_iter().collect(); - if fresh.is_empty() { + found.retain(|p| *p != me && !stopped.contains(p)); + if found.is_empty() { break; } - seen.extend(&fresh); - } - signal("KILL", &seen.iter().copied().collect::>()); - let others = seen.len().saturating_sub(1); - if !marker_seen { - return format!( - "killed it and {others} process(es) it started that were still its descendants; ones that outlived their parent \ - could not be looked for (no /proc or ps eww) and may still run" - ); + fresh = found.into_iter().collect(); + } + signal("KILL", &order.iter().rev().copied().collect::>()); + let started = order.len().saturating_sub(usize::from(root.is_some())); + if !by_marker { + return match root { + Some(_) => format!( + "killed it and the {started} process(es) it started that were still its descendants; on this OS processes that \ + outlived their parent can't be found, and may still run" + ), + None => "on this OS the processes it started that outlived it can't be found, and may still run".to_owned(), + }; } - // a killed process leaves the list once its parent (or init) reaps it + // a killed process loses its environment as it dies, before it is reaped let until = Instant::now() + Duration::from_secs(2); - let mut alive = marked(&marker.key).unwrap_or_default(); + let mut alive = marked(&entry); while !alive.is_empty() && Instant::now() < until { std::thread::sleep(TICK); - alive = marked(&marker.key).unwrap_or_default(); - } - alive.retain(|p| *p != me && *p != child.id()); - let mut note = if others == 0 { - "killed it; it had started no other process (looked for by the run's environment marker)".to_owned() - } else { - format!("killed it and the {others} process(es) it started (found by the run's environment marker, reparented ones too)") + alive = marked(&entry); + } + let mut note = match (root, started) { + (Some(_), 0) => "killed it; it had started no other process (looked for in its process tree and by the run's environment marker)".to_owned(), + (Some(_), n) => format!( + "killed it and the {n} process(es) it started (found in its process tree and by the run's environment marker, so reparented ones too)" + ), + (None, 0) => "no process it started was left (looked for by the run's environment marker)".to_owned(), + (None, n) => format!("killed the {n} process(es) it started that outlived it (found by the run's environment marker)"), }; if !alive.is_empty() { let pids: Vec = alive.iter().map(u32::to_string).collect(); @@ -552,13 +675,16 @@ fn kill_all(child: &Child, marker: &Marker) -> String { } #[cfg(windows)] -fn kill_all(child: &Child, _marker: &Marker) -> String { - let _ = Command::new("taskkill").args(["/PID", &child.id().to_string(), "/T", "/F"]).stdout(Stdio::null()).stderr(Stdio::null()).status(); +fn kill_all(root: Option, _marker: &Marker) -> String { + let Some(root) = root else { + return "on this OS the processes it started that outlived it can't be found, and may still run".to_owned(); + }; + let _ = Command::new("taskkill").args(["/PID", &root.to_string(), "/T", "/F"]).stdout(Stdio::null()).stderr(Stdio::null()).status(); "killed it and its process tree (taskkill /T); processes that outlived their parent may still run".to_owned() } #[cfg(not(any(unix, windows)))] -fn kill_all(_child: &Child, _marker: &Marker) -> String { +fn kill_all(_root: Option, _marker: &Marker) -> String { "killed it; processes it started may still run".to_owned() } @@ -570,68 +696,58 @@ fn signal(name: &str, pids: &[u32]) { let _ = Command::new("kill").arg(format!("-{name}")).args(pids.iter().map(u32::to_string)).stdout(Stdio::null()).stderr(Stdio::null()).status(); } -/// The processes descended from `root`, from `ps`'s pid / parent pid table (empty if `ps` fails). +/// Every process's pid and parent pid, from `ps` (empty if it fails). #[cfg(unix)] -fn descendants(root: u32) -> Vec { +fn process_table() -> Vec<(u32, u32)> { let Ok(out) = Command::new("ps").args(["-A", "-o", "pid=", "-o", "ppid="]).stderr(Stdio::null()).output() else { return Vec::new(); }; - descendants_in(&String::from_utf8_lossy(&out.stdout), root) + parse_process_table(&String::from_utf8_lossy(&out.stdout)) } -/// The descendants of `root` in a `pid ppid` table, one process per line. +/// The `pid ppid` pairs of a process table, one process per line. #[cfg_attr(not(unix), allow(dead_code))] -fn descendants_in(table: &str, root: u32) -> Vec { - let pairs: Vec<(u32, u32)> = table +fn parse_process_table(table: &str) -> Vec<(u32, u32)> { + table .lines() .filter_map(|l| { let mut w = l.split_whitespace(); Some((w.next()?.parse().ok()?, w.next()?.parse().ok()?)) }) - .collect(); - let mut found: BTreeSet = BTreeSet::new(); - let mut frontier = vec![root]; - while let Some(parent) = frontier.pop() { - for (pid, _) in pairs.iter().filter(|(pid, ppid)| *ppid == parent && *pid != root) { - if found.insert(*pid) { - frontier.push(*pid); - } - } - } - found.into_iter().collect() + .collect() } -/// The processes whose environment holds `key` (this user's; zombies have none), or `None` when -/// they can't be looked for. -#[cfg(unix)] -fn marked(key: &str) -> Option> { - let entry = format!("{key}="); - if let Ok(dir) = std::fs::read_dir("/proc") - && Path::new("/proc/self/environ").exists() - { - let pids = dir - .filter_map(Result::ok) - .filter_map(|e| e.file_name().to_str()?.parse::().ok()) - .filter(|pid| { - // another user's process can't be read: it isn't ours - std::fs::read(format!("/proc/{pid}/environ")).is_ok_and(|env| env.split(|b| *b == 0).any(|var| var.starts_with(entry.as_bytes()))) - }) - .collect(); - return Some(pids); - } - // macOS, BSD: `ps eww` appends each process's environment to its command line - let out = Command::new("ps").args(["eww", "-A", "-o", "pid=", "-o", "command="]).stderr(Stdio::null()).output().ok()?; - if !out.status.success() { - return None; - } - Some(marked_in(&String::from_utf8_lossy(&out.stdout), key)) +/// The direct children of `parents` in a process table. +#[cfg_attr(not(unix), allow(dead_code))] +fn children_of(table: &[(u32, u32)], parents: &BTreeSet) -> BTreeSet { + table.iter().filter(|(pid, ppid)| parents.contains(ppid) && !parents.contains(pid)).map(|(pid, _)| *pid).collect() } -/// The pids in `ps eww -o pid= -o command=` output whose environment holds `key`. -#[cfg_attr(not(unix), allow(dead_code))] -fn marked_in(table: &str, key: &str) -> Vec { - let entry = format!(" {key}="); - table.lines().filter(|l| l.contains(&entry)).filter_map(|l| l.split_whitespace().next()?.parse().ok()).collect() +/// Whether a NUL-separated environment block holds exactly `entry` (`KEY=VALUE`), not as part of +/// another variable's name or value. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn has_entry(environ: &[u8], entry: &str) -> bool { + environ.split(|b| *b == 0).any(|var| var == entry.as_bytes()) +} + +/// This user's processes whose environment holds exactly `entry` (`/proc//environ`; a +/// process that can't be read is skipped, and zombies have no environment). +#[cfg(target_os = "linux")] +fn marked(entry: &str) -> Vec { + use std::os::unix::fs::MetadataExt; + let (Ok(me), Ok(dir)) = (std::fs::metadata("/proc/self"), std::fs::read_dir("/proc")) else { + return Vec::new(); + }; + dir.filter_map(Result::ok) + .filter_map(|e| e.file_name().to_str()?.parse::().ok()) + .filter(|pid| std::fs::metadata(format!("/proc/{pid}")).is_ok_and(|m| m.uid() == me.uid())) + .filter(|pid| std::fs::read(format!("/proc/{pid}/environ")).is_ok_and(|env| has_entry(&env, entry))) + .collect() +} + +#[cfg(all(unix, not(target_os = "linux")))] +fn marked(_entry: &str) -> Vec { + Vec::new() } /// A copy of `cmd`: its program, arguments, directory and environment changes. @@ -659,14 +775,16 @@ pub struct Listed { } /// The tests a test binary would run, from `c` (the binary with its arguments) plus `--list`; -/// `None` when that fails or takes over `limit` from start to exit (then it is killed, with what -/// it started). At most `max_bytes` of its output are read. -fn list_tests(mut c: Command, limit: Duration, max_bytes: usize) -> Option { +/// `None` when that fails or takes over `limit` from start to exit. At most `max_bytes` of its +/// output are read. Whatever it started is killed when it is done, early or not, including +/// processes that outlived it and hold its output open. +fn list_tests(c: Command, limit: Duration, max_bytes: usize) -> Option { + let mut c = c; c.arg("--list").stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()); let until = Instant::now() + limit; let (mut child, marker) = spawn_marked(&mut c).ok()?; let Some(mut stdout) = child.stdout.take() else { - kill_marked(&mut child, &marker); + kill_run(Some(&mut child), &marker); return None; }; let (tx, rx) = mpsc::channel(); @@ -697,44 +815,42 @@ fn list_tests(mut c: Command, limit: Duration, max_bytes: usize) -> Option status = s, - Err(_) => break, + Err(_) => break None, } } if listed.is_none() { match rx.try_recv() { Ok(l) => listed = Some(l), Err(mpsc::TryRecvError::Empty) => {} - Err(mpsc::TryRecvError::Disconnected) => break, + Err(mpsc::TryRecvError::Disconnected) => break None, } } match (status, listed.as_ref()) { // read as much as it may: whatever more it writes (or how the cut pipe ends it) doesn't matter - (status, Some(l)) if l.cut => { - if status.is_none() { - kill_marked(&mut child, &marker); - } - return listed; - } - (Some(s), Some(_)) => return listed.filter(|_| s.success()), + (_, Some(l)) if l.cut => break listed, + (Some(s), Some(_)) => break listed.filter(|_| s.success()), _ => {} } if Instant::now() >= until { - break; + break None; } std::thread::sleep(TICK); - } + }; + // its pid is signalled only while it is unreaped; after that, only the marked processes if status.is_none() { - kill_marked(&mut child, &marker); + kill_run(Some(&mut child), &marker); + } else { + kill_run(None, &marker); } - None + result } /// What to tell about a test binary that ran out of `limit`: the lines to print and the one-line @@ -811,7 +927,7 @@ fn test_binary(mut cmd: Command, label: &str, limit: Option, shown: &m if std::io::stdout().is_terminal() && !sets_color(&cmd) { cmd.args(["--color", "always"]); } - match watch(cmd, limit, Clock::Start)? { + match watch(cmd, limit, Clock::Start, Output::Stream)?.ended { Ended::Exited(status) if status.success() => Ok(()), Ended::Exited(status) => Err(crate::test::describe(status)), Ended::TimedOut(progress, killed) => { @@ -872,7 +988,7 @@ fn cargo_tests(cmd: Command, limit: Option, shown: &mut Vec) - cmd.env("CARGO_TERM_COLOR", "always"); } let dir = cmd.get_current_dir().map(Path::to_path_buf); - match watch(cmd, limit, Clock::EachBinary)? { + match watch(cmd, limit, Clock::EachBinary, Output::Stream)?.ended { Ended::Exited(status) if status.success() => Ok(()), Ended::Exited(status) => Err(format!("exited with {status}")), Ended::TimedOut(progress, killed) => { @@ -891,6 +1007,37 @@ fn cargo_tests(cmd: Command, limit: Option, shown: &mut Vec) - } } +/// The longest a probe of the machine (the GPU probe) may run, per test binary it starts. +const PROBE_LIMIT: Duration = Duration::from_secs(5 * 60); + +/// The limit of a probe: [`PROBE_LIMIT`], or the test binaries' limit when that is shorter. A +/// probe is optional, so it keeps its own limit when the tests have none. +pub fn probe_limit(test_limit: Option) -> Duration { + test_limit.map_or(PROBE_LIMIT, |l| l.min(PROBE_LIMIT)) +} + +/// A captured cargo run: how it ended (`Err`: out of time, and what was killed) and its output. +#[derive(Debug)] +pub struct Captured { + pub status: Result, + pub stdout: String, + pub stderr_tail: Vec, +} + +/// Run `cmd`, a cargo command that runs test binaries, with its output kept rather than shown +/// ([`Output::Capture`]) and each test binary it starts under `limit`, as [`run_cargo_tests`] does. +pub fn capture_cargo(cmd: &Command, limit: Duration) -> Result { + let watched = watch(loud(cmd), limit, Clock::EachBinary, Output::Capture)?; + let status = match watched.ended { + Ended::Exited(status) => Ok(status), + Ended::TimedOut(progress, killed) => { + let binary = progress.binary.clone().unwrap_or_else(|| "a test binary".to_owned()); + Err(format!("timed out after {}: {binary} ({killed})", show(limit))) + } + }; + Ok(Captured { status, stdout: watched.stdout, stderr_tail: watched.stderr_tail }) +} + #[cfg(test)] mod tests { use super::*; @@ -1000,18 +1147,65 @@ mod tests { } #[test] - fn finds_every_descendant_in_a_process_table() { - let table = " 1 0\n 10 1\n 11 10\n 12 11\n 13 10\n 20 1\n 21 20\n junk\n 14 12"; - assert_eq!(descendants_in(table, 10), [11, 12, 13, 14]); - assert!(descendants_in(table, 99).is_empty()); - assert_eq!(descendants_in("5 6\n6 5", 5), [6], "a cycle ends"); + fn finds_the_children_of_stopped_processes_in_a_process_table() { + let table = parse_process_table(" 1 0\n 10 1\n 11 10\n 12 11\n 13 10\n 20 1\n 21 20\n junk\n 14 12"); + assert_eq!(table.len(), 8); + assert_eq!(children_of(&table, &BTreeSet::from([10])), BTreeSet::from([11, 13]), "only direct children: their parent is stopped"); + assert_eq!(children_of(&table, &BTreeSet::from([10, 11, 13])), BTreeSet::from([12])); + assert!(children_of(&table, &BTreeSet::from([99])).is_empty()); + assert!(children_of(&parse_process_table("5 6\n6 5"), &BTreeSet::from([5, 6])).is_empty(), "a cycle ends"); } #[test] - fn finds_marked_processes_in_ps_eww_output() { - let table = " 10 /bin/sleep 600 HOME=/h LIGHTCRAFT_XTASK_RUN_7_1=1 PATH=/bin\n 11 sh -c x LIGHTCRAFT_XTASK_RUN_7_10=1\n\ - 12 vim LIGHTCRAFT_XTASK_RUN_7_1=1\n bad LIGHTCRAFT_XTASK_RUN_7_1=1"; - assert_eq!(marked_in(table, "LIGHTCRAFT_XTASK_RUN_7_1"), [10, 12]); + fn a_marker_is_an_exact_environment_entry_of_this_process_and_run() { + let m = Marker::with(42, 0xabc, 3); + assert_eq!(m.entry(), "LIGHTCRAFT_XTASK_RUN_42_0000000000000abc_3=1"); + let env = |vars: &[&str]| vars.join("\0").into_bytes(); + assert!(has_entry(&env(&["HOME=/h", &m.entry(), "PATH=/bin"]), &m.entry())); + assert!(!has_entry(&env(&[&format!("OTHER={}", m.entry())]), &m.entry()), "another variable's value"); + assert!(!has_entry(&env(&[&format!("X{}", m.entry())]), &m.entry()), "another variable's name"); + assert!(!has_entry(&env(&[&format!("{}0", m.entry())]), &m.entry()), "another value"); + assert!(!has_entry(&env(&[&Marker::with(42, 0xabd, 3).entry()]), &m.entry()), "the same pid and run of another xtask"); + let (a, b) = (Marker::new(), Marker::new()); + assert_ne!(a.entry(), b.entry(), "each run its own"); + assert!(a.key.starts_with(&format!("LIGHTCRAFT_XTASK_RUN_{}_{:016x}_", std::process::id(), process_nonce()))); + } + + /// Only a process carrying the exact entry is found: not one with the text in an argument, in + /// another variable, or with an earlier xtask's marker of the same pid. + #[cfg(target_os = "linux")] + #[test] + fn only_processes_with_the_exact_marker_are_found() { + let marker = Marker::new(); + let stale = Marker::with(std::process::id(), process_nonce() ^ 1, 0); + let spawn = |args: &[&str], env: Option<(&str, &str)>| { + let mut c = Command::new("/bin/sh"); + // `read` is a builtin: the shell itself waits, with these arguments and environment + c.args(["-c", "read x"]).args(args).stdin(Stdio::piped()).stdout(Stdio::null()); + if let Some((k, v)) = env { + c.env(k, v); + } + c.spawn().unwrap() + }; + let mut ours = spawn(&[], Some((&marker.key, MARK_VALUE))); + let other_value = format!("x {}", marker.entry()); + let mut decoys = [ + spawn(&["sh", &marker.entry()], None), + spawn(&[], Some(("OTHER", &other_value))), + spawn(&[], Some((&stale.key, MARK_VALUE))), + spawn(&[], Some((&marker.key, "2"))), + ]; + let until = Instant::now() + Duration::from_secs(10); + while marked(&marker.entry()).is_empty() && Instant::now() < until { + std::thread::sleep(TICK); + } + // give the decoys time to start too, then look again + std::thread::sleep(Duration::from_millis(300)); + assert_eq!(marked(&marker.entry()), [ours.id()]); + for c in decoys.iter_mut().chain([&mut ours]) { + let _ = c.kill(); + let _ = c.wait(); + } } #[test] @@ -1140,7 +1334,7 @@ mod tests { assert!(test_binary(sh(script), "fake", Some(Duration::from_millis(500)), &mut shown).is_err()); assert_eq!( shown.get(1).map(String::as_str), - Some(" killed it; it had started no other process (looked for by the run's environment marker)") + Some(" killed it; it had started no other process (looked for in its process tree and by the run's environment marker)") ); } @@ -1159,6 +1353,51 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// A `--list` run that exits but leaves a process holding its output: past the deadline that + /// process is killed by its marker (the exited run's own pid is not signalled). + #[cfg(target_os = "linux")] + #[test] + fn what_an_exited_list_run_left_behind_is_killed() { + let dir = scratch("list-left"); + let (hung, cut) = (dir.join("hung.pid"), dir.join("cut.pid")); + let script = format!("sleep 300 & echo $! > '{}'; exit 0", hung.display()); + let t = Instant::now(); + assert!(list_tests(sh(&script), Duration::from_secs(1), LIST_MAX_BYTES).is_none(), "its output never ended"); + assert!(t.elapsed() < Duration::from_secs(10), "{:?}", t.elapsed()); + let pid = std::fs::read_to_string(&hung).unwrap(); + assert!(wait_gone(pid.trim()), "the sleep holding its output was killed"); + // the same when the output is cut short + let script = + format!("sleep 300 & echo $! > '{}'; i=0; while [ $i -lt 1000 ]; do echo \"t$i: test\"; i=$((i+1)); done; exit 0", cut.display()); + assert!(list_tests(sh(&script), MIN, 1000).is_some_and(|l| l.cut)); + let pid = std::fs::read_to_string(&cut).unwrap(); + assert!(wait_gone(pid.trim()), "the sleep of a cut list was killed"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[cfg(unix)] + #[test] + fn a_captured_cargo_run_is_bounded_and_keeps_its_output() { + let ok = capture_cargo(&sh("echo 'gpu_probe: {}'; echo warn >&2; echo last >&2"), MIN).unwrap(); + assert!(ok.status.as_ref().is_ok_and(ExitStatus::success)); + assert_eq!((ok.stdout.as_str(), ok.stderr_tail.as_slice()), ("gpu_probe: {}\n", ["warn".to_owned(), "last".to_owned()].as_slice())); + // a probe whose GPU never answers: the binary cargo started hangs + let script = "echo ' Running tests/it/main.rs (target/debug/deps/it-2)' >&2; i=0; \ + while [ $i -lt 30 ]; do echo \"line $i\" >&2; i=$((i+1)); done; head -c 3000000 /dev/zero; sleep 300"; + let t = Instant::now(); + let hung = capture_cargo(&sh(script), Duration::from_secs(1)).unwrap(); + assert!(t.elapsed() < Duration::from_secs(10), "{:?}", t.elapsed()); + let err = hung.status.unwrap_err(); + assert!(err.starts_with("timed out after 1 s: tests/it/main.rs (target/debug/deps/it-2) (killed it"), "{err}"); + assert_eq!(hung.stdout.len(), CAPTURE_MAX, "stdout is kept up to its cap"); + assert_eq!(hung.stderr_tail.len(), STDERR_TAIL); + assert_eq!(hung.stderr_tail.last().map(String::as_str), Some("line 29")); + assert!(any_timed_out(), "the optional probes after it are skipped"); + assert_eq!(probe_limit(None), PROBE_LIMIT); + assert_eq!(probe_limit(Some(MIN)), MIN); + assert_eq!(probe_limit(Some(MIN * 60)), PROBE_LIMIT); + } + #[cfg(unix)] #[test] fn a_list_run_is_read_only_so_far() { From 9c4e9d4beba2e8ef30929e17c2cc9c6a0f028de5 Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Tue, 3 Nov 2026 00:05:59 -0600 Subject: [PATCH 16/40] docs: #3060 the build isn't timed, only what a run waits on after it Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +++--- docs/architecture.md | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index d724f9f4735..7626744c747 100644 --- a/README.md +++ b/README.md @@ -418,9 +418,9 @@ config tests everything. GitHub runs the full `cargo xtask ci` on every pull req worktree say, waits for the first and names it, since several at once take longer in total than in turn. `LIGHTCRAFT_CI_SLOTS=2` allows two; `LIGHTCRAFT_CI_LOCK=off` skips the lock. The wait gives up after `LIGHTCRAFT_CI_LOCK_WAIT` minutes (default 120; `0` waits as long as it takes) and -names the run holding the slot. Nothing a run waits on is unbounded either: each test binary may run -for `LIGHTCRAFT_TEST_BINARY_TIMEOUT` minutes (default 30, timed from cargo's `Running` line for it; -`0` for no limit). One that runs longer, a test hung on a GPU device say, is killed with every +names the run holding the slot. The build isn't timed (a first build can rightly take long), but the +test binaries are: each may run for `LIGHTCRAFT_TEST_BINARY_TIMEOUT` minutes (default 30, timed from +cargo's `Running` line for it; `0` for no limit). One that runs longer, a test hung on a GPU device say, is killed with every process it started (on Linux found by an environment variable they inherit, so those that outlived their parent too), and the run reports it as `timed out after 30 min` with the tests still running and those that never reported a result. Under `LIGHTCRAFT_NEXTEST=1`, `.config/nextest.toml` kills a diff --git a/docs/architecture.md b/docs/architecture.md index 1022a48f10f..874d5ea420c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -81,8 +81,8 @@ runs each test binary, or the `-p` packages' binaries, itself (`test::run_binary uses too); `--keep-going` runs every binary and names each that failed instead of stopping at the first. -Nothing these runs wait on is unbounded (`xtask/src/deadline.rs`, #3060). Stable libtest has no -per-test timeout, so each test binary gets `LIGHTCRAFT_TEST_BINARY_TIMEOUT` minutes (default 30; `0` +What these runs wait on after the build is bounded (`xtask/src/deadline.rs`, #3060). Stable libtest +has no per-test timeout, so each test binary gets `LIGHTCRAFT_TEST_BINARY_TIMEOUT` minutes (default 30; `0` for none): timed from its start when xtask runs it (`test::run_binary`), and from cargo's `Running` / `Doc-tests` line for it, and again from its own `running N tests` line, when `cargo test` runs it (the full `ci`'s test and HEIF steps; the build before isn't bounded; cargo runs with From f37fccb2ee98c6bfcf2145f72ab958dab90df68a Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Tue, 3 Nov 2026 00:36:17 -0600 Subject: [PATCH 17/40] docs: #3060 a reparented process that cleared its environment isn't found on timeout Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +++--- docs/architecture.md | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 7626744c747..1fcece34590 100644 --- a/README.md +++ b/README.md @@ -420,9 +420,9 @@ turn. `LIGHTCRAFT_CI_SLOTS=2` allows two; `LIGHTCRAFT_CI_LOCK=off` skips the loc gives up after `LIGHTCRAFT_CI_LOCK_WAIT` minutes (default 120; `0` waits as long as it takes) and names the run holding the slot. The build isn't timed (a first build can rightly take long), but the test binaries are: each may run for `LIGHTCRAFT_TEST_BINARY_TIMEOUT` minutes (default 30, timed from -cargo's `Running` line for it; `0` for no limit). One that runs longer, a test hung on a GPU device say, is killed with every -process it started (on Linux found by an environment variable they inherit, so those that outlived -their parent too), and the run reports it as `timed out after 30 min` with the tests still running +cargo's `Running` line for it; `0` for no limit). One that runs longer, a test hung on a GPU device say, is killed with the +processes it started (on Linux found by an environment variable they inherit, so those that outlived +their parent too, unless they cleared their environment), and the run reports it as `timed out after 30 min` with the tests still running and those that never reported a result. Under `LIGHTCRAFT_NEXTEST=1`, `.config/nextest.toml` kills a test after 30 minutes instead. After a timeout, `ci` skips its GPU probe and translation gaps report. diff --git a/docs/architecture.md b/docs/architecture.md index 874d5ea420c..1f8bae37d7c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -87,12 +87,12 @@ for none): timed from its start when xtask runs it (`test::run_binary`), and fro `Doc-tests` line for it, and again from its own `running N tests` line, when `cargo test` runs it (the full `ci`'s test and HEIF steps; the build before isn't bounded; cargo runs with `CARGO_TERM_QUIET=false` and without `-q` so it prints those lines). The output streams through and is -read for libtest's lines, keeping a bounded amount. On timeout the binary and every process it started -are killed, and no process xtask didn't start: the binary and its process tree (a process only once +read for libtest's lines, keeping a bounded amount. On timeout the binary and the processes it started +that xtask can find are killed, and no process xtask didn't start: the binary and its process tree (a process only once its parent is frozen, so its pid can't be reused meanwhile), and on Linux every process whose `/proc//environ` holds the run's exact marker entry (`LIGHTCRAFT_XTASK_RUN___=1`, inherited by all it starts; the nonce is random per xtask process), which finds those that outlived -their parent. They are frozen with SIGSTOP, then killed (`taskkill /T` on Windows; elsewhere the +their parent (one that also cleared its environment isn't found and may keep running). They are frozen with SIGSTOP, then killed (`taskkill /T` on Windows; elsewhere the report says reparented ones can't be found). The child stays in xtask's process group, so Ctrl-C still reaches it. The run reports `timed out after N min: `, what the kill found, the tests still running (libtest's "has been running for over 60 seconds" warnings, From b7180d2f3c0025dd147d72973e402a0b8fdb84ba Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Tue, 3 Nov 2026 13:44:07 -0600 Subject: [PATCH 18/40] fix(xtask): #3060 signal a timed-out run's processes through pidfds, and leave none stopped Two kill-path problems from the third review of #3099: - A bare pid could be reused before it was signalled: a marked orphan read from /proc could exit and be reaped (and its pid reused) before the SIGSTOP, and a stopped parent doesn't stop the kernel reaping its children when it ignores SIGCHLD. On Linux each process is now held by a pidfd opened before what makes it ours (a stopped parent, or the run's marker) is read again, and every signal goes through it, so a pid that passed to another process gets nothing. Elsewhere on Unix a process is still signalled by pid only once its parent is stopped. - A failed SIGKILL could leave descendants stopped: signal() dropped the kill command's spawn error and exit status. Signals are now syscalls (rustix, already in the lock) with their result per process; a failed SIGKILL is retried once, then the process is sent SIGCONT so it isn't left frozen, and the report names it. The direct child's wait after the kill is bounded. The kill code moves to xtask/src/deadline/kill.rs behind a small Os trait so tests can inject a reused pid and a refused SIGKILL; both tests fail with the fix disabled. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + docs/architecture.md | 14 +- xtask/Cargo.toml | 6 + xtask/src/deadline.rs | 192 ++--------- xtask/src/deadline/kill.rs | 642 +++++++++++++++++++++++++++++++++++++ xtask/src/main.rs | 2 +- 6 files changed, 682 insertions(+), 175 deletions(-) create mode 100644 xtask/src/deadline/kill.rs diff --git a/Cargo.lock b/Cargo.lock index a715ac36cb4..84497d38e03 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7930,6 +7930,7 @@ version = "0.21.1" dependencies = [ "brotli", "flate2", + "rustix 1.1.5", "serde_json", "sha2", ] diff --git a/docs/architecture.md b/docs/architecture.md index 1f8bae37d7c..00416684a10 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -88,12 +88,15 @@ for none): timed from its start when xtask runs it (`test::run_binary`), and fro full `ci`'s test and HEIF steps; the build before isn't bounded; cargo runs with `CARGO_TERM_QUIET=false` and without `-q` so it prints those lines). The output streams through and is read for libtest's lines, keeping a bounded amount. On timeout the binary and the processes it started -that xtask can find are killed, and no process xtask didn't start: the binary and its process tree (a process only once -its parent is frozen, so its pid can't be reused meanwhile), and on Linux every process whose -`/proc//environ` holds the run's exact marker entry (`LIGHTCRAFT_XTASK_RUN___=1`, +that xtask can find are killed, and no process xtask didn't start: the binary and its process tree, and on Linux every +process whose `/proc//environ` holds the run's exact marker entry (`LIGHTCRAFT_XTASK_RUN___=1`, inherited by all it starts; the nonce is random per xtask process), which finds those that outlived -their parent (one that also cleared its environment isn't found and may keep running). They are frozen with SIGSTOP, then killed (`taskkill /T` on Windows; elsewhere the -report says reparented ones can't be found). The child stays in xtask's process group, so Ctrl-C +their parent (one that also cleared its environment isn't found and may keep running). On Linux each +is held by a pidfd and signalled only through it, so a pid reused meanwhile is never signalled; +elsewhere on Unix a process is signalled only once its parent is frozen and can't reap it. They are +frozen with SIGSTOP, then killed; one whose SIGKILL fails twice is continued with SIGCONT rather than +left stopped, and the report names it (`taskkill /T` on Windows; elsewhere the report says +reparented ones can't be found). The child stays in xtask's process group, so Ctrl-C still reaches it. The run reports `timed out after N min: `, what the kill found, the tests still running (libtest's "has been running for over 60 seconds" warnings, or the test a single-threaded run started) and those that never reported a result (`--list`, itself @@ -125,6 +128,7 @@ the `lightcraft-gpu` tests once per backend with a hardware adapter (`LIGHTCRAFT | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | Quality gates: a timed-out test run's processes are signalled through pidfds on Linux (never a reused pid), and one that can't be killed is continued rather than left stopped | | 2026-10-26 | minor | Quality gates: each test binary's run (`LIGHTCRAFT_TEST_BINARY_TIMEOUT`) and the wait for the CI slot (`LIGHTCRAFT_CI_LOCK_WAIT`) have a time limit | | 2026-10-26 | minor | Quality gates: plain `cargo test` (and `cargo nextest run`) runs at most 4 tests at once; xtask tells that default from a caller's `RUST_TEST_THREADS` | | 2026-10-26 | minor | Quality gates: `cargo xtask test` runs the tests with `ci`'s caps and slot, and can keep going past a failing binary | diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index c68c7dca25f..f49b0397d2e 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -15,3 +15,9 @@ sha2 = { workspace = true } # precompressed web bundle (`cargo xtask web`); pure Rust flate2 = "1" brotli = { version = "9", default-features = false, features = ["std"] } + +# ending a timed-out test run (deadline/kill.rs): signals through pidfds on Linux, so a pid that +# passed to another process is never signalled, and kill(2) with its error elsewhere; no unsafe +# here, pure Rust on Linux (already in the lock through tempfile and wayland) +[target.'cfg(unix)'.dependencies] +rustix = { version = "1", default-features = false, features = ["std", "process", "event"] } diff --git a/xtask/src/deadline.rs b/xtask/src/deadline.rs index 39259ffe003..f0759829164 100644 --- a/xtask/src/deadline.rs +++ b/xtask/src/deadline.rs @@ -25,15 +25,19 @@ //! Containment, and never a process xtask didn't start: every process xtask watches gets an //! environment variable of its own ([`Marker`], `LIGHTCRAFT_XTASK_RUN___=1`, the //! nonce random per xtask process so an earlier xtask with the same pid had another) that -//! everything it starts inherits. On timeout the binary (while unreaped, so its pid is its own) and -//! its process tree are frozen with SIGSTOP level by level, a process only once its parent is -//! stopped and so can't reap it and free its pid; on Linux also every process of this user whose -//! `/proc//environ` holds the exact entry, which finds those that outlived their parent. Once -//! no new one turns up they are killed with SIGKILL; the report says how many, names any still -//! alive, and says when the OS doesn't allow looking for the reparented ones (Unix other than -//! Linux: only the tree; Windows: `taskkill /T /F`). Only a process that clears its environment -//! escapes. The child stays in xtask's process group rather than one of its own, so Ctrl-C in the -//! terminal still reaches the test binaries as before. +//! everything it starts inherits. On timeout ([`kill`]) the binary (while unreaped, so its pid is +//! its own) and its process tree are frozen with SIGSTOP level by level; on Linux also every +//! process of this user whose `/proc//environ` holds the exact entry, which finds those that +//! outlived their parent. On Linux each one is held by a pidfd, opened before what makes it ours is +//! read again, and signalled only through it, so a pid that passed to another process in between +//! is never signalled; elsewhere on Unix a process is signalled by its pid only once its parent is +//! stopped and can't reap it. Once no new one turns up they are killed with SIGKILL; one it fails +//! for is tried again and then continued with SIGCONT rather than left stopped, and the report says +//! how many were killed and names any that failed or are still alive. It also says when the OS +//! doesn't allow looking for the reparented ones (Unix other than Linux: only the tree; Windows: +//! `taskkill /T /F`). Only a process that clears its environment and leaves the tree escapes. The +//! child stays in xtask's process group rather than one of its own, so Ctrl-C in the terminal +//! still reaches the test binaries as before. //! //! A timeout also turns off the optional probes after it in the same run ([`any_timed_out`]): the //! GPU probe, which runs bounded too ([`capture_cargo`], [`probe_limit`]), and the translation @@ -48,6 +52,9 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, mpsc}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; +mod kill; +use kill::kill_run; + /// The limit, in minutes, on each test binary's run. pub const TEST_BINARY_TIMEOUT_ENV: &str = "LIGHTCRAFT_TEST_BINARY_TIMEOUT"; /// The default of [`TEST_BINARY_TIMEOUT_ENV`]: the slowest binary, the ui-egui library tests, takes @@ -590,139 +597,6 @@ fn pump(mut pipe: Box, is_stdout: bool, clock: Clock, output: O } } -/// Kill everything a run started, reap its direct child, and say what was done. -/// -/// `child` is the run's direct child while it hasn't been reaped (so its pid is still its own): -/// it and its process tree are signalled, plus every process carrying the run's `marker`. `None` -/// once it has been reaped: then only processes carrying the marker are, never the old pid, which -/// may belong to another process by now. -fn kill_run(child: Option<&mut Child>, marker: &Marker) -> String { - let root = child.as_ref().map(|c| c.id()); - let note = kill_all(root, marker); - if let Some(child) = child { - let _ = child.kill(); - let _ = child.wait(); - } - note -} - -/// Whether this OS lets xtask find a run's processes by their marker (Linux: `/proc/*/environ`). -#[cfg_attr(not(unix), allow(dead_code))] -fn can_find_marked() -> bool { - cfg!(target_os = "linux") && Path::new("/proc/self/environ").exists() -} - -/// Freeze and kill `root` (unreaped) and what it started (see [`kill_run`]); what was done. -/// -/// Only processes xtask started are signalled. One found through the process tree is signalled only -/// once its parent is stopped: a stopped parent can't reap it, so its pid can't pass to another -/// process meanwhile. One found by its marker carries this run's exact entry, which nothing else -/// has. Everything found is frozen with SIGSTOP until no new one turns up, then killed with -/// SIGKILL, the last found first. -#[cfg(unix)] -fn kill_all(root: Option, marker: &Marker) -> String { - let me = std::process::id(); - let entry = marker.entry(); - let by_marker = can_find_marked(); - let mut order: Vec = Vec::new(); - let mut stopped: BTreeSet = BTreeSet::new(); - let mut fresh: Vec = root.into_iter().collect(); - for _ in 0..64 { - signal("STOP", &fresh); - stopped.extend(&fresh); - order.extend(&fresh); - let mut found = children_of(&process_table(), &stopped); - if by_marker { - found.extend(marked(&entry)); - } - found.retain(|p| *p != me && !stopped.contains(p)); - if found.is_empty() { - break; - } - fresh = found.into_iter().collect(); - } - signal("KILL", &order.iter().rev().copied().collect::>()); - let started = order.len().saturating_sub(usize::from(root.is_some())); - if !by_marker { - return match root { - Some(_) => format!( - "killed it and the {started} process(es) it started that were still its descendants; on this OS processes that \ - outlived their parent can't be found, and may still run" - ), - None => "on this OS the processes it started that outlived it can't be found, and may still run".to_owned(), - }; - } - // a killed process loses its environment as it dies, before it is reaped - let until = Instant::now() + Duration::from_secs(2); - let mut alive = marked(&entry); - while !alive.is_empty() && Instant::now() < until { - std::thread::sleep(TICK); - alive = marked(&entry); - } - let mut note = match (root, started) { - (Some(_), 0) => "killed it; it had started no other process (looked for in its process tree and by the run's environment marker)".to_owned(), - (Some(_), n) => format!( - "killed it and the {n} process(es) it started (found in its process tree and by the run's environment marker, so reparented ones too)" - ), - (None, 0) => "no process it started was left (looked for by the run's environment marker)".to_owned(), - (None, n) => format!("killed the {n} process(es) it started that outlived it (found by the run's environment marker)"), - }; - if !alive.is_empty() { - let pids: Vec = alive.iter().map(u32::to_string).collect(); - note.push_str(&format!("; still alive after the kill: pid {} (they carry {})", pids.join(", "), marker.key)); - } - note -} - -#[cfg(windows)] -fn kill_all(root: Option, _marker: &Marker) -> String { - let Some(root) = root else { - return "on this OS the processes it started that outlived it can't be found, and may still run".to_owned(); - }; - let _ = Command::new("taskkill").args(["/PID", &root.to_string(), "/T", "/F"]).stdout(Stdio::null()).stderr(Stdio::null()).status(); - "killed it and its process tree (taskkill /T); processes that outlived their parent may still run".to_owned() -} - -#[cfg(not(any(unix, windows)))] -fn kill_all(_root: Option, _marker: &Marker) -> String { - "killed it; processes it started may still run".to_owned() -} - -#[cfg(unix)] -fn signal(name: &str, pids: &[u32]) { - if pids.is_empty() { - return; - } - let _ = Command::new("kill").arg(format!("-{name}")).args(pids.iter().map(u32::to_string)).stdout(Stdio::null()).stderr(Stdio::null()).status(); -} - -/// Every process's pid and parent pid, from `ps` (empty if it fails). -#[cfg(unix)] -fn process_table() -> Vec<(u32, u32)> { - let Ok(out) = Command::new("ps").args(["-A", "-o", "pid=", "-o", "ppid="]).stderr(Stdio::null()).output() else { - return Vec::new(); - }; - parse_process_table(&String::from_utf8_lossy(&out.stdout)) -} - -/// The `pid ppid` pairs of a process table, one process per line. -#[cfg_attr(not(unix), allow(dead_code))] -fn parse_process_table(table: &str) -> Vec<(u32, u32)> { - table - .lines() - .filter_map(|l| { - let mut w = l.split_whitespace(); - Some((w.next()?.parse().ok()?, w.next()?.parse().ok()?)) - }) - .collect() -} - -/// The direct children of `parents` in a process table. -#[cfg_attr(not(unix), allow(dead_code))] -fn children_of(table: &[(u32, u32)], parents: &BTreeSet) -> BTreeSet { - table.iter().filter(|(pid, ppid)| parents.contains(ppid) && !parents.contains(pid)).map(|(pid, _)| *pid).collect() -} - /// Whether a NUL-separated environment block holds exactly `entry` (`KEY=VALUE`), not as part of /// another variable's name or value. #[cfg_attr(not(target_os = "linux"), allow(dead_code))] @@ -730,26 +604,6 @@ fn has_entry(environ: &[u8], entry: &str) -> bool { environ.split(|b| *b == 0).any(|var| var == entry.as_bytes()) } -/// This user's processes whose environment holds exactly `entry` (`/proc//environ`; a -/// process that can't be read is skipped, and zombies have no environment). -#[cfg(target_os = "linux")] -fn marked(entry: &str) -> Vec { - use std::os::unix::fs::MetadataExt; - let (Ok(me), Ok(dir)) = (std::fs::metadata("/proc/self"), std::fs::read_dir("/proc")) else { - return Vec::new(); - }; - dir.filter_map(Result::ok) - .filter_map(|e| e.file_name().to_str()?.parse::().ok()) - .filter(|pid| std::fs::metadata(format!("/proc/{pid}")).is_ok_and(|m| m.uid() == me.uid())) - .filter(|pid| std::fs::read(format!("/proc/{pid}/environ")).is_ok_and(|env| has_entry(&env, entry))) - .collect() -} - -#[cfg(all(unix, not(target_os = "linux")))] -fn marked(_entry: &str) -> Vec { - Vec::new() -} - /// A copy of `cmd`: its program, arguments, directory and environment changes. fn copy_command(cmd: &Command) -> Command { let mut c = Command::new(cmd.get_program()); @@ -1148,12 +1002,12 @@ mod tests { #[test] fn finds_the_children_of_stopped_processes_in_a_process_table() { - let table = parse_process_table(" 1 0\n 10 1\n 11 10\n 12 11\n 13 10\n 20 1\n 21 20\n junk\n 14 12"); + let table = kill::parse_process_table(" 1 0\n 10 1\n 11 10\n 12 11\n 13 10\n 20 1\n 21 20\n junk\n 14 12"); assert_eq!(table.len(), 8); - assert_eq!(children_of(&table, &BTreeSet::from([10])), BTreeSet::from([11, 13]), "only direct children: their parent is stopped"); - assert_eq!(children_of(&table, &BTreeSet::from([10, 11, 13])), BTreeSet::from([12])); - assert!(children_of(&table, &BTreeSet::from([99])).is_empty()); - assert!(children_of(&parse_process_table("5 6\n6 5"), &BTreeSet::from([5, 6])).is_empty(), "a cycle ends"); + assert_eq!(kill::children_of(&table, &BTreeSet::from([10])), BTreeSet::from([11, 13]), "only direct children: their parent is stopped"); + assert_eq!(kill::children_of(&table, &BTreeSet::from([10, 11, 13])), BTreeSet::from([12])); + assert!(kill::children_of(&table, &BTreeSet::from([99])).is_empty()); + assert!(kill::children_of(&kill::parse_process_table("5 6\n6 5"), &BTreeSet::from([5, 6])).is_empty(), "a cycle ends"); } #[test] @@ -1196,12 +1050,12 @@ mod tests { spawn(&[], Some((&marker.key, "2"))), ]; let until = Instant::now() + Duration::from_secs(10); - while marked(&marker.entry()).is_empty() && Instant::now() < until { + while kill::marked(&marker.entry()).is_empty() && Instant::now() < until { std::thread::sleep(TICK); } // give the decoys time to start too, then look again std::thread::sleep(Duration::from_millis(300)); - assert_eq!(marked(&marker.entry()), [ours.id()]); + assert_eq!(kill::marked(&marker.entry()), [ours.id()]); for c in decoys.iter_mut().chain([&mut ours]) { let _ = c.kill(); let _ = c.wait(); diff --git a/xtask/src/deadline/kill.rs b/xtask/src/deadline/kill.rs new file mode 100644 index 00000000000..13f00bae3a6 --- /dev/null +++ b/xtask/src/deadline/kill.rs @@ -0,0 +1,642 @@ +//! Ending a run that ran out of time: its direct child and every process it started, and never a +//! process xtask didn't start (#3060; the module docs of [`super`] say how the processes are found). +//! +//! **No signal by a pid that may name another process by now.** A pid read from the process table +//! or `/proc` passes to another process as soon as its process exits and is reaped. On Linux each +//! process is therefore held by a pidfd ([`Held`]), opened *before* what makes it ours is read again +//! (its parent is one of the stopped processes, or its environment holds the run's marker), and +//! every signal goes through that pidfd: if the process exited and its pid was reused in between, +//! the signal fails as "gone" and reaches no one. Elsewhere on Unix (no pidfds; no marker lookup +//! either) a process is signalled by its pid only once its parent is stopped and so can't reap it; +//! a parent that ignores `SIGCHLD` has its children reaped by the kernel all the same, which is the +//! one gap left there. +//! +//! **Nothing is left frozen.** Every signal's result is kept. A process whose SIGKILL fails is sent +//! it once more, and if that fails too it is sent SIGCONT, so it runs on rather than staying +//! stopped (it was frozen only so it couldn't start more processes while the others were found); +//! the report names it either way. The direct child is waited for a bounded time. + +use std::collections::BTreeSet; +#[cfg(unix)] +use std::process::Stdio; +use std::process::{Child, Command}; +use std::time::{Duration, Instant}; + +use super::{Marker, TICK}; + +/// How long the direct child is waited for after the kill, and the others to exit. +const AFTER_KILL: Duration = Duration::from_secs(2); +/// How many rounds of looking for new processes (each a level of the tree) before killing. +#[cfg(unix)] +const ROUNDS: usize = 64; + +/// Kill everything a run started, reap its direct child, and say what was done. +/// +/// `child` is the run's direct child while it hasn't been reaped (so its pid is still its own): +/// it and its process tree are signalled, plus every process carrying the run's `marker`. `None` +/// once it has been reaped: then only processes carrying the marker are, never the old pid, which +/// may belong to another process by now. +pub(super) fn kill_run(child: Option<&mut Child>, marker: &Marker) -> String { + #[cfg(unix)] + let mut note = kill_all(child.as_ref().map(|c| c.id()), marker, &mut Real); + #[cfg(not(unix))] + let mut note = kill_all(child.as_ref().map(|c| c.id()), marker); + if let Some(child) = child { + // unreaped until the wait below succeeds: its pid is still its own + let _ = child.kill(); + if !reaped(child, AFTER_KILL) { + note.push_str(&format!("; it was still running {} s after the kill (pid {})", AFTER_KILL.as_secs(), child.id())); + } + } + note +} + +/// Wait at most `limit` for `child` to exit; whether it did (and was reaped). +fn reaped(child: &mut Child, limit: Duration) -> bool { + let until = Instant::now() + limit; + loop { + match child.try_wait() { + Ok(Some(_)) => return true, + Ok(None) if Instant::now() < until => std::thread::sleep(TICK), + _ => return false, + } + } +} + +/// Whether this OS lets xtask find a run's processes by their marker (Linux: `/proc/*/environ`). +#[cfg_attr(not(unix), allow(dead_code))] +fn can_find_marked() -> bool { + cfg!(target_os = "linux") && std::path::Path::new("/proc/self/environ").exists() +} + +/// A signal sent while ending a run. +#[cfg(unix)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Sig { + Stop, + Kill, + Cont, +} + +/// Why a signal wasn't delivered. +#[cfg(unix)] +#[derive(Debug, PartialEq, Eq)] +pub(super) enum Unsent { + /// The process is gone (with a pidfd: it exited, whatever holds its pid now). + Gone, + /// The signal failed: why. + Failed(String), +} + +/// A process to signal: its pid and, on Linux, a pidfd that refers to it alone, whatever its pid +/// passes to after it exits. `fd` is `None` only for a process whose parent is stopped (or the +/// unreaped direct child), whose pid can't pass to another process meanwhile. +#[cfg(unix)] +pub(super) struct Held { + pid: u32, + /// Whether the kill stopped it (only those are continued when they can't be killed). + frozen: bool, + #[cfg(target_os = "linux")] + fd: Option, +} + +#[cfg(unix)] +impl Held { + /// By its pid alone: only for a process whose pid can't be reused meanwhile. + fn by_pid(pid: u32) -> Self { + Self { + pid, + frozen: false, + #[cfg(target_os = "linux")] + fd: None, + } + } +} + +/// What [`Os::hold`] made of a pid that looked like one of the run's processes. +#[cfg(unix)] +pub(super) enum Hold { + Held(Held), + /// It exited, or what made it look like ours no longer holds (its pid passed to another process). + Not, + /// It still looks like ours but can't be held, so it isn't signalled: why. + Unheld(String), +} + +/// Where the kill looks for processes and how it signals them; tests replace a part. +#[cfg(unix)] +pub(super) trait Os { + /// The process table (pid, parent pid) and the pids whose environment holds `entry` (on + /// Linux with `by_marker`; else none). + fn scan(&mut self, entry: &str, by_marker: bool) -> (Vec<(u32, u32)>, BTreeSet) { + scan(entry, by_marker) + } + + /// Hold `pid`, found as a child of `stopped` or by `entry`, if it still is one. + fn hold(&mut self, pid: u32, entry: &str, stopped: &BTreeSet, by_marker: bool) -> Hold { + hold(pid, entry, stopped, by_marker) + } + + /// Hold the direct child (unreaped, so its pid is its own). + fn hold_root(&mut self, pid: u32) -> Held { + hold_root(pid) + } + + fn send(&mut self, held: &Held, sig: Sig) -> Result<(), Unsent> { + send(held, sig) + } + + /// Whether the process has exited (`None`: this OS can't tell without its pid). + fn exited(&mut self, held: &Held) -> Option { + exited(held) + } +} + +/// The real process table and signals. +#[cfg(unix)] +pub(super) struct Real; + +#[cfg(unix)] +impl Os for Real {} + +/// Freeze and kill `root` (unreaped) and what it started (see [`kill_run`]); what was done. +/// +/// Everything found is frozen with SIGSTOP until no new one turns up, a level of the tree a round, +/// then killed with SIGKILL, the last found first. Then the failures are dealt with (module docs). +#[cfg(unix)] +pub(super) fn kill_all(root: Option, marker: &Marker, os: &mut dyn Os) -> String { + let entry = marker.entry(); + let by_marker = can_find_marked(); + let mut end = Ending::default(); + let found = freeze(root, &entry, by_marker, os, &mut end); + let kill_failed = kill(os, &end.held); + end.problems.extend(thaw(os, &end.held, &kill_failed)); + let mut alive = if by_marker { wait_exited(os, &end.held, &entry) } else { Vec::new() }; + // those are told of above + alive.retain(|p| !kill_failed.iter().any(|(i, _)| end.held.get(*i).is_some_and(|h| h.pid == *p))); + let started = end.held.iter().filter(|h| Some(h.pid) != root).count(); + let mut note = summary(root, started, by_marker); + if found == ROUNDS { + note.push_str(&format!("; it kept starting processes, so xtask stopped looking after {ROUNDS} rounds")); + } + if !alive.is_empty() { + let pids: Vec = alive.iter().map(u32::to_string).collect(); + end.problems.push(format!("still alive after the kill: pid {} (they carry {})", pids.join(", "), marker.key)); + } + for problem in &end.problems { + note.push_str("; "); + note.push_str(problem); + } + note +} + +/// The processes held so far, in the order found, and what went wrong on the way. +#[cfg(unix)] +#[derive(Default)] +struct Ending { + held: Vec, + problems: Vec, +} + +/// Hold and stop `root` and then, a round at a time, every new process found; how many rounds ran. +#[cfg(unix)] +fn freeze(root: Option, entry: &str, by_marker: bool, os: &mut dyn Os, end: &mut Ending) -> usize { + let me = std::process::id(); + let mut fresh: Vec = root.map(|pid| os.hold_root(pid)).into_iter().collect(); + // the stopped ones, whose children can't be reaped meanwhile, and every pid already dealt with + let (mut stopped, mut seen) = (BTreeSet::new(), BTreeSet::from([me])); + for round in 1..=ROUNDS { + for mut held in fresh.drain(..) { + match os.send(&held, Sig::Stop) { + Ok(()) => { + held.frozen = true; + stopped.insert(held.pid); + } + // exited (or, with a pidfd, its pid passed to another process): nothing to do + Err(Unsent::Gone) => continue, + // not frozen, but still ours: it is killed with the rest + Err(Unsent::Failed(e)) => end.problems.push(format!("could not stop pid {} ({e})", held.pid)), + } + seen.insert(held.pid); + end.held.push(held); + } + let (table, marked) = os.scan(entry, by_marker); + let mut found = children_of(&table, &stopped); + found.extend(marked); + found.retain(|p| !seen.contains(p)); + for pid in found { + match os.hold(pid, entry, &stopped, by_marker) { + Hold::Held(held) => fresh.push(held), + Hold::Not => {} + Hold::Unheld(why) => { + seen.insert(pid); + end.problems.push(format!("pid {pid} carries the run's marker but couldn't be held ({why}), so it wasn't signalled")); + } + } + } + if fresh.is_empty() { + return round; + } + } + ROUNDS +} + +/// SIGKILL every held process, the last found first, and once more those it failed for; the +/// indexes (into `held`) and errors of the ones it failed for twice. +#[cfg(unix)] +fn kill(os: &mut dyn Os, held: &[Held]) -> Vec<(usize, String)> { + let mut failed: Vec = Vec::new(); + for (i, h) in held.iter().enumerate().rev() { + if let Err(Unsent::Failed(_)) = os.send(h, Sig::Kill) { + failed.push(i); + } + } + failed + .into_iter() + .filter_map(|i| match os.send(held.get(i)?, Sig::Kill) { + Ok(()) | Err(Unsent::Gone) => None, + Err(Unsent::Failed(e)) => Some((i, e)), + }) + .collect() +} + +/// SIGCONT the processes the kill stopped and SIGKILL failed for, so none stays stopped; what to +/// report of each. +/// +/// Still ours to signal: a stopped process can't exit by itself, so its pid stays its own even +/// without a pidfd. +#[cfg(unix)] +fn thaw(os: &mut dyn Os, held: &[Held], failed: &[(usize, String)]) -> Vec { + failed + .iter() + .filter_map(|(i, e)| { + let h = held.get(*i)?; + if !h.frozen { + return Some(format!("could not kill pid {} ({e}); it may still run", h.pid)); + } + Some(match os.send(h, Sig::Cont) { + Ok(()) => format!("could not kill pid {} ({e}), so it was continued with SIGCONT rather than left stopped", h.pid), + Err(Unsent::Gone) => format!("could not kill pid {} ({e}), but it has exited", h.pid), + Err(Unsent::Failed(c)) => format!("could not kill pid {} ({e}) nor continue it ({c}): it may be left stopped", h.pid), + }) + }) + .collect() +} + +/// Wait at most [`AFTER_KILL`] for the held processes to exit; the pids still alive then (held ones +/// that haven't exited, and any that still carry `entry`: a killed process loses its environment +/// as it dies, before it is reaped). +#[cfg(unix)] +fn wait_exited(os: &mut dyn Os, held: &[Held], entry: &str) -> Vec { + let until = Instant::now() + AFTER_KILL; + loop { + let mut alive: BTreeSet = held.iter().filter(|h| os.exited(h) == Some(false)).map(|h| h.pid).collect(); + alive.extend(os.scan(entry, true).1); + if alive.is_empty() || Instant::now() >= until { + return alive.into_iter().collect(); + } + std::thread::sleep(TICK); + } +} + +/// What the kill did, before its problems. +#[cfg(unix)] +fn summary(root: Option, started: usize, by_marker: bool) -> String { + if !by_marker { + return match root { + Some(_) => format!( + "killed it and the {started} process(es) it started that were still its descendants; on this OS processes that \ + outlived their parent can't be found, and may still run" + ), + None => "on this OS the processes it started that outlived it can't be found, and may still run".to_owned(), + }; + } + match (root, started) { + (Some(_), 0) => "killed it; it had started no other process (looked for in its process tree and by the run's environment marker)".to_owned(), + (Some(_), n) => format!( + "killed it and the {n} process(es) it started (found in its process tree and by the run's environment marker, so reparented ones too)" + ), + (None, 0) => "no process it started was left (looked for by the run's environment marker)".to_owned(), + (None, n) => format!("killed the {n} process(es) it started that outlived it (found by the run's environment marker)"), + } +} + +#[cfg(windows)] +pub(super) fn kill_all(root: Option, _marker: &Marker) -> String { + let Some(root) = root else { + return "on this OS the processes it started that outlived it can't be found, and may still run".to_owned(); + }; + let _ = Command::new("taskkill") + .args(["/PID", &root.to_string(), "/T", "/F"]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status(); + "killed it and its process tree (taskkill /T); processes that outlived their parent may still run".to_owned() +} + +#[cfg(not(any(unix, windows)))] +pub(super) fn kill_all(_root: Option, _marker: &Marker) -> String { + "killed it; processes it started may still run".to_owned() +} + +#[cfg(unix)] +fn send(held: &Held, sig: Sig) -> Result<(), Unsent> { + use rustix::process::Signal; + let sig = match sig { + Sig::Stop => Signal::STOP, + Sig::Kill => Signal::KILL, + Sig::Cont => Signal::CONT, + }; + let unsent = |e: rustix::io::Errno| if e == rustix::io::Errno::SRCH { Unsent::Gone } else { Unsent::Failed(e.to_string()) }; + #[cfg(target_os = "linux")] + if let Some(fd) = &held.fd { + return rustix::process::pidfd_send_signal(fd, sig).map_err(unsent); + } + let pid = i32::try_from(held.pid).ok().and_then(rustix::process::Pid::from_raw).ok_or_else(|| Unsent::Failed("not a pid".to_owned()))?; + rustix::process::kill_process(pid, sig).map_err(unsent) +} + +#[cfg(target_os = "linux")] +fn exited(held: &Held) -> Option { + use rustix::event::{PollFd, PollFlags, Timespec}; + let fd = held.fd.as_ref()?; + let mut fds = [PollFd::new(fd, PollFlags::IN)]; + // a pidfd is readable once its process has exited + let now = Timespec { tv_sec: 0, tv_nsec: 0 }; + rustix::event::poll(&mut fds, Some(&now)).ok()?; + Some(fds.first().is_some_and(|f| !f.revents().is_empty())) +} + +#[cfg(all(unix, not(target_os = "linux")))] +fn exited(_held: &Held) -> Option { + None +} + +#[cfg(target_os = "linux")] +fn hold_root(pid: u32) -> Held { + // the unreaped child's pid is its own, so a pidfd from it is too; without one its pid serves + Held { pid, frozen: false, fd: open_pidfd(pid).ok() } +} + +#[cfg(all(unix, not(target_os = "linux")))] +fn hold_root(pid: u32) -> Held { + Held::by_pid(pid) +} + +#[cfg(target_os = "linux")] +fn open_pidfd(pid: u32) -> Result { + let pid = i32::try_from(pid).ok().and_then(rustix::process::Pid::from_raw).ok_or(rustix::io::Errno::INVAL)?; + rustix::process::pidfd_open(pid, rustix::process::PidfdFlags::empty()) +} + +/// Hold `pid` by a pidfd, then read again what makes it ours: once the pidfd is open, a signal +/// through it reaches this process or none, so if the pid passed to another process before the +/// read, the stop that follows fails as gone. +#[cfg(target_os = "linux")] +fn hold(pid: u32, entry: &str, stopped: &BTreeSet, by_marker: bool) -> Hold { + let ours = |about: Option<(u32, bool)>| about.is_some_and(|(ppid, marked)| marked || stopped.contains(&ppid)); + if !by_marker { + // no /proc to read again: only a child of a stopped process, found in the process table + return Hold::Held(Held::by_pid(pid)); + } + match open_pidfd(pid) { + Ok(fd) if ours(about(pid, entry)) => Hold::Held(Held { pid, frozen: false, fd: Some(fd) }), + Ok(_) | Err(rustix::io::Errno::SRCH) => Hold::Not, + // no pidfd (an old kernel, out of descriptors): a child of a stopped process can't be + // reaped meanwhile, so its pid serves; one found only by its marker is left alone + Err(e) => match about(pid, entry) { + Some((ppid, _)) if stopped.contains(&ppid) => Hold::Held(Held::by_pid(pid)), + Some((_, true)) => Hold::Unheld(e.to_string()), + _ => Hold::Not, + }, + } +} + +#[cfg(all(unix, not(target_os = "linux")))] +fn hold(pid: u32, _entry: &str, _stopped: &BTreeSet, _by_marker: bool) -> Hold { + // found as a child of a stopped process, which can't reap it meanwhile + Hold::Held(Held::by_pid(pid)) +} + +/// The process table, and the pids whose environment holds `entry`: from `/proc` on Linux (with +/// `by_marker`), else the table from `ps` and no marked pids. +#[cfg(unix)] +fn scan(entry: &str, by_marker: bool) -> (Vec<(u32, u32)>, BTreeSet) { + #[cfg(target_os = "linux")] + if by_marker { + return proc_scan(entry); + } + let _ = (entry, by_marker); + (process_table(), BTreeSet::new()) +} + +/// Every process's pid and parent pid, from `ps` (empty if it fails). +#[cfg(unix)] +fn process_table() -> Vec<(u32, u32)> { + let Ok(out) = Command::new("ps").args(["-A", "-o", "pid=", "-o", "ppid="]).stderr(Stdio::null()).output() else { + return Vec::new(); + }; + parse_process_table(&String::from_utf8_lossy(&out.stdout)) +} + +/// The `pid ppid` pairs of a process table, one process per line. +#[cfg_attr(not(unix), allow(dead_code))] +pub(super) fn parse_process_table(table: &str) -> Vec<(u32, u32)> { + table + .lines() + .filter_map(|l| { + let mut w = l.split_whitespace(); + Some((w.next()?.parse().ok()?, w.next()?.parse().ok()?)) + }) + .collect() +} + +/// The direct children of `parents` in a process table. +#[cfg_attr(not(unix), allow(dead_code))] +pub(super) fn children_of(table: &[(u32, u32)], parents: &BTreeSet) -> BTreeSet { + table.iter().filter(|(pid, ppid)| parents.contains(ppid) && !parents.contains(pid)).map(|(pid, _)| *pid).collect() +} + +/// This user's processes in `/proc`: the table (pid, parent pid) and the pids whose environment +/// holds exactly `entry`. +#[cfg(target_os = "linux")] +fn proc_scan(entry: &str) -> (Vec<(u32, u32)>, BTreeSet) { + let (mut table, mut marked) = (Vec::new(), BTreeSet::new()); + for pid in proc_pids() { + if let Some((ppid, has)) = about(pid, entry) { + table.push((pid, ppid)); + if has { + marked.insert(pid); + } + } + } + (table, marked) +} + +/// The pids in `/proc`. +#[cfg(target_os = "linux")] +fn proc_pids() -> Vec { + let Ok(dir) = std::fs::read_dir("/proc") else { return Vec::new() }; + dir.filter_map(Result::ok).filter_map(|e| e.file_name().to_str()?.parse::().ok()).collect() +} + +/// What `/proc` says of `pid` if it is this user's: its parent and whether its environment holds +/// exactly `entry` (a process that can't be read has none, and neither has a zombie). +#[cfg(target_os = "linux")] +fn about(pid: u32, entry: &str) -> Option<(u32, bool)> { + use std::os::unix::fs::MetadataExt; + let me = std::fs::metadata("/proc/self").ok()?.uid(); + if std::fs::metadata(format!("/proc/{pid}")).ok()?.uid() != me { + return None; + } + let ppid = parent_in_stat(&std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?)?; + let marked = std::fs::read(format!("/proc/{pid}/environ")).is_ok_and(|env| super::has_entry(&env, entry)); + Some((ppid, marked)) +} + +/// The parent pid in a `/proc//stat` line: `pid (comm) state ppid …`, where `comm` may hold +/// spaces and parentheses. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +pub(super) fn parent_in_stat(stat: &str) -> Option { + let (_, rest) = stat.rsplit_once(')')?; + rest.split_whitespace().nth(1)?.parse().ok() +} + +/// This user's processes whose environment holds exactly `entry`. +#[cfg(all(test, target_os = "linux"))] +pub(super) fn marked(entry: &str) -> Vec { + proc_scan(entry).1.into_iter().collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_parent_is_read_past_any_parenthesis_in_the_command_name() { + assert_eq!(parent_in_stat("42 (sleep) S 7 42 42 0 -1"), Some(7)); + assert_eq!(parent_in_stat("42 (a) b) (c) R 9 1"), Some(9)); + assert_eq!(parent_in_stat("42 (sh) Z"), None); + assert_eq!(parent_in_stat("garbage"), None); + } + + /// The state letter of a process (`ps`'s first `stat` letter), or `None` once it is gone. + #[cfg(unix)] + fn state(pid: u32) -> Option { + let out = Command::new("ps").args(["-o", "stat=", "-p", &pid.to_string()]).output().ok()?; + String::from_utf8_lossy(&out.stdout).trim().chars().next() + } + + /// `sh` running `script` with the marker, and the pid it writes to a file (waited for). + #[cfg(unix)] + fn marked_sh(script: &str, name: &str) -> (Child, Marker, u32, std::path::PathBuf) { + let dir = std::env::temp_dir().join(format!("xtask-kill-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let pidfile = dir.join("pid"); + let mut c = Command::new("/bin/sh"); + c.args(["-c", &script.replace("PIDFILE", &pidfile.display().to_string())]).stdin(Stdio::null()); + let (child, marker) = super::super::spawn_marked(&mut c).unwrap(); + let until = Instant::now() + Duration::from_secs(10); + let pid = loop { + if let Some(pid) = std::fs::read_to_string(&pidfile).ok().and_then(|s| s.trim().parse().ok()) { + break pid; + } + assert!(Instant::now() < until, "the script wrote no pid"); + std::thread::sleep(TICK); + }; + (child, marker, pid, dir) + } + + /// The real OS, except that SIGKILL fails for every process but the direct child. + #[cfg(unix)] + struct KillFails { + root: u32, + refused: Vec, + } + + #[cfg(unix)] + impl Os for KillFails { + fn send(&mut self, held: &Held, sig: Sig) -> Result<(), Unsent> { + if sig == Sig::Kill && held.pid != self.root { + self.refused.push(held.pid); + return Err(Unsent::Failed("refused by the test".to_owned())); + } + send(held, sig) + } + } + + /// When SIGKILL fails, the processes the kill froze are continued, not left stopped, and the + /// report says so (the grandchild used to stay in state `T`). + #[cfg(unix)] + #[test] + fn a_process_whose_kill_fails_is_not_left_stopped() { + let (mut child, marker, grandchild, dir) = marked_sh("sleep 300 & echo $! > PIDFILE; wait", "thaw"); + let mut os = KillFails { root: child.id(), refused: Vec::new() }; + let note = kill_all(Some(child.id()), &marker, &mut os); + assert_eq!(os.refused.iter().filter(|p| **p == grandchild).count(), 2, "tried twice: {:?}", os.refused); + let s = state(grandchild); + // clean up before asserting: the grandchild runs on, as it should + let _ = Command::new("kill").args(["-KILL", &grandchild.to_string()]).status(); + let _ = child.kill(); + let _ = child.wait(); + let _ = std::fs::remove_dir_all(&dir); + assert!(s.is_some_and(|s| s != 'T'), "the grandchild was continued, not left stopped: state {s:?}"); + assert!( + note.contains(&format!( + "could not kill pid {grandchild} (refused by the test), so it was continued with SIGCONT rather than left stopped" + )), + "{note}" + ); + } + + /// The real OS, except that the first scan also reports `decoy` as carrying the marker, as if + /// the marked process it read had exited and its pid passed to `decoy` before it was signalled. + #[cfg(target_os = "linux")] + struct PidReused { + decoy: Option, + } + + #[cfg(target_os = "linux")] + impl Os for PidReused { + fn scan(&mut self, entry: &str, by_marker: bool) -> (Vec<(u32, u32)>, BTreeSet) { + let (table, mut marked) = scan(entry, by_marker); + marked.extend(self.decoy.take()); + (table, marked) + } + } + + /// A pid found by its marker that names another process by the time it is held is never + /// signalled: what makes it ours is read again once it is held by a pidfd (the old code + /// stopped and killed whatever the pid named by then). + #[cfg(target_os = "linux")] + #[test] + fn a_pid_that_passed_to_another_process_is_not_signalled() { + let mut decoy = Command::new("sleep").arg("300").stdin(Stdio::null()).spawn().unwrap(); + let (mut child, marker, grandchild, dir) = marked_sh("sleep 300 & echo $! > PIDFILE; wait", "reused"); + let note = kill_all(Some(child.id()), &marker, &mut PidReused { decoy: Some(decoy.id()) }); + let decoy_state = state(decoy.id()); + let _ = decoy.kill(); + let _ = decoy.wait(); + let _ = child.wait(); + let _ = std::fs::remove_dir_all(&dir); + assert!(decoy_state.is_some_and(|s| s != 'T' && s != 'Z'), "the decoy runs on: state {decoy_state:?}"); + assert!(state(grandchild).is_none_or(|s| s == 'Z'), "the run's own processes were killed"); + assert!(note.starts_with("killed it and the 1 process(es) it started") && !note.contains("still alive"), "{note}"); + } + + /// A pidfd refers to its process alone: once that process has exited and been reaped, a + /// signal through it fails as gone, whatever holds the pid now. + #[cfg(target_os = "linux")] + #[test] + fn a_held_process_that_was_reaped_gets_no_signal() { + let mut c = Command::new("sleep").arg("300").spawn().unwrap(); + let held = hold_root(c.id()); + assert!(held.fd.is_some(), "this kernel has pidfds"); + assert_eq!(exited(&held), Some(false)); + c.kill().unwrap(); + c.wait().unwrap(); + assert_eq!(exited(&held), Some(true)); + assert_eq!(send(&held, Sig::Stop), Err(Unsent::Gone)); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 202a262c488..20fe567e4e1 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,6 +1,6 @@ //! Workspace tooling: `cargo xtask `. //! -//! Pure Rust (std + serde_json; flate2/brotli for the web bundle). External tools (`cargo`, `curl`, `tar`) are +//! Pure Rust (std + serde_json; flate2/brotli for the web bundle; rustix on Unix to end a timed-out test run). External tools (`cargo`, `curl`, `tar`) are //! invoked through `std::process::Command`. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] From 659d806ffe6fc2ebf9507964e5be30f7a164e229 Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Tue, 3 Nov 2026 13:57:20 -0600 Subject: [PATCH 19/40] fix(xtask): #3060 trust a parent only while it lives, and signal no bare pid but the child Review of 47a727d3 (GPT-6 Astra): - A parent pid was trusted because a SIGSTOP to it once succeeded, but that also succeeds on a zombie; once reaped, its pid can pass to an unrelated process whose children then looked like ours. A child is now ours by its parent only if the held parent's pidfd shows it hasn't exited, checked after the child's parent pid is read. - The bare-pid fallbacks (no pidfd on Linux, every other Unix) kept the SIGCHLD-ignored reaping race. Now the only process signalled by its pid is the unreaped direct child; without pidfds the processes it started aren't signalled and the report says they may still run (on macOS and the BSDs that means only the binary itself is killed). rustix becomes a Linux-only dependency, and ps is no longer run. - Out of file descriptors or a /proc read error is reported rather than read as "not ours" or "nothing left". - taskkill on Windows is bounded (10 s) and its failure reported. - The tests clean up through a drop guard, so a failing one doesn't leave processes stopped or running. Co-Authored-By: Claude Opus 5.5 --- README.md | 3 +- docs/architecture.md | 20 +- xtask/Cargo.toml | 7 +- xtask/src/deadline.rs | 51 ++-- xtask/src/deadline/kill.rs | 584 +++++++++++++++++++++---------------- xtask/src/main.rs | 2 +- 6 files changed, 365 insertions(+), 302 deletions(-) diff --git a/README.md b/README.md index 1fcece34590..79eaab74eab 100644 --- a/README.md +++ b/README.md @@ -422,7 +422,8 @@ names the run holding the slot. The build isn't timed (a first build can rightly test binaries are: each may run for `LIGHTCRAFT_TEST_BINARY_TIMEOUT` minutes (default 30, timed from cargo's `Running` line for it; `0` for no limit). One that runs longer, a test hung on a GPU device say, is killed with the processes it started (on Linux found by an environment variable they inherit, so those that outlived -their parent too, unless they cleared their environment), and the run reports it as `timed out after 30 min` with the tests still running +their parent too, unless they cleared their environment; on macOS and the BSDs only the binary itself is +killed), and the run reports it as `timed out after 30 min` with the tests still running and those that never reported a result. Under `LIGHTCRAFT_NEXTEST=1`, `.config/nextest.toml` kills a test after 30 minutes instead. After a timeout, `ci` skips its GPU probe and translation gaps report. diff --git a/docs/architecture.md b/docs/architecture.md index 00416684a10..4a8ceed6146 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -88,15 +88,15 @@ for none): timed from its start when xtask runs it (`test::run_binary`), and fro full `ci`'s test and HEIF steps; the build before isn't bounded; cargo runs with `CARGO_TERM_QUIET=false` and without `-q` so it prints those lines). The output streams through and is read for libtest's lines, keeping a bounded amount. On timeout the binary and the processes it started -that xtask can find are killed, and no process xtask didn't start: the binary and its process tree, and on Linux every -process whose `/proc//environ` holds the run's exact marker entry (`LIGHTCRAFT_XTASK_RUN___=1`, -inherited by all it starts; the nonce is random per xtask process), which finds those that outlived -their parent (one that also cleared its environment isn't found and may keep running). On Linux each -is held by a pidfd and signalled only through it, so a pid reused meanwhile is never signalled; -elsewhere on Unix a process is signalled only once its parent is frozen and can't reap it. They are -frozen with SIGSTOP, then killed; one whose SIGKILL fails twice is continued with SIGCONT rather than -left stopped, and the report names it (`taskkill /T` on Windows; elsewhere the report says -reparented ones can't be found). The child stays in xtask's process group, so Ctrl-C +that xtask can find are killed, and no process xtask didn't start. On Linux that is the binary, its process +tree and every process whose `/proc//environ` holds the run's exact marker entry +(`LIGHTCRAFT_XTASK_RUN___=1`, inherited by all it starts; the nonce is random per xtask +process), which finds those that outlived their parent (one that also cleared its environment isn't +found and may keep running). Each is held by a pidfd and signalled only through it, so a pid reused +meanwhile is never signalled. They are frozen with SIGSTOP, then killed; one whose SIGKILL fails twice +is continued with SIGCONT rather than left stopped, and the report names it. Without pidfds (other +Unix, Linux before 5.3) only the binary is killed and the report says what it started may still run; +Windows uses `taskkill /T`. The child stays in xtask's process group, so Ctrl-C still reaches it. The run reports `timed out after N min: `, what the kill found, the tests still running (libtest's "has been running for over 60 seconds" warnings, or the test a single-threaded run started) and those that never reported a result (`--list`, itself @@ -128,7 +128,7 @@ the `lightcraft-gpu` tests once per backend with a hardware adapter (`LIGHTCRAFT | Date | Change | Summary | |---|---|---| -| 2026-11-03 | minor | Quality gates: a timed-out test run's processes are signalled through pidfds on Linux (never a reused pid), and one that can't be killed is continued rather than left stopped | +| 2026-11-03 | minor | Quality gates: a timed-out test run's processes are signalled through pidfds on Linux (never a reused pid; without pidfds only the binary is killed), and one that can't be killed is continued rather than left stopped | | 2026-10-26 | minor | Quality gates: each test binary's run (`LIGHTCRAFT_TEST_BINARY_TIMEOUT`) and the wait for the CI slot (`LIGHTCRAFT_CI_LOCK_WAIT`) have a time limit | | 2026-10-26 | minor | Quality gates: plain `cargo test` (and `cargo nextest run`) runs at most 4 tests at once; xtask tells that default from a caller's `RUST_TEST_THREADS` | | 2026-10-26 | minor | Quality gates: `cargo xtask test` runs the tests with `ci`'s caps and slot, and can keep going past a failing binary | diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index f49b0397d2e..418af229503 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -16,8 +16,7 @@ sha2 = { workspace = true } flate2 = "1" brotli = { version = "9", default-features = false, features = ["std"] } -# ending a timed-out test run (deadline/kill.rs): signals through pidfds on Linux, so a pid that -# passed to another process is never signalled, and kill(2) with its error elsewhere; no unsafe -# here, pure Rust on Linux (already in the lock through tempfile and wayland) -[target.'cfg(unix)'.dependencies] +# ending a timed-out test run (deadline/kill.rs): pidfds, so a pid that passed to another process +# is never signalled; no unsafe here, pure Rust (already in the lock through tempfile and wayland) +[target.'cfg(target_os = "linux")'.dependencies] rustix = { version = "1", default-features = false, features = ["std", "process", "event"] } diff --git a/xtask/src/deadline.rs b/xtask/src/deadline.rs index f0759829164..1fc2afd16ad 100644 --- a/xtask/src/deadline.rs +++ b/xtask/src/deadline.rs @@ -26,18 +26,18 @@ //! environment variable of its own ([`Marker`], `LIGHTCRAFT_XTASK_RUN___=1`, the //! nonce random per xtask process so an earlier xtask with the same pid had another) that //! everything it starts inherits. On timeout ([`kill`]) the binary (while unreaped, so its pid is -//! its own) and its process tree are frozen with SIGSTOP level by level; on Linux also every -//! process of this user whose `/proc//environ` holds the exact entry, which finds those that -//! outlived their parent. On Linux each one is held by a pidfd, opened before what makes it ours is -//! read again, and signalled only through it, so a pid that passed to another process in between -//! is never signalled; elsewhere on Unix a process is signalled by its pid only once its parent is -//! stopped and can't reap it. Once no new one turns up they are killed with SIGKILL; one it fails -//! for is tried again and then continued with SIGCONT rather than left stopped, and the report says -//! how many were killed and names any that failed or are still alive. It also says when the OS -//! doesn't allow looking for the reparented ones (Unix other than Linux: only the tree; Windows: -//! `taskkill /T /F`). Only a process that clears its environment and leaves the tree escapes. The -//! child stays in xtask's process group rather than one of its own, so Ctrl-C in the terminal -//! still reaches the test binaries as before. +//! its own) is frozen with SIGSTOP, and on Linux so is everything it started, level by level: its +//! process tree, and every process of this user whose `/proc//environ` holds the exact entry, +//! which finds those that outlived their parent. Each of those is held by a pidfd, opened before +//! what makes it ours is read again, and signalled only through it, so a pid that passed to +//! another process in between is never signalled. Once no new one turns up they are killed with +//! SIGKILL; one it fails for is tried again and then continued with SIGCONT rather than left +//! stopped, and the report says how many were killed and names any that failed or are still alive. +//! Without pidfds (Unix other than Linux, Linux before 5.3) only the binary itself is killed and +//! the report says what it started may still run; Windows uses `taskkill /T /F` (bounded). Only a +//! process that clears its environment and leaves the tree escapes on Linux. The child stays in +//! xtask's process group rather than one of its own, so Ctrl-C in the terminal still reaches the +//! test binaries as before. //! //! A timeout also turns off the optional probes after it in the same run ([`any_timed_out`]): the //! GPU probe, which runs bounded too ([`capture_cargo`], [`probe_limit`]), and the translation @@ -422,7 +422,7 @@ impl Marker { } /// The exact environment entry that marks the run's processes. - #[cfg_attr(not(unix), allow(dead_code))] + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] fn entry(&self) -> String { format!("{}={MARK_VALUE}", self.key) } @@ -1000,16 +1000,6 @@ mod tests { assert_eq!(lines.rest(), "part"); } - #[test] - fn finds_the_children_of_stopped_processes_in_a_process_table() { - let table = kill::parse_process_table(" 1 0\n 10 1\n 11 10\n 12 11\n 13 10\n 20 1\n 21 20\n junk\n 14 12"); - assert_eq!(table.len(), 8); - assert_eq!(kill::children_of(&table, &BTreeSet::from([10])), BTreeSet::from([11, 13]), "only direct children: their parent is stopped"); - assert_eq!(kill::children_of(&table, &BTreeSet::from([10, 11, 13])), BTreeSet::from([12])); - assert!(kill::children_of(&table, &BTreeSet::from([99])).is_empty()); - assert!(kill::children_of(&kill::parse_process_table("5 6\n6 5"), &BTreeSet::from([5, 6])).is_empty(), "a cycle ends"); - } - #[test] fn a_marker_is_an_exact_environment_entry_of_this_process_and_run() { let m = Marker::with(42, 0xabc, 3); @@ -1103,14 +1093,14 @@ mod tests { } /// Whether process `pid` is gone (or a zombie no one has reaped yet). - #[cfg(unix)] + #[cfg(target_os = "linux")] fn gone(pid: &str) -> bool { let out = Command::new("ps").args(["-o", "stat=", "-p", pid]).output().unwrap(); let stat = String::from_utf8_lossy(&out.stdout); stat.trim().is_empty() || stat.trim().starts_with('Z') } - #[cfg(unix)] + #[cfg(target_os = "linux")] fn scratch(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("xtask-deadline-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); @@ -1118,7 +1108,7 @@ mod tests { dir } - #[cfg(unix)] + #[cfg(target_os = "linux")] fn wait_gone(pid: &str) -> bool { let until = Instant::now() + Duration::from_secs(10); while Instant::now() < until { @@ -1137,7 +1127,8 @@ mod tests { c } - #[cfg(unix)] + // Linux: elsewhere the processes the binary started aren't signalled (no pidfds) + #[cfg(target_os = "linux")] #[test] fn a_hung_binary_is_killed_with_the_processes_it_started_and_named() { let dir = scratch("hung"); @@ -1192,7 +1183,8 @@ mod tests { ); } - #[cfg(unix)] + // Linux: elsewhere the processes the binary started aren't signalled (no pidfds) + #[cfg(target_os = "linux")] #[test] fn a_list_run_that_hangs_is_bounded_and_killed() { let dir = scratch("list"); @@ -1272,7 +1264,8 @@ mod tests { assert!(run("kill -9 $$").unwrap_err().contains("SIGKILL")); } - #[cfg(unix)] + // Linux: elsewhere the processes the binary started aren't signalled (no pidfds) + #[cfg(target_os = "linux")] #[test] fn under_cargo_each_binary_gets_the_limit_and_the_build_does_not_count() { // the "build" outlasts the limit, then each "binary" finishes in time diff --git a/xtask/src/deadline/kill.rs b/xtask/src/deadline/kill.rs index 13f00bae3a6..d2a461aa075 100644 --- a/xtask/src/deadline/kill.rs +++ b/xtask/src/deadline/kill.rs @@ -1,25 +1,29 @@ -//! Ending a run that ran out of time: its direct child and every process it started, and never a -//! process xtask didn't start (#3060; the module docs of [`super`] say how the processes are found). +//! Ending a run that ran out of time: its direct child and every process it started that xtask can +//! signal safely, and never a process xtask didn't start (#3060; the module docs of [`super`] say +//! how the processes are found). //! -//! **No signal by a pid that may name another process by now.** A pid read from the process table -//! or `/proc` passes to another process as soon as its process exits and is reaped. On Linux each -//! process is therefore held by a pidfd ([`Held`]), opened *before* what makes it ours is read again -//! (its parent is one of the stopped processes, or its environment holds the run's marker), and -//! every signal goes through that pidfd: if the process exited and its pid was reused in between, -//! the signal fails as "gone" and reaches no one. Elsewhere on Unix (no pidfds; no marker lookup -//! either) a process is signalled by its pid only once its parent is stopped and so can't reap it; -//! a parent that ignores `SIGCHLD` has its children reaped by the kernel all the same, which is the -//! one gap left there. +//! **No signal by a pid that may name another process by now.** A pid read from `/proc` passes to +//! another process as soon as its process exits and is reaped, and a parent that ignores `SIGCHLD` +//! has its children reaped by the kernel even while it is stopped. So the only process signalled +//! by its pid is the direct child, which xtask hasn't reaped yet. On Linux every other one is held +//! by a pidfd ([`Held`]), opened *before* what makes it ours is read again, and signalled only +//! through it, so if its pid passed to another process in between, the signal fails as "gone" and +//! reaches no one. What makes a process ours: the run's marker in its environment, or a parent +//! that is one of the held processes and hasn't exited (checked through the parent's pidfd after +//! the child's parent pid is read, so that pid can't have passed to another process meanwhile). +//! Where there are no pidfds (Unix other than Linux, a Linux kernel before 5.3), the processes the +//! child started aren't signalled, and the report says they may still run. //! -//! **Nothing is left frozen.** Every signal's result is kept. A process whose SIGKILL fails is sent -//! it once more, and if that fails too it is sent SIGCONT, so it runs on rather than staying -//! stopped (it was frozen only so it couldn't start more processes while the others were found); -//! the report names it either way. The direct child is waited for a bounded time. +//! **Nothing is left frozen, and nothing waits without a bound.** Every signal's result is kept. A +//! process whose SIGKILL fails is sent it once more, and if that fails too it is sent SIGCONT, so +//! it runs on rather than staying stopped (it was frozen only so it couldn't start more processes +//! while the others were found); the report names it either way, and says when the processes +//! couldn't all be looked for or held (out of file descriptors, say). The direct child (and +//! `taskkill` on Windows) is waited for a bounded time. +#[cfg(target_os = "linux")] use std::collections::BTreeSet; -#[cfg(unix)] -use std::process::Stdio; -use std::process::{Child, Command}; +use std::process::{Child, ExitStatus}; use std::time::{Duration, Instant}; use super::{Marker, TICK}; @@ -27,50 +31,85 @@ use super::{Marker, TICK}; /// How long the direct child is waited for after the kill, and the others to exit. const AFTER_KILL: Duration = Duration::from_secs(2); /// How many rounds of looking for new processes (each a level of the tree) before killing. -#[cfg(unix)] +#[cfg(target_os = "linux")] const ROUNDS: usize = 64; -/// Kill everything a run started, reap its direct child, and say what was done. +/// Kill everything a run started that can be signalled safely, reap its direct child, and say +/// what was done. /// /// `child` is the run's direct child while it hasn't been reaped (so its pid is still its own): -/// it and its process tree are signalled, plus every process carrying the run's `marker`. `None` -/// once it has been reaped: then only processes carrying the marker are, never the old pid, which -/// may belong to another process by now. +/// it is signalled, plus what it started. `None` once it has been reaped: then only processes +/// carrying the marker are, never the old pid, which may belong to another process by now. pub(super) fn kill_run(child: Option<&mut Child>, marker: &Marker) -> String { - #[cfg(unix)] + #[cfg(target_os = "linux")] let mut note = kill_all(child.as_ref().map(|c| c.id()), marker, &mut Real); - #[cfg(not(unix))] + #[cfg(not(target_os = "linux"))] let mut note = kill_all(child.as_ref().map(|c| c.id()), marker); if let Some(child) = child { // unreaped until the wait below succeeds: its pid is still its own let _ = child.kill(); - if !reaped(child, AFTER_KILL) { + if wait_for(child, AFTER_KILL).is_none() { note.push_str(&format!("; it was still running {} s after the kill (pid {})", AFTER_KILL.as_secs(), child.id())); } } note } -/// Wait at most `limit` for `child` to exit; whether it did (and was reaped). -fn reaped(child: &mut Child, limit: Duration) -> bool { +/// Wait at most `limit` for `child` to exit; its status if it did (and was reaped). +fn wait_for(child: &mut Child, limit: Duration) -> Option { let until = Instant::now() + limit; loop { match child.try_wait() { - Ok(Some(_)) => return true, + Ok(Some(status)) => return Some(status), Ok(None) if Instant::now() < until => std::thread::sleep(TICK), - _ => return false, + _ => return None, } } } -/// Whether this OS lets xtask find a run's processes by their marker (Linux: `/proc/*/environ`). -#[cfg_attr(not(unix), allow(dead_code))] -fn can_find_marked() -> bool { - cfg!(target_os = "linux") && std::path::Path::new("/proc/self/environ").exists() +/// What the kill says when it can signal only the direct child. +#[cfg_attr(target_os = "windows", allow(dead_code))] +fn child_only(root: Option, why: &str) -> String { + match root { + Some(_) => format!("killed it; the processes it started weren't signalled ({why}), and may still run"), + None => format!("the processes it started that outlived it weren't looked for ({why}), and may still run"), + } +} + +#[cfg(all(unix, not(target_os = "linux")))] +pub(super) fn kill_all(root: Option, _marker: &Marker) -> String { + child_only(root, "this OS has no pidfds, and a bare pid may name another process by the time it is signalled") +} + +#[cfg(windows)] +pub(super) fn kill_all(root: Option, _marker: &Marker) -> String { + use std::process::{Command, Stdio}; + let Some(root) = root else { + return "on this OS the processes it started that outlived it can't be found, and may still run".to_owned(); + }; + let spawned = Command::new("taskkill").args(["/PID", &root.to_string(), "/T", "/F"]).stdout(Stdio::null()).stderr(Stdio::null()).spawn(); + let mut taskkill = match spawned { + Ok(t) => t, + Err(e) => return format!("could not run taskkill ({e}): the processes it started may still run"), + }; + match wait_for(&mut taskkill, Duration::from_secs(10)) { + Some(s) if s.success() => "killed it and its process tree (taskkill /T); processes that outlived their parent may still run".to_owned(), + Some(s) => format!("taskkill /T failed ({s}): the processes it started may still run"), + None => { + let _ = taskkill.kill(); + let _ = wait_for(&mut taskkill, AFTER_KILL); + "taskkill /T didn't finish in 10 s: the processes it started may still run".to_owned() + } + } +} + +#[cfg(not(any(unix, windows)))] +pub(super) fn kill_all(root: Option, _marker: &Marker) -> String { + child_only(root, "not supported on this OS") } /// A signal sent while ending a run. -#[cfg(unix)] +#[cfg(target_os = "linux")] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum Sig { Stop, @@ -79,106 +118,100 @@ pub(super) enum Sig { } /// Why a signal wasn't delivered. -#[cfg(unix)] +#[cfg(target_os = "linux")] #[derive(Debug, PartialEq, Eq)] pub(super) enum Unsent { - /// The process is gone (with a pidfd: it exited, whatever holds its pid now). + /// The process is gone (with a pidfd: it exited and was reaped, whatever holds its pid now). Gone, /// The signal failed: why. Failed(String), } -/// A process to signal: its pid and, on Linux, a pidfd that refers to it alone, whatever its pid -/// passes to after it exits. `fd` is `None` only for a process whose parent is stopped (or the -/// unreaped direct child), whose pid can't pass to another process meanwhile. -#[cfg(unix)] +/// A process to signal: its pid and a pidfd that refers to it alone, whatever its pid passes to +/// after it exits. `fd` is `None` only for the unreaped direct child, whose pid is its own. +#[cfg(target_os = "linux")] pub(super) struct Held { pid: u32, /// Whether the kill stopped it (only those are continued when they can't be killed). frozen: bool, - #[cfg(target_os = "linux")] fd: Option, } -#[cfg(unix)] -impl Held { - /// By its pid alone: only for a process whose pid can't be reused meanwhile. - fn by_pid(pid: u32) -> Self { - Self { - pid, - frozen: false, - #[cfg(target_os = "linux")] - fd: None, - } - } -} - /// What [`Os::hold`] made of a pid that looked like one of the run's processes. -#[cfg(unix)] +#[cfg(target_os = "linux")] pub(super) enum Hold { - Held(Held), - /// It exited, or what made it look like ours no longer holds (its pid passed to another process). + /// Held, and what `/proc` said of it after that: its parent pid and whether it carries the marker. + Held(Held, u32, bool), + /// It exited, or it isn't this user's. Not, - /// It still looks like ours but can't be held, so it isn't signalled: why. + /// It can't be held or looked at, so it isn't signalled: why. Unheld(String), } +/// A look through `/proc`: the process table (pid, parent pid) and the pids whose environment +/// holds the run's marker. +#[cfg(target_os = "linux")] +pub(super) type Scan = (Vec<(u32, u32)>, BTreeSet); + /// Where the kill looks for processes and how it signals them; tests replace a part. -#[cfg(unix)] +#[cfg(target_os = "linux")] pub(super) trait Os { - /// The process table (pid, parent pid) and the pids whose environment holds `entry` (on - /// Linux with `by_marker`; else none). - fn scan(&mut self, entry: &str, by_marker: bool) -> (Vec<(u32, u32)>, BTreeSet) { - scan(entry, by_marker) + fn scan(&mut self, entry: &str) -> Result { + proc_scan(entry) } - /// Hold `pid`, found as a child of `stopped` or by `entry`, if it still is one. - fn hold(&mut self, pid: u32, entry: &str, stopped: &BTreeSet, by_marker: bool) -> Hold { - hold(pid, entry, stopped, by_marker) + /// Hold `pid` by a pidfd and read again what may make it ours. + fn hold(&mut self, pid: u32, entry: &str) -> Hold { + hold(pid, entry) } /// Hold the direct child (unreaped, so its pid is its own). fn hold_root(&mut self, pid: u32) -> Held { - hold_root(pid) + Held { pid, frozen: false, fd: open_pidfd(pid).ok() } } fn send(&mut self, held: &Held, sig: Sig) -> Result<(), Unsent> { send(held, sig) } - /// Whether the process has exited (`None`: this OS can't tell without its pid). + /// Whether the process has exited (`None`: no pidfd to tell, so it's the unreaped child). fn exited(&mut self, held: &Held) -> Option { exited(held) } } -/// The real process table and signals. -#[cfg(unix)] +/// The real `/proc` and signals. +#[cfg(target_os = "linux")] pub(super) struct Real; -#[cfg(unix)] +#[cfg(target_os = "linux")] impl Os for Real {} /// Freeze and kill `root` (unreaped) and what it started (see [`kill_run`]); what was done. /// /// Everything found is frozen with SIGSTOP until no new one turns up, a level of the tree a round, /// then killed with SIGKILL, the last found first. Then the failures are dealt with (module docs). -#[cfg(unix)] +#[cfg(target_os = "linux")] pub(super) fn kill_all(root: Option, marker: &Marker, os: &mut dyn Os) -> String { + if !std::path::Path::new("/proc/self/environ").exists() { + return child_only(root, "no /proc to find them in"); + } let entry = marker.entry(); - let by_marker = can_find_marked(); let mut end = Ending::default(); - let found = freeze(root, &entry, by_marker, os, &mut end); + let rounds = freeze(root, &entry, os, &mut end); let kill_failed = kill(os, &end.held); end.problems.extend(thaw(os, &end.held, &kill_failed)); - let mut alive = if by_marker { wait_exited(os, &end.held, &entry) } else { Vec::new() }; + let mut alive = wait_exited(os, &end.held, &entry); // those are told of above alive.retain(|p| !kill_failed.iter().any(|(i, _)| end.held.get(*i).is_some_and(|h| h.pid == *p))); let started = end.held.iter().filter(|h| Some(h.pid) != root).count(); - let mut note = summary(root, started, by_marker); - if found == ROUNDS { + let mut note = summary(root, started); + if rounds == ROUNDS { note.push_str(&format!("; it kept starting processes, so xtask stopped looking after {ROUNDS} rounds")); } + if let Some((n, why)) = end.unheld.first().map(|why| (end.unheld.len(), why)) { + note.push_str(&format!("; {n} process(es) it started couldn't be held by a pidfd or looked at ({why}), so they weren't signalled")); + } if !alive.is_empty() { let pids: Vec = alive.iter().map(u32::to_string).collect(); end.problems.push(format!("still alive after the kill: pid {} (they carry {})", pids.join(", "), marker.key)); @@ -191,20 +224,21 @@ pub(super) fn kill_all(root: Option, marker: &Marker, os: &mut dyn Os) -> S } /// The processes held so far, in the order found, and what went wrong on the way. -#[cfg(unix)] +#[cfg(target_os = "linux")] #[derive(Default)] struct Ending { held: Vec, problems: Vec, + /// Why each process found that couldn't be held wasn't. + unheld: Vec, } /// Hold and stop `root` and then, a round at a time, every new process found; how many rounds ran. -#[cfg(unix)] -fn freeze(root: Option, entry: &str, by_marker: bool, os: &mut dyn Os, end: &mut Ending) -> usize { - let me = std::process::id(); +#[cfg(target_os = "linux")] +fn freeze(root: Option, entry: &str, os: &mut dyn Os, end: &mut Ending) -> usize { let mut fresh: Vec = root.map(|pid| os.hold_root(pid)).into_iter().collect(); - // the stopped ones, whose children can't be reaped meanwhile, and every pid already dealt with - let (mut stopped, mut seen) = (BTreeSet::new(), BTreeSet::from([me])); + // the stopped ones, whose children are looked for, and every pid already dealt with + let (mut stopped, mut seen) = (BTreeSet::new(), BTreeSet::from([std::process::id()])); for round in 1..=ROUNDS { for mut held in fresh.drain(..) { match os.send(&held, Sig::Stop) { @@ -212,7 +246,7 @@ fn freeze(root: Option, entry: &str, by_marker: bool, os: &mut dyn Os, end: held.frozen = true; stopped.insert(held.pid); } - // exited (or, with a pidfd, its pid passed to another process): nothing to do + // reaped (whatever holds its pid now): nothing to do Err(Unsent::Gone) => continue, // not frozen, but still ours: it is killed with the rest Err(Unsent::Failed(e)) => end.problems.push(format!("could not stop pid {} ({e})", held.pid)), @@ -220,17 +254,24 @@ fn freeze(root: Option, entry: &str, by_marker: bool, os: &mut dyn Os, end: seen.insert(held.pid); end.held.push(held); } - let (table, marked) = os.scan(entry, by_marker); + let (table, marked) = match os.scan(entry) { + Ok(scan) => scan, + Err(e) => { + end.problems.push(format!("could not look for the processes it started ({e}), so some may still run")); + return round; + } + }; let mut found = children_of(&table, &stopped); found.extend(marked); found.retain(|p| !seen.contains(p)); for pid in found { - match os.hold(pid, entry, &stopped, by_marker) { - Hold::Held(held) => fresh.push(held), - Hold::Not => {} + match os.hold(pid, entry) { + Hold::Held(held, ppid, marked) if marked || has_live_parent(os, &end.held, ppid) => fresh.push(held), + // not ours after all: its pid passed to another process since the scan + Hold::Held(..) | Hold::Not => {} Hold::Unheld(why) => { seen.insert(pid); - end.problems.push(format!("pid {pid} carries the run's marker but couldn't be held ({why}), so it wasn't signalled")); + end.unheld.push(why); } } } @@ -241,9 +282,18 @@ fn freeze(root: Option, entry: &str, by_marker: bool, os: &mut dyn Os, end: ROUNDS } +/// Whether `ppid`, read from a child's `/proc` after the child was held, is one of the held +/// processes: one that hasn't exited now, so it held that pid when it was read (a pid passes to +/// another process only once its process has exited and been reaped). The direct child, held +/// without a pidfd, is unreaped, so its pid is its own. +#[cfg(target_os = "linux")] +fn has_live_parent(os: &mut dyn Os, held: &[Held], ppid: u32) -> bool { + held.iter().filter(|h| h.pid == ppid).any(|h| os.exited(h) != Some(true)) +} + /// SIGKILL every held process, the last found first, and once more those it failed for; the /// indexes (into `held`) and errors of the ones it failed for twice. -#[cfg(unix)] +#[cfg(target_os = "linux")] fn kill(os: &mut dyn Os, held: &[Held]) -> Vec<(usize, String)> { let mut failed: Vec = Vec::new(); for (i, h) in held.iter().enumerate().rev() { @@ -262,10 +312,7 @@ fn kill(os: &mut dyn Os, held: &[Held]) -> Vec<(usize, String)> { /// SIGCONT the processes the kill stopped and SIGKILL failed for, so none stays stopped; what to /// report of each. -/// -/// Still ours to signal: a stopped process can't exit by itself, so its pid stays its own even -/// without a pidfd. -#[cfg(unix)] +#[cfg(target_os = "linux")] fn thaw(os: &mut dyn Os, held: &[Held], failed: &[(usize, String)]) -> Vec { failed .iter() @@ -286,12 +333,12 @@ fn thaw(os: &mut dyn Os, held: &[Held], failed: &[(usize, String)]) -> Vec Vec { let until = Instant::now() + AFTER_KILL; loop { let mut alive: BTreeSet = held.iter().filter(|h| os.exited(h) == Some(false)).map(|h| h.pid).collect(); - alive.extend(os.scan(entry, true).1); + alive.extend(os.scan(entry).map(|(_, marked)| marked).unwrap_or_default()); if alive.is_empty() || Instant::now() >= until { return alive.into_iter().collect(); } @@ -300,17 +347,8 @@ fn wait_exited(os: &mut dyn Os, held: &[Held], entry: &str) -> Vec { } /// What the kill did, before its problems. -#[cfg(unix)] -fn summary(root: Option, started: usize, by_marker: bool) -> String { - if !by_marker { - return match root { - Some(_) => format!( - "killed it and the {started} process(es) it started that were still its descendants; on this OS processes that \ - outlived their parent can't be found, and may still run" - ), - None => "on this OS the processes it started that outlived it can't be found, and may still run".to_owned(), - }; - } +#[cfg(target_os = "linux")] +fn summary(root: Option, started: usize) -> String { match (root, started) { (Some(_), 0) => "killed it; it had started no other process (looked for in its process tree and by the run's environment marker)".to_owned(), (Some(_), n) => format!( @@ -321,25 +359,7 @@ fn summary(root: Option, started: usize, by_marker: bool) -> String { } } -#[cfg(windows)] -pub(super) fn kill_all(root: Option, _marker: &Marker) -> String { - let Some(root) = root else { - return "on this OS the processes it started that outlived it can't be found, and may still run".to_owned(); - }; - let _ = Command::new("taskkill") - .args(["/PID", &root.to_string(), "/T", "/F"]) - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .status(); - "killed it and its process tree (taskkill /T); processes that outlived their parent may still run".to_owned() -} - -#[cfg(not(any(unix, windows)))] -pub(super) fn kill_all(_root: Option, _marker: &Marker) -> String { - "killed it; processes it started may still run".to_owned() -} - -#[cfg(unix)] +#[cfg(target_os = "linux")] fn send(held: &Held, sig: Sig) -> Result<(), Unsent> { use rustix::process::Signal; let sig = match sig { @@ -348,10 +368,10 @@ fn send(held: &Held, sig: Sig) -> Result<(), Unsent> { Sig::Cont => Signal::CONT, }; let unsent = |e: rustix::io::Errno| if e == rustix::io::Errno::SRCH { Unsent::Gone } else { Unsent::Failed(e.to_string()) }; - #[cfg(target_os = "linux")] if let Some(fd) = &held.fd { return rustix::process::pidfd_send_signal(fd, sig).map_err(unsent); } + // no pidfd: only the unreaped direct child is held this way let pid = i32::try_from(held.pid).ok().and_then(rustix::process::Pid::from_raw).ok_or_else(|| Unsent::Failed("not a pid".to_owned()))?; rustix::process::kill_process(pid, sig).map_err(unsent) } @@ -367,131 +387,84 @@ fn exited(held: &Held) -> Option { Some(fds.first().is_some_and(|f| !f.revents().is_empty())) } -#[cfg(all(unix, not(target_os = "linux")))] -fn exited(_held: &Held) -> Option { - None -} - -#[cfg(target_os = "linux")] -fn hold_root(pid: u32) -> Held { - // the unreaped child's pid is its own, so a pidfd from it is too; without one its pid serves - Held { pid, frozen: false, fd: open_pidfd(pid).ok() } -} - -#[cfg(all(unix, not(target_os = "linux")))] -fn hold_root(pid: u32) -> Held { - Held::by_pid(pid) -} - #[cfg(target_os = "linux")] fn open_pidfd(pid: u32) -> Result { let pid = i32::try_from(pid).ok().and_then(rustix::process::Pid::from_raw).ok_or(rustix::io::Errno::INVAL)?; rustix::process::pidfd_open(pid, rustix::process::PidfdFlags::empty()) } -/// Hold `pid` by a pidfd, then read again what makes it ours: once the pidfd is open, a signal +/// Hold `pid` by a pidfd, then read again what may make it ours: once the pidfd is open, a signal /// through it reaches this process or none, so if the pid passed to another process before the /// read, the stop that follows fails as gone. #[cfg(target_os = "linux")] -fn hold(pid: u32, entry: &str, stopped: &BTreeSet, by_marker: bool) -> Hold { - let ours = |about: Option<(u32, bool)>| about.is_some_and(|(ppid, marked)| marked || stopped.contains(&ppid)); - if !by_marker { - // no /proc to read again: only a child of a stopped process, found in the process table - return Hold::Held(Held::by_pid(pid)); - } - match open_pidfd(pid) { - Ok(fd) if ours(about(pid, entry)) => Hold::Held(Held { pid, frozen: false, fd: Some(fd) }), - Ok(_) | Err(rustix::io::Errno::SRCH) => Hold::Not, - // no pidfd (an old kernel, out of descriptors): a child of a stopped process can't be - // reaped meanwhile, so its pid serves; one found only by its marker is left alone - Err(e) => match about(pid, entry) { - Some((ppid, _)) if stopped.contains(&ppid) => Hold::Held(Held::by_pid(pid)), - Some((_, true)) => Hold::Unheld(e.to_string()), - _ => Hold::Not, - }, - } -} - -#[cfg(all(unix, not(target_os = "linux")))] -fn hold(pid: u32, _entry: &str, _stopped: &BTreeSet, _by_marker: bool) -> Hold { - // found as a child of a stopped process, which can't reap it meanwhile - Hold::Held(Held::by_pid(pid)) -} - -/// The process table, and the pids whose environment holds `entry`: from `/proc` on Linux (with -/// `by_marker`), else the table from `ps` and no marked pids. -#[cfg(unix)] -fn scan(entry: &str, by_marker: bool) -> (Vec<(u32, u32)>, BTreeSet) { - #[cfg(target_os = "linux")] - if by_marker { - return proc_scan(entry); - } - let _ = (entry, by_marker); - (process_table(), BTreeSet::new()) -} - -/// Every process's pid and parent pid, from `ps` (empty if it fails). -#[cfg(unix)] -fn process_table() -> Vec<(u32, u32)> { - let Ok(out) = Command::new("ps").args(["-A", "-o", "pid=", "-o", "ppid="]).stderr(Stdio::null()).output() else { - return Vec::new(); +fn hold(pid: u32, entry: &str) -> Hold { + let fd = match open_pidfd(pid) { + Ok(fd) => fd, + Err(rustix::io::Errno::SRCH) => return Hold::Not, + Err(e) => return Hold::Unheld(format!("pidfd: {e}")), }; - parse_process_table(&String::from_utf8_lossy(&out.stdout)) -} - -/// The `pid ppid` pairs of a process table, one process per line. -#[cfg_attr(not(unix), allow(dead_code))] -pub(super) fn parse_process_table(table: &str) -> Vec<(u32, u32)> { - table - .lines() - .filter_map(|l| { - let mut w = l.split_whitespace(); - Some((w.next()?.parse().ok()?, w.next()?.parse().ok()?)) - }) - .collect() + match about(pid, entry) { + Ok(Some((ppid, marked))) => Hold::Held(Held { pid, frozen: false, fd: Some(fd) }, ppid, marked), + Ok(None) => Hold::Not, + Err(e) => Hold::Unheld(e), + } } /// The direct children of `parents` in a process table. -#[cfg_attr(not(unix), allow(dead_code))] +#[cfg(target_os = "linux")] pub(super) fn children_of(table: &[(u32, u32)], parents: &BTreeSet) -> BTreeSet { table.iter().filter(|(pid, ppid)| parents.contains(ppid) && !parents.contains(pid)).map(|(pid, _)| *pid).collect() } /// This user's processes in `/proc`: the table (pid, parent pid) and the pids whose environment -/// holds exactly `entry`. +/// holds exactly `entry`. An error when `/proc` can't be listed or a process can't be looked at +/// for a reason other than its exit (out of file descriptors, say). #[cfg(target_os = "linux")] -fn proc_scan(entry: &str) -> (Vec<(u32, u32)>, BTreeSet) { +fn proc_scan(entry: &str) -> Result { let (mut table, mut marked) = (Vec::new(), BTreeSet::new()); - for pid in proc_pids() { - if let Some((ppid, has)) = about(pid, entry) { + let dir = std::fs::read_dir("/proc").map_err(|e| format!("/proc: {e}"))?; + for pid in dir.filter_map(Result::ok).filter_map(|e| e.file_name().to_str()?.parse::().ok()) { + if let Some((ppid, has)) = about(pid, entry)? { table.push((pid, ppid)); if has { marked.insert(pid); } } } - (table, marked) + Ok((table, marked)) } -/// The pids in `/proc`. +/// Whether an error reading a process's `/proc` files means it has gone (or is another user's). #[cfg(target_os = "linux")] -fn proc_pids() -> Vec { - let Ok(dir) = std::fs::read_dir("/proc") else { return Vec::new() }; - dir.filter_map(Result::ok).filter_map(|e| e.file_name().to_str()?.parse::().ok()).collect() +fn gone(e: &std::io::Error) -> bool { + // ESRCH: it exited while being read; EACCES / EPERM: another user's, or no longer dumpable + matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::PermissionDenied) || e.raw_os_error() == Some(3) } /// What `/proc` says of `pid` if it is this user's: its parent and whether its environment holds -/// exactly `entry` (a process that can't be read has none, and neither has a zombie). +/// exactly `entry` (a zombie's is empty). `None` when it has gone or is another user's; an error +/// when it can't be looked at for another reason. #[cfg(target_os = "linux")] -fn about(pid: u32, entry: &str) -> Option<(u32, bool)> { +fn about(pid: u32, entry: &str) -> Result, String> { use std::os::unix::fs::MetadataExt; - let me = std::fs::metadata("/proc/self").ok()?.uid(); - if std::fs::metadata(format!("/proc/{pid}")).ok()?.uid() != me { - return None; - } - let ppid = parent_in_stat(&std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?)?; - let marked = std::fs::read(format!("/proc/{pid}/environ")).is_ok_and(|env| super::has_entry(&env, entry)); - Some((ppid, marked)) + let failed = |e: std::io::Error| if gone(&e) { Ok(None) } else { Err(format!("/proc/{pid}: {e}")) }; + let me = std::fs::metadata("/proc/self").map_err(|e| format!("/proc/self: {e}"))?.uid(); + match std::fs::metadata(format!("/proc/{pid}")) { + Ok(m) if m.uid() == me => {} + Ok(_) => return Ok(None), + Err(e) => return failed(e), + } + let stat = match std::fs::read_to_string(format!("/proc/{pid}/stat")) { + Ok(s) => s, + Err(e) => return failed(e), + }; + let Some(ppid) = parent_in_stat(&stat) else { return Ok(None) }; + let marked = match std::fs::read(format!("/proc/{pid}/environ")) { + Ok(env) => super::has_entry(&env, entry), + Err(e) if gone(&e) => false, + Err(e) => return Err(format!("/proc/{pid}/environ: {e}")), + }; + Ok(Some((ppid, marked))) } /// The parent pid in a `/proc//stat` line: `pid (comm) state ppid …`, where `comm` may hold @@ -505,7 +478,7 @@ pub(super) fn parent_in_stat(stat: &str) -> Option { /// This user's processes whose environment holds exactly `entry`. #[cfg(all(test, target_os = "linux"))] pub(super) fn marked(entry: &str) -> Vec { - proc_scan(entry).1.into_iter().collect() + proc_scan(entry).map(|(_, m)| m.into_iter().collect()).unwrap_or_default() } #[cfg(test)] @@ -520,23 +493,62 @@ mod tests { assert_eq!(parent_in_stat("garbage"), None); } - /// The state letter of a process (`ps`'s first `stat` letter), or `None` once it is gone. - #[cfg(unix)] + #[cfg(target_os = "linux")] + #[test] + fn finds_the_children_of_stopped_processes_in_a_process_table() { + let table = [(1, 0), (10, 1), (11, 10), (12, 11), (13, 10), (20, 1), (21, 20), (14, 12)]; + assert_eq!(children_of(&table, &BTreeSet::from([10])), BTreeSet::from([11, 13]), "only direct children"); + assert_eq!(children_of(&table, &BTreeSet::from([10, 11, 13])), BTreeSet::from([12])); + assert!(children_of(&table, &BTreeSet::from([99])).is_empty()); + assert!(children_of(&[(5, 6), (6, 5)], &BTreeSet::from([5, 6])).is_empty(), "a cycle ends"); + } + + /// The state letter of a process, or `None` once it is gone. + #[cfg(target_os = "linux")] fn state(pid: u32) -> Option { - let out = Command::new("ps").args(["-o", "stat=", "-p", &pid.to_string()]).output().ok()?; - String::from_utf8_lossy(&out.stdout).trim().chars().next() + let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; + stat.rsplit_once(')')?.1.split_whitespace().next()?.chars().next() + } + + /// Kills (through a pidfd) and reaps what a test started when it drops, also when it fails. + #[cfg(target_os = "linux")] + #[derive(Default)] + struct Cleanup { + children: Vec, + others: Vec, + dir: Option, } - /// `sh` running `script` with the marker, and the pid it writes to a file (waited for). - #[cfg(unix)] - fn marked_sh(script: &str, name: &str) -> (Child, Marker, u32, std::path::PathBuf) { + #[cfg(target_os = "linux")] + impl Drop for Cleanup { + fn drop(&mut self) { + for h in &self.others { + let _ = send(h, Sig::Kill); + } + for c in &mut self.children { + let _ = c.kill(); + let _ = wait_for(c, Duration::from_secs(5)); + } + if let Some(dir) = &self.dir { + let _ = std::fs::remove_dir_all(dir); + } + } + } + + /// `sh` running `script` with the marker, and the pid it writes to PIDFILE (waited for, and + /// held so the cleanup can kill it). + #[cfg(target_os = "linux")] + fn marked_sh(script: &str, name: &str, cleanup: &mut Cleanup) -> (u32, Marker, u32) { let dir = std::env::temp_dir().join(format!("xtask-kill-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); + cleanup.dir = Some(dir.clone()); let pidfile = dir.join("pid"); - let mut c = Command::new("/bin/sh"); - c.args(["-c", &script.replace("PIDFILE", &pidfile.display().to_string())]).stdin(Stdio::null()); + let mut c = std::process::Command::new("/bin/sh"); + c.args(["-c", &script.replace("PIDFILE", &pidfile.display().to_string())]).stdin(std::process::Stdio::null()); let (child, marker) = super::super::spawn_marked(&mut c).unwrap(); + let root = child.id(); + cleanup.children.push(child); let until = Instant::now() + Duration::from_secs(10); let pid = loop { if let Some(pid) = std::fs::read_to_string(&pidfile).ok().and_then(|s| s.trim().parse().ok()) { @@ -545,17 +557,29 @@ mod tests { assert!(Instant::now() < until, "the script wrote no pid"); std::thread::sleep(TICK); }; - (child, marker, pid, dir) + let held = Real.hold_root(pid); + assert!(held.fd.is_some(), "this kernel has pidfds (Linux 5.3)"); + cleanup.others.push(held); + (root, marker, pid) + } + + /// A process with no marker, for the kill to leave alone. + #[cfg(target_os = "linux")] + fn decoy(cleanup: &mut Cleanup) -> u32 { + let c = std::process::Command::new("sleep").arg("300").stdin(std::process::Stdio::null()).spawn().unwrap(); + let pid = c.id(); + cleanup.children.push(c); + pid } /// The real OS, except that SIGKILL fails for every process but the direct child. - #[cfg(unix)] + #[cfg(target_os = "linux")] struct KillFails { root: u32, refused: Vec, } - #[cfg(unix)] + #[cfg(target_os = "linux")] impl Os for KillFails { fn send(&mut self, held: &Held, sig: Sig) -> Result<(), Unsent> { if sig == Sig::Kill && held.pid != self.root { @@ -568,20 +592,16 @@ mod tests { /// When SIGKILL fails, the processes the kill froze are continued, not left stopped, and the /// report says so (the grandchild used to stay in state `T`). - #[cfg(unix)] + #[cfg(target_os = "linux")] #[test] fn a_process_whose_kill_fails_is_not_left_stopped() { - let (mut child, marker, grandchild, dir) = marked_sh("sleep 300 & echo $! > PIDFILE; wait", "thaw"); - let mut os = KillFails { root: child.id(), refused: Vec::new() }; - let note = kill_all(Some(child.id()), &marker, &mut os); - assert_eq!(os.refused.iter().filter(|p| **p == grandchild).count(), 2, "tried twice: {:?}", os.refused); + let mut cleanup = Cleanup::default(); + let (root, marker, grandchild) = marked_sh("sleep 300 & echo $! > PIDFILE; wait", "thaw", &mut cleanup); + let mut os = KillFails { root, refused: Vec::new() }; + let note = kill_all(Some(root), &marker, &mut os); let s = state(grandchild); - // clean up before asserting: the grandchild runs on, as it should - let _ = Command::new("kill").args(["-KILL", &grandchild.to_string()]).status(); - let _ = child.kill(); - let _ = child.wait(); - let _ = std::fs::remove_dir_all(&dir); assert!(s.is_some_and(|s| s != 'T'), "the grandchild was continued, not left stopped: state {s:?}"); + assert_eq!(os.refused.iter().filter(|p| **p == grandchild).count(), 2, "tried twice: {:?}", os.refused); assert!( note.contains(&format!( "could not kill pid {grandchild} (refused by the test), so it was continued with SIGCONT rather than left stopped" @@ -599,10 +619,10 @@ mod tests { #[cfg(target_os = "linux")] impl Os for PidReused { - fn scan(&mut self, entry: &str, by_marker: bool) -> (Vec<(u32, u32)>, BTreeSet) { - let (table, mut marked) = scan(entry, by_marker); + fn scan(&mut self, entry: &str) -> Result { + let (table, mut marked) = proc_scan(entry)?; marked.extend(self.decoy.take()); - (table, marked) + Ok((table, marked)) } } @@ -612,28 +632,78 @@ mod tests { #[cfg(target_os = "linux")] #[test] fn a_pid_that_passed_to_another_process_is_not_signalled() { - let mut decoy = Command::new("sleep").arg("300").stdin(Stdio::null()).spawn().unwrap(); - let (mut child, marker, grandchild, dir) = marked_sh("sleep 300 & echo $! > PIDFILE; wait", "reused"); - let note = kill_all(Some(child.id()), &marker, &mut PidReused { decoy: Some(decoy.id()) }); - let decoy_state = state(decoy.id()); - let _ = decoy.kill(); - let _ = decoy.wait(); - let _ = child.wait(); - let _ = std::fs::remove_dir_all(&dir); - assert!(decoy_state.is_some_and(|s| s != 'T' && s != 'Z'), "the decoy runs on: state {decoy_state:?}"); + let mut cleanup = Cleanup::default(); + let decoy = decoy(&mut cleanup); + let (root, marker, grandchild) = marked_sh("sleep 300 & echo $! > PIDFILE; wait", "reused", &mut cleanup); + let note = kill_all(Some(root), &marker, &mut PidReused { decoy: Some(decoy) }); + let s = state(decoy); + assert!(s.is_some_and(|s| s != 'T' && s != 'Z'), "the decoy runs on: state {s:?}"); assert!(state(grandchild).is_none_or(|s| s == 'Z'), "the run's own processes were killed"); assert!(note.starts_with("killed it and the 1 process(es) it started") && !note.contains("still alive"), "{note}"); } + /// The real OS, except that the first scan also reports `decoy` as a child of `parent`, as if + /// `parent` (held, then exited) had been reaped and its pid passed to the decoy's parent. + #[cfg(target_os = "linux")] + struct ParentReused { + decoy: u32, + parent: u32, + once: bool, + } + + #[cfg(target_os = "linux")] + impl Os for ParentReused { + fn scan(&mut self, entry: &str) -> Result { + let (mut table, marked) = proc_scan(entry)?; + if std::mem::take(&mut self.once) { + table.push((self.decoy, self.parent)); + } + Ok((table, marked)) + } + + fn hold(&mut self, pid: u32, entry: &str) -> Hold { + match hold(pid, entry) { + Hold::Held(h, _, marked) if pid == self.decoy => Hold::Held(h, self.parent, marked), + other => other, + } + } + } + + /// A child is ours by its parent only while that parent hasn't exited: a stop that succeeded + /// once doesn't prove it (it succeeds on a zombie), and an exited parent's pid can pass to + /// another process, whose children are not ours. + #[cfg(target_os = "linux")] + #[test] + fn the_children_of_a_parent_that_exited_are_not_trusted() { + let mut cleanup = Cleanup::default(); + let decoy = decoy(&mut cleanup); + // a direct child that has exited but isn't reaped: a zombie, held by its pidfd + let mut c = std::process::Command::new("true"); + let (child, marker) = super::super::spawn_marked(&mut c).unwrap(); + let root = child.id(); + cleanup.children.push(child); + let until = Instant::now() + Duration::from_secs(10); + while state(root) != Some('Z') { + assert!(Instant::now() < until, "`true` didn't exit"); + std::thread::sleep(TICK); + } + let note = kill_all(Some(root), &marker, &mut ParentReused { decoy, parent: root, once: true }); + let s = state(decoy); + assert!(s.is_some_and(|s| s != 'T' && s != 'Z'), "the decoy runs on: state {s:?}"); + assert!(note.starts_with("killed it; it had started no other process"), "{note}"); + } + /// A pidfd refers to its process alone: once that process has exited and been reaped, a /// signal through it fails as gone, whatever holds the pid now. #[cfg(target_os = "linux")] #[test] fn a_held_process_that_was_reaped_gets_no_signal() { - let mut c = Command::new("sleep").arg("300").spawn().unwrap(); - let held = hold_root(c.id()); - assert!(held.fd.is_some(), "this kernel has pidfds"); + let mut cleanup = Cleanup::default(); + let pid = decoy(&mut cleanup); + let held = Real.hold_root(pid); + assert!(held.fd.is_some(), "this kernel has pidfds (Linux 5.3)"); assert_eq!(exited(&held), Some(false)); + let mut c = cleanup.children.pop().unwrap(); c.kill().unwrap(); c.wait().unwrap(); assert_eq!(exited(&held), Some(true)); diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 20fe567e4e1..37af1344841 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,6 +1,6 @@ //! Workspace tooling: `cargo xtask `. //! -//! Pure Rust (std + serde_json; flate2/brotli for the web bundle; rustix on Unix to end a timed-out test run). External tools (`cargo`, `curl`, `tar`) are +//! Pure Rust (std + serde_json; flate2/brotli for the web bundle; rustix on Linux to end a timed-out test run). External tools (`cargo`, `curl`, `tar`) are //! invoked through `std::process::Command`. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] From d5ffde0d67ddb378e3110f3e586a446c86a3c33c Mon Sep 17 00:00:00 2001 From: Chad Elliott Date: Tue, 3 Nov 2026 14:08:27 -0600 Subject: [PATCH 20/40] fix(xtask): #3060 a pidfd that can't be asked vouches for nothing; SIGCHLD ignored, the child too Second review (GPT-6 Astra) of bd68c1d2: - A failed poll of a parent's pidfd counted as "hasn't exited", so a reused parent pid could still vouch for unrelated children. Only an answer that it hasn't exited does now; an unanswerable one counts as alive in the after-kill check. - If xtask inherits SIGCHLD ignored, the kernel reaps its children itself, so even the direct child's pid can pass to another process. xtask reads its SigIgn mask; when SIGCHLD is ignored the direct child is held only like the others (pidfd, then its marker read again) and never signalled by pid, and the report says so. - /proc//stat is read as bytes (a command name needn't be UTF-8), and one process that can't be looked at no longer discards the scan: it is counted and reported, as is a final check that fails. - The tests check for pidfds before they start anything and register every process with the cleanup guard before asserting; the deadline tests read /proc instead of running ps. - The docs say what the fallback kills: xtask's own child, which under the full ci is cargo. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- docs/architecture.md | 6 +- xtask/src/deadline.rs | 9 +- xtask/src/deadline/kill.rs | 339 +++++++++++++++++++++++++++---------- 4 files changed, 261 insertions(+), 97 deletions(-) diff --git a/README.md b/README.md index 79eaab74eab..ab03d976cb6 100644 --- a/README.md +++ b/README.md @@ -422,8 +422,8 @@ names the run holding the slot. The build isn't timed (a first build can rightly test binaries are: each may run for `LIGHTCRAFT_TEST_BINARY_TIMEOUT` minutes (default 30, timed from cargo's `Running` line for it; `0` for no limit). One that runs longer, a test hung on a GPU device say, is killed with the processes it started (on Linux found by an environment variable they inherit, so those that outlived -their parent too, unless they cleared their environment; on macOS and the BSDs only the binary itself is -killed), and the run reports it as `timed out after 30 min` with the tests still running +their parent too, unless they cleared their environment; on macOS and the BSDs only the process xtask +started is killed, which under the full `ci` is cargo, so a hung test binary may keep running), and the run reports it as `timed out after 30 min` with the tests still running and those that never reported a result. Under `LIGHTCRAFT_NEXTEST=1`, `.config/nextest.toml` kills a test after 30 minutes instead. After a timeout, `ci` skips its GPU probe and translation gaps report. diff --git a/docs/architecture.md b/docs/architecture.md index 4a8ceed6146..6575372d5b0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -95,8 +95,8 @@ process), which finds those that outlived their parent (one that also cleared it found and may keep running). Each is held by a pidfd and signalled only through it, so a pid reused meanwhile is never signalled. They are frozen with SIGSTOP, then killed; one whose SIGKILL fails twice is continued with SIGCONT rather than left stopped, and the report names it. Without pidfds (other -Unix, Linux before 5.3) only the binary is killed and the report says what it started may still run; -Windows uses `taskkill /T`. The child stays in xtask's process group, so Ctrl-C +Unix, Linux before 5.3) only xtask's own child is killed (the test binary, or under the full `ci` +cargo, whose test binary may then keep running) and the report says so; Windows uses `taskkill /T`. The child stays in xtask's process group, so Ctrl-C still reaches it. The run reports `timed out after N min: `, what the kill found, the tests still running (libtest's "has been running for over 60 seconds" warnings, or the test a single-threaded run started) and those that never reported a result (`--list`, itself @@ -128,7 +128,7 @@ the `lightcraft-gpu` tests once per backend with a hardware adapter (`LIGHTCRAFT | Date | Change | Summary | |---|---|---| -| 2026-11-03 | minor | Quality gates: a timed-out test run's processes are signalled through pidfds on Linux (never a reused pid; without pidfds only the binary is killed), and one that can't be killed is continued rather than left stopped | +| 2026-11-03 | minor | Quality gates: a timed-out test run's processes are signalled through pidfds on Linux (never a reused pid; without pidfds only xtask's own child is killed), and one that can't be killed is continued rather than left stopped | | 2026-10-26 | minor | Quality gates: each test binary's run (`LIGHTCRAFT_TEST_BINARY_TIMEOUT`) and the wait for the CI slot (`LIGHTCRAFT_CI_LOCK_WAIT`) have a time limit | | 2026-10-26 | minor | Quality gates: plain `cargo test` (and `cargo nextest run`) runs at most 4 tests at once; xtask tells that default from a caller's `RUST_TEST_THREADS` | | 2026-10-26 | minor | Quality gates: `cargo xtask test` runs the tests with `ci`'s caps and slot, and can keep going past a failing binary | diff --git a/xtask/src/deadline.rs b/xtask/src/deadline.rs index 1fc2afd16ad..d88b3ffc1b3 100644 --- a/xtask/src/deadline.rs +++ b/xtask/src/deadline.rs @@ -33,8 +33,9 @@ //! another process in between is never signalled. Once no new one turns up they are killed with //! SIGKILL; one it fails for is tried again and then continued with SIGCONT rather than left //! stopped, and the report says how many were killed and names any that failed or are still alive. -//! Without pidfds (Unix other than Linux, Linux before 5.3) only the binary itself is killed and -//! the report says what it started may still run; Windows uses `taskkill /T /F` (bounded). Only a +//! Without pidfds (Unix other than Linux, Linux before 5.3) only xtask's own child is killed (the +//! test binary, or under the full `ci` cargo, whose test binary may then keep running) and the +//! report says what it started may still run; Windows uses `taskkill /T /F` (bounded). Only a //! process that clears its environment and leaves the tree escapes on Linux. The child stays in //! xtask's process group rather than one of its own, so Ctrl-C in the terminal still reaches the //! test binaries as before. @@ -1095,9 +1096,7 @@ mod tests { /// Whether process `pid` is gone (or a zombie no one has reaped yet). #[cfg(target_os = "linux")] fn gone(pid: &str) -> bool { - let out = Command::new("ps").args(["-o", "stat=", "-p", pid]).output().unwrap(); - let stat = String::from_utf8_lossy(&out.stdout); - stat.trim().is_empty() || stat.trim().starts_with('Z') + pid.parse().map_or(true, |pid| kill::tests::state(pid).is_none_or(|s| s == 'Z')) } #[cfg(target_os = "linux")] diff --git a/xtask/src/deadline/kill.rs b/xtask/src/deadline/kill.rs index d2a461aa075..c7426f346f5 100644 --- a/xtask/src/deadline/kill.rs +++ b/xtask/src/deadline/kill.rs @@ -5,21 +5,25 @@ //! **No signal by a pid that may name another process by now.** A pid read from `/proc` passes to //! another process as soon as its process exits and is reaped, and a parent that ignores `SIGCHLD` //! has its children reaped by the kernel even while it is stopped. So the only process signalled -//! by its pid is the direct child, which xtask hasn't reaped yet. On Linux every other one is held -//! by a pidfd ([`Held`]), opened *before* what makes it ours is read again, and signalled only -//! through it, so if its pid passed to another process in between, the signal fails as "gone" and -//! reaches no one. What makes a process ours: the run's marker in its environment, or a parent -//! that is one of the held processes and hasn't exited (checked through the parent's pidfd after -//! the child's parent pid is read, so that pid can't have passed to another process meanwhile). -//! Where there are no pidfds (Unix other than Linux, a Linux kernel before 5.3), the processes the -//! child started aren't signalled, and the report says they may still run. +//! by its pid is the direct child, which xtask hasn't reaped yet, and only while xtask doesn't +//! ignore `SIGCHLD` itself (inherited from whatever started it; then the kernel reaps xtask's +//! children too, and on Linux the direct child is treated like the others below). On Linux every +//! other one is held by a pidfd ([`Held`]), opened *before* what makes it ours is read again, and +//! signalled only through it, so if its pid passed to another process in between, the signal fails +//! as "gone" and reaches no one. What makes a process ours: the run's marker in its environment, or +//! a parent that is one of the held processes and that its pidfd says hasn't exited (asked after +//! the child's parent pid is read, so that pid can't have passed to another process meanwhile; when +//! it can't be asked, the child isn't trusted). Where there are no pidfds (Unix other than Linux, a +//! Linux kernel before 5.3), only the direct child is killed; under the full `ci` that is cargo, +//! so the test binary it started may keep running, and the report says so. //! -//! **Nothing is left frozen, and nothing waits without a bound.** Every signal's result is kept. A -//! process whose SIGKILL fails is sent it once more, and if that fails too it is sent SIGCONT, so -//! it runs on rather than staying stopped (it was frozen only so it couldn't start more processes -//! while the others were found); the report names it either way, and says when the processes -//! couldn't all be looked for or held (out of file descriptors, say). The direct child (and -//! `taskkill` on Windows) is waited for a bounded time. +//! **Nothing waits without a bound, and a frozen process is continued if it can't be killed.** +//! Every signal's result is kept. A process whose SIGKILL fails is sent it once more, and if that +//! fails too it is sent SIGCONT so that it runs on rather than staying stopped (it was frozen only +//! so it couldn't start more processes while the others were found); the report names it either +//! way, says if SIGCONT failed too, and says when the processes couldn't all be looked at or held +//! (out of file descriptors, say). The direct child (and `taskkill` on Windows) is waited for a +//! bounded time. #[cfg(target_os = "linux")] use std::collections::BTreeSet; @@ -41,14 +45,18 @@ const ROUNDS: usize = 64; /// it is signalled, plus what it started. `None` once it has been reaped: then only processes /// carrying the marker are, never the old pid, which may belong to another process by now. pub(super) fn kill_run(child: Option<&mut Child>, marker: &Marker) -> String { + // whether the direct child is unreaped until xtask waits for it, so its pid is its own #[cfg(target_os = "linux")] - let mut note = kill_all(child.as_ref().map(|c| c.id()), marker, &mut Real); + let own = !sigchld_ignored().unwrap_or(false); + #[cfg(target_os = "linux")] + let mut note = kill_all(child.as_ref().map(|c| c.id()), own, marker, &mut Real); #[cfg(not(target_os = "linux"))] - let mut note = kill_all(child.as_ref().map(|c| c.id()), marker); + let (own, mut note) = (true, kill_all(child.as_ref().map(|c| c.id()), marker)); if let Some(child) = child { - // unreaped until the wait below succeeds: its pid is still its own - let _ = child.kill(); - if wait_for(child, AFTER_KILL).is_none() { + if own { + let _ = child.kill(); + } + if wait_for(child, AFTER_KILL).is_none() && own { note.push_str(&format!("; it was still running {} s after the kill (pid {})", AFTER_KILL.as_secs(), child.id())); } } @@ -67,6 +75,22 @@ fn wait_for(child: &mut Child, limit: Duration) -> Option { } } +/// Whether xtask ignores `SIGCHLD` (so the kernel reaps its children without a wait), from +/// `/proc/self/status`; `None` when that can't be read. +#[cfg(target_os = "linux")] +fn sigchld_ignored() -> Option { + ignores_sigchld(&std::fs::read_to_string("/proc/self/status").ok()?) +} + +/// Whether a `/proc//status` text's `SigIgn` mask holds `SIGCHLD`. +#[cfg(target_os = "linux")] +fn ignores_sigchld(status: &str) -> Option { + let mask = status.lines().find_map(|l| l.strip_prefix("SigIgn:"))?; + let mask = u64::from_str_radix(mask.trim(), 16).ok()?; + let bit = u32::try_from(rustix::process::Signal::CHILD.as_raw()).ok()?.checked_sub(1)?; + Some(mask.checked_shr(bit).is_some_and(|m| m & 1 == 1)) +} + /// What the kill says when it can signal only the direct child. #[cfg_attr(target_os = "windows", allow(dead_code))] fn child_only(root: Option, why: &str) -> String { @@ -78,7 +102,10 @@ fn child_only(root: Option, why: &str) -> String { #[cfg(all(unix, not(target_os = "linux")))] pub(super) fn kill_all(root: Option, _marker: &Marker) -> String { - child_only(root, "this OS has no pidfds, and a bare pid may name another process by the time it is signalled") + child_only( + root, + "this OS has no pidfds, and a bare pid may name another process by the time it is signalled; under cargo, the test binary is one of them", + ) } #[cfg(windows)] @@ -148,10 +175,17 @@ pub(super) enum Hold { Unheld(String), } -/// A look through `/proc`: the process table (pid, parent pid) and the pids whose environment -/// holds the run's marker. +/// A look through `/proc`. #[cfg(target_os = "linux")] -pub(super) type Scan = (Vec<(u32, u32)>, BTreeSet); +#[derive(Default)] +pub(super) struct Scan { + /// The process table: pid, parent pid. + table: Vec<(u32, u32)>, + /// The pids whose environment holds the run's marker. + marked: BTreeSet, + /// The processes that couldn't be looked at, and why. + failed: Vec, +} /// Where the kill looks for processes and how it signals them; tests replace a part. #[cfg(target_os = "linux")] @@ -165,7 +199,7 @@ pub(super) trait Os { hold(pid, entry) } - /// Hold the direct child (unreaped, so its pid is its own). + /// Hold the direct child while it is unreaped, so its pid is its own. fn hold_root(&mut self, pid: u32) -> Held { Held { pid, frozen: false, fd: open_pidfd(pid).ok() } } @@ -174,8 +208,9 @@ pub(super) trait Os { send(held, sig) } - /// Whether the process has exited (`None`: no pidfd to tell, so it's the unreaped child). - fn exited(&mut self, held: &Held) -> Option { + /// Whether the process has exited (`Ok(None)`: no pidfd to ask, so it's the unreaped child; + /// an error when its pidfd can't be asked). + fn exited(&mut self, held: &Held) -> Result, String> { exited(held) } } @@ -187,31 +222,41 @@ pub(super) struct Real; #[cfg(target_os = "linux")] impl Os for Real {} -/// Freeze and kill `root` (unreaped) and what it started (see [`kill_run`]); what was done. +/// Freeze and kill `root` and what it started (see [`kill_run`]); what was done. `own`: `root` is +/// unreaped until xtask waits for it, so its pid is its own; else it is held only by its marker. /// /// Everything found is frozen with SIGSTOP until no new one turns up, a level of the tree a round, /// then killed with SIGKILL, the last found first. Then the failures are dealt with (module docs). #[cfg(target_os = "linux")] -pub(super) fn kill_all(root: Option, marker: &Marker, os: &mut dyn Os) -> String { +pub(super) fn kill_all(root: Option, own: bool, marker: &Marker, os: &mut dyn Os) -> String { if !std::path::Path::new("/proc/self/environ").exists() { return child_only(root, "no /proc to find them in"); } let entry = marker.entry(); let mut end = Ending::default(); - let rounds = freeze(root, &entry, os, &mut end); + if !own && root.is_some() { + end.problems.push("xtask ignores SIGCHLD, so its child's pid was trusted only with the run's marker".to_owned()); + } + let rounds = freeze(root.map(|pid| (pid, own)), &entry, os, &mut end); let kill_failed = kill(os, &end.held); end.problems.extend(thaw(os, &end.held, &kill_failed)); - let mut alive = wait_exited(os, &end.held, &entry); + let mut alive = wait_exited(os, &end.held, &entry, &mut end.problems); // those are told of above alive.retain(|p| !kill_failed.iter().any(|(i, _)| end.held.get(*i).is_some_and(|h| h.pid == *p))); let started = end.held.iter().filter(|h| Some(h.pid) != root).count(); let mut note = summary(root, started); + if let Some(root) = root.filter(|r| !end.held.iter().any(|h| h.pid == *r)) { + note.push_str(&format!("; but pid {root} wasn't signalled: it no longer named the run's process (it may have exited and been reaped)")); + } if rounds == ROUNDS { note.push_str(&format!("; it kept starting processes, so xtask stopped looking after {ROUNDS} rounds")); } if let Some((n, why)) = end.unheld.first().map(|why| (end.unheld.len(), why)) { note.push_str(&format!("; {n} process(es) it started couldn't be held by a pidfd or looked at ({why}), so they weren't signalled")); } + if let Some((n, why)) = end.unseen.first().map(|why| (end.unseen.len(), why)) { + note.push_str(&format!("; {n} process(es) of this user couldn't be looked at ({why}); any of them it started weren't signalled")); + } if !alive.is_empty() { let pids: Vec = alive.iter().map(u32::to_string).collect(); end.problems.push(format!("still alive after the kill: pid {} (they carry {})", pids.join(", "), marker.key)); @@ -231,12 +276,25 @@ struct Ending { problems: Vec, /// Why each process found that couldn't be held wasn't. unheld: Vec, + /// Why each process the scans couldn't look at couldn't be. + unseen: BTreeSet, } -/// Hold and stop `root` and then, a round at a time, every new process found; how many rounds ran. +/// Hold and stop `root` (with whether its pid is its own) and then, a round at a time, every new +/// process found; how many rounds ran. #[cfg(target_os = "linux")] -fn freeze(root: Option, entry: &str, os: &mut dyn Os, end: &mut Ending) -> usize { - let mut fresh: Vec = root.map(|pid| os.hold_root(pid)).into_iter().collect(); +fn freeze(root: Option<(u32, bool)>, entry: &str, os: &mut dyn Os, end: &mut Ending) -> usize { + let mut fresh: Vec = Vec::new(); + match root { + Some((pid, true)) => fresh.push(os.hold_root(pid)), + // reaped by the kernel perhaps, so its pid may be another's: held only as a marked process + Some((pid, false)) => match os.hold(pid, entry) { + Hold::Held(held, _, true) => fresh.push(held), + Hold::Held(..) | Hold::Not => {} + Hold::Unheld(why) => end.unheld.push(why), + }, + None => {} + } // the stopped ones, whose children are looked for, and every pid already dealt with let (mut stopped, mut seen) = (BTreeSet::new(), BTreeSet::from([std::process::id()])); for round in 1..=ROUNDS { @@ -254,15 +312,16 @@ fn freeze(root: Option, entry: &str, os: &mut dyn Os, end: &mut Ending) -> seen.insert(held.pid); end.held.push(held); } - let (table, marked) = match os.scan(entry) { + let scan = match os.scan(entry) { Ok(scan) => scan, Err(e) => { end.problems.push(format!("could not look for the processes it started ({e}), so some may still run")); return round; } }; - let mut found = children_of(&table, &stopped); - found.extend(marked); + end.unseen.extend(scan.failed); + let mut found = children_of(&scan.table, &stopped); + found.extend(scan.marked); found.retain(|p| !seen.contains(p)); for pid in found { match os.hold(pid, entry) { @@ -283,12 +342,13 @@ fn freeze(root: Option, entry: &str, os: &mut dyn Os, end: &mut Ending) -> } /// Whether `ppid`, read from a child's `/proc` after the child was held, is one of the held -/// processes: one that hasn't exited now, so it held that pid when it was read (a pid passes to -/// another process only once its process has exited and been reaped). The direct child, held -/// without a pidfd, is unreaped, so its pid is its own. +/// processes: one whose pidfd says it hasn't exited now, so it held that pid when it was read (a +/// pid passes to another process only once its process has exited and been reaped). The direct +/// child is held without a pidfd only while it is unreaped, so its pid is its own. A pidfd that +/// can't be asked proves nothing. #[cfg(target_os = "linux")] fn has_live_parent(os: &mut dyn Os, held: &[Held], ppid: u32) -> bool { - held.iter().filter(|h| h.pid == ppid).any(|h| os.exited(h) != Some(true)) + held.iter().filter(|h| h.pid == ppid).any(|h| matches!(os.exited(h), Ok(None | Some(false)))) } /// SIGKILL every held process, the last found first, and once more those it failed for; the @@ -333,13 +393,24 @@ fn thaw(os: &mut dyn Os, held: &[Held], failed: &[(usize, String)]) -> Vec Vec { +fn wait_exited(os: &mut dyn Os, held: &[Held], entry: &str, problems: &mut Vec) -> Vec { let until = Instant::now() + AFTER_KILL; loop { - let mut alive: BTreeSet = held.iter().filter(|h| os.exited(h) == Some(false)).map(|h| h.pid).collect(); - alive.extend(os.scan(entry).map(|(_, marked)| marked).unwrap_or_default()); + let mut alive: BTreeSet = held.iter().filter(|h| matches!(os.exited(h), Ok(Some(false)) | Err(_))).map(|h| h.pid).collect(); + let scan = os.scan(entry); + if let Ok(scan) = &scan { + alive.extend(&scan.marked); + } if alive.is_empty() || Instant::now() >= until { + match scan { + Err(e) => problems.push(format!("could not check that they are gone ({e})")), + Ok(scan) if !scan.failed.is_empty() => { + problems.push(format!("could not check that they are gone ({})", scan.failed.join(", "))); + } + Ok(_) => {} + } return alive.into_iter().collect(); } std::thread::sleep(TICK); @@ -377,14 +448,18 @@ fn send(held: &Held, sig: Sig) -> Result<(), Unsent> { } #[cfg(target_os = "linux")] -fn exited(held: &Held) -> Option { +fn exited(held: &Held) -> Result, String> { use rustix::event::{PollFd, PollFlags, Timespec}; - let fd = held.fd.as_ref()?; + let Some(fd) = held.fd.as_ref() else { return Ok(None) }; let mut fds = [PollFd::new(fd, PollFlags::IN)]; // a pidfd is readable once its process has exited let now = Timespec { tv_sec: 0, tv_nsec: 0 }; - rustix::event::poll(&mut fds, Some(&now)).ok()?; - Some(fds.first().is_some_and(|f| !f.revents().is_empty())) + rustix::event::poll(&mut fds, Some(&now)).map_err(|e| format!("poll: {e}"))?; + let revents = fds.first().map_or(PollFlags::empty(), PollFd::revents); + if revents.intersects(PollFlags::ERR | PollFlags::NVAL) { + return Err(format!("poll: {revents:?}")); + } + Ok(Some(revents.contains(PollFlags::IN))) } #[cfg(target_os = "linux")] @@ -421,17 +496,28 @@ pub(super) fn children_of(table: &[(u32, u32)], parents: &BTreeSet) -> BTre /// for a reason other than its exit (out of file descriptors, say). #[cfg(target_os = "linux")] fn proc_scan(entry: &str) -> Result { - let (mut table, mut marked) = (Vec::new(), BTreeSet::new()); - let dir = std::fs::read_dir("/proc").map_err(|e| format!("/proc: {e}"))?; - for pid in dir.filter_map(Result::ok).filter_map(|e| e.file_name().to_str()?.parse::().ok()) { - if let Some((ppid, has)) = about(pid, entry)? { - table.push((pid, ppid)); - if has { - marked.insert(pid); + let mut scan = Scan::default(); + for e in std::fs::read_dir("/proc").map_err(|e| format!("/proc: {e}"))? { + let e = match e { + Ok(e) => e, + Err(e) => { + scan.failed.push(format!("/proc: {e}")); + continue; } + }; + let Some(pid) = e.file_name().to_str().and_then(|n| n.parse::().ok()) else { continue }; + match about(pid, entry) { + Ok(Some((ppid, has))) => { + scan.table.push((pid, ppid)); + if has { + scan.marked.insert(pid); + } + } + Ok(None) => {} + Err(e) => scan.failed.push(e), } } - Ok((table, marked)) + Ok(scan) } /// Whether an error reading a process's `/proc` files means it has gone (or is another user's). @@ -454,11 +540,14 @@ fn about(pid: u32, entry: &str) -> Result, String> { Ok(_) => return Ok(None), Err(e) => return failed(e), } - let stat = match std::fs::read_to_string(format!("/proc/{pid}/stat")) { + // bytes: the command name in it is the process's to choose, and needn't be UTF-8 + let stat = match std::fs::read(format!("/proc/{pid}/stat")) { Ok(s) => s, Err(e) => return failed(e), }; let Some(ppid) = parent_in_stat(&stat) else { return Ok(None) }; + // a process that made itself undumpable (as ssh-agent does) can't have its environment read: + // counted as unmarked, else every kill would report those of the user's session let marked = match std::fs::read(format!("/proc/{pid}/environ")) { Ok(env) => super::has_entry(&env, entry), Err(e) if gone(&e) => false, @@ -470,27 +559,46 @@ fn about(pid: u32, entry: &str) -> Result, String> { /// The parent pid in a `/proc//stat` line: `pid (comm) state ppid …`, where `comm` may hold /// spaces and parentheses. #[cfg_attr(not(target_os = "linux"), allow(dead_code))] -pub(super) fn parent_in_stat(stat: &str) -> Option { - let (_, rest) = stat.rsplit_once(')')?; +pub(super) fn parent_in_stat(stat: &[u8]) -> Option { + let close = stat.iter().rposition(|b| *b == b')')?; + let rest = std::str::from_utf8(stat.get(close.checked_add(1)?..)?).ok()?; rest.split_whitespace().nth(1)?.parse().ok() } /// This user's processes whose environment holds exactly `entry`. #[cfg(all(test, target_os = "linux"))] pub(super) fn marked(entry: &str) -> Vec { - proc_scan(entry).map(|(_, m)| m.into_iter().collect()).unwrap_or_default() + proc_scan(entry).map(|s| s.marked.into_iter().collect()).unwrap_or_default() } #[cfg(test)] -mod tests { +pub(super) mod tests { use super::*; #[test] fn the_parent_is_read_past_any_parenthesis_in_the_command_name() { - assert_eq!(parent_in_stat("42 (sleep) S 7 42 42 0 -1"), Some(7)); - assert_eq!(parent_in_stat("42 (a) b) (c) R 9 1"), Some(9)); - assert_eq!(parent_in_stat("42 (sh) Z"), None); - assert_eq!(parent_in_stat("garbage"), None); + assert_eq!(parent_in_stat(b"42 (sleep) S 7 42 42 0 -1"), Some(7)); + assert_eq!(parent_in_stat(b"42 (a) b) (c) R 9 1"), Some(9)); + assert_eq!(parent_in_stat(b"42 (\xff\xfe x) S 8 1"), Some(8), "a command name that isn't UTF-8"); + assert_eq!(parent_in_stat(b"42 (sh) Z"), None); + assert_eq!(parent_in_stat(b"garbage"), None); + } + + /// The `SigIgn` mask read for `SIGCHLD`, from a real process that ignores it (an ignored + /// signal stays ignored across exec) and one that doesn't. + #[cfg(target_os = "linux")] + #[test] + fn a_process_that_ignores_sigchld_is_told_from_one_that_does_not() { + let status = |trap: &str| { + // bash: dash keeps SIGCHLD for itself and doesn't ignore it for `trap ''` + let out = std::process::Command::new("bash").args(["-c", &format!("{trap} exec cat /proc/self/status")]).output().unwrap(); + ignores_sigchld(&String::from_utf8_lossy(&out.stdout)) + }; + assert_eq!(status("trap '' CHLD;"), Some(true)); + assert_eq!(status(""), Some(false)); + assert_eq!(ignores_sigchld("Name: x\nSigIgn:\t0000000000010000\n"), Some(true), "SIGCHLD is 17 on Linux"); + assert_eq!(ignores_sigchld("SigIgn: zz"), None); + assert_eq!(ignores_sigchld(""), None); } #[cfg(target_os = "linux")] @@ -505,20 +613,28 @@ mod tests { /// The state letter of a process, or `None` once it is gone. #[cfg(target_os = "linux")] - fn state(pid: u32) -> Option { + pub(in crate::deadline) fn state(pid: u32) -> Option { let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; stat.rsplit_once(')')?.1.split_whitespace().next()?.chars().next() } /// Kills (through a pidfd) and reaps what a test started when it drops, also when it fails. #[cfg(target_os = "linux")] - #[derive(Default)] struct Cleanup { children: Vec, others: Vec, dir: Option, } + #[cfg(target_os = "linux")] + impl Cleanup { + /// Before the test starts anything: these tests need pidfds (Linux 5.3). + fn new() -> Self { + assert!(open_pidfd(std::process::id()).is_ok(), "this kernel has pidfds (Linux 5.3)"); + Self { children: Vec::new(), others: Vec::new(), dir: None } + } + } + #[cfg(target_os = "linux")] impl Drop for Cleanup { fn drop(&mut self) { @@ -558,8 +674,9 @@ mod tests { std::thread::sleep(TICK); }; let held = Real.hold_root(pid); - assert!(held.fd.is_some(), "this kernel has pidfds (Linux 5.3)"); + let fd = held.fd.is_some(); cleanup.others.push(held); + assert!(fd, "the grandchild is held by a pidfd"); (root, marker, pid) } @@ -595,10 +712,10 @@ mod tests { #[cfg(target_os = "linux")] #[test] fn a_process_whose_kill_fails_is_not_left_stopped() { - let mut cleanup = Cleanup::default(); + let mut cleanup = Cleanup::new(); let (root, marker, grandchild) = marked_sh("sleep 300 & echo $! > PIDFILE; wait", "thaw", &mut cleanup); let mut os = KillFails { root, refused: Vec::new() }; - let note = kill_all(Some(root), &marker, &mut os); + let note = kill_all(Some(root), true, &marker, &mut os); let s = state(grandchild); assert!(s.is_some_and(|s| s != 'T'), "the grandchild was continued, not left stopped: state {s:?}"); assert_eq!(os.refused.iter().filter(|p| **p == grandchild).count(), 2, "tried twice: {:?}", os.refused); @@ -620,9 +737,9 @@ mod tests { #[cfg(target_os = "linux")] impl Os for PidReused { fn scan(&mut self, entry: &str) -> Result { - let (table, mut marked) = proc_scan(entry)?; - marked.extend(self.decoy.take()); - Ok((table, marked)) + let mut scan = proc_scan(entry)?; + scan.marked.extend(self.decoy.take()); + Ok(scan) } } @@ -632,10 +749,10 @@ mod tests { #[cfg(target_os = "linux")] #[test] fn a_pid_that_passed_to_another_process_is_not_signalled() { - let mut cleanup = Cleanup::default(); + let mut cleanup = Cleanup::new(); let decoy = decoy(&mut cleanup); let (root, marker, grandchild) = marked_sh("sleep 300 & echo $! > PIDFILE; wait", "reused", &mut cleanup); - let note = kill_all(Some(root), &marker, &mut PidReused { decoy: Some(decoy) }); + let note = kill_all(Some(root), true, &marker, &mut PidReused { decoy: Some(decoy) }); let s = state(decoy); assert!(s.is_some_and(|s| s != 'T' && s != 'Z'), "the decoy runs on: state {s:?}"); assert!(state(grandchild).is_none_or(|s| s == 'Z'), "the run's own processes were killed"); @@ -643,22 +760,31 @@ mod tests { } /// The real OS, except that the first scan also reports `decoy` as a child of `parent`, as if - /// `parent` (held, then exited) had been reaped and its pid passed to the decoy's parent. + /// `parent` (held, then exited) had been reaped and its pid passed to the decoy's parent; and, + /// with `poll_fails`, no pidfd can be asked whether its process has exited. #[cfg(target_os = "linux")] struct ParentReused { decoy: u32, parent: u32, once: bool, + poll_fails: bool, } #[cfg(target_os = "linux")] impl Os for ParentReused { fn scan(&mut self, entry: &str) -> Result { - let (mut table, marked) = proc_scan(entry)?; + let mut scan = proc_scan(entry)?; if std::mem::take(&mut self.once) { - table.push((self.decoy, self.parent)); + scan.table.push((self.decoy, self.parent)); } - Ok((table, marked)) + Ok(scan) + } + + fn exited(&mut self, held: &Held) -> Result, String> { + if self.poll_fails && held.fd.is_some() { + return Err("poll refused by the test".to_owned()); + } + exited(held) } fn hold(&mut self, pid: u32, entry: &str) -> Hold { @@ -675,7 +801,7 @@ mod tests { #[cfg(target_os = "linux")] #[test] fn the_children_of_a_parent_that_exited_are_not_trusted() { - let mut cleanup = Cleanup::default(); + let mut cleanup = Cleanup::new(); let decoy = decoy(&mut cleanup); // a direct child that has exited but isn't reaped: a zombie, held by its pidfd let mut c = std::process::Command::new("true"); @@ -687,26 +813,65 @@ mod tests { assert!(Instant::now() < until, "`true` didn't exit"); std::thread::sleep(TICK); } - let note = kill_all(Some(root), &marker, &mut ParentReused { decoy, parent: root, once: true }); + let note = kill_all(Some(root), true, &marker, &mut ParentReused { decoy, parent: root, once: true, poll_fails: false }); let s = state(decoy); assert!(s.is_some_and(|s| s != 'T' && s != 'Z'), "the decoy runs on: state {s:?}"); assert!(note.starts_with("killed it; it had started no other process"), "{note}"); } + /// A parent whose pidfd can't be asked whether it has exited vouches for no child: the poll + /// failing proves nothing (its own marked processes are still found by the marker). + #[cfg(target_os = "linux")] + #[test] + fn a_parent_that_cannot_be_asked_vouches_for_no_child() { + let mut cleanup = Cleanup::new(); + let decoy = decoy(&mut cleanup); + let (root, marker, grandchild) = marked_sh("sleep 300 & echo $! > PIDFILE; wait", "poll", &mut cleanup); + // the root's pidfd is the one asked: held through the marker path, it has one + let mut os = ParentReused { decoy, parent: root, once: true, poll_fails: true }; + let note = kill_all(Some(root), true, &marker, &mut os); + let s = state(decoy); + assert!(s.is_some_and(|s| s != 'T' && s != 'Z'), "the decoy runs on: state {s:?}"); + let until = Instant::now() + Duration::from_secs(5); + while state(grandchild).is_some_and(|s| s != 'Z') && Instant::now() < until { + std::thread::sleep(TICK); + } + assert!(state(grandchild).is_none_or(|s| s == 'Z'), "the marked grandchild was killed: {note}"); + } + + /// When xtask ignores SIGCHLD the kernel may have reaped the direct child, so its pid is + /// trusted only with the run's marker: a pid that names an unmarked process is left alone. + #[cfg(target_os = "linux")] + #[test] + fn a_child_that_may_have_been_reaped_is_trusted_only_with_the_marker() { + let mut cleanup = Cleanup::new(); + let decoy = decoy(&mut cleanup); + let note = kill_all(Some(decoy), false, &Marker::new(), &mut Real); + let s = state(decoy); + assert!(s.is_some_and(|s| s != 'T' && s != 'Z'), "an unmarked process under the child's pid runs on: state {s:?}"); + assert!(note.contains("xtask ignores SIGCHLD"), "{note}"); + // and a marked child is still killed + let (root, marker, grandchild) = marked_sh("sleep 300 & echo $! > PIDFILE; wait", "sigign", &mut cleanup); + let note = kill_all(Some(root), false, &marker, &mut Real); + assert!(note.starts_with("killed it and the 1 process(es) it started"), "{note}"); + assert!(state(grandchild).is_none_or(|s| s == 'Z')); + } + /// A pidfd refers to its process alone: once that process has exited and been reaped, a /// signal through it fails as gone, whatever holds the pid now. #[cfg(target_os = "linux")] #[test] fn a_held_process_that_was_reaped_gets_no_signal() { - let mut cleanup = Cleanup::default(); + let mut cleanup = Cleanup::new(); let pid = decoy(&mut cleanup); let held = Real.hold_root(pid); - assert!(held.fd.is_some(), "this kernel has pidfds (Linux 5.3)"); - assert_eq!(exited(&held), Some(false)); - let mut c = cleanup.children.pop().unwrap(); - c.kill().unwrap(); - c.wait().unwrap(); - assert_eq!(exited(&held), Some(true)); + assert!(held.fd.is_some(), "held by a pidfd"); + assert_eq!(exited(&held), Ok(Some(false))); + if let Some(c) = cleanup.children.last_mut() { + c.kill().unwrap(); + c.wait().unwrap(); + } + assert_eq!(exited(&held), Ok(Some(true))); assert_eq!(send(&held, Sig::Stop), Err(Unsent::Gone)); } } From 743f33195ab2a0e9f93e8f473939ea852550f8fd Mon Sep 17 00:00:00 2001 From: THEtheChad <880190+THEtheChad@users.noreply.github.com> Date: Tue, 3 Nov 2026 22:20:07 -0600 Subject: [PATCH 21/40] fix(xtask): #3060 the CI-slot wait never sleeps past its limit Each poll sleeps at most what is left of the wait, and the limit is checked before each try, so a limit shorter than the poll interval returns on time and a slot freed after the limit isn't taken. Co-Authored-By: Claude Opus 5.5 --- xtask/src/ci_lock.rs | 36 ++++++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/xtask/src/ci_lock.rs b/xtask/src/ci_lock.rs index 0042285cd53..9d18512cbb2 100644 --- a/xtask/src/ci_lock.rs +++ b/xtask/src/ci_lock.rs @@ -135,14 +135,16 @@ fn wait_for_slot(dir: &Path, slots: usize, owner: &str, wait: Option, eprintln!(" running: {h}"); } loop { - std::thread::sleep(poll); + // never past the limit: a sleep ends by it, and the limit is checked before each try, so + // a slot freed after it isn't taken + std::thread::sleep(wait.map_or(poll, |w| poll.min(w.saturating_sub(waiting.elapsed())))); + if let Some(wait) = wait.filter(|w| waiting.elapsed() >= *w) { + return Err(gave_up(wait, &holders(dir, slots))); + } if let Some(held) = try_acquire(dir, slots, owner)? { eprintln!("=== ci: waited {:.0} s for a CI slot ===", waiting.elapsed().as_secs_f64()); return Ok(Some(held)); } - if let Some(wait) = wait.filter(|w| waiting.elapsed() >= *w) { - return Err(gave_up(wait, &holders(dir, slots))); - } } } @@ -206,6 +208,32 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn a_limit_shorter_than_the_poll_interval_is_kept() { + let dir = scratch("short-limit"); + let _held = try_acquire(&dir, 1, "first").unwrap().expect("free slot"); + let t = Instant::now(); + let err = wait_for_slot(&dir, 1, "second", Some(Duration::from_millis(100)), Duration::from_secs(5)).err().expect("gave up"); + assert!(t.elapsed() >= Duration::from_millis(100) && t.elapsed() < Duration::from_secs(2), "{:?}", t.elapsed()); + assert!(err.contains("gave up after waiting 100 ms"), "{err}"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_slot_freed_after_the_limit_is_not_taken() { + let dir = scratch("late"); + let held = try_acquire(&dir, 1, "first").unwrap().expect("free slot"); + // freed after the 100 ms limit and before the 1 s poll would have looked again + let release = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(400)); + drop(held); + }); + let got = wait_for_slot(&dir, 1, "second", Some(Duration::from_millis(100)), Duration::from_secs(1)); + assert!(got.is_err_and(|e| e.contains("gave up")), "the limit ended the wait first"); + release.join().unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn giving_up_names_an_unrecorded_holder_too() { assert!( From f9dbd8166d4542932dfa7ec812ba9d245ccea1f3 Mon Sep 17 00:00:00 2001 From: THEtheChad <880190+THEtheChad@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:57:51 -0600 Subject: [PATCH 22/40] docs(agents): #3061 how to run tests, and what to do when ci fails on another test AGENTS.md (which CLAUDE.md includes) gets a "Running tests" section: run tests through `cargo xtask test` (with --keep-going to see every failing binary) or `cargo xtask ci --quick`, never plain `cargo test --workspace`; when `ci` fails on a test the change doesn't touch, rerun only that package's tests, report an intermittent one in the PR with its issue, and cover the binaries and steps `ci` didn't reach without widening the run; never leave a test run going after the session, and wrap long runs in `timeout`. The parallel-agents bullet notes that test runs share the machine's memory. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 8d0ca31a605..dcef48e79f2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -175,10 +175,27 @@ of it. - Text boxes use `crates/ui-egui/src/widgets/text_field.rs` (`TextField`), not `egui::TextEdit`: it gives every field the Cut / Copy / Paste / Select All menu, Esc restoring the text, and reports how an edit ended. Give each a widget id that is unique on screen. Older fields still on `TextEdit` move over as they are touched. -- Parallel agents: separate git worktrees and `CARGO_TARGET_DIR=target/agent-`; each agent uses its **own control port** (pick one in 18000–19999, never the default 7980) and its own scratch subfolder (`//`) — never `rm -rf` shared paths; delete your target dir when done (disk is shared); keep every `Cargo.toml` valid at all times (the `crates/*` glob means one broken manifest breaks everyone). +- Parallel agents: separate git worktrees and `CARGO_TARGET_DIR=target/agent-`; each agent uses its **own control port** (pick one in 18000–19999, never the default 7980) and its own scratch subfolder (`//`) — never `rm -rf` shared paths; delete your target dir when done (disk is shared); keep every `Cargo.toml` valid at all times (the `crates/*` glob means one broken manifest breaks everyone). Test runs share the machine's memory too (the ui-egui tests alone take several GB): run them through `cargo xtask test` or `ci`, whose slot lets one run at a time per machine (below). - Test corpora: `cargo xtask corpus --download` into `corpus/` (gitignored, CC0 only). Never commit media. - Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`. +## Running tests +- **Run tests through xtask:** `cargo xtask test [-p PKG]… [-- FILTER]` (`--keep-going` runs every test binary and + names each that fails, instead of stopping at the first) or `cargo xtask ci --quick`. Both take the machine's CI slot + and `ci`'s RAM-aware caps; README → Quick start describes them and the settings that change them. Plain + `cargo test -p PKG` on a small crate is fine while you iterate. +- **Never run plain `cargo test --workspace`**, with or without `--no-fail-fast`. It takes no CI slot, so it runs on + top of every other agent's tests, and gets none of `ci`'s caps (`.cargo/config.toml` only limits it to 4 tests at + once in each binary). +- **When `ci` fails on a test your change doesn't touch,** rerun only that package's tests: `cargo xtask test -p PKG` + (`-- TEST_NAME` narrows it to the one test). If it's intermittent, or fails without your change too, say so in the + PR and link its issue, or file one. Don't widen the run or bypass xtask to get past it. `ci` stops at the first + failing binary, so cover what it didn't reach: `cargo xtask test --keep-going -p …` for the packages you changed and + those that depend on them, and `cargo xtask parity`, `layers`, `assets` and `wasm` for the steps after `test`. +- **Nothing outlives your session:** never leave a test run going in the background when you finish, and wrap a long + run in `timeout` (`timeout 60m cargo xtask test -p …`). Before you stop, check that no `cargo` or test process you + started is still running. + ## Testing & performance (do this often) - Unit/property tests next to the code; end-to-end tests drive real binaries (`crates/mcp/tests/e2e.rs`, `apps/lightcraft-cli/tests/`). New features need at least one test that would fail without them. From dc58e6c3bd5809a4c7f77be1b35db1612037f8c7 Mon Sep 17 00:00:00 2001 From: THEtheChad <880190+THEtheChad@users.noreply.github.com> Date: Tue, 3 Nov 2026 22:20:07 -0600 Subject: [PATCH 23/40] fix(xtask): #3060 a stalled output reader can't hold up the clock; no output after the run - pump writes the output outside the lock watch checks the clock under, so a reader of xtask's output that stops reading blocks only that thread, never the timeout. - Once watch returns, the readers drop what a leftover process still writes (they keep reading, so it never blocks on the pipe) instead of forwarding it into later binaries and steps; the run notes it. - Only the first `running N tests` line after each Running / Doc-tests line restarts the per-binary clock, so a test's own output can't keep a hung binary alive. - A timed-out binary's --list gets the run's arguments after `--` (its filters); the heif step passes its filter there. - Under nextest, a set LIGHTCRAFT_TEST_BINARY_TIMEOUT is noted as not applying (nextest's slow-timeout does), and the docs say so. Co-Authored-By: Claude Opus 5.5 --- .config/nextest.toml | 3 +- README.md | 3 +- docs/architecture.md | 5 +- xtask/src/ci.rs | 7 +- xtask/src/deadline.rs | 335 ++++++++++++++++++++++++++++++++++-------- 5 files changed, 286 insertions(+), 67 deletions(-) diff --git a/.config/nextest.toml b/.config/nextest.toml index 951b5bb5279..6bf46665327 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -4,5 +4,6 @@ [profile.default] test-threads = 4 # A test still running after 30 minutes is killed (`cargo xtask` gives each test binary under -# `cargo test` the same limit, LIGHTCRAFT_TEST_BINARY_TIMEOUT, #3060). +# `cargo test` the same limit, LIGHTCRAFT_TEST_BINARY_TIMEOUT, #3060). That variable doesn't change +# this one (`0` included): add a profile without terminate-after and pick it with NEXTEST_PROFILE. slow-timeout = { period = "60s", terminate-after = 30 } diff --git a/README.md b/README.md index ab03d976cb6..c3489cf4a8b 100644 --- a/README.md +++ b/README.md @@ -425,7 +425,8 @@ processes it started (on Linux found by an environment variable they inherit, so their parent too, unless they cleared their environment; on macOS and the BSDs only the process xtask started is killed, which under the full `ci` is cargo, so a hung test binary may keep running), and the run reports it as `timed out after 30 min` with the tests still running and those that never reported a result. Under `LIGHTCRAFT_NEXTEST=1`, `.config/nextest.toml` kills a -test after 30 minutes instead. After a timeout, `ci` skips its GPU probe and translation gaps report. +test after 30 minutes instead, whatever `LIGHTCRAFT_TEST_BINARY_TIMEOUT` says (`0` included; a +profile there without `terminate-after`, picked with `NEXTEST_PROFILE`, runs without it). After a timeout, `ci` skips its GPU probe and translation gaps report. CI defaults to line-table debug information and one build job per 1.5 GB of RAM available when it starts (at most one per CPU; 4 if memory can't be read), so an diff --git a/docs/architecture.md b/docs/architecture.md index 6575372d5b0..1467daa0a30 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -84,7 +84,7 @@ first. What these runs wait on after the build is bounded (`xtask/src/deadline.rs`, #3060). Stable libtest has no per-test timeout, so each test binary gets `LIGHTCRAFT_TEST_BINARY_TIMEOUT` minutes (default 30; `0` for none): timed from its start when xtask runs it (`test::run_binary`), and from cargo's `Running` / -`Doc-tests` line for it, and again from its own `running N tests` line, when `cargo test` runs it (the +`Doc-tests` line for it, and again from its own first `running N tests` line, when `cargo test` runs it (the full `ci`'s test and HEIF steps; the build before isn't bounded; cargo runs with `CARGO_TERM_QUIET=false` and without `-q` so it prints those lines). The output streams through and is read for libtest's lines, keeping a bounded amount. On timeout the binary and the processes it started @@ -101,7 +101,7 @@ still reaches it. The run reports `timed out after N min: `, what the kill found, the tests still running (libtest's "has been running for over 60 seconds" warnings, or the test a single-threaded run started) and those that never reported a result (`--list`, itself bounded in time and size). Under nextest, `.config/nextest.toml`'s `slow-timeout` kills a test -after 30 minutes instead. The wait for the CI slot gives up after `LIGHTCRAFT_CI_LOCK_WAIT` minutes +after 30 minutes instead, whatever `LIGHTCRAFT_TEST_BINARY_TIMEOUT` says (xtask notes that when it is set). The wait for the CI slot gives up after `LIGHTCRAFT_CI_LOCK_WAIT` minutes (default 120, several full runs; `0` for no limit) with an error naming the run that holds it. Outside `ci`, `.cargo/config.toml`'s `[env]` limits plain `cargo test` to 4 tests at once per test @@ -128,6 +128,7 @@ the `lightcraft-gpu` tests once per backend with a hardware adapter (`LIGHTCRAFT | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | Quality gates: a test run's output is forwarded outside the lock its clock is checked under, and not after the run ends; only a binary's first `running N tests` line restarts its clock; the slot wait never sleeps past its limit | | 2026-11-03 | minor | Quality gates: a timed-out test run's processes are signalled through pidfds on Linux (never a reused pid; without pidfds only xtask's own child is killed), and one that can't be killed is continued rather than left stopped | | 2026-10-26 | minor | Quality gates: each test binary's run (`LIGHTCRAFT_TEST_BINARY_TIMEOUT`) and the wait for the CI slot (`LIGHTCRAFT_CI_LOCK_WAIT`) have a time limit | | 2026-10-26 | minor | Quality gates: plain `cargo test` (and `cargo nextest run`) runs at most 4 tests at once; xtask tells that default from a caller's `RUST_TEST_THREADS` | diff --git a/xtask/src/ci.rs b/xtask/src/ci.rs index 69b314d5ebb..ef2414ad9e2 100644 --- a/xtask/src/ci.rs +++ b/xtask/src/ci.rs @@ -88,6 +88,8 @@ pub(crate) fn nextest() -> bool { .is_ok_and(|s| s.success()); if !found { eprintln!("note: LIGHTCRAFT_NEXTEST=1 but cargo-nextest is not installed, so the tests run under cargo test (cargo install cargo-nextest --locked)"); + } else if let Some(note) = deadline::nextest_note(std::env::var_os(deadline::TEST_BINARY_TIMEOUT_ENV).as_deref()) { + eprintln!("{note}"); } found }) @@ -248,8 +250,9 @@ pub(crate) fn cmd_ci(args: &[&str]) -> Result<(), String> { c.args(["clippy", "-p", "lightcraft-codecs", "--features", "heif", "--all-targets", "--", "-D", "warnings"]); run(c, "cargo clippy -p lightcraft-codecs --features heif --all-targets -- -D warnings")?; test(tests(&with_test_targets(&["-p", "lightcraft-codecs", "--features", "lightcraft-codecs/heif"])), "heif")?; - // the engine's HEIC import test, with the decoder (the workspace run checks the error) - test(tests(&["-p", "lightcraft-engine", "--lib", "--features", "lightcraft-codecs/heif", "heic"]), "heif") + // the engine's HEIC import test, with the decoder (the workspace run checks the error); + // the filter after `--`, so a timeout's `--list` keeps to the tests it selects + test(tests(&["-p", "lightcraft-engine", "--lib", "--features", "lightcraft-codecs/heif", "--", "heic"]), "heif") }), ), ( diff --git a/xtask/src/deadline.rs b/xtask/src/deadline.rs index d88b3ffc1b3..e1f18fedf8c 100644 --- a/xtask/src/deadline.rs +++ b/xtask/src/deadline.rs @@ -10,10 +10,11 @@ //! timed from its start. //! - A `cargo test` run ([`run_cargo_tests`]: the full `ci`'s test and heif steps, doctests) is timed //! per test binary, from the `Running` (or `Doc-tests`) line cargo prints as it starts each one, -//! and again from the binary's own `running N tests` line; the build before the first one isn't -//! bounded. Cargo runs loud for this (`CARGO_TERM_QUIET=false`, no `-q`): a quiet cargo prints no +//! and again from the binary's own first `running N tests` line (later ones are a test's own +//! output); the build before the first one isn't bounded. Cargo runs loud for this (`CARGO_TERM_QUIET=false`, no `-q`): a quiet cargo prints no //! `Running` lines. Under `cargo nextest run` (no such lines) nextest's own `slow-timeout` in -//! `.config/nextest.toml` ends a hung test instead. +//! `.config/nextest.toml` ends a hung test instead, whatever [`TEST_BINARY_TIMEOUT_ENV`] says +//! ([`nextest_note`]). //! //! The output streams through as it arrives, and is read on the way for libtest's lines: `running N //! tests`, `test NAME ... ok` as each test finishes (or `test NAME ... ` as it starts, when one runs @@ -115,6 +116,19 @@ pub fn test_binary_timeout() -> Result, String> { minutes_from_env(TEST_BINARY_TIMEOUT_ENV, DEFAULT_TEST_BINARY_TIMEOUT_MIN) } +/// What to say when the tests run under `cargo nextest run` and [`TEST_BINARY_TIMEOUT_ENV`] is +/// set: nextest prints no `Running` lines for xtask's clock, so its own `slow-timeout` +/// (`.config/nextest.toml`, 30 minutes per test) applies instead, whatever the variable says (`0` +/// included). `None` when the variable isn't set. +pub fn nextest_note(value: Option<&std::ffi::OsStr>) -> Option { + let value = value.filter(|v| !v.is_empty())?; + Some(format!( + "note: {TEST_BINARY_TIMEOUT_ENV}={} doesn't apply under cargo nextest: .config/nextest.toml's slow-timeout ends a test \ + after 30 minutes instead (a profile there without terminate-after, chosen with NEXTEST_PROFILE, runs without it)", + value.to_string_lossy() + )) +} + /// `30 min`, `1.5 min`, `20 s`, `1.2 s`, `300 ms`: a limit as the reports show it. pub fn show(limit: Duration) -> String { let secs = limit.as_secs_f64(); @@ -292,6 +306,9 @@ pub struct Progress { pub active: Option, /// The unfinished last line of stdout: `test NAME ... ` while a single-threaded run runs NAME. pub pending: String, + /// A `running N tests` line counted for the clock since cargo's last `Running` / `Doc-tests` + /// line (or since the start): later ones are a test's own output and don't restart it. + pub header_seen: bool, } impl Progress { @@ -316,6 +333,13 @@ impl Progress { if let (Some(n), Some("test" | "tests"), None) = (words.next().and_then(|n| n.parse().ok()), words.next(), words.next()) { self.reset(); self.total = Some(n); + // one per binary restarts the clock: uncaptured test output can print the same + // line, and must not keep a hung binary alive. The binary's header can be read + // before cargo's `Running` line for it (stdout and stderr are read apart); then + // that `Running` line restarts the clock instead. + if std::mem::replace(&mut self.header_seen, true) { + return Event::Other; + } return Event::Tests; } return Event::Other; @@ -355,6 +379,7 @@ impl Progress { fn start_binary(&mut self, name: String, exe: Option) { self.binary = Some(name); self.exe = exe; + self.header_seen = false; } fn reset(&mut self) { @@ -385,8 +410,8 @@ impl Progress { pub enum Clock { /// When the process starts: a test binary run directly. Start, - /// At each test binary cargo starts (its `Running` / `Doc-tests` line, and its own `running N - /// tests` line): the limit is per binary, and the build before the first isn't bounded. + /// At each test binary cargo starts (its `Running` / `Doc-tests` line, and its own first `running + /// N tests` line): the limit is per binary, and the build before the first isn't bounded. EachBinary, } @@ -473,6 +498,9 @@ pub struct Watched { pub ended: Ended, pub stdout: String, pub stderr_tail: Vec, + /// A process the run started still held its output open [`DRAIN`] after the run ended (one + /// that outlived it); what that process writes from then on is read and dropped, not shown. + pub held_open: bool, } struct Watch { @@ -483,17 +511,51 @@ struct Watch { stderr_tail: std::collections::VecDeque, } +/// Where a streamed run's output goes (`true`: stdout): xtask's own stdout and stderr ([`stdio`]), +/// or a test's writer. +type Sink = Arc; + +/// xtask's stdout and stderr, flushed after each chunk. +fn stdio() -> Sink { + Arc::new(|is_stdout, chunk| { + if is_stdout { + let mut out = std::io::stdout().lock(); + let _ = out.write_all(chunk).and_then(|()| out.flush()); + } else { + let mut err = std::io::stderr().lock(); + let _ = err.write_all(chunk).and_then(|()| err.flush()); + } + }) +} + +/// What a watched run's output readers share with [`watch`]. +struct Shared { + state: Mutex, + sink: Sink, + /// Set once `watch` returns: from then on the readers drop what they read (see [`pump`]). + closed: AtomicBool, +} + /// Run `cmd` with its output streamed through (or captured) and read for libtest's lines, until it /// exits or `limit` runs out (timed as `clock` says); then kill it and every process it started. -pub fn watch(mut cmd: Command, limit: Duration, clock: Clock, output: Output) -> Result { +pub fn watch(cmd: Command, limit: Duration, clock: Clock, output: Output) -> Result { + watch_into(cmd, limit, clock, output, stdio(), DRAIN) +} + +/// [`watch`], streaming to `sink` and waiting `drain` for the output pipes to close after the run. +fn watch_into(mut cmd: Command, limit: Duration, clock: Clock, output: Output, sink: Sink, drain: Duration) -> Result { cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); let (mut child, marker) = spawn_marked(&mut cmd).map_err(|e| format!("failed to start: {e}"))?; - let state = Arc::new(Mutex::new(Watch { - progress: Progress::default(), - since: (clock == Clock::Start).then(Instant::now), - stdout: Vec::new(), - stderr_tail: std::collections::VecDeque::new(), - })); + let shared = Arc::new(Shared { + state: Mutex::new(Watch { + progress: Progress::default(), + since: (clock == Clock::Start).then(Instant::now), + stdout: Vec::new(), + stderr_tail: std::collections::VecDeque::new(), + }), + sink, + closed: AtomicBool::new(false), + }); let (done_tx, done_rx) = mpsc::channel(); let mut readers = 0; let pipes: [(Option>, bool); 2] = [ @@ -502,58 +564,64 @@ pub fn watch(mut cmd: Command, limit: Duration, clock: Clock, output: Output) -> ]; for (pipe, is_stdout) in pipes { let Some(pipe) = pipe else { continue }; - let (state, done) = (Arc::clone(&state), done_tx.clone()); + let (reader, done) = (Arc::clone(&shared), done_tx.clone()); let spawned = std::thread::Builder::new().name("xtask-output".into()).spawn(move || { - pump(pipe, is_stdout, clock, output, &state); + pump(pipe, is_stdout, clock, output, &reader); let _ = done.send(()); }); if let Err(e) = spawned { + shared.closed.store(true, Ordering::Release); kill_run(Some(&mut child), &marker); return Err(format!("could not start a thread to read its output: {e}")); } readers += 1; } drop(done_tx); - let drain = |readers: usize| { - let until = Instant::now() + DRAIN; - for _ in 0..readers { - if done_rx.recv_timeout(until.saturating_duration_since(Instant::now())).is_err() { - break; - } - } + // Whether every reader saw its pipe close within `drain`. A process the run started that + // outlives it may hold a pipe open longer: past `drain` the readers stop forwarding (they + // keep reading, so that process never blocks on a full pipe), and later binaries' and steps' + // output isn't interleaved with its. + let drained = |readers: usize| { + let until = Instant::now() + drain; + let closed = (0..readers).all(|_| done_rx.recv_timeout(until.saturating_duration_since(Instant::now())).is_ok()); + shared.closed.store(true, Ordering::Release); + closed }; - let finish = |ended: Ended| { - let mut w = lock(&state); + let finish = |ended: Ended, held_open: bool| { + let mut w = lock(&shared.state); let stdout = String::from_utf8_lossy(&std::mem::take(&mut w.stdout)).into_owned(); - Watched { ended, stdout, stderr_tail: w.stderr_tail.drain(..).collect() } + Watched { ended, stdout, stderr_tail: w.stderr_tail.drain(..).collect(), held_open } }; loop { match child.try_wait() { Ok(Some(status)) => { - drain(readers); - return Ok(finish(Ended::Exited(status))); + let held_open = !drained(readers); + return Ok(finish(Ended::Exited(status), held_open)); } Ok(None) => {} Err(e) => { + shared.closed.store(true, Ordering::Release); kill_run(Some(&mut child), &marker); return Err(format!("waiting for it failed: {e}")); } } - if lock(&state).since.is_some_and(|since| since.elapsed() >= limit) { + if lock(&shared.state).since.is_some_and(|since| since.elapsed() >= limit) { TIMED_OUT.store(true, Ordering::Relaxed); // not reaped yet (try_wait said it runs): its pid is still its own let killed = kill_run(Some(&mut child), &marker); - drain(readers); - let progress = Box::new(lock(&state).progress.clone()); - return Ok(finish(Ended::TimedOut(progress, killed))); + let held_open = !drained(readers); + let progress = Box::new(lock(&shared.state).progress.clone()); + return Ok(finish(Ended::TimedOut(progress, killed), held_open)); } std::thread::sleep(TICK); } } -/// Copy `pipe` to xtask's stdout or stderr as it arrives (or keep it, bounded), feeding whole lines -/// to the progress. -fn pump(mut pipe: Box, is_stdout: bool, clock: Clock, output: Output, state: &Mutex) { +/// Copy `pipe` to the sink as it arrives (or keep it, bounded), feeding whole lines to the +/// progress. The sink is written outside the lock: a reader of xtask's output that stalls blocks +/// only this thread (and, through the pipe, the run), never [`watch`]'s check of the clock. Once +/// `watch` has returned what is read is dropped. +fn pump(mut pipe: Box, is_stdout: bool, clock: Clock, output: Output, shared: &Shared) { let mut buf = [0u8; 8192]; let mut lines = Lines::default(); loop { @@ -563,41 +631,43 @@ fn pump(mut pipe: Box, is_stdout: bool, clock: Clock, output: O Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, Err(_) => break, }; + if shared.closed.load(Ordering::Acquire) { + continue; + } let chunk = buf.get(..n).unwrap_or_default(); - let mut watch = lock(state); - match (output, is_stdout) { - (Output::Stream, true) => { - let mut out = std::io::stdout().lock(); - let _ = out.write_all(chunk).and_then(|()| out.flush()); - } - (Output::Stream, false) => { - let mut err = std::io::stderr().lock(); - let _ = err.write_all(chunk).and_then(|()| err.flush()); - } - (Output::Capture, true) => { + { + let mut watch = lock(&shared.state); + if output == Output::Capture && is_stdout { let room = CAPTURE_MAX.saturating_sub(watch.stdout.len()); watch.stdout.extend_from_slice(chunk.get(..room.min(chunk.len())).unwrap_or_default()); } - (Output::Capture, false) => {} - } - lines.feed(chunk, |line| { - let event = watch.progress.line(line); - if clock == Clock::EachBinary && event != Event::Other { - watch.since = Some(Instant::now()); - } - if output == Output::Capture && !is_stdout { - if watch.stderr_tail.len() >= STDERR_TAIL { - watch.stderr_tail.pop_front(); + lines.feed(chunk, |line| { + let event = watch.progress.line(line); + if clock == Clock::EachBinary && event != Event::Other { + watch.since = Some(Instant::now()); } - watch.stderr_tail.push_back(line.trim_end().to_owned()); + if output == Output::Capture && !is_stdout { + if watch.stderr_tail.len() >= STDERR_TAIL { + watch.stderr_tail.pop_front(); + } + watch.stderr_tail.push_back(line.trim_end().to_owned()); + } + }); + if is_stdout { + watch.progress.pending = lines.rest(); } - }); - if is_stdout { - watch.progress.pending = lines.rest(); + } + if output == Output::Stream && !shared.closed.load(Ordering::Acquire) { + (shared.sink)(is_stdout, chunk); } } } +/// The note when a run's output was still held open after it ended ([`Watched::held_open`]). +fn held_open_note() -> String { + format!("note: a process the run started still held its output open {} after the run ended; xtask no longer shows what it writes", show(DRAIN)) +} + /// Whether a NUL-separated environment block holds exactly `entry` (`KEY=VALUE`), not as part of /// another variable's name or value. #[cfg_attr(not(target_os = "linux"), allow(dead_code))] @@ -782,7 +852,11 @@ fn test_binary(mut cmd: Command, label: &str, limit: Option, shown: &m if std::io::stdout().is_terminal() && !sets_color(&cmd) { cmd.args(["--color", "always"]); } - match watch(cmd, limit, Clock::Start, Output::Stream)?.ended { + let watched = watch(cmd, limit, Clock::Start, Output::Stream)?; + if watched.held_open { + shown.push(held_open_note()); + } + match watched.ended { Ended::Exited(status) if status.success() => Ok(()), Ended::Exited(status) => Err(crate::test::describe(status)), Ended::TimedOut(progress, killed) => { @@ -821,6 +895,14 @@ fn loud(cmd: &Command) -> Command { c } +/// What `cmd`, a cargo command, passes each test binary: its arguments after `--` (filters, +/// `--exact`, `--skip`, …), so the `--list` of a timed-out binary names only the tests the run +/// selected. A filter among cargo's own arguments (`cargo test NAME`) isn't seen: callers put it +/// after `--`. +fn lister_args(cmd: &Command) -> Vec { + cmd.get_args().skip_while(|a| *a != "--").skip(1).map(std::ffi::OsStr::to_os_string).collect() +} + /// Run `cmd`, a `cargo test` (or `cargo nextest run`) command, with each test binary it starts /// under `limit` ([`Clock::EachBinary`]; `None`: no limit, and the output isn't piped). pub fn run_cargo_tests(cmd: Command, limit: Option) -> Result<(), String> { @@ -843,7 +925,12 @@ fn cargo_tests(cmd: Command, limit: Option, shown: &mut Vec) - cmd.env("CARGO_TERM_COLOR", "always"); } let dir = cmd.get_current_dir().map(Path::to_path_buf); - match watch(cmd, limit, Clock::EachBinary, Output::Stream)?.ended { + let filters = lister_args(&cmd); + let watched = watch(cmd, limit, Clock::EachBinary, Output::Stream)?; + if watched.held_open { + shown.push(held_open_note()); + } + match watched.ended { Ended::Exited(status) if status.success() => Ok(()), Ended::Exited(status) => Err(format!("exited with {status}")), Ended::TimedOut(progress, killed) => { @@ -852,7 +939,9 @@ fn cargo_tests(cmd: Command, limit: Option, shown: &mut Vec) - Some(dir) if exe.is_relative() => dir.join(exe), _ => exe.clone(), }; - list_tests(Command::new(exe), LIST_LIMIT, LIST_MAX_BYTES) + let mut lister = Command::new(exe); + lister.args(&filters); + list_tests(lister, LIST_LIMIT, LIST_MAX_BYTES) }); let binary = progress.binary.clone().unwrap_or_else(|| "a test binary".to_owned()); let (lines, error) = report(limit, &binary, &progress, listed.as_ref(), &killed); @@ -1307,6 +1396,130 @@ mod tests { assert_eq!(err, "timed out after 1 s: a test binary"); } + /// A sink that keeps what it gets, and blocks a stdout write while `gate` is shut. + #[cfg(unix)] + fn sink(gate: Arc<(Mutex, std::sync::Condvar)>) -> (Sink, Arc, Vec)>>) { + let got = Arc::new(Mutex::new((Vec::new(), Vec::new()))); + let kept = Arc::clone(&got); + let sink: Sink = Arc::new(move |is_stdout, chunk| { + if is_stdout { + let (open, cv) = &*gate; + let mut open = open.lock().unwrap(); + while !*open { + open = cv.wait(open).unwrap(); + } + } + let mut got = kept.lock().unwrap(); + if is_stdout { &mut got.0 } else { &mut got.1 }.extend_from_slice(chunk); + }); + (sink, got) + } + + #[cfg(unix)] + fn open_gate(gate: &(Mutex, std::sync::Condvar)) { + *gate.0.lock().unwrap() = true; + gate.1.notify_all(); + } + + /// A reader of xtask's output that stops reading (a paused terminal, a full pipe) blocks the + /// thread that forwards the output, never the check of the clock: the run still times out. + #[cfg(unix)] + #[test] + fn a_blocked_output_sink_cannot_stop_the_timeout() { + let gate = Arc::new((Mutex::new(false), std::sync::Condvar::new())); + let (sink, got) = sink(Arc::clone(&gate)); + let (tx, rx) = mpsc::channel(); + let t = Instant::now(); + let watcher = std::thread::spawn(move || { + let watched = + watch_into(sh("echo out; exec sleep 300"), Duration::from_secs(1), Clock::Start, Output::Stream, sink, Duration::from_millis(300)); + let _ = tx.send(watched.map(|w| matches!(w.ended, Ended::TimedOut(..)))); + }); + let timed_out = rx.recv_timeout(Duration::from_secs(15)); + let took = t.elapsed(); + open_gate(&gate); + watcher.join().unwrap(); + assert_eq!(timed_out, Ok(Ok(true)), "the limit ended the run while the sink was blocked ({took:?})"); + assert!(took < Duration::from_secs(10), "{took:?}"); + // the blocked write goes through once the reader reads again + let until = Instant::now() + Duration::from_secs(5); + while got.lock().unwrap().0.is_empty() && Instant::now() < until { + std::thread::sleep(TICK); + } + assert_eq!(got.lock().unwrap().0, b"out\n"); + } + + /// A process that outlives the run and holds its output: what it writes once the run is over + /// isn't forwarded into what xtask runs next, and the run says so. + #[cfg(unix)] + #[test] + fn output_after_the_run_ended_is_not_forwarded() { + let gate = Arc::new((Mutex::new(true), std::sync::Condvar::new())); + let (sink, got) = sink(gate); + let dir = std::env::temp_dir().join(format!("xtask-deadline-late-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let done = dir.join("done"); + let script = format!("(sleep 1; echo late; echo late >&2; touch '{}') & echo early; echo early >&2", done.display()); + let watched = watch_into(sh(&script), MIN, Clock::Start, Output::Stream, sink, Duration::from_millis(300)).unwrap(); + assert!(matches!(watched.ended, Ended::Exited(s) if s.success())); + assert!(watched.held_open, "the subshell still held the pipes"); + let until = Instant::now() + Duration::from_secs(10); + while !done.exists() && Instant::now() < until { + std::thread::sleep(TICK); + } + assert!(done.exists(), "the leftover wrote its lines (it never blocked on the pipe)"); + std::thread::sleep(Duration::from_millis(300)); + let got = got.lock().unwrap(); + assert_eq!((got.0.as_slice(), got.1.as_slice()), (&b"early\n"[..], &b"early\n"[..]), "what came during the drain only"); + assert!(held_open_note().contains("no longer shows what it writes")); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn only_the_first_header_after_each_running_line_restarts_the_clock() { + let mut p = Progress::default(); + assert_eq!(p.line("running 2 tests"), Event::Tests, "before any Running line (a quiet cargo)"); + assert_eq!(p.line("running 1 test"), Event::Other, "a test's own output"); + assert_eq!(p.line(" Running unittests src/lib.rs (target/debug/deps/a-1)"), Event::Binary); + assert_eq!(p.line("running 3 tests"), Event::Tests); + assert_eq!(p.total, Some(3)); + p.line("test x ... ok"); + for _ in 0..3 { + assert_eq!(p.line("running 9 tests"), Event::Other, "printed by a test, again and again"); + } + // the next binary's header read before cargo's line for it: that line restarts the clock + assert_eq!(p.line("running 4 tests"), Event::Other); + assert_eq!(p.line(" Running tests/it/main.rs (target/debug/deps/it-2)"), Event::Binary); + assert_eq!(p.line("\u{1b}[1m\u{1b}[92m Doc-tests\u{1b}[0m a"), Event::Binary); + assert_eq!(p.line("running 5 tests"), Event::Tests, "rustdoc's header, after it compiled them"); + assert_eq!(p.line("running 2 tests"), Event::Other); + } + + #[test] + fn a_timed_out_binary_is_listed_with_the_runs_filters() { + let mut c = Command::new("cargo"); + c.args(["test", "-p", "lightcraft-engine", "--lib", "--", "heic", "--skip", "slow", "--exact"]); + assert_eq!(lister_args(&c), ["heic", "--skip", "slow", "--exact"]); + let mut c = Command::new("cargo"); + c.args(["test", "--workspace"]); + assert!(lister_args(&c).is_empty(), "no filter: every test"); + let mut c = Command::new("cargo"); + c.args(["test", "--", "--", "x"]); + assert_eq!(lister_args(&c), ["--", "x"], "only the first `--` is cargo's"); + } + + #[test] + fn a_limit_set_under_nextest_is_noted_as_not_applying() { + assert_eq!(nextest_note(None), None); + assert_eq!(nextest_note(Some(std::ffi::OsStr::new(""))), None); + let note = nextest_note(Some(std::ffi::OsStr::new("0"))).unwrap(); + assert!( + note.starts_with("note: LIGHTCRAFT_TEST_BINARY_TIMEOUT=0 doesn't apply under cargo nextest") && note.contains("NEXTEST_PROFILE"), + "{note}" + ); + } + #[cfg(unix)] #[test] fn no_limit_runs_as_before() { From 3c86c7cb010b1ff5dcca24d97a06d55d0794ab03 Mon Sep 17 00:00:00 2001 From: Chad Elliott <880190+THEtheChad@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:35:34 -0500 Subject: [PATCH 24/40] docs(agents): #3061 xtask test --doc covers the doctests ci skipped; ci --quick's test caps Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index dcef48e79f2..09a49b279dc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -182,16 +182,17 @@ of it. ## Running tests - **Run tests through xtask:** `cargo xtask test [-p PKG]… [-- FILTER]` (`--keep-going` runs every test binary and names each that fails, instead of stopping at the first) or `cargo xtask ci --quick`. Both take the machine's CI slot - and `ci`'s RAM-aware caps; README → Quick start describes them and the settings that change them. Plain - `cargo test -p PKG` on a small crate is fine while you iterate. + and `ci`'s RAM-aware build caps, and run at most 4 tests at once in each binary; README → Quick start describes them + and the settings that change them. Plain `cargo test -p PKG` on a small crate is fine while you iterate. - **Never run plain `cargo test --workspace`**, with or without `--no-fail-fast`. It takes no CI slot, so it runs on top of every other agent's tests, and gets none of `ci`'s caps (`.cargo/config.toml` only limits it to 4 tests at once in each binary). - **When `ci` fails on a test your change doesn't touch,** rerun only that package's tests: `cargo xtask test -p PKG` (`-- TEST_NAME` narrows it to the one test). If it's intermittent, or fails without your change too, say so in the PR and link its issue, or file one. Don't widen the run or bypass xtask to get past it. `ci` stops at the first - failing binary, so cover what it didn't reach: `cargo xtask test --keep-going -p …` for the packages you changed and - those that depend on them, and `cargo xtask parity`, `layers`, `assets` and `wasm` for the steps after `test`. + failing binary, so cover what it didn't reach: `cargo xtask test --keep-going --doc -p …` for the packages you + changed and those that depend on them (`--doc` adds the doctests, which `ci` runs after the test binaries), and + `cargo xtask parity`, `layers`, `assets` and `wasm` for the steps after `test`. - **Nothing outlives your session:** never leave a test run going in the background when you finish, and wrap a long run in `timeout` (`timeout 60m cargo xtask test -p …`). Before you stop, check that no `cargo` or test process you started is still running. From 66d92d2a68bb1ac265ad5079b72d34df43999423 Mon Sep 17 00:00:00 2001 From: THEtheChad <880190+THEtheChad@users.noreply.github.com> Date: Tue, 3 Nov 2026 22:26:44 -0600 Subject: [PATCH 25/40] fix(xtask): #3060 say what the output gate can't stop; handshake the leftover-output test - A write already under way when watch returns still completes, and a stalled stream still blocks xtask's own later writes to it: the docs and the held-open note say so rather than promising no output at all. - output_after_the_run_ended_is_not_forwarded lets the leftover write only after watch returned (a file it waits for), not after a sleep. - Drop a_slot_freed_after_the_limit_is_not_taken: it raced a release thread against the test thread's entry into the wait, and the short-limit test covers the capped sleep. Co-Authored-By: Claude Opus 5.5 --- docs/architecture.md | 2 +- xtask/src/ci_lock.rs | 15 --------------- xtask/src/deadline.rs | 37 ++++++++++++++++++++++++++----------- 3 files changed, 27 insertions(+), 27 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 1467daa0a30..341bb79b956 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -128,7 +128,7 @@ the `lightcraft-gpu` tests once per backend with a hardware adapter (`LIGHTCRAFT | Date | Change | Summary | |---|---|---| -| 2026-11-03 | minor | Quality gates: a test run's output is forwarded outside the lock its clock is checked under, and not after the run ends; only a binary's first `running N tests` line restarts its clock; the slot wait never sleeps past its limit | +| 2026-11-03 | minor | Quality gates: a test run's output is forwarded outside the lock its clock is checked under, and not (but for a write under way) after the run ends; only a binary's first `running N tests` line restarts its clock; the slot wait never sleeps past its limit | | 2026-11-03 | minor | Quality gates: a timed-out test run's processes are signalled through pidfds on Linux (never a reused pid; without pidfds only xtask's own child is killed), and one that can't be killed is continued rather than left stopped | | 2026-10-26 | minor | Quality gates: each test binary's run (`LIGHTCRAFT_TEST_BINARY_TIMEOUT`) and the wait for the CI slot (`LIGHTCRAFT_CI_LOCK_WAIT`) have a time limit | | 2026-10-26 | minor | Quality gates: plain `cargo test` (and `cargo nextest run`) runs at most 4 tests at once; xtask tells that default from a caller's `RUST_TEST_THREADS` | diff --git a/xtask/src/ci_lock.rs b/xtask/src/ci_lock.rs index 9d18512cbb2..8e3f17b5d00 100644 --- a/xtask/src/ci_lock.rs +++ b/xtask/src/ci_lock.rs @@ -219,21 +219,6 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } - #[test] - fn a_slot_freed_after_the_limit_is_not_taken() { - let dir = scratch("late"); - let held = try_acquire(&dir, 1, "first").unwrap().expect("free slot"); - // freed after the 100 ms limit and before the 1 s poll would have looked again - let release = std::thread::spawn(move || { - std::thread::sleep(Duration::from_millis(400)); - drop(held); - }); - let got = wait_for_slot(&dir, 1, "second", Some(Duration::from_millis(100)), Duration::from_secs(1)); - assert!(got.is_err_and(|e| e.contains("gave up")), "the limit ended the wait first"); - release.join().unwrap(); - let _ = std::fs::remove_dir_all(&dir); - } - #[test] fn giving_up_names_an_unrecorded_holder_too() { assert!( diff --git a/xtask/src/deadline.rs b/xtask/src/deadline.rs index e1f18fedf8c..74cd86fb5ae 100644 --- a/xtask/src/deadline.rs +++ b/xtask/src/deadline.rs @@ -498,8 +498,9 @@ pub struct Watched { pub ended: Ended, pub stdout: String, pub stderr_tail: Vec, - /// A process the run started still held its output open [`DRAIN`] after the run ended (one - /// that outlived it); what that process writes from then on is read and dropped, not shown. + /// The run's output wasn't done [`DRAIN`] after the run ended: a process it started still held + /// a pipe open, or a reader was still writing to a stalled sink. From then on what is read is + /// dropped, not shown (a write already under way still completes). pub held_open: bool, } @@ -577,10 +578,11 @@ fn watch_into(mut cmd: Command, limit: Duration, clock: Clock, output: Output, s readers += 1; } drop(done_tx); - // Whether every reader saw its pipe close within `drain`. A process the run started that - // outlives it may hold a pipe open longer: past `drain` the readers stop forwarding (they - // keep reading, so that process never blocks on a full pipe), and later binaries' and steps' - // output isn't interleaved with its. + // Whether every reader was done (its pipe closed, its last write made) within `drain`. A + // process the run started that outlives it may hold a pipe open longer: past `drain` the + // readers stop forwarding (they keep reading, so that process never blocks on a full pipe), + // and later binaries' and steps' output isn't interleaved with its, but for a write already + // under way. let drained = |readers: usize| { let until = Instant::now() + drain; let closed = (0..readers).all(|_| done_rx.recv_timeout(until.saturating_duration_since(Instant::now())).is_ok()); @@ -619,8 +621,10 @@ fn watch_into(mut cmd: Command, limit: Duration, clock: Clock, output: Output, s /// Copy `pipe` to the sink as it arrives (or keep it, bounded), feeding whole lines to the /// progress. The sink is written outside the lock: a reader of xtask's output that stalls blocks -/// only this thread (and, through the pipe, the run), never [`watch`]'s check of the clock. Once -/// `watch` has returned what is read is dropped. +/// only this thread (and, through the pipe, the run), never [`watch`]'s check of the clock, so a +/// hung run is still killed on time. (xtask's own later writes to that stalled stream, the +/// timeout report say, block like any write to it until it is read again.) Once `watch` has +/// returned what is read is dropped; a write already under way completes. fn pump(mut pipe: Box, is_stdout: bool, clock: Clock, output: Output, shared: &Shared) { let mut buf = [0u8; 8192]; let mut lines = Lines::default(); @@ -665,7 +669,10 @@ fn pump(mut pipe: Box, is_stdout: bool, clock: Clock, output: O /// The note when a run's output was still held open after it ended ([`Watched::held_open`]). fn held_open_note() -> String { - format!("note: a process the run started still held its output open {} after the run ended; xtask no longer shows what it writes", show(DRAIN)) + format!( + "note: the run's output wasn't done {} after it ended (a process it started may still hold it open); xtask shows no more of it", + show(DRAIN) + ) } /// Whether a NUL-separated environment block holds exactly `entry` (`KEY=VALUE`), not as part of @@ -1460,10 +1467,18 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let done = dir.join("done"); - let script = format!("(sleep 1; echo late; echo late >&2; touch '{}') & echo early; echo early >&2", done.display()); + let go = dir.join("go"); + // the leftover writes only once the test says so (after watch returned), waiting 20 s at most + let script = format!( + "(i=0; while [ ! -e '{}' ] && [ $i -lt 400 ]; do sleep 0.05; i=$((i+1)); done; echo late; echo late >&2; touch '{}') & \ + echo early; echo early >&2", + go.display(), + done.display() + ); let watched = watch_into(sh(&script), MIN, Clock::Start, Output::Stream, sink, Duration::from_millis(300)).unwrap(); assert!(matches!(watched.ended, Ended::Exited(s) if s.success())); assert!(watched.held_open, "the subshell still held the pipes"); + std::fs::write(&go, b"").unwrap(); let until = Instant::now() + Duration::from_secs(10); while !done.exists() && Instant::now() < until { std::thread::sleep(TICK); @@ -1472,7 +1487,7 @@ mod tests { std::thread::sleep(Duration::from_millis(300)); let got = got.lock().unwrap(); assert_eq!((got.0.as_slice(), got.1.as_slice()), (&b"early\n"[..], &b"early\n"[..]), "what came during the drain only"); - assert!(held_open_note().contains("no longer shows what it writes")); + assert!(held_open_note().contains("shows no more of it")); let _ = std::fs::remove_dir_all(&dir); } From 14d94a4f9e083de1549d9669aed7f730e996ba2e Mon Sep 17 00:00:00 2001 From: Chad Elliott <880190+THEtheChad@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:50:41 -0600 Subject: [PATCH 26/40] docs(agents): #3061 ci --quick's test threads are RAM-aware too, as xtask test's are Since #3086's 3dcfc271, `ci --quick` runs each test binary under all of ci's caps, so its test threads are sized by available memory as `cargo xtask test`'s are, not only its build jobs. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 09a49b279dc..c1f4a8c535d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -182,8 +182,9 @@ of it. ## Running tests - **Run tests through xtask:** `cargo xtask test [-p PKG]… [-- FILTER]` (`--keep-going` runs every test binary and names each that fails, instead of stopping at the first) or `cargo xtask ci --quick`. Both take the machine's CI slot - and `ci`'s RAM-aware build caps, and run at most 4 tests at once in each binary; README → Quick start describes them - and the settings that change them. Plain `cargo test -p PKG` on a small crate is fine while you iterate. + and `ci`'s RAM-aware caps: build jobs and test threads sized by the memory available, at most 4 tests at once in + each binary. README → Quick start describes them and the settings that change them. Plain `cargo test -p PKG` on a + small crate is fine while you iterate. - **Never run plain `cargo test --workspace`**, with or without `--no-fail-fast`. It takes no CI slot, so it runs on top of every other agent's tests, and gets none of `ci`'s caps (`.cargo/config.toml` only limits it to 4 tests at once in each binary). From 4cf76a5f62282fbd64e97feb694397978e7adf09 Mon Sep 17 00:00:00 2001 From: THEtheChad <880190+THEtheChad@users.noreply.github.com> Date: Tue, 3 Nov 2026 22:53:34 -0600 Subject: [PATCH 27/40] fix(xtask): #3060 a CI slot taken only after the wait's limit, while the try scanned, is given back Co-Authored-By: Claude Opus 5.5 --- xtask/src/ci_lock.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/xtask/src/ci_lock.rs b/xtask/src/ci_lock.rs index 8e3f17b5d00..a089003ae06 100644 --- a/xtask/src/ci_lock.rs +++ b/xtask/src/ci_lock.rs @@ -135,13 +135,19 @@ fn wait_for_slot(dir: &Path, slots: usize, owner: &str, wait: Option, eprintln!(" running: {h}"); } loop { - // never past the limit: a sleep ends by it, and the limit is checked before each try, so - // a slot freed after it isn't taken + // never past the limit: a sleep ends by it, and the limit is checked before each try and + // after one that took a slot, so a slot freed after it isn't kept std::thread::sleep(wait.map_or(poll, |w| poll.min(w.saturating_sub(waiting.elapsed())))); if let Some(wait) = wait.filter(|w| waiting.elapsed() >= *w) { return Err(gave_up(wait, &holders(dir, slots))); } if let Some(held) = try_acquire(dir, slots, owner)? { + // the try scans every slot file: one freed only after the limit, while it scanned, + // is given back rather than taken late + if let Some(wait) = wait.filter(|w| waiting.elapsed() >= *w) { + drop(held); + return Err(gave_up(wait, &holders(dir, slots))); + } eprintln!("=== ci: waited {:.0} s for a CI slot ===", waiting.elapsed().as_secs_f64()); return Ok(Some(held)); } From 09fa9764cce9abc2126bedb84df8562fcc97e847 Mon Sep 17 00:00:00 2001 From: Chad Elliott <880190+THEtheChad@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:06:12 -0600 Subject: [PATCH 28/40] docs(agents): #3061 on macOS the timeout command is gtimeout, from coreutils Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c1f4a8c535d..0794d64039f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -195,8 +195,8 @@ of it. changed and those that depend on them (`--doc` adds the doctests, which `ci` runs after the test binaries), and `cargo xtask parity`, `layers`, `assets` and `wasm` for the steps after `test`. - **Nothing outlives your session:** never leave a test run going in the background when you finish, and wrap a long - run in `timeout` (`timeout 60m cargo xtask test -p …`). Before you stop, check that no `cargo` or test process you - started is still running. + run in `timeout` (`timeout 60m cargo xtask test -p …`; on macOS that's `gtimeout`, from Homebrew's + `coreutils`). Before you stop, check that no `cargo` or test process you started is still running. ## Testing & performance (do this often) - Unit/property tests next to the code; end-to-end tests drive real binaries (`crates/mcp/tests/e2e.rs`, From 646c3fb9d0901c53de55e9cdba28b088088bad90 Mon Sep 17 00:00:00 2001 From: THEtheChad <880190+THEtheChad@users.noreply.github.com> Date: Tue, 3 Nov 2026 22:59:24 -0600 Subject: [PATCH 29/40] fix(xtask): #3060 a slot freed as the wait ran out says so, instead of naming a holder to end Co-Authored-By: Claude Opus 5.5 --- xtask/src/ci_lock.rs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/xtask/src/ci_lock.rs b/xtask/src/ci_lock.rs index a089003ae06..3a8d5c7980c 100644 --- a/xtask/src/ci_lock.rs +++ b/xtask/src/ci_lock.rs @@ -146,7 +146,7 @@ fn wait_for_slot(dir: &Path, slots: usize, owner: &str, wait: Option, // is given back rather than taken late if let Some(wait) = wait.filter(|w| waiting.elapsed() >= *w) { drop(held); - return Err(gave_up(wait, &holders(dir, slots))); + return Err(freed_as_it_ended(wait)); } eprintln!("=== ci: waited {:.0} s for a CI slot ===", waiting.elapsed().as_secs_f64()); return Ok(Some(held)); @@ -154,6 +154,15 @@ fn wait_for_slot(dir: &Path, slots: usize, owner: &str, wait: Option, } } +/// The error when a slot came free only as the wait ran out: nothing to end, just run again. +fn freed_as_it_ended(wait: Duration) -> String { + format!( + "ci lock: a CI slot came free just as the {} wait for one ran out, so it wasn't taken; run again \ + (it's free now), or set {WAIT_ENV}= to wait longer (0 for as long as it takes)", + crate::deadline::show(wait) + ) +} + /// The error when the wait for a slot ran out: who holds the slots, and what to do. fn gave_up(wait: Duration, holders: &[String]) -> String { let held_by = if holders.is_empty() { "a run that didn't record itself".to_owned() } else { holders.join("; ") }; @@ -174,6 +183,13 @@ mod tests { dir } + #[test] + fn a_slot_freed_as_the_wait_ended_says_so_and_names_no_holder() { + let e = freed_as_it_ended(Duration::from_secs(120)); + assert!(e.contains("came free just as the") && e.contains("run again"), "{e}"); + assert!(!e.contains("held by") && !e.contains("is stuck"), "nothing to end: {e}"); + } + #[test] fn one_slot_is_exclusive_until_dropped() { let dir = scratch("one"); From 63e559abf3b9228d82a4f1446452b414c90f5afb Mon Sep 17 00:00:00 2001 From: Chad Elliott <880190+THEtheChad@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:36:28 -0600 Subject: [PATCH 30/40] docs(agents): #3061 --exact with the full path reruns one test; a bare name runs every match Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0794d64039f..a3a5a79498d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -189,8 +189,9 @@ of it. top of every other agent's tests, and gets none of `ci`'s caps (`.cargo/config.toml` only limits it to 4 tests at once in each binary). - **When `ci` fails on a test your change doesn't touch,** rerun only that package's tests: `cargo xtask test -p PKG` - (`-- TEST_NAME` narrows it to the one test). If it's intermittent, or fails without your change too, say so in the - PR and link its issue, or file one. Don't widen the run or bypass xtask to get past it. `ci` stops at the first + (`-- --exact TEST_PATH` narrows it to the one test; a bare `-- NAME` runs every test whose path contains it). If + it's intermittent, or fails without your change too, say so in the PR and link its issue, or file + one. Don't widen the run or bypass xtask to get past it. `ci` stops at the first failing binary, so cover what it didn't reach: `cargo xtask test --keep-going --doc -p …` for the packages you changed and those that depend on them (`--doc` adds the doctests, which `ci` runs after the test binaries), and `cargo xtask parity`, `layers`, `assets` and `wasm` for the steps after `test`. From 2e13ab9aca8dafa460754d6e96abcb688413dd9f Mon Sep 17 00:00:00 2001 From: THEtheChad <880190+THEtheChad@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:11:14 -0600 Subject: [PATCH 31/40] fix(xtask): #3060 the freed-slot message doesn't claim the slot is still free Co-Authored-By: Claude Opus 5.5 --- xtask/src/ci_lock.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xtask/src/ci_lock.rs b/xtask/src/ci_lock.rs index 3a8d5c7980c..859a4fd3c40 100644 --- a/xtask/src/ci_lock.rs +++ b/xtask/src/ci_lock.rs @@ -157,8 +157,8 @@ fn wait_for_slot(dir: &Path, slots: usize, owner: &str, wait: Option, /// The error when a slot came free only as the wait ran out: nothing to end, just run again. fn freed_as_it_ended(wait: Duration) -> String { format!( - "ci lock: a CI slot came free just as the {} wait for one ran out, so it wasn't taken; run again \ - (it's free now), or set {WAIT_ENV}= to wait longer (0 for as long as it takes)", + "ci lock: a CI slot came free just as the {} wait for one ran out, so it wasn't taken; run again, \ + or set {WAIT_ENV}= to wait longer (0 for as long as it takes)", crate::deadline::show(wait) ) } From 0c22a489821e2bb531530973a27b6f2e04c448f6 Mon Sep 17 00:00:00 2001 From: Chad Elliott <880190+THEtheChad@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:48:47 -0600 Subject: [PATCH 32/40] docs(agents): #3061 a RUST_TEST_THREADS you set (other than 4) wins over the cap Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a3a5a79498d..e8382aef16d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -183,8 +183,8 @@ of it. - **Run tests through xtask:** `cargo xtask test [-p PKG]… [-- FILTER]` (`--keep-going` runs every test binary and names each that fails, instead of stopping at the first) or `cargo xtask ci --quick`. Both take the machine's CI slot and `ci`'s RAM-aware caps: build jobs and test threads sized by the memory available, at most 4 tests at once in - each binary. README → Quick start describes them and the settings that change them. Plain `cargo test -p PKG` on a - small crate is fine while you iterate. + each binary unless you set `RUST_TEST_THREADS` (a value other than 4 wins). README → Quick start describes them + and the settings that change them. Plain `cargo test -p PKG` on a small crate is fine while you iterate. - **Never run plain `cargo test --workspace`**, with or without `--no-fail-fast`. It takes no CI slot, so it runs on top of every other agent's tests, and gets none of `ci`'s caps (`.cargo/config.toml` only limits it to 4 tests at once in each binary). From d3be7e7bab0c0ae066c3bd24aec6d2ff35d5e16f Mon Sep 17 00:00:00 2001 From: Chad Elliott <880190+THEtheChad@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:48:39 -0600 Subject: [PATCH 33/40] test(xtask): #3059 the config check ignores a trailing comment on the line it reads Co-Authored-By: Claude Opus 5.5 --- xtask/src/ci.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/xtask/src/ci.rs b/xtask/src/ci.rs index d79f52e9fd5..5be97c4f690 100644 --- a/xtask/src/ci.rs +++ b/xtask/src/ci.rs @@ -482,7 +482,8 @@ mod ci_jobs_tests { in_env && l.split('=').next().is_some_and(|k| k.trim() == key) })?; let value = line.split("value = \"").nth(1)?.split('"').next()?.to_owned(); - Some((value, line.to_owned())) + // without a trailing comment, so a `# force = …` note can't stand in for the setting + Some((value, line.split('#').next().unwrap_or(line).to_owned())) } #[test] @@ -493,6 +494,8 @@ mod ci_jobs_tests { assert_eq!(config_env(&format!("[build]\n{}\n[env]\n", line("4")), k), None, "another table's key"); assert_eq!(config_env(&format!("[env]\n[alias]\n{}\n", line("4")), k), None, "after [env] ends"); assert_eq!(config_env(&format!("{}\n[env]\nX = 1\n", line("4")), k), None, "before any table"); + let commented = format!("[env]\n{k} = {{ value = \"4\", force = true }} # force = false\n"); + assert!(!config_env(&commented, k).unwrap().1.contains("force = false"), "a comment isn't the setting"); } #[test] From 01c22366d29829ca4577eadc48970965bfc5ecc6 Mon Sep 17 00:00:00 2001 From: THEtheChad <880190+THEtheChad@users.noreply.github.com> Date: Mon, 9 Nov 2026 10:46:35 -0600 Subject: [PATCH 34/40] Issue #3060: the README names the GPU probe's 5-minute limit, as docs/architecture.md does --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c3489cf4a8b..bf66d4542b4 100644 --- a/README.md +++ b/README.md @@ -420,7 +420,8 @@ turn. `LIGHTCRAFT_CI_SLOTS=2` allows two; `LIGHTCRAFT_CI_LOCK=off` skips the loc gives up after `LIGHTCRAFT_CI_LOCK_WAIT` minutes (default 120; `0` waits as long as it takes) and names the run holding the slot. The build isn't timed (a first build can rightly take long), but the test binaries are: each may run for `LIGHTCRAFT_TEST_BINARY_TIMEOUT` minutes (default 30, timed from -cargo's `Running` line for it; `0` for no limit). One that runs longer, a test hung on a GPU device say, is killed with the +cargo's `Running` line for it; `0` for no limit). The GPU probe's test binaries get 5 minutes each, or +`LIGHTCRAFT_TEST_BINARY_TIMEOUT` when that is shorter (5 minutes even at `0`: the probe is optional). One that runs longer, a test hung on a GPU device say, is killed with the processes it started (on Linux found by an environment variable they inherit, so those that outlived their parent too, unless they cleared their environment; on macOS and the BSDs only the process xtask started is killed, which under the full `ci` is cargo, so a hung test binary may keep running), and the run reports it as `timed out after 30 min` with the tests still running From b4dc0afd5078092f493317e2409ec493bffa3812 Mon Sep 17 00:00:00 2001 From: THEtheChad <880190+THEtheChad@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:26:11 -0600 Subject: [PATCH 35/40] Issue #3061: the Running tests section defers to the flaky-test policy and ci's --no-fail-fast test step (#3791) --- AGENTS.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e8382aef16d..9534954b33f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -190,11 +190,11 @@ of it. once in each binary). - **When `ci` fails on a test your change doesn't touch,** rerun only that package's tests: `cargo xtask test -p PKG` (`-- --exact TEST_PATH` narrows it to the one test; a bare `-- NAME` runs every test whose path contains it). If - it's intermittent, or fails without your change too, say so in the PR and link its issue, or file - one. Don't widen the run or bypass xtask to get past it. `ci` stops at the first - failing binary, so cover what it didn't reach: `cargo xtask test --keep-going --doc -p …` for the packages you - changed and those that depend on them (`--doc` adds the doctests, which `ci` runs after the test binaries), and - `cargo xtask parity`, `layers`, `assets` and `wasm` for the steps after `test`. + it fails without your change too, say so in the PR and link its issue, or file one; if it passes on a rerun, it's + flaky (**Flaky tests** below). Don't widen the run or bypass xtask to get past it. `ci`'s test step runs every + test binary, but it runs the doctests only when they all pass, and `ci` stops at the first failing step, so cover + what it didn't reach: `cargo xtask test --doc -p …` for the packages you changed (their tests, then their + doctests), and `cargo xtask parity`, `layers`, `assets`, `roots` and `wasm` for the steps after `test`. - **Nothing outlives your session:** never leave a test run going in the background when you finish, and wrap a long run in `timeout` (`timeout 60m cargo xtask test -p …`; on macOS that's `gtimeout`, from Homebrew's `coreutils`). Before you stop, check that no `cargo` or test process you started is still running. From 024d889b839b7e07ee07491336da35abd7c99523 Mon Sep 17 00:00:00 2001 From: THEtheChad <880190+THEtheChad@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:25:02 -0600 Subject: [PATCH 36/40] Issue #3059: plain cargo test keeps libtest's defaults; only xtask test and ci cap test threads FredApps on #3058: keep the caps inside `cargo xtask test` and `ci`, and add no default thread cap for plain `cargo test`. This drops the `[env]` RUST_TEST_THREADS default in `.cargo/config.toml`, `.config/nextest.toml`'s test-threads, the LIGHTCRAFT_TEST_THREADS_DEFAULT marker xtask needed to tell that default apart (`set_by_caller`, `caller_sets`) with its tests, and the README and docs/architecture.md text about them. A RUST_TEST_THREADS the caller sets wins again, 4 included. Kept: ci --quick's test binaries get ci's RAM-aware test threads, as `cargo xtask test`'s do (9ef72f59). Co-Authored-By: Claude Opus 5.5 --- .cargo/config.toml | 10 ----- .config/nextest.toml | 5 --- README.md | 13 ++----- docs/architecture.md | 10 ----- xtask/src/ci.rs | 92 -------------------------------------------- xtask/src/main.rs | 37 +++--------------- xtask/src/test.rs | 12 +++--- 7 files changed, 13 insertions(+), 166 deletions(-) delete mode 100644 .config/nextest.toml diff --git a/.cargo/config.toml b/.cargo/config.toml index dd3f07df33a..35049cbcb13 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,12 +1,2 @@ [alias] xtask = "run --package xtask --" - -# Plain `cargo test` runs at most 4 tests at once in each test binary, as `cargo xtask ci` does: -# libtest's default of one per CPU ran the UI tests out of memory on a 16-core machine (#3059). -# A RUST_TEST_THREADS already in the environment wins (`force = false`). -# `cargo xtask` runs under this config too: the marker beside it holds the value set here, so xtask -# can tell this default from a caller's setting and size `ci`'s test threads by available RAM. Keep -# the two values equal (`xtask` tests it). -[env] -RUST_TEST_THREADS = { value = "4", force = false } -LIGHTCRAFT_TEST_THREADS_DEFAULT = { value = "4", force = true } diff --git a/.config/nextest.toml b/.config/nextest.toml deleted file mode 100644 index 2615c88a76d..00000000000 --- a/.config/nextest.toml +++ /dev/null @@ -1,5 +0,0 @@ -# Plain `cargo nextest run` runs at most 4 tests at once, as plain `cargo test` does -# (`.cargo/config.toml`, #3059). NEXTEST_TEST_THREADS or `--test-threads` wins; `cargo xtask ci` -# and `cargo xtask test` set it from available RAM. -[profile.default] -test-threads = 4 diff --git a/README.md b/README.md index af4332b2ca9..620de9d8989 100644 --- a/README.md +++ b/README.md @@ -424,20 +424,13 @@ available when it starts (at most one per CPU; 4 if memory can't be read), so an builds with fewer. Test threads follow, capped at 4. Full-debuginfo linkers, one per CPU, otherwise exhaust RAM before any test runs. GPU coverage is unchanged. Explicit `CARGO_PROFILE_DEV_DEBUG`, `CARGO_BUILD_JOBS`, `RUST_TEST_THREADS` and -`NEXTEST_TEST_THREADS` settings override these defaults. Outside `ci`, `.cargo/config.toml` limits -plain `cargo test` to 4 tests at once in each test binary (`RUST_TEST_THREADS=4` unless the -environment sets it; libtest's own default is one per CPU), and `.config/nextest.toml` does the same -for `cargo nextest run`. `cargo xtask` inherits that default but doesn't count it as an explicit -setting (a marker beside it, `LIGHTCRAFT_TEST_THREADS_DEFAULT`, tells it apart), so `ci` still -lowers the threads on a machine short of RAM. An explicit `RUST_TEST_THREADS` other than 4 wins -as-is; an explicit 4 can't be told apart from the default, so `ci` and `cargo xtask test` may lower -it to their RAM-aware value (never raise it). The tests run under +`NEXTEST_TEST_THREADS` settings override these defaults. The tests run under `cargo test`; `LIGHTCRAFT_NEXTEST=1` runs them under [cargo-nextest](https://nexte.st) instead (one process per test, slower here because each regenerates the demo scenes). Ordinary development commands keep their own settings. To run tests without the rest of `ci`, use `cargo xtask test` rather than `cargo test --workspace`, -which gets none of `ci`'s RAM-aware caps (only the 4-thread default above) and takes no CI slot. -It has `ci`'s caps and waits for its slot, builds every test target +which runs one test per CPU in every test binary (on a 16-core machine the UI tests alone run out of +memory) and takes no CI slot. It has `ci`'s caps and waits for its slot, builds every test target once (the same build as `ci`'s, so neither rebuilds the other) and runs each test binary, or those of the `-p PKG` packages, with whatever follows `--` (`cargo xtask test -p lightcraft-ui-egui -- i18n::`). It stops at the first failing binary; `--keep-going` runs them all and names each that diff --git a/docs/architecture.md b/docs/architecture.md index 9e29536a876..65d90506753 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -81,15 +81,6 @@ runs each test binary, or the `-p` packages' binaries, itself (`test::run_binary uses too); `--keep-going` runs every binary and names each that failed instead of stopping at the first. -Outside `ci`, `.cargo/config.toml`'s `[env]` limits plain `cargo test` to 4 tests at once per test -binary (`RUST_TEST_THREADS = { value = "4", force = false }`, so a value already in the environment -wins), and `.config/nextest.toml` sets `test-threads = 4` for `cargo nextest run`. `cargo xtask` runs -under that config too, so `[env]` also sets a marker, `LIGHTCRAFT_TEST_THREADS_DEFAULT`, to the same -value: a `RUST_TEST_THREADS` equal to it counts as unset (`caller_sets` in `xtask/src/main.rs`) and the -caps replace it with the RAM-aware value, while any other value is the caller's and wins as-is. An -explicit `RUST_TEST_THREADS=4` can't be told apart from the default, so `ci` and `xtask test` may -lower it to their RAM-aware value (never raise it). - `ci` also probes the machine: OS, CPUs, RAM, the GPU adapters of each backend (from the ignored `gpu_probe` test of `lightcraft-gpu`, run after the workspace tests so it reuses their build; xtask has no wgpu), the corpus and `CRAFT_FONTS_DIR`. Tests @@ -104,7 +95,6 @@ the `lightcraft-gpu` tests once per backend with a hardware adapter (`LIGHTCRAFT | Date | Change | Summary | |---|---|---| -| 2026-10-26 | minor | Quality gates: plain `cargo test` (and `cargo nextest run`) runs at most 4 tests at once; xtask tells that default from a caller's `RUST_TEST_THREADS` | | 2026-10-26 | minor | Quality gates: `cargo xtask test` runs the tests with `ci`'s caps and slot, and can keep going past a failing binary | | 2026-10-23 | minor | Quality gates: one integration-test binary per crate, doctests apart, nextest on request, one WASM check | | 2026-10-11 | minor | Quality gates: the CI machine probe, visible skips (`testkit`) and `target/ci/report.json` | diff --git a/xtask/src/ci.rs b/xtask/src/ci.rs index 5be97c4f690..ee8968a5eec 100644 --- a/xtask/src/ci.rs +++ b/xtask/src/ci.rs @@ -419,96 +419,4 @@ mod ci_jobs_tests { assert_eq!(set.iter().map(|(k, _)| *k).collect::>(), ["CARGO_PROFILE_DEV_DEBUG", "CARGO_BUILD_JOBS", "NEXTEST_TEST_THREADS"]); assert!(crate::caps_to_set(caps, |_| true).is_empty()); } - - /// An environment of `vars` for [`crate::set_by_caller`]. - fn env(vars: &[(&str, &str)]) -> impl Fn(&str) -> Option { - let vars: Vec<(String, String)> = vars.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(); - move |key| vars.iter().find(|(k, _)| k == key).map(|(_, v)| v.into()) - } - - #[test] - fn the_config_test_threads_default_is_not_a_callers_setting() { - use crate::set_by_caller; - const MARKER: &str = crate::TEST_THREADS_DEFAULT_MARKER; - let threads = "RUST_TEST_THREADS"; - assert!(!set_by_caller(threads, env(&[])), "unset, outside cargo"); - assert!(!set_by_caller(threads, env(&[(MARKER, "4")])), "unset (no RUST_TEST_THREADS at all)"); - assert!(!set_by_caller(threads, env(&[(threads, "4"), (MARKER, "4")])), "the config default: ci sizes it by RAM"); - assert!(set_by_caller(threads, env(&[(threads, "9"), (MARKER, "4")])), "RUST_TEST_THREADS=9 cargo xtask ci"); - assert!(set_by_caller(threads, env(&[(threads, "2"), (MARKER, "4")])), "a lower explicit value wins too"); - assert!(set_by_caller(threads, env(&[(threads, "4")])), "no marker: xtask run outside cargo, the value is the caller's"); - assert!(set_by_caller(threads, env(&[(threads, "")])), "set, even if empty"); - // the marker only speaks for RUST_TEST_THREADS - assert!(set_by_caller("NEXTEST_TEST_THREADS", env(&[("NEXTEST_TEST_THREADS", "4"), (MARKER, "4")]))); - assert!(set_by_caller("CARGO_BUILD_JOBS", env(&[("CARGO_BUILD_JOBS", "4"), (MARKER, "4")]))); - assert!(!set_by_caller("CARGO_BUILD_JOBS", env(&[(MARKER, "4")]))); - } - - /// The `RUST_TEST_THREADS` a capped run's test binaries get in environment `vars` when `ci`'s - /// RAM-aware value is `cap`: the cap where the caller didn't set it, else the environment's. - fn test_threads(vars: &[(&str, &str)], cap: &str) -> String { - let caps = [("RUST_TEST_THREADS", cap.to_owned())]; - let get = env(vars); - let set = crate::caps_to_set(&caps, |key| crate::set_by_caller(key, &get)); - match set.first() { - Some((_, value)) => (*value).to_owned(), - None => get("RUST_TEST_THREADS").unwrap().into_string().unwrap(), - } - } - - #[test] - fn an_explicit_test_thread_count_wins_except_one_equal_to_the_config_default() { - const MARKER: &str = crate::TEST_THREADS_DEFAULT_MARKER; - let threads = "RUST_TEST_THREADS"; - assert_eq!(test_threads(&[(threads, "9"), (MARKER, "4")], "2"), "9", "explicit 9 is kept"); - assert_eq!(test_threads(&[(threads, "2"), (MARKER, "4")], "3"), "2", "explicit 2 is kept"); - assert_eq!(test_threads(&[(threads, "4"), (MARKER, "4")], "2"), "2", "the config default yields to the RAM-aware cap"); - // An explicit RUST_TEST_THREADS=4 looks the same as the config default (documented): it - // may be lowered, never raised. - assert_eq!(test_threads(&[(threads, "4"), (MARKER, "4")], "2"), "2", "explicit 4 under cargo is lowered like the default"); - assert_eq!(test_threads(&[(threads, "4")], "2"), "4", "no marker (xtask run outside cargo): 4 is the caller's"); - assert_eq!(test_threads(&[(MARKER, "4")], "3"), "3", "unset: the cap"); - } - - /// The quoted `value` of the `key = { value = "…", … }` line in `.cargo/config.toml`'s `[env]`. - fn config_env(config: &str, key: &str) -> Option<(String, String)> { - // only inside `[env]`: the same key in another table isn't an environment default - let mut in_env = false; - let line = config.lines().find(|l| { - if l.trim_start().starts_with('[') { - in_env = l.trim() == "[env]"; - return false; - } - in_env && l.split('=').next().is_some_and(|k| k.trim() == key) - })?; - let value = line.split("value = \"").nth(1)?.split('"').next()?.to_owned(); - // without a trailing comment, so a `# force = …` note can't stand in for the setting - Some((value, line.split('#').next().unwrap_or(line).to_owned())) - } - - #[test] - fn config_env_reads_only_the_env_table() { - let k = "RUST_TEST_THREADS"; - let line = |v: &str| format!("{k} = {{ value = \"{v}\", force = false }}"); - assert_eq!(config_env(&format!("[env]\n{}\n", line("4")), k).map(|(v, _)| v).as_deref(), Some("4")); - assert_eq!(config_env(&format!("[build]\n{}\n[env]\n", line("4")), k), None, "another table's key"); - assert_eq!(config_env(&format!("[env]\n[alias]\n{}\n", line("4")), k), None, "after [env] ends"); - assert_eq!(config_env(&format!("{}\n[env]\nX = 1\n", line("4")), k), None, "before any table"); - let commented = format!("[env]\n{k} = {{ value = \"4\", force = true }} # force = false\n"); - assert!(!config_env(&commented, k).unwrap().1.contains("force = false"), "a comment isn't the setting"); - } - - #[test] - fn the_cargo_config_sets_the_test_threads_default_and_its_marker_to_one_value() { - let config = std::fs::read_to_string(super::root().join(".cargo/config.toml")).unwrap(); - let (threads, line) = config_env(&config, "RUST_TEST_THREADS").expect("RUST_TEST_THREADS in [env]"); - assert!(line.contains("force = false"), "an explicit RUST_TEST_THREADS must win: {line}"); - let (marker, marker_line) = config_env(&config, crate::TEST_THREADS_DEFAULT_MARKER).expect("the marker in [env]"); - // forced, so an inherited marker can't make a caller's equal value look like the default - assert!(marker_line.contains("force = true"), "cargo must overwrite an inherited marker: {marker_line}"); - assert_eq!(threads, marker, "xtask tells the default apart by this marker"); - let n: usize = threads.parse().unwrap(); - assert!((1..=4).contains(&n), "{n}"); - assert!(config.contains("[env]")); - } } diff --git a/xtask/src/main.rs b/xtask/src/main.rs index fccfa7b38fe..bd797b8f227 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -66,8 +66,7 @@ commands: LIGHTCRAFT_CI_LOCK=off to skip the lock) test [-p PKG]... [--keep-going] [--doc] [-- ARGS] the workspace's tests (or PKG's) with ci's caps (build jobs by free RAM, at most 4 test - threads, line-table debuginfo; a CARGO_BUILD_JOBS or RUST_TEST_THREADS you set wins, - but RUST_TEST_THREADS=4 can't be told from .cargo/config.toml's default) + threads, line-table debuginfo; a CARGO_BUILD_JOBS or RUST_TEST_THREADS you set wins) in ci's machine-wide slot, instead of `cargo test`: builds every test target once, then runs each test binary with ARGS (a filter, --exact, --skip, --nocapture); stops at the first failing binary unless --keep-going @@ -189,44 +188,18 @@ fn ci_caps() -> &'static [(&'static str, String); 4] { }) } -/// The caps `c` gets: each of `caps` the environment doesn't set itself (`is_set`, normally -/// [`caller_sets`]), so a caller's setting wins; see [`set_by_caller`] for an explicit -/// `RUST_TEST_THREADS=4`. +/// The caps `c` gets: each of `caps` the environment doesn't set itself (`is_set`), so an explicit +/// setting always wins. fn caps_to_set<'a>(caps: &'a [(&'static str, String)], is_set: impl Fn(&str) -> bool) -> Vec<(&'static str, &'a str)> { caps.iter().filter(|(key, _)| !is_set(key)).map(|(key, value)| (*key, value.as_str())).collect() } -/// The variable `.cargo/config.toml` sets beside its `RUST_TEST_THREADS` default, to the same -/// value (#3059). `cargo xtask` runs under that config, so it inherits the default like any cargo -/// run; the marker tells it apart from a caller's own setting. -const TEST_THREADS_DEFAULT_MARKER: &str = "LIGHTCRAFT_TEST_THREADS_DEFAULT"; - -/// Whether the caller set `key` in the environment (`get` reads it), rather than leaving it unset -/// or to the `RUST_TEST_THREADS` default of `.cargo/config.toml`: that one counts as unset when it -/// equals the marker [`TEST_THREADS_DEFAULT_MARKER`] holds. So an explicit value other than the -/// default (4) wins as-is, but an explicit `RUST_TEST_THREADS=4` can't be told apart from the -/// default: `ci` and `xtask test` may lower it to their RAM-aware value (never raise it, as that is -/// at most 4). Without the marker (xtask run outside cargo) every value is the caller's. -fn set_by_caller(key: &str, get: impl Fn(&str) -> Option) -> bool { - let Some(value) = get(key) else { - return false; - }; - !(key == "RUST_TEST_THREADS" && get(TEST_THREADS_DEFAULT_MARKER).is_some_and(|default| default == value)) -} - -/// [`set_by_caller`] for this process's environment (an explicit `RUST_TEST_THREADS=4` counts as -/// the config default). -pub fn caller_sets(key: &str) -> bool { - set_by_caller(key, |k| std::env::var_os(k)) -} - /// Give `c` CI's resource caps when this run opted in ([`use_ci_caps`]). Full Windows debuginfo /// plus one linker per CPU can exhaust RAM before any tests run, and one test thread per CPU -/// can exhaust it while they run (#3057). A caller's setting wins ([`caller_sets`]), except that an -/// explicit `RUST_TEST_THREADS=4` looks like the config default and may be lowered. +/// can exhaust it while they run (#3057). fn apply_ci_caps(c: &mut Command) { if CI_CAPS.load(std::sync::atomic::Ordering::Relaxed) { - c.envs(caps_to_set(ci_caps(), caller_sets)); + c.envs(caps_to_set(ci_caps(), |key| std::env::var_os(key).is_some())); } } diff --git a/xtask/src/test.rs b/xtask/src/test.rs index 09eae7c01c8..301c011e412 100644 --- a/xtask/src/test.rs +++ b/xtask/src/test.rs @@ -1,9 +1,8 @@ //! `cargo xtask test [-p PKG]… [--keep-going] [--doc] [-- ARGS]`: the workspace tests, or some //! packages' tests, under the same caps as `ci` and in its machine-wide slot. //! -//! Plain `cargo test --workspace` takes no CI slot and gets only `.cargo/config.toml`'s 4 test -//! threads per binary (libtest's own default, one per CPU, ran the ui-egui tests alone out of memory -//! on a 16-core machine, #3057, #3059), not `ci`'s RAM-aware caps. This runs them the +//! Plain `cargo test --workspace` runs one test per CPU in every test binary and takes no CI slot: +//! on a 16-core machine the ui-egui tests alone then run out of memory (#3057). This runs them the //! way `ci` does: build jobs by available RAM, at most 4 test threads, line-table debuginfo //! ([`super::use_ci_caps`]), one run per machine ([`ci_lock`]). //! @@ -159,10 +158,9 @@ fn names<'a>(packages: impl Iterator) -> String { /// Run one test binary as `cargo test` would (from its package's directory, with its /// `CARGO_MANIFEST_DIR` and `CARGO_PKG_NAME`) under CI's caps ([`super::apply_ci_caps`]: where the /// caller doesn't set it, `RUST_TEST_THREADS` is the RAM-aware `min(build jobs by available RAM, 4)` -/// of `ci`'s cargo runs; `.cargo/config.toml`'s default doesn't count, [`super::caller_sets`]), with -/// `args`; skips the tests record go to `skip_log`. The one place `test` and `ci --quick` start a -/// test binary and wait for it. The error says how it ended: its exit status, the signal that killed -/// it, or why it didn't start. +/// of `ci`'s cargo runs), with `args`; skips the tests record go to `skip_log`. The one place `test` +/// and `ci --quick` start a test binary and wait for it. The error says how it ended: its exit +/// status, the signal that killed it, or why it didn't start. pub fn run_binary(root: &Path, binary: &Binary, args: &[&str], skip_log: Option<&Path>) -> Result<(), String> { let dir = Path::new(&binary.manifest).parent().unwrap_or(root); let mut c = Command::new(&binary.exe); From 1c389d0bd86d757663a54c3c688221c77e10ea57 Mon Sep 17 00:00:00 2001 From: THEtheChad <880190+THEtheChad@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:22:06 -0600 Subject: [PATCH 37/40] Issue #3060: the CI-slot wait defaults to 240 min, room for three full runs queued on a busy machine A full `cargo xtask ci` takes about 15 minutes on an idle machine, but GitHub's gate allows one 80 minutes before it stops it as hung (#3794). On a shared machine with two or three full runs queued, the old 120-minute default could run out with nothing wrong. 240 minutes is three runs at that limit. The give-up error already says how to wait longer or without limit. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/architecture.md | 3 ++- xtask/src/ci_lock.rs | 19 +++++++++++++++---- xtask/src/main.rs | 2 +- 4 files changed, 19 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index bf66d4542b4..0d9bd75ec06 100644 --- a/README.md +++ b/README.md @@ -417,7 +417,7 @@ config tests everything. GitHub runs the full `cargo xtask ci` on every pull req (`.github/workflows/ci.yml`). Only one `ci` runs at a time per machine: a second one, from another worktree say, waits for the first and names it, since several at once take longer in total than in turn. `LIGHTCRAFT_CI_SLOTS=2` allows two; `LIGHTCRAFT_CI_LOCK=off` skips the lock. The wait -gives up after `LIGHTCRAFT_CI_LOCK_WAIT` minutes (default 120; `0` waits as long as it takes) and +gives up after `LIGHTCRAFT_CI_LOCK_WAIT` minutes (default 240; `0` waits as long as it takes) and names the run holding the slot. The build isn't timed (a first build can rightly take long), but the test binaries are: each may run for `LIGHTCRAFT_TEST_BINARY_TIMEOUT` minutes (default 30, timed from cargo's `Running` line for it; `0` for no limit). The GPU probe's test binaries get 5 minutes each, or diff --git a/docs/architecture.md b/docs/architecture.md index 341bb79b956..f5b55a399f5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -102,7 +102,7 @@ the kill found, the tests still running (libtest's "has been running for over 60 or the test a single-threaded run started) and those that never reported a result (`--list`, itself bounded in time and size). Under nextest, `.config/nextest.toml`'s `slow-timeout` kills a test after 30 minutes instead, whatever `LIGHTCRAFT_TEST_BINARY_TIMEOUT` says (xtask notes that when it is set). The wait for the CI slot gives up after `LIGHTCRAFT_CI_LOCK_WAIT` minutes -(default 120, several full runs; `0` for no limit) with an error naming the run that holds it. +(default 240, three full runs at the 80 minutes GitHub's gate allows one; `0` for no limit) with an error naming the run that holds it. Outside `ci`, `.cargo/config.toml`'s `[env]` limits plain `cargo test` to 4 tests at once per test binary (`RUST_TEST_THREADS = { value = "4", force = false }`, so a value already in the environment @@ -128,6 +128,7 @@ the `lightcraft-gpu` tests once per backend with a hardware adapter (`LIGHTCRAFT | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | Quality gates: the wait for the CI slot (`LIGHTCRAFT_CI_LOCK_WAIT`) defaults to 240 minutes, room for two or three full runs queued on a shared machine | | 2026-11-03 | minor | Quality gates: a test run's output is forwarded outside the lock its clock is checked under, and not (but for a write under way) after the run ends; only a binary's first `running N tests` line restarts its clock; the slot wait never sleeps past its limit | | 2026-11-03 | minor | Quality gates: a timed-out test run's processes are signalled through pidfds on Linux (never a reused pid; without pidfds only xtask's own child is killed), and one that can't be killed is continued rather than left stopped | | 2026-10-26 | minor | Quality gates: each test binary's run (`LIGHTCRAFT_TEST_BINARY_TIMEOUT`) and the wait for the CI slot (`LIGHTCRAFT_CI_LOCK_WAIT`) have a time limit | diff --git a/xtask/src/ci_lock.rs b/xtask/src/ci_lock.rs index 859a4fd3c40..9c2a7d72bf1 100644 --- a/xtask/src/ci_lock.rs +++ b/xtask/src/ci_lock.rs @@ -11,9 +11,12 @@ //! - `LIGHTCRAFT_CI_LOCK=`: keep the lock files there instead. //! - `LIGHTCRAFT_CI_LOCK_WAIT=MIN`: give up after waiting MIN minutes for a slot (default //! [`DEFAULT_WAIT_MIN`]; `0` or `off` waits as long as it takes), with an error naming the run -//! that holds it (#3060). A full `ci` takes about 15 minutes on a 16-core machine, and a hung test -//! binary can't hold a slot past its own limit any more ([`crate::deadline`]), so two hours is -//! several runs ahead in the queue; a wait longer than that means something is stuck. +//! that holds it (#3060). A full `ci` takes about 15 minutes on an idle 16-core machine, but far +//! longer on a shared, busy one: GitHub's gate allows a run 80 minutes before it stops it as hung +//! (#3794). Four hours is three such runs ahead in the queue, so two or three full runs queued on +//! a shared machine don't run the wait out with nothing wrong. A hung test binary can't hold a +//! slot past its own limit ([`crate::deadline`]), so a wait longer than that means something is +//! stuck. use std::fs::{File, OpenOptions, TryLockError}; use std::io::Write; @@ -25,7 +28,7 @@ const POLL: Duration = Duration::from_secs(2); /// How long to wait for a slot, in minutes. pub const WAIT_ENV: &str = "LIGHTCRAFT_CI_LOCK_WAIT"; /// The default of [`WAIT_ENV`]. -pub const DEFAULT_WAIT_MIN: u64 = 120; +pub const DEFAULT_WAIT_MIN: u64 = 240; /// A held CI slot; dropping it releases the slot. pub struct Held { @@ -248,6 +251,14 @@ mod tests { ); } + #[test] + fn the_default_wait_outlasts_three_full_runs_at_the_gates_limit() { + // GitHub's gate stops a hung full run at 80 minutes (#3794); three queued ahead must fit + let e = gave_up(Duration::from_secs(DEFAULT_WAIT_MIN * 60), &["pid 1 in /w: cargo xtask ci".to_owned()]); + assert!(e.contains("gave up after waiting 240 min"), "{e}"); + assert!(e.contains("LIGHTCRAFT_CI_LOCK_WAIT= waits longer (0 for as long as it takes)"), "says how to wait longer: {e}"); + } + #[test] fn more_slots_admit_more_runs() { let dir = scratch("two"); diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 37af1344841..eda10c5cf03 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -65,7 +65,7 @@ commands: break: clippy, the changed packages' tests, and heif / parity / wasm when they apply. One ci runs at a time per machine; others wait (LIGHTCRAFT_CI_SLOTS=N for N at once, LIGHTCRAFT_CI_LOCK=off to skip the lock) for up to LIGHTCRAFT_CI_LOCK_WAIT minutes - (default 120; 0: no limit). Each test binary may run LIGHTCRAFT_TEST_BINARY_TIMEOUT + (default 240; 0: no limit). Each test binary may run LIGHTCRAFT_TEST_BINARY_TIMEOUT minutes (default 30; 0: no limit); one that runs longer is killed with the processes it started and reported with the tests still running test [-p PKG]... [--keep-going] [--doc] [-- ARGS] From 6e7c5b97f3325b4c835f10de3d5443948d2e685f Mon Sep 17 00:00:00 2001 From: THEtheChad <880190+THEtheChad@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:32:14 -0600 Subject: [PATCH 38/40] Issue #3060: nextest's 30-minute limit per test is in an xtask profile, so plain cargo nextest run keeps its defaults FredApps on #3058: keep the caps inside `cargo xtask test` and `ci`, and leave plain runs as they are. `.config/nextest.toml`'s slow-timeout moves from the default profile to `[profile.xtask]`. `ci`'s test step and `cargo xtask test` set NEXTEST_PROFILE=xtask for their nextest runs unless the caller set one; NEXTEST_PROFILE=default runs without the limit. The note for LIGHTCRAFT_TEST_BINARY_TIMEOUT under nextest, README.md and docs/architecture.md say so. `only_xtasks_nextest_profile_has_the_time_limit` fails on the old config (the limit in the default profile); `xtask_picks_its_nextest_profile_unless_the_caller_chose_one` covers the caller's choice. Co-Authored-By: Claude Opus 5.5 --- .config/nextest.toml | 7 ++++-- README.md | 7 +++--- docs/architecture.md | 7 ++++-- xtask/src/ci.rs | 58 ++++++++++++++++++++++++++++++++++++++++++- xtask/src/deadline.rs | 10 ++++---- xtask/src/test.rs | 1 + 6 files changed, 77 insertions(+), 13 deletions(-) diff --git a/.config/nextest.toml b/.config/nextest.toml index f96a80472ed..965ee560f42 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -1,5 +1,8 @@ -[profile.default] +# `cargo xtask ci` and `cargo xtask test` run nextest (LIGHTCRAFT_NEXTEST=1) with this profile, set +# through NEXTEST_PROFILE unless you set it yourself. A plain `cargo nextest run` uses the default +# profile and keeps nextest's own defaults (#3058). +[profile.xtask] # A test still running after 30 minutes is killed (`cargo xtask` gives each test binary under # `cargo test` the same limit, LIGHTCRAFT_TEST_BINARY_TIMEOUT, #3060). That variable doesn't change -# this one (`0` included): add a profile without terminate-after and pick it with NEXTEST_PROFILE. +# this one (`0` included): NEXTEST_PROFILE=default runs without it. slow-timeout = { period = "60s", terminate-after = 30 } diff --git a/README.md b/README.md index c59fb54053f..f698165d70d 100644 --- a/README.md +++ b/README.md @@ -425,9 +425,10 @@ cargo's `Running` line for it; `0` for no limit). The GPU probe's test binaries processes it started (on Linux found by an environment variable they inherit, so those that outlived their parent too, unless they cleared their environment; on macOS and the BSDs only the process xtask started is killed, which under the full `ci` is cargo, so a hung test binary may keep running), and the run reports it as `timed out after 30 min` with the tests still running -and those that never reported a result. Under `LIGHTCRAFT_NEXTEST=1`, `.config/nextest.toml` kills a -test after 30 minutes instead, whatever `LIGHTCRAFT_TEST_BINARY_TIMEOUT` says (`0` included; a -profile there without `terminate-after`, picked with `NEXTEST_PROFILE`, runs without it). After a timeout, `ci` skips its GPU probe and translation gaps report. +and those that never reported a result. Under `LIGHTCRAFT_NEXTEST=1`, xtask runs nextest with the `xtask` profile of +`.config/nextest.toml`, which kills a test after 30 minutes instead, whatever +`LIGHTCRAFT_TEST_BINARY_TIMEOUT` says (`0` included; `NEXTEST_PROFILE=default` runs without it). A +plain `cargo nextest run` uses the default profile, so it keeps nextest's own defaults. After a timeout, `ci` skips its GPU probe and translation gaps report. CI defaults to line-table debug information and one build job per 1.5 GB of RAM available when it starts (at most one per CPU; 4 if memory can't be read), so an diff --git a/docs/architecture.md b/docs/architecture.md index b417b20a37c..6b70bd6d557 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -100,8 +100,10 @@ cargo, whose test binary may then keep running) and the report says so; Windows still reaches it. The run reports `timed out after N min: `, what the kill found, the tests still running (libtest's "has been running for over 60 seconds" warnings, or the test a single-threaded run started) and those that never reported a result (`--list`, itself -bounded in time and size). Under nextest, `.config/nextest.toml`'s `slow-timeout` kills a test -after 30 minutes instead, whatever `LIGHTCRAFT_TEST_BINARY_TIMEOUT` says (xtask notes that when it is set). The wait for the CI slot gives up after `LIGHTCRAFT_CI_LOCK_WAIT` minutes +bounded in time and size). Under nextest, xtask sets `NEXTEST_PROFILE=xtask` (unless the caller set +one), and that profile's `slow-timeout` in `.config/nextest.toml` kills a test after 30 minutes +instead, whatever `LIGHTCRAFT_TEST_BINARY_TIMEOUT` says (xtask notes that when it is set); a plain +`cargo nextest run` uses the default profile and keeps nextest's own defaults. The wait for the CI slot gives up after `LIGHTCRAFT_CI_LOCK_WAIT` minutes (default 240, three full runs at the 80 minutes GitHub's gate allows one; `0` for no limit) with an error naming the run that holds it. `ci` also probes the machine: OS, CPUs, RAM, the GPU adapters of each backend (from the ignored @@ -119,6 +121,7 @@ the `lightcraft-gpu` tests once per backend with a hardware adapter (`LIGHTCRAFT | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | Quality gates: nextest's 30-minute limit per test is in an `xtask` profile that `ci` and `xtask test` pick, so a plain `cargo nextest run` keeps nextest's defaults | | 2026-11-20 | minor | Quality gates: the wait for the CI slot (`LIGHTCRAFT_CI_LOCK_WAIT`) defaults to 240 minutes, room for two or three full runs queued on a shared machine | | 2026-11-03 | minor | Quality gates: a test run's output is forwarded outside the lock its clock is checked under, and not (but for a write under way) after the run ends; only a binary's first `running N tests` line restarts its clock; the slot wait never sleeps past its limit | | 2026-11-03 | minor | Quality gates: a timed-out test run's processes are signalled through pidfds on Linux (never a reused pid; without pidfds only xtask's own child is killed), and one that can't be killed is continued rather than left stopped | diff --git a/xtask/src/ci.rs b/xtask/src/ci.rs index 07911382db6..cbaaa4b3c93 100644 --- a/xtask/src/ci.rs +++ b/xtask/src/ci.rs @@ -95,12 +95,34 @@ pub(crate) fn nextest() -> bool { }) } +/// The nextest profile xtask's nextest runs use: `.config/nextest.toml`'s `[profile.xtask]` holds +/// the per-test time limit, so a plain `cargo nextest run` (the default profile) keeps nextest's own +/// defaults (#3058, #3060). +pub(crate) const NEXTEST_PROFILE: &str = "xtask"; + +/// The `NEXTEST_PROFILE` a nextest run of xtask sets, given the caller's (`caller`): xtask's profile, +/// unless the caller chose one. +fn nextest_profile_to_set(caller: Option<&std::ffi::OsStr>) -> Option<&'static str> { + if caller.is_some_and(|v| !v.is_empty()) { None } else { Some(NEXTEST_PROFILE) } +} + +/// Run `c`, a `cargo nextest run`, with xtask's nextest profile unless the caller chose one. +pub(crate) fn use_nextest_profile(c: &mut Command) { + if let Some(profile) = nextest_profile_to_set(std::env::var_os("NEXTEST_PROFILE").as_deref()) { + c.env("NEXTEST_PROFILE", profile); + } +} + /// A test run of `args` (packages, features, targets, filters): `cargo nextest run`, or `cargo /// test`. The command and how to print it. `--no-fail-fast`: a failing test binary doesn't stop /// the others, so one CI run shows every failure, not just the first crate's. fn tests(args: &[&str]) -> (Command, String) { let mut c = cargo(); - let tool = if nextest() { "nextest run" } else { "test" }; + let nextest = nextest(); + let tool = if nextest { "nextest run" } else { "test" }; + if nextest { + use_nextest_profile(&mut c); + } c.args(tool.split(' ')).arg("--no-fail-fast").args(args); (c, format!("cargo {tool} --no-fail-fast {}", args.join(" "))) } @@ -412,6 +434,40 @@ fn probe_gpu(backend: Option<&str>, limit: Option) -> Resul } } +#[cfg(test)] +mod nextest_profile_tests { + use super::{NEXTEST_PROFILE, nextest_profile_to_set}; + + #[test] + fn xtask_picks_its_nextest_profile_unless_the_caller_chose_one() { + assert_eq!(nextest_profile_to_set(None), Some(NEXTEST_PROFILE)); + assert_eq!(nextest_profile_to_set(Some(std::ffi::OsStr::new(""))), Some(NEXTEST_PROFILE), "empty is unset"); + assert_eq!(nextest_profile_to_set(Some(std::ffi::OsStr::new("default"))), None, "the caller's profile wins"); + } + + /// The per-test time limit lives in xtask's profile, not the default one, so a plain + /// `cargo nextest run` keeps nextest's defaults (FredApps on #3058). + #[test] + fn only_xtasks_nextest_profile_has_the_time_limit() { + let config = std::fs::read_to_string(super::root().join(".config/nextest.toml")).unwrap(); + let mut table = ""; + let mut limits = Vec::new(); + for line in config.lines().map(|l| l.split('#').next().unwrap_or(l).trim()) { + if line.starts_with('[') { + table = line; + } else if line.starts_with("slow-timeout") || line.starts_with("test-threads") { + limits.push((table, line)); + } + } + let xtask = format!("[profile.{NEXTEST_PROFILE}]"); + assert!(!limits.is_empty(), "the time limit is in .config/nextest.toml"); + for (table, line) in &limits { + assert_eq!(*table, xtask, "only xtask's profile sets `{line}`"); + } + assert!(limits.iter().any(|(_, l)| l.contains("terminate-after = 30")), "{limits:?}"); + } +} + #[cfg(test)] mod ci_jobs_tests { use super::ci_jobs; diff --git a/xtask/src/deadline.rs b/xtask/src/deadline.rs index 74cd86fb5ae..0d5a8325fcd 100644 --- a/xtask/src/deadline.rs +++ b/xtask/src/deadline.rs @@ -117,14 +117,14 @@ pub fn test_binary_timeout() -> Result, String> { } /// What to say when the tests run under `cargo nextest run` and [`TEST_BINARY_TIMEOUT_ENV`] is -/// set: nextest prints no `Running` lines for xtask's clock, so its own `slow-timeout` -/// (`.config/nextest.toml`, 30 minutes per test) applies instead, whatever the variable says (`0` -/// included). `None` when the variable isn't set. +/// set: nextest prints no `Running` lines for xtask's clock, so the `slow-timeout` of xtask's nextest +/// profile (`.config/nextest.toml`, 30 minutes per test) applies instead, whatever the variable says +/// (`0` included). `None` when the variable isn't set. pub fn nextest_note(value: Option<&std::ffi::OsStr>) -> Option { let value = value.filter(|v| !v.is_empty())?; Some(format!( - "note: {TEST_BINARY_TIMEOUT_ENV}={} doesn't apply under cargo nextest: .config/nextest.toml's slow-timeout ends a test \ - after 30 minutes instead (a profile there without terminate-after, chosen with NEXTEST_PROFILE, runs without it)", + "note: {TEST_BINARY_TIMEOUT_ENV}={} doesn't apply under cargo nextest: the slow-timeout of .config/nextest.toml's \ + xtask profile ends a test after 30 minutes instead (NEXTEST_PROFILE=default runs without it)", value.to_string_lossy() )) } diff --git a/xtask/src/test.rs b/xtask/src/test.rs index 5d5e556a0f8..f393b3fb78b 100644 --- a/xtask/src/test.rs +++ b/xtask/src/test.rs @@ -336,6 +336,7 @@ pub fn run(raw: &[&str]) -> Result<(), String> { let mut summary = Vec::new(); if let Some(nextest) = nextest { let mut c = super::cargo(); + crate::ci::use_nextest_profile(&mut c); c.args(["nextest", "run"]).args(&nextest); if let Err(e) = super::run_tests(c, &format!("cargo nextest run {}", nextest.join(" ")), limit) { failed.push(("cargo nextest run".to_owned(), e)); From 30fa4764acaf673753a8e8f556ec3d19cb00cebf Mon Sep 17 00:00:00 2001 From: THEtheChad <880190+THEtheChad@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:32:42 -0600 Subject: [PATCH 39/40] Issue #3061: Running tests no longer describes a plain cargo test default #3086 dropped `.cargo/config.toml`'s RUST_TEST_THREADS default (FredApps on #3058), so plain `cargo test` runs one test per CPU core in every binary again, and any RUST_TEST_THREADS you set wins in xtask's runs, 4 included. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9534954b33f..e46e773e0fa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -183,11 +183,11 @@ of it. - **Run tests through xtask:** `cargo xtask test [-p PKG]… [-- FILTER]` (`--keep-going` runs every test binary and names each that fails, instead of stopping at the first) or `cargo xtask ci --quick`. Both take the machine's CI slot and `ci`'s RAM-aware caps: build jobs and test threads sized by the memory available, at most 4 tests at once in - each binary unless you set `RUST_TEST_THREADS` (a value other than 4 wins). README → Quick start describes them + each binary unless you set `RUST_TEST_THREADS` (a value you set wins). README → Quick start describes them and the settings that change them. Plain `cargo test -p PKG` on a small crate is fine while you iterate. - **Never run plain `cargo test --workspace`**, with or without `--no-fail-fast`. It takes no CI slot, so it runs on - top of every other agent's tests, and gets none of `ci`'s caps (`.cargo/config.toml` only limits it to 4 tests at - once in each binary). + top of every other agent's tests, and gets none of `ci`'s caps (libtest runs one test per CPU core in every + binary). - **When `ci` fails on a test your change doesn't touch,** rerun only that package's tests: `cargo xtask test -p PKG` (`-- --exact TEST_PATH` narrows it to the one test; a bare `-- NAME` runs every test whose path contains it). If it fails without your change too, say so in the PR and link its issue, or file one; if it passes on a rerun, it's From 0079127264698371bc6656343d40fd89f0a501e3 Mon Sep 17 00:00:00 2001 From: THEtheChad <880190+THEtheChad@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:32:51 -0600 Subject: [PATCH 40/40] Issue #3061: the test-thread sentence says once that RUST_TEST_THREADS wins Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index e46e773e0fa..313cec462b3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -183,7 +183,7 @@ of it. - **Run tests through xtask:** `cargo xtask test [-p PKG]… [-- FILTER]` (`--keep-going` runs every test binary and names each that fails, instead of stopping at the first) or `cargo xtask ci --quick`. Both take the machine's CI slot and `ci`'s RAM-aware caps: build jobs and test threads sized by the memory available, at most 4 tests at once in - each binary unless you set `RUST_TEST_THREADS` (a value you set wins). README → Quick start describes them + each binary unless you set `RUST_TEST_THREADS`. README → Quick start describes them and the settings that change them. Plain `cargo test -p PKG` on a small crate is fine while you iterate. - **Never run plain `cargo test --workspace`**, with or without `--no-fail-fast`. It takes no CI slot, so it runs on top of every other agent's tests, and gets none of `ci`'s caps (libtest runs one test per CPU core in every