diff --git a/.config/nextest.toml b/.config/nextest.toml new file mode 100644 index 00000000000..965ee560f42 --- /dev/null +++ b/.config/nextest.toml @@ -0,0 +1,8 @@ +# `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): NEXTEST_PROFILE=default runs without it. +slow-timeout = { period = "60s", terminate-after = 30 } diff --git a/AGENTS.md b/AGENTS.md index 8d0ca31a605..313cec462b3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -175,10 +175,30 @@ 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: 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`. 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 + 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 + 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. + ## 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. 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/README.md b/README.md index a3e49813607..f698165d70d 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; runs every binary, names each that failed ``` `cargo xtask ci --quick` compares with the merge base of `origin/main` (`--base REF` for another) @@ -415,7 +416,19 @@ 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 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 +`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 +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 @@ -427,6 +440,16 @@ 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; `--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 `--`. + **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..6b70bd6d557 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -73,8 +73,42 @@ 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. + +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 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 +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 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 +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 -`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, @@ -87,6 +121,12 @@ 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 | +| 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: `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/Cargo.toml b/xtask/Cargo.toml index c68c7dca25f..418af229503 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -15,3 +15,8 @@ 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): 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/ci.rs b/xtask/src/ci.rs index f5aa147a2dd..cbaaa4b3c93 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, 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, 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 @@ -63,7 +65,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 +74,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") { @@ -86,17 +88,41 @@ 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 }) } +/// 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(" "))) } @@ -108,67 +134,17 @@ 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"; /// 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) { + 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"])); @@ -188,7 +164,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}"); @@ -211,10 +189,13 @@ 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) - 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); @@ -235,17 +216,21 @@ 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()); // 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; } @@ -287,14 +272,15 @@ 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") }), ), ( "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")), }), ), @@ -316,7 +302,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, @@ -355,7 +341,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)); @@ -425,22 +411,61 @@ 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}")), + } +} + +#[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:?}"); } - Ok(String::from_utf8_lossy(&out.stdout).into_owned()) } #[cfg(test)] @@ -458,4 +483,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/ci_lock.rs b/xtask/src/ci_lock.rs index 70c90b043bb..9c2a7d72bf1 100644 --- a/xtask/src/ci_lock.rs +++ b/xtask/src/ci_lock.rs @@ -9,6 +9,14 @@ //! - `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 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; @@ -17,6 +25,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 = 240; + /// A held CI slot; dropping it releases the slot. pub struct Held { _file: File, @@ -108,25 +121,61 @@ 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)? { + // 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(freed_as_it_ended(wait)); + } eprintln!("=== ci: waited {:.0} s for a CI slot ===", waiting.elapsed().as_secs_f64()); return Ok(Some(held)); } } } +/// 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, \ + 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("; ") }; + 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::*; @@ -137,6 +186,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"); @@ -149,6 +205,60 @@ 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 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 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 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/deadline.rs b/xtask/src/deadline.rs new file mode 100644 index 00000000000..0d5a8325fcd --- /dev/null +++ b/xtask/src/deadline.rs @@ -0,0 +1,1544 @@ +//! 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, +//! 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, 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 +//! 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). +//! +//! 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 ([`kill`]) the binary (while unreaped, so its pid is +//! 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 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. +//! +//! 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::{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 +/// 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 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, 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; + +/// 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) +} + +/// 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 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: 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() + )) +} + +/// `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; + 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 +} + +/// 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)] +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`, `bench:`). + pub finished: Names, + /// The tests libtest said had been running for over 60 seconds, in that order. + 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, + /// 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 { + /// 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(); + // 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 Event::Binary; + } + if let Some(rest) = text.strip_prefix("Doc-tests ").filter(|_| cargo_status) { + self.start_binary(format!("doctests of {rest}"), None); + 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); + // 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; + } + 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; + } + } + + /// 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; + self.header_seen = false; + } + + fn reset(&mut self) { + 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)).map(str::to_owned).collect(); + let pending = strip_ansi(&self.pending); + 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 + } +} + +/// 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, and its own first `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 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::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(target_os = "linux"), 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, 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 { + Exited(ExitStatus), + /// Out of time: killed (what the kill did), with what its output said by then. + 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, + /// 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, +} + +struct Watch { + progress: Progress, + /// When the current limit started, `None` while it doesn't run. + since: Option, + stdout: Vec, + 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(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 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] = [ + (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 (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, &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); + // 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()); + shared.closed.store(true, Ordering::Release); + closed + }; + 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(), held_open } + }; + loop { + match child.try_wait() { + Ok(Some(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(&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); + 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 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, 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(); + 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, + }; + if shared.closed.load(Ordering::Acquire) { + continue; + } + let chunk = buf.get(..n).unwrap_or_default(); + { + 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()); + } + 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(); + } + } + 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: 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 +/// 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()) +} + +/// 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 (`--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 `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_run(Some(&mut child), &marker); + return None; + }; + let (tx, rx) = mpsc::channel(); + 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 }); + }); + if reader.is_err() { + kill_run(Some(&mut child), &marker); + return None; + } + let (mut status, mut listed) = (None, None); + let result = loop { + if status.is_none() { + match child.try_wait() { + Ok(s) => status = s, + 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 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 + (_, Some(l)) if l.cut => break listed, + (Some(s), Some(_)) => break listed.filter(|_| s.success()), + _ => {} + } + if Instant::now() >= until { + 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_run(Some(&mut child), &marker); + } else { + kill_run(None, &marker); + } + result +} + +/// 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; `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}", 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(|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).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, |l| l.names.len()), + shown.join(", ") + )); + } + (None, Some(total)) => { + lines.push(format!(" {} of {total} test(s) had finished", progress.finished.len().min(total))); + } + _ => {} + } + 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))) +} + +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"]); + } + 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) => { + 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 +} + +/// 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> { + 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(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"); + } + let dir = cmd.get_current_dir().map(Path::to_path_buf); + 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) => { + let listed = progress.exe.as_ref().and_then(|exe| { + let exe = match &dir { + Some(dir) if exe.is_relative() => dir.join(exe), + _ => exe.clone(), + }; + 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); + shown.extend(lines); + Err(format!("{error}: {binary}")) + } + } +} + +/// 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::*; + + 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_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_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"); + 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"); + 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_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"); + 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 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 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 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!(kill::marked(&marker.entry()), [ours.id()]); + for c in decoys.iter_mut().chain([&mut ours]) { + let _ = c.kill(); + let _ = c.wait(); + } + } + + #[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 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)\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) && !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 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). + #[cfg(target_os = "linux")] + fn gone(pid: &str) -> bool { + pid.parse().map_or(true, |pid| kill::tests::state(pid).is_none_or(|s| s == 'Z')) + } + + #[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); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[cfg(target_os = "linux")] + 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)] + fn sh(script: &str) -> Command { + let mut c = Command::new("/bin/sh"); + c.args(["-c", script]); + c + } + + // 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"); + 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 t = Instant::now(); + let mut shown = Vec::new(); + 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)\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 in its process tree and by the run's environment marker)") + ); + } + + // 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"); + 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); + } + + /// 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() { + 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 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")); + } + + // 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 + 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'"; + assert_eq!(run_cargo_tests(sh(script), 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 shown = Vec::new(); + 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(); + assert!(wait_gone(binary.trim()), "the test binary cargo started was killed too"); + 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"); + } + + /// 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 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); + } + 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("shows no more of it")); + 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() { + 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())); + } +} diff --git a/xtask/src/deadline/kill.rs b/xtask/src/deadline/kill.rs new file mode 100644 index 00000000000..c7426f346f5 --- /dev/null +++ b/xtask/src/deadline/kill.rs @@ -0,0 +1,877 @@ +//! 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 `/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, 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 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; +use std::process::{Child, ExitStatus}; +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(target_os = "linux")] +const ROUNDS: usize = 64; + +/// 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 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 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 (own, mut note) = (true, kill_all(child.as_ref().map(|c| c.id()), marker)); + if let Some(child) = child { + 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())); + } + } + note +} + +/// 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(status)) => return Some(status), + Ok(None) if Instant::now() < until => std::thread::sleep(TICK), + _ => return None, + } + } +} + +/// 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 { + 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; under cargo, the test binary is one of them", + ) +} + +#[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(target_os = "linux")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Sig { + Stop, + Kill, + Cont, +} + +/// Why a signal wasn't delivered. +#[cfg(target_os = "linux")] +#[derive(Debug, PartialEq, Eq)] +pub(super) enum Unsent { + /// 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 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, + fd: Option, +} + +/// What [`Os::hold`] made of a pid that looked like one of the run's processes. +#[cfg(target_os = "linux")] +pub(super) enum Hold { + /// 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 can't be held or looked at, so it isn't signalled: why. + Unheld(String), +} + +/// A look through `/proc`. +#[cfg(target_os = "linux")] +#[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")] +pub(super) trait Os { + fn scan(&mut self, entry: &str) -> Result { + proc_scan(entry) + } + + /// 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 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() } + } + + fn send(&mut self, held: &Held, sig: Sig) -> Result<(), Unsent> { + send(held, sig) + } + + /// 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) + } +} + +/// The real `/proc` and signals. +#[cfg(target_os = "linux")] +pub(super) struct Real; + +#[cfg(target_os = "linux")] +impl Os for Real {} + +/// 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, 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(); + 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, &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)); + } + 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(target_os = "linux")] +#[derive(Default)] +struct Ending { + held: Vec, + 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` (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<(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 { + for mut held in fresh.drain(..) { + match os.send(&held, Sig::Stop) { + Ok(()) => { + held.frozen = true; + stopped.insert(held.pid); + } + // 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)), + } + seen.insert(held.pid); + end.held.push(held); + } + 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; + } + }; + 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) { + 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.unheld.push(why); + } + } + } + if fresh.is_empty() { + return round; + } + } + ROUNDS +} + +/// Whether `ppid`, read from a child's `/proc` after the child was held, is one of the held +/// 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| matches!(os.exited(h), Ok(None | Some(false)))) +} + +/// 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(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() { + 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. +#[cfg(target_os = "linux")] +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). +/// A held process that can't be asked counts as alive; a look that fails is added to `problems`. +#[cfg(target_os = "linux")] +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| 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); + } +} + +/// What the kill did, before its problems. +#[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!( + "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(target_os = "linux")] +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()) }; + 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) +} + +#[cfg(target_os = "linux")] +fn exited(held: &Held) -> Result, String> { + use rustix::event::{PollFd, PollFlags, Timespec}; + 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)).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")] +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 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) -> 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}")), + }; + 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(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`. 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) -> Result { + 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(scan) +} + +/// Whether an error reading a process's `/proc` files means it has gone (or is another user's). +#[cfg(target_os = "linux")] +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 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) -> Result, String> { + use std::os::unix::fs::MetadataExt; + 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), + } + // 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, + 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 +/// spaces and parentheses. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +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(|s| s.marked.into_iter().collect()).unwrap_or_default() +} + +#[cfg(test)] +pub(super) mod tests { + use super::*; + + #[test] + fn the_parent_is_read_past_any_parenthesis_in_the_command_name() { + 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")] + #[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")] + 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")] + 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) { + 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 = 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()) { + break pid; + } + assert!(Instant::now() < until, "the script wrote no pid"); + std::thread::sleep(TICK); + }; + let held = Real.hold_root(pid); + let fd = held.fd.is_some(); + cleanup.others.push(held); + assert!(fd, "the grandchild is held by a pidfd"); + (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(target_os = "linux")] + struct KillFails { + root: u32, + refused: Vec, + } + + #[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 { + 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(target_os = "linux")] + #[test] + fn a_process_whose_kill_fails_is_not_left_stopped() { + 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), 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); + 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) -> Result { + let mut scan = proc_scan(entry)?; + scan.marked.extend(self.decoy.take()); + Ok(scan) + } + } + + /// 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 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), 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"); + 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; 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 scan = proc_scan(entry)?; + if std::mem::take(&mut self.once) { + scan.table.push((self.decoy, self.parent)); + } + 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 { + 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::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"); + 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), 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::new(); + let pid = decoy(&mut cleanup); + let held = Real.hold_root(pid); + 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)); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 33b236b56d9..0a43813b8eb 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 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)] @@ -10,11 +10,13 @@ mod bench; mod ci_lock; mod ci_quick; mod ci_report; +mod deadline; mod ico; mod layers; mod parity; mod roots; mod stats; +mod test; mod version; mod web; @@ -62,7 +64,20 @@ 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 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] + 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) + 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 + (--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`) @@ -87,6 +102,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 +155,66 @@ 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 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); +} + +/// 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())); + } +} + +/// [`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 new file mode 100644 index 00000000000..f393b3fb78b --- /dev/null +++ b/xtask/src/test.rs @@ -0,0 +1,559 @@ +//! `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; `--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`]). 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, deadline}; + +/// 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 ([`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), 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, 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); + 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(" "); + eprintln!("$ {shown}"); + 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 +/// (`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, each with how it ended. + pub failed: Vec<(String, String)>, + /// 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() { + let Err(error) = run_one(binary) else { + outcome.passed += 1; + continue; + }; + outcome.failed.push((binary.label(), error)); + 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, 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), limit)); + 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 +/// filter expression (so the build is still the workspace's), `--no-fail-fast` for `--keep-going`. +/// +/// 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(" | "); + v.extend(["-E".to_owned(), filter]); + } + if args.keep_going { + v.push("--no-fail-fast".to_owned()); + } + 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(filters); + } + Ok(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); `--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() { + 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.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())); + } + Some(v) +} + +/// `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 }; + 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)?; + super::use_ci_caps(&slot); + let packages = packages(&super::metadata()?, &args.packages)?; + let mut failed = Vec::new(); + 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)); + } + } 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, 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)); + } + 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 let Err(e) = super::run_tests(c, &format!("cargo {}", doc.join(" ")), limit) { + failed.push(("doctests".to_owned(), e)); + } + } + 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 (label, error) in &failed { + println!(" FAIL {label}: {error}"); + } + Err(format!("tests failed in {}", failed.iter().map(|(label, _)| label.as_str()).collect::>().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"]); + 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] + 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(), "exit 101".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).unwrap(), ["--workspace", "--lib", "--bins", "--tests"]); + let some = parse(&["-p", "b", "-p", "a", "--keep-going", "--", "foo"]).unwrap(); + assert_eq!( + 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(); + 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 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, 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}"); + } + + #[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() }; + 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}"); + } + } +}