Skip to main content

tak_cli/
measure.rs

1//! Measurement backends.
2//!
3//! Two tiers, deliberately separated:
4//!
5//! - **Deterministic** (`instructions`) — reproducible to ~0.02% run-to-run and
6//!   ~0.035% across wildly different machine load. This is the only tier that may
7//!   gate CI.
8//! - **Timing** (`wall_*`) — recorded and charted, never gated. On a quiet 32-core
9//!   host wall clock still shows 4–20% coefficient of variation; under contention
10//!   the median moves ~150%.
11//!
12//! Syscall counts and peak RSS sit awkwardly between the two: better than wall
13//! clock (~1%) but not deterministic, because they move with thread scheduling.
14//! They are recorded, and may be flagged, but must not gate at a tight threshold.
15
16use crate::config::{AutoRuns, DEFAULT_OK_EXIT_CODES, Runs, SELF_TOOL, Subject};
17use crate::settings::Settings;
18use anyhow::{Context, Result, bail};
19use std::collections::BTreeMap;
20use std::path::Path;
21use std::process::{Command, Stdio};
22use std::sync::{Arc, Mutex};
23use std::time::Duration;
24use std::time::Instant;
25
26#[derive(Debug, Clone)]
27pub struct Plan {
28    pub cmd: Vec<String>,
29    pub warmup: u32,
30    pub runs: u32,
31    /// Directory to run in. Declared benchmarks resolve relative commands
32    /// against `tak.toml`'s directory, not the caller's — otherwise the same
33    /// benchmark measures different things depending on where you stood.
34    pub dir: Option<std::path::PathBuf>,
35    /// Resolved settings. Carried on the plan rather than read from a global so
36    /// a test can measure under a different configuration without touching the
37    /// environment of the whole test binary.
38    pub settings: Settings,
39}
40
41/// A command for running a benchmark subject, with the scrubbed variables
42/// removed.
43///
44/// Every subject spawn goes through here. Under cachegrind the removal is
45/// applied to valgrind itself, which the subject inherits from.
46///
47/// What gets removed is [`Settings::scrubbed_env`] — `env_deny` less
48/// `env_allow`, both declared on the `Settings` registry. The default is the
49/// forge tokens because a CLI that finds one often does more with it than
50/// without, so a measurement would move depending on whether CI happened to
51/// export one.
52///
53/// This controls direct inheritance, not hostile-code isolation. A subject can
54/// still inspect accessible same-user processes and files, so `backfill` must
55/// run without credentials when its release binaries are not trusted.
56///
57/// tak's own network calls are unaffected — `backfill` authenticates with
58/// `curl` directly rather than through this path.
59fn subject(bin: &str, settings: &Settings) -> Command {
60    let mut c = Command::new(bin);
61    for key in settings.scrubbed_env() {
62        c.env_remove(key);
63    }
64    c
65}
66
67/// Where a command runs and what it sees, beyond its argv.
68#[derive(Debug, Clone, Copy)]
69struct Site<'a> {
70    dir: Option<&'a Path>,
71    env: &'a BTreeMap<String, String>,
72    settings: &'a Settings,
73}
74
75/// Build a spawn of `argv` at `site`.
76///
77/// Declared variables are applied after the scrub. A variable written into
78/// `tak.toml` for a subject is an explicit choice, not something inherited by
79/// accident, which is the only thing the scrub exists to stop.
80fn command(argv: &[String], site: &Site) -> Result<Command> {
81    let (bin, args) = argv.split_first().context("empty command")?;
82    let mut c = subject(bin, site.settings);
83    c.args(args).envs(site.env);
84    if let Some(d) = site.dir {
85        c.current_dir(d);
86    }
87    Ok(c)
88}
89
90/// One successful run of a subject's timed command.
91#[derive(Debug, Clone, Copy, PartialEq)]
92pub struct Sample {
93    /// Elapsed wall time in milliseconds.
94    pub ms: f64,
95    /// What the command exited with: one of its `ok_exit_codes`, kept so the
96    /// export shows what actually happened rather than assuming 0.
97    pub exit_code: i32,
98}
99
100/// The exit code of a sample that counts, or the error that drops its
101/// subject.
102///
103/// A death by signal has no exit code and always fails: a subject that
104/// crashed or was killed did not do the work being measured, whatever its
105/// `ok_exit_codes` allow.
106fn accepted(bin: &str, status: std::process::ExitStatus, ok: &[i32], via: &str) -> Result<i32> {
107    match status.code() {
108        Some(code) if ok.contains(&code) => Ok(code),
109        // Name the accepted codes only when they are not the default, where
110        // "exited with 1" alone would leave the reader wondering why that
111        // was a failure.
112        _ if ok == DEFAULT_OK_EXIT_CODES => {
113            bail!("benchmark subject `{bin}` exited with {status}{via}")
114        }
115        _ => bail!(
116            "benchmark subject `{bin}` exited with {status}{via}, and ok_exit_codes is {}",
117            ok.iter().map(i32::to_string).collect::<Vec<_>>().join(", ")
118        ),
119    }
120}
121
122/// Run once, discarding output, returning elapsed wall time and exit code.
123///
124/// No shell. Spawning a shell adds its own startup cost and variance to every
125/// sample, which for commands in the 10ms range is a large fraction of the
126/// measurement — the same reasoning behind poop's refusal to support one.
127fn time_once(cmd: &[String], site: &Site, ok: &[i32]) -> Result<Sample> {
128    let mut c = command(cmd, site)?;
129    c.stdout(Stdio::null()).stderr(Stdio::null());
130    let bin = &cmd[0];
131    let start = Instant::now();
132    let status = c
133        .status()
134        .with_context(|| format!("failed to spawn `{bin}`"))?;
135    let ms = start.elapsed().as_secs_f64() * 1000.0;
136    let exit_code = accepted(bin, status, ok, "")?;
137    Ok(Sample { ms, exit_code })
138}
139
140/// How much of a failing prepare, setup or check step's stderr to keep for
141/// the message. Enough for the last few lines; a verbose reset command's full
142/// output would otherwise sit in memory before every sample.
143const UNTIMED_STDERR_TAIL: usize = 4096;
144
145/// Run a subject's prepare step. Untimed, so reading its stderr for the error
146/// message costs the measurement nothing.
147fn prepare_once(cmd: &[String], site: &Site) -> Result<()> {
148    required("prepare", cmd, site)
149}
150
151/// Run an untimed step that must succeed: `prepare` or `setup`.
152fn required(what: &str, cmd: &[String], site: &Site) -> Result<()> {
153    match untimed(what, cmd, site)? {
154        None => Ok(()),
155        Some(failure) => bail!("{failure}"),
156    }
157}
158
159/// Run a subject's check step after a timed sample. `Ok(None)` is a pass and
160/// `Ok(Some(why))` a failed sample. Only a check that cannot be started at
161/// all is an error: that is a mistake in `tak.toml`, not a finding about the
162/// subject, and would otherwise read as every sample having failed.
163fn check_once(cmd: &[String], site: &Site) -> Result<Option<String>> {
164    untimed("check", cmd, site)
165}
166
167/// Run an untimed step — `prepare`, `setup` or `check`, named by `step` in
168/// messages. `Ok(Some(why))` when it exits non-zero, naming the step and the
169/// last line of its stderr.
170///
171/// Its output is not passed through: on a terminal it would tear up the
172/// progress bar, and in a log a setup that clones a fixture could bury the
173/// results. The tail of stderr is kept for the message.
174///
175/// Always judged by exit 0, whatever the subject's `ok_exit_codes` say: those
176/// describe the program being measured. A setup or reset that failed leaves
177/// every later sample starting from the wrong state, and a check passes only
178/// by exiting 0.
179///
180/// stderr goes to an anonymous temporary file, not a pipe, and the step is
181/// done when its process exits. With a pipe, a step that starts something in
182/// the background — a fixture server, a daemon, a build server, `sleep 600 &`
183/// — leaves that process holding the write end: waiting for EOF hung the
184/// whole run, and closing the read end instead would kill the process with
185/// SIGPIPE the next time it logged. A file has neither problem. tak neither
186/// waits for nor kills such processes, since a server started by `setup` may
187/// be exactly the point; one still running while samples are timed competes
188/// with them, and the timings show it.
189///
190/// The cost is disk: whatever a leftover process writes to stderr lands in
191/// the file, in the temp directory, for as long as it runs. The file has no
192/// name on Unix and is deleted when its last handle closes on Windows, so the
193/// space comes back once tak has dropped its handle and the process exits. A
194/// step whose background process logs heavily should redirect that output.
195///
196/// There is deliberately no overall deadline: a setup that builds or clones a
197/// fixture can legitimately take minutes.
198fn untimed(step: &str, cmd: &[String], site: &Site) -> Result<Option<String>> {
199    let mut c = command(cmd, site)?;
200    let bin = &cmd[0];
201    let err = tempfile::tempfile()
202        .with_context(|| format!("failed to create a file for {step} `{bin}`'s stderr"))?;
203    let reader = err
204        .try_clone()
205        .with_context(|| format!("failed to create a file for {step} `{bin}`'s stderr"))?;
206    let status = c
207        .stdin(Stdio::null())
208        .stdout(Stdio::null())
209        .stderr(Stdio::from(err))
210        .status()
211        .with_context(|| format!("failed to spawn {step} `{bin}`"))?;
212    if status.success() {
213        return Ok(None);
214    }
215    // A check like `git diff --quiet` says nothing on failure by design, so
216    // silence is reported as the status alone. An unreadable file is treated
217    // the same way: the status is the finding, the stderr only decoration.
218    let tail = stderr_tail(&reader).unwrap_or_default();
219    let stderr = String::from_utf8_lossy(&tail);
220    Ok(Some(match stderr.lines().rfind(|l| !l.trim().is_empty()) {
221        Some(last) => format!("{step} `{bin}` exited with {status}: {}", last.trim()),
222        None => format!("{step} `{bin}` exited with {status}"),
223    }))
224}
225
226/// The last [`UNTIMED_STDERR_TAIL`] bytes of a step's stderr file.
227///
228/// Read by position, not through the file cursor: the handle is a duplicate
229/// of the one a leftover process may still be writing through, and on Unix
230/// they share the cursor, so seeking would move where that process writes.
231/// Windows has no positional read that leaves the cursor alone; there a
232/// leftover writer may overwrite part of a file nobody reads again.
233fn stderr_tail(f: &std::fs::File) -> std::io::Result<Vec<u8>> {
234    let len = f.metadata()?.len();
235    let start = len.saturating_sub(UNTIMED_STDERR_TAIL as u64);
236    let mut buf = vec![0u8; (len - start) as usize];
237    let mut filled = 0;
238    while filled < buf.len() {
239        let n = read_at(f, &mut buf[filled..], start + filled as u64)?;
240        if n == 0 {
241            break;
242        }
243        filled += n;
244    }
245    buf.truncate(filled);
246    Ok(buf)
247}
248
249#[cfg(unix)]
250fn read_at(f: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result<usize> {
251    std::os::unix::fs::FileExt::read_at(f, buf, offset)
252}
253
254#[cfg(windows)]
255fn read_at(f: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result<usize> {
256    std::os::windows::fs::FileExt::seek_read(f, buf, offset)
257}
258
259/// One entry in a run's sample order.
260#[derive(Debug, Clone, Copy, PartialEq, Eq)]
261pub struct Slot {
262    /// Index into the subjects being measured.
263    pub subject: usize,
264    /// Whether this sample is kept. Warmup samples run through the same
265    /// prepare-then-run path and are discarded.
266    pub timed: bool,
267}
268
269/// The order in which to take samples: every warmup round, then every timed
270/// round, each round a fresh shuffle of the subjects due in it.
271///
272/// Measuring one subject to completion before starting the next puts any
273/// drift over the run — contention on a shared host, thermal throttling, a
274/// cache filling up — entirely on whichever subjects ran while it happened,
275/// where it reads as a difference between them. One sample of each per round
276/// spreads that drift across all of them, and shuffling each round stops any
277/// subject from systematically running first (cold) or right after a
278/// particular other one (whose leftovers it inherits).
279///
280/// A subject with fewer samples than there are rounds sits out evenly spaced
281/// rounds rather than dropping out at the end, which would leave the late
282/// part of the run — and its drift — to the others.
283///
284/// `counts` is `(warmup, runs)` per subject. The same seed gives the same
285/// order for the same subjects.
286pub fn schedule(counts: &[(u32, u32)], seed: u64) -> Vec<Slot> {
287    let mut rng = fastrand::Rng::with_seed(seed);
288    let warmups: Vec<u64> = counts.iter().map(|&(w, _)| u64::from(w)).collect();
289    let runs: Vec<u64> = counts.iter().map(|&(_, r)| u64::from(r)).collect();
290    let mut out = rounds(&warmups, false, &mut rng);
291    out.extend(rounds(&runs, true, &mut rng));
292    out
293}
294
295/// Shuffled rounds taking `count[i]` samples of subject `i`.
296fn rounds(count: &[u64], timed: bool, rng: &mut fastrand::Rng) -> Vec<Slot> {
297    let total = count.iter().copied().max().unwrap_or(0);
298    let mut out = Vec::new();
299    for round in 0..total {
300        // Subject i is due in the rounds where floor(r * k / R) steps up:
301        // exactly k of the R rounds, as evenly spaced as integers allow.
302        let mut due: Vec<usize> = (0..count.len())
303            .filter(|&i| (round + 1) * count[i] / total > round * count[i] / total)
304            .collect();
305        rng.shuffle(&mut due);
306        out.extend(due.into_iter().map(|subject| Slot { subject, timed }));
307    }
308    out
309}
310
311/// Derive a benchmark's seed from the run's, so `--bench x --seed n` takes
312/// the same order for `x` as the full run with `--seed n` did.
313pub fn seed_for(seed: u64, bench: &str) -> u64 {
314    // FNV-1a: a fixed function, unlike std's randomly keyed hasher.
315    bench.bytes().fold(seed ^ 0xcbf2_9ce4_8422_2325, |h, b| {
316        (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)
317    })
318}
319
320/// Told about a run as it happens, to report progress.
321pub trait Observer {
322    /// Samples still to take per subject, warmups included. Called before the
323    /// first sample and again once `runs = "auto"` has settled its counts.
324    fn planned(&mut self, _remaining: &[u64]) {}
325    /// `subject`'s setup step is starting. Untimed and not a sample, so it
326    /// counts toward neither the samples taken nor their average.
327    fn setting_up(&mut self, _subject: usize) {}
328    /// A sample of `subject` is starting.
329    fn started(&mut self, _subject: usize) {}
330    /// A sample of `subject` finished; `elapsed` covers its prepare step too.
331    fn finished(&mut self, _subject: usize, _elapsed: Duration) {}
332    /// `subject` failed and takes no more samples.
333    fn dropped(&mut self, _subject: usize) {}
334}
335
336/// An observer that reports nothing.
337pub struct Quiet;
338impl Observer for Quiet {}
339
340/// What one subject's run produced.
341#[derive(Debug, Clone, Default, PartialEq)]
342pub struct Samples {
343    /// Timed samples in milliseconds, in the order taken.
344    pub times: Vec<f64>,
345    /// Whether the subject's `check` passed after each timed sample, aligned
346    /// with `times`. Empty when the subject has no check.
347    pub checks: Vec<bool>,
348    /// What each timed sample exited with, aligned with `times`: always one
349    /// of the subject's `ok_exit_codes`.
350    pub exit_codes: Vec<i32>,
351    /// Why the first failing check failed, for the warning that reports it.
352    pub first_failure: Option<String>,
353}
354
355impl Samples {
356    /// Checks that passed.
357    pub fn passed(&self) -> usize {
358        self.checks.iter().filter(|&&ok| ok).count()
359    }
360}
361
362/// Measure several subjects against each other, interleaved.
363///
364/// Returns each subject's timed samples in the order they were taken, with
365/// the outcome of its check after each one, or the error that stopped it. A failing subject is dropped from the remaining
366/// rounds and the others carry on: one competitor breaking should not throw
367/// away a long run's worth of everyone else's samples. Subject directories
368/// are used as given, so the caller resolves them first.
369///
370/// Every subject's `setup` runs first, once, in the order given: before
371/// any warmup, so a subject's first sample never shares the machine with
372/// another's setup and none of it is counted toward an auto run count. A
373/// subject whose setup fails is dropped like one whose prepare does.
374///
375/// Sampling then runs in two phases. The warmups come first, plus one kept
376/// sample of every `runs = "auto"` subject that has no warmups, so each auto
377/// subject has been timed at least once. Its run count is then fixed from the
378/// fastest of those samples, and every remaining timed sample is taken in
379/// shuffled rounds.
380///
381/// A subject's `check` runs after each of its timed samples, pilots included,
382/// and never after a warmup: a warmup is discarded, so whether it did the
383/// right work says nothing about any result. A failing check is recorded
384/// against its sample and the subject carries on — how often it fails is the
385/// finding — so only a check that cannot be started drops the subject.
386pub fn interleaved(
387    subjects: &[Subject],
388    seed: u64,
389    settings: &Settings,
390    observer: &mut dyn Observer,
391) -> Vec<Result<Samples>> {
392    interleaved_with_versions(subjects, seed, settings, observer).0
393}
394
395/// A subject's `version_cmd` result: `None` when it declares none or never
396/// got that far, otherwise what it printed or why it could not tell.
397pub type Version = Option<Result<String>>;
398
399/// [`interleaved`], also returning each subject's version.
400///
401/// Versions are asked for after every `setup` and before any warmup: setup
402/// may be what installs or builds the subject, so asking earlier would name
403/// the wrong program or none, and a tool that warms a cache or checks for
404/// updates on `--version` does so before the first sample rather than
405/// between samples. A subject whose setup failed is not asked.
406pub fn interleaved_with_versions(
407    subjects: &[Subject],
408    seed: u64,
409    settings: &Settings,
410    observer: &mut dyn Observer,
411) -> (Vec<Result<Samples>>, Vec<Version>) {
412    let mut rng = fastrand::Rng::with_seed(seed);
413    let mut results: Vec<Result<Samples>> = subjects
414        .iter()
415        .map(|s| {
416            // Zero runs would leave nothing to report on.
417            if s.runs == Runs::Fixed(0) {
418                bail!("runs must be at least 1");
419            }
420            Ok(Samples::default())
421        })
422        .collect();
423    // The fastest whole sample of each subject so far, prepare included —
424    // what an auto count is sized from. The fastest, because a warmup is
425    // often a cold outlier and would shrink the count for no reason.
426    let mut fastest: Vec<Option<Duration>> = vec![None; subjects.len()];
427
428    let warmups: Vec<u64> = subjects.iter().map(|s| u64::from(s.warmup)).collect();
429    let pilots: Vec<u64> = subjects
430        .iter()
431        .map(|s| u64::from(s.runs == Runs::Auto && s.warmup == 0))
432        .collect();
433    // Until the auto counts are known, plan on each one's floor.
434    let provisional: Vec<u64> = subjects
435        .iter()
436        .zip(&warmups)
437        .map(|(s, w)| {
438            w + u64::from(match s.runs {
439                Runs::Fixed(n) => n,
440                Runs::Auto => s.auto.min,
441            })
442        })
443        .collect();
444    observer.planned(&provisional);
445
446    for (i, s) in subjects.iter().enumerate() {
447        let (Some(setup), Ok(_)) = (&s.setup, &results[i]) else {
448            continue;
449        };
450        observer.setting_up(i);
451        let site = Site {
452            dir: s.setup_dir.as_deref(),
453            env: &s.env,
454            settings,
455        };
456        if let Err(e) = required("setup", setup, &site) {
457            results[i] = Err(e);
458            observer.dropped(i);
459        }
460    }
461
462    let versions: Vec<Version> = subjects
463        .iter()
464        .zip(&results)
465        .map(|(s, r)| r.as_ref().ok().and_then(|_| subject_version(s, settings)))
466        .collect();
467
468    let mut first = rounds(&warmups, false, &mut rng);
469    first.extend(rounds(&pilots, true, &mut rng));
470    run_slots(
471        &first,
472        subjects,
473        settings,
474        &mut results,
475        &mut fastest,
476        observer,
477    );
478
479    let remaining: Vec<u64> = subjects
480        .iter()
481        .enumerate()
482        .map(|(i, s)| match (&results[i], s.runs) {
483            (Err(_), _) => 0,
484            (Ok(_), Runs::Fixed(n)) => u64::from(n),
485            (Ok(taken), Runs::Auto) => {
486                let n = auto_runs(&s.auto, fastest[i]);
487                u64::from(n).saturating_sub(taken.times.len() as u64)
488            }
489        })
490        .collect();
491    observer.planned(&remaining);
492    let second = rounds(&remaining, true, &mut rng);
493    run_slots(
494        &second,
495        subjects,
496        settings,
497        &mut results,
498        &mut fastest,
499        observer,
500    );
501    (results, versions)
502}
503
504/// An auto subject's run count. One that was never timed — its every sample
505/// failed, so it is being dropped anyway — gets the floor.
506fn auto_runs(auto: &AutoRuns, fastest: Option<Duration>) -> u32 {
507    fastest.map_or(auto.min, |d| auto.runs_for(d))
508}
509
510/// Take the given samples, recording timed ones and the fastest slot seen.
511///
512/// `fastest` covers prepare and the command but not the check, so an auto
513/// count is sized from the same kind of sample whether it was a warmup (which
514/// runs no check) or a pilot. The observer is told the whole slot, check
515/// included, because that is what its time estimate has to cover.
516fn run_slots(
517    slots: &[Slot],
518    subjects: &[Subject],
519    settings: &Settings,
520    results: &mut [Result<Samples>],
521    fastest: &mut [Option<Duration>],
522    observer: &mut dyn Observer,
523) {
524    for slot in slots {
525        let Ok(samples) = &mut results[slot.subject] else {
526            continue;
527        };
528        let s = &subjects[slot.subject];
529        let site = Site {
530            dir: s.dir.as_deref(),
531            env: &s.env,
532            settings,
533        };
534        observer.started(slot.subject);
535        let began = Instant::now();
536        let taken = s
537            .prepare
538            .as_deref()
539            .map_or(Ok(()), |p| prepare_once(p, &site))
540            .and_then(|()| time_once(&s.cmd, &site, &s.ok_exit_codes));
541        let elapsed = began.elapsed();
542        // Only after the clock has stopped: the check is outside the
543        // measurement, however long it takes.
544        let checked = match (&taken, &s.check) {
545            (Ok(_), Some(check)) if slot.timed => check_once(check, &site).map(Some),
546            _ => Ok(None),
547        };
548        match taken.and_then(|sample| checked.map(|c| (sample, c))) {
549            Ok((sample, check)) => {
550                if slot.timed {
551                    samples.times.push(sample.ms);
552                    samples.exit_codes.push(sample.exit_code);
553                }
554                if let Some(failure) = check {
555                    samples.checks.push(failure.is_none());
556                    if samples.first_failure.is_none() {
557                        samples.first_failure = failure;
558                    }
559                }
560                let f = &mut fastest[slot.subject];
561                *f = Some(f.map_or(elapsed, |f| f.min(elapsed)));
562                observer.finished(slot.subject, began.elapsed());
563            }
564            Err(e) => {
565                results[slot.subject] = Err(e);
566                observer.dropped(slot.subject);
567            }
568        }
569    }
570}
571
572/// Wall-clock statistics over a set of samples, in milliseconds.
573///
574/// Reports `min` alongside the mean because contention is one-sided — a busy
575/// machine can only make a run slower, never faster — so the minimum is a far
576/// more robust estimator than the mean on shared CI hardware. The standard
577/// deviation is there to show how noisy the run was, not to be compared.
578pub fn stats(samples: &[f64]) -> BTreeMap<String, f64> {
579    let mut sorted = samples.to_vec();
580    sorted.sort_by(f64::total_cmp);
581    let n = sorted.len();
582    let mean = sorted.iter().sum::<f64>() / n as f64;
583    // Sample (n - 1) deviation, as hyperfine reports; a single sample has none.
584    let stddev = if n > 1 {
585        (sorted.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64).sqrt()
586    } else {
587        0.0
588    };
589    BTreeMap::from([
590        ("wall_min_ms".to_string(), sorted[0]),
591        ("wall_p50_ms".to_string(), sorted[n / 2]),
592        ("wall_mean_ms".to_string(), mean),
593        ("wall_max_ms".to_string(), sorted[n - 1]),
594        ("wall_stddev_ms".to_string(), stddev),
595        ("wall_n".to_string(), n as f64),
596    ])
597}
598
599/// Signs a subject's samples should not be taken at face value, as
600/// sentences for stderr. `samples` must be in the order they were taken.
601///
602/// Two, both from hyperfine's experience of what goes wrong:
603///
604/// - **Outliers**, by modified z-score (0.6745 x distance from the median /
605///   median absolute deviation) above 3.5, the usual cut-off. Something else
606///   on the machine ran, or the command's own work varies from run to run.
607/// - **A slow first sample**, over twice the median of the rest: a cache the
608///   warmup did not fill. The first timed sample should look like the others.
609///
610/// Nothing is dropped or corrected; the point is to say when a comparison
611/// deserves a second run. Slow outliers leave the minimum alone, but a fast
612/// one may be the minimum, so the two are reported apart.
613pub fn warnings(samples: &[f64]) -> Vec<String> {
614    let mut out = Vec::new();
615    let n = samples.len();
616    if n < 5 {
617        return out;
618    }
619    let median = |v: &mut Vec<f64>| {
620        v.sort_by(f64::total_cmp);
621        let m = v.len();
622        if m.is_multiple_of(2) {
623            (v[m / 2 - 1] + v[m / 2]) / 2.0
624        } else {
625            v[m / 2]
626        }
627    };
628    let med = median(&mut samples.to_vec());
629    let mad = median(&mut samples.iter().map(|x| (x - med).abs()).collect());
630    // The modified z-score needs a spread to divide by. When over half the
631    // samples equal the median the median deviation is zero, and any
632    // stand-in computed from all the samples would be inflated by the very
633    // spikes it should catch. With a flat majority there is no noise to
634    // measure against, so anything over a quarter away from the median
635    // counts. Identical samples still raise nothing.
636    let outlier = |x: f64| {
637        if mad > 0.0 {
638            0.6745 * (x - med).abs() / mad > 3.5
639        } else {
640            med > 0.0 && (x - med).abs() > 0.25 * med
641        }
642    };
643    {
644        let (fast, slow) = samples
645            .iter()
646            .filter(|&&x| outlier(x))
647            .fold(
648                (0, 0),
649                |(f, s), &x| if x < med { (f + 1, s) } else { (f, s + 1) },
650            );
651        if slow > 0 {
652            out.push(format!(
653                "{slow} of {n} samples are slow outliers; something else was running, or the \
654                 command's work varies. Consider a quieter machine or more runs."
655            ));
656        }
657        // A fast outlier is not harmless the way a slow one is: it is the
658        // minimum tak reports, so the headline number may rest on it.
659        if fast > 0 {
660            out.push(format!(
661                "{fast} of {n} samples are fast outliers, and the reported minimum may be one of \
662                 them; check the command did the same work every time."
663            ));
664        }
665    }
666    let rest = median(&mut samples[1..].to_vec());
667    if rest > 0.0 && samples[0] > 2.0 * rest {
668        out.push(format!(
669            "the first sample took {:.1}x the median of the rest; the warmup did not fill some \
670             cache. Consider more warmup runs.",
671            samples[0] / rest
672        ));
673    }
674    out
675}
676
677/// Wall-clock statistics over `plan.runs` samples of one command.
678pub fn wall(plan: &Plan) -> Result<BTreeMap<String, f64>> {
679    let subject = Subject {
680        name: SELF_TOOL.to_string(),
681        cmd: plan.cmd.clone(),
682        prepare: None,
683        setup: None,
684        setup_dir: None,
685        check: None,
686        dir: plan.dir.clone(),
687        version_cmd: None,
688        env: BTreeMap::new(),
689        vars: BTreeMap::new(),
690        when: None,
691        runs: Runs::Fixed(plan.runs),
692        auto: AutoRuns {
693            budget: crate::config::DEFAULT_BUDGET,
694            min: crate::config::DEFAULT_MIN_RUNS,
695            max: crate::config::DEFAULT_MAX_RUNS,
696        },
697        warmup: plan.warmup,
698        counters: false,
699        ok_exit_codes: DEFAULT_OK_EXIT_CODES.to_vec(),
700    };
701    // One subject has one possible order, so the seed is irrelevant.
702    let samples = interleaved(
703        std::slice::from_ref(&subject),
704        0,
705        &plan.settings,
706        &mut Quiet,
707    )
708    .pop()
709    .expect("one result per subject")?;
710    Ok(stats(&samples.times))
711}
712
713/// Is cachegrind usable on this machine?
714///
715/// Exposed so callers can tell "no counters because valgrind is missing" from
716/// "no counters because the measurement failed" — two problems with entirely
717/// different fixes.
718pub fn valgrind_available() -> bool {
719    Command::new("valgrind")
720        .arg("--version")
721        .stdout(Stdio::null())
722        .stderr(Stdio::null())
723        .status()
724        .map(|s| s.success())
725        .unwrap_or(false)
726}
727
728/// Repeats of the cachegrind run. Three is enough to catch a bimodal subject
729/// without tripling the cost of a measurement that is already ~50x slowed.
730const COUNTER_RUNS: u32 = 3;
731
732/// A subject varying by more than this is doing environment-dependent work, and
733/// its instruction count is not a usable gate. Well above the ~0.005% observed
734/// for a genuinely hermetic command, far below the 16% seen from one that
735/// touches the network.
736const SPREAD_WARN_PCT: f64 = 0.5;
737
738/// Instruction counts from repeated cachegrind runs.
739#[derive(Debug, Clone, Copy)]
740pub struct Counted {
741    pub min: u64,
742    pub max: u64,
743    pub runs: u32,
744}
745
746impl Counted {
747    /// Relative spread across runs, as a percentage of the minimum.
748    pub fn spread_pct(&self) -> f64 {
749        if self.min == 0 {
750            return 0.0;
751        }
752        (self.max - self.min) as f64 / self.min as f64 * 100.0
753    }
754
755    /// Whether this subject looks non-hermetic.
756    ///
757    /// The metric is deterministic; the program being measured need not be. A
758    /// CLI that checks for updates, reads a cache it may have just created, or
759    /// resolves DNS retires a different number of instructions depending on
760    /// conditions that have nothing to do with the code under test.
761    pub fn is_suspect(&self) -> bool {
762        self.spread_pct() > SPREAD_WARN_PCT
763    }
764}
765
766/// Instruction count via `valgrind --tool=cachegrind`, repeated.
767///
768/// Reports the **minimum**, for the same reason wall clock does: the extra work
769/// a subject sometimes performs is one-sided. A run that consults the network or
770/// populates a cache can only retire *more* instructions than the quiet path,
771/// never fewer, so the floor is the stable estimator.
772///
773/// Returns `Ok(None)` when valgrind is unavailable rather than failing: this is
774/// the expected state on macOS (no usable Apple Silicon support) and Windows.
775/// Those platforms record timing only, and the CI gate lives on the Linux job.
776/// Locally, a container gets you counters on any host.
777pub fn instructions(
778    cmd: &[String],
779    dir: Option<&std::path::Path>,
780    settings: &Settings,
781) -> Result<Option<Counted>> {
782    count(
783        cmd,
784        None,
785        &Site {
786            dir,
787            env: &BTreeMap::new(),
788            settings,
789        },
790        &DEFAULT_OK_EXIT_CODES,
791    )
792}
793
794/// [`instructions`] for a declared subject: its environment, its
795/// `ok_exit_codes`, and its prepare step before every cachegrind run, since
796/// each run has to start from the same state the timed samples did.
797pub fn subject_instructions(s: &Subject, settings: &Settings) -> Result<Option<Counted>> {
798    count(
799        &s.cmd,
800        s.prepare.as_deref(),
801        &Site {
802            dir: s.dir.as_deref(),
803            env: &s.env,
804            settings,
805        },
806        &s.ok_exit_codes,
807    )
808}
809
810/// Run a subject's `version_cmd` once and return the version it reports, or
811/// `None` when the subject declares none.
812///
813/// It runs where the subject does — its directory, its environment, the same
814/// scrub — because that decides which binary a bare name resolves to, and the
815/// point is to name the program that was measured. The result is the first
816/// non-empty line of stdout, or of stderr when stdout has none: `java
817/// -version` and some older tools print only there. Only one line, because a
818/// version is a label on a results page, and several tools follow it with a
819/// licence or build banner.
820pub fn subject_version(s: &Subject, settings: &Settings) -> Option<Result<String>> {
821    let argv = s.version_cmd.as_ref()?;
822    let site = Site {
823        dir: s.dir.as_deref(),
824        env: &s.env,
825        settings,
826    };
827    Some(version_once(argv, &site, VERSION_TIMEOUT))
828}
829
830/// How much of each stream a `version_cmd` keeps. A version is its first
831/// non-empty line; a tool that follows it with a banner, or a help dump,
832/// must not be held in memory for the rest.
833const VERSION_OUTPUT_CAP: usize = 8192;
834
835/// How long a `version_cmd` may take. Asking a tool its version should be
836/// instant; one that stalls on a network or licence check must cost a
837/// warning, not hang the run before its first sample with nothing on
838/// screen. Fixed rather than a setting until a real tool needs longer.
839const VERSION_TIMEOUT: Duration = Duration::from_secs(10);
840
841/// After the command exits, how long to wait for its output to finish
842/// arriving. Anything it wrote is already in the pipe by then, so this only
843/// ends up mattering when a process it started in the background still
844/// holds the pipe open — and that must not hold up the run.
845const VERSION_OUTPUT_GRACE: Duration = Duration::from_millis(500);
846
847/// Read `r` to the end, keeping the first `cap` bytes in `kept` and
848/// discarding the rest. Draining it all means the writer never blocks on a
849/// full pipe, so the command can finish and report its real exit status.
850fn keep_prefix(mut r: impl std::io::Read, cap: usize, kept: &Mutex<Vec<u8>>) {
851    let mut buf = [0u8; 8192];
852    loop {
853        match r.read(&mut buf) {
854            Ok(0) => return,
855            Ok(n) => {
856                let Ok(mut k) = kept.lock() else { return };
857                let room = cap.saturating_sub(k.len());
858                k.extend_from_slice(&buf[..n.min(room)]);
859            }
860            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
861            Err(_) => return,
862        }
863    }
864}
865
866/// Passing a fatal signal on to a running `version_cmd`'s process group.
867///
868/// The group is what lets a timeout stop everything the command started,
869/// but it also takes the command out of the terminal's foreground group, so
870/// a Ctrl-C — or a SIGTERM from CI cancelling the job — would stop tak and
871/// leave the command running, however long it would otherwise have hung.
872/// While a guard is alive, SIGINT, SIGTERM and SIGHUP kill that group and
873/// then stop tak exactly as they would have without the handler. The
874/// previous handlers come back when the guard drops, so the rest of a run
875/// behaves as before: the measured commands share tak's group and get the
876/// terminal's signals directly.
877#[cfg(unix)]
878mod forward_signals {
879    use std::sync::atomic::{AtomicBool, AtomicI32, Ordering::SeqCst};
880
881    const SIGNALS: [libc::c_int; 3] = [libc::SIGINT, libc::SIGTERM, libc::SIGHUP];
882
883    /// What the handler knows, as atomics alone: nothing else is safe to
884    /// touch from a signal handler.
885    ///
886    /// A handler can run on any thread and be preempted anywhere, so every
887    /// path that records a signal in `pending` must end with someone acting
888    /// on it. All accesses are `SeqCst`, which puts them in one order:
889    ///
890    /// - The handler writes `pending`, then reads `done` and `pgid`.
891    ///   [`State::spawned`] writes `pgid` and then takes `pending`;
892    ///   [`State::end`] writes `done` and then takes `pending`. Either a take
893    ///   comes after the handler's write, and the spawning thread acts on the
894    ///   signal, or every take that could have collected it came before, and
895    ///   so did the store preceding it, which the handler's later read sees,
896    ///   so the handler acts on the signal itself.
897    /// - The handler reads `spawning` before `pgid`, and `spawned` writes
898    ///   them in the opposite order, so a handler that sees `spawning`
899    ///   cleared also sees the group.
900    ///
901    /// A handler that starts after [`State::end`] sees `spawning` cleared and
902    /// never writes `pending`; one that started earlier and was preempted
903    /// sees `done` and stops tak itself, without killing a group whose id may
904    /// have been reused by then.
905    pub(super) struct State {
906        /// Between installing the handlers and recording the group: a
907        /// command may exist whose group the handler cannot know yet.
908        spawning: AtomicBool,
909        /// The group to kill, or 0 when there is none.
910        pgid: AtomicI32,
911        /// A signal that arrived while `spawning`, for the spawning thread
912        /// to act on once the group is known.
913        pending: AtomicI32,
914        /// The version step is over and nothing will look at `pending`
915        /// again, so a late handler must act on its signal itself.
916        done: AtomicBool,
917    }
918
919    /// What the handler should do with a signal.
920    #[derive(Debug, PartialEq, Eq)]
921    pub(super) enum Act {
922        /// Leave it for [`State::spawned`] or [`State::end`].
923        Defer,
924        /// Kill this group (0 for none) and stop tak.
925        Die { pgid: i32 },
926    }
927
928    impl State {
929        pub(super) const fn new() -> State {
930            State {
931                spawning: AtomicBool::new(false),
932                pgid: AtomicI32::new(0),
933                pending: AtomicI32::new(0),
934                done: AtomicBool::new(true),
935            }
936        }
937
938        pub(super) fn begin(&self) {
939            self.pending.store(0, SeqCst);
940            self.pgid.store(0, SeqCst);
941            self.done.store(false, SeqCst);
942            self.spawning.store(true, SeqCst);
943        }
944
945        /// The handler's decision.
946        pub(super) fn on_signal(&self, sig: libc::c_int) -> Act {
947            if self.wants_to_defer() {
948                self.defer(sig)
949            } else {
950                Act::Die {
951                    pgid: self.pgid.load(SeqCst),
952                }
953            }
954        }
955
956        /// First half of [`State::on_signal`]: still spawning, group not yet
957        /// known. Separate so a test can pause a handler between the halves.
958        fn wants_to_defer(&self) -> bool {
959            let spawning = self.spawning.load(SeqCst);
960            spawning && self.pgid.load(SeqCst) == 0
961        }
962
963        /// Second half: record the signal, then check whether whoever would
964        /// have collected it already has.
965        fn defer(&self, sig: libc::c_int) -> Act {
966            self.pending.store(sig, SeqCst);
967            if self.done.load(SeqCst) {
968                return Act::Die { pgid: 0 };
969            }
970            match self.pgid.load(SeqCst) {
971                0 => Act::Defer,
972                pgid => Act::Die { pgid },
973            }
974        }
975
976        /// Record the group once the spawn returns (`None` if it failed),
977        /// and hand back any signal that arrived meanwhile with the group
978        /// to kill for it.
979        pub(super) fn spawned(&self, pid: Option<u32>) -> Option<(libc::c_int, i32)> {
980            let pgid = pid.map_or(0, |p| p as i32);
981            self.pgid.store(pgid, SeqCst);
982            self.spawning.store(false, SeqCst);
983            let sig = self.pending.swap(0, SeqCst);
984            (sig != 0).then_some((sig, pgid))
985        }
986
987        /// The step is over. Returns a signal a late handler deferred, which
988        /// the caller must still act on; its group is not killed, since the
989        /// command has been reaped and the id may be reused.
990        pub(super) fn end(&self) -> Option<libc::c_int> {
991            self.spawning.store(false, SeqCst);
992            self.done.store(true, SeqCst);
993            self.pgid.store(0, SeqCst);
994            let sig = self.pending.swap(0, SeqCst);
995            (sig != 0).then_some(sig)
996        }
997    }
998
999    static STATE: State = State::new();
1000
1001    /// Kill the group, then stop tak the way `sig` would have. The signal is
1002    /// blocked while a handler runs, so from there the raise takes effect —
1003    /// with the default action — as soon as the handler returns.
1004    fn die(sig: libc::c_int, pgid: i32) {
1005        // SAFETY: killpg, signal and raise are async-signal-safe.
1006        unsafe {
1007            if pgid > 0 {
1008                libc::killpg(pgid, libc::SIGKILL);
1009            }
1010            libc::signal(sig, libc::SIG_DFL);
1011            libc::raise(sig);
1012        }
1013    }
1014
1015    extern "C" fn forward(sig: libc::c_int) {
1016        if let Act::Die { pgid } = STATE.on_signal(sig) {
1017            die(sig, pgid);
1018        }
1019    }
1020
1021    pub struct Guard {
1022        previous: Vec<(libc::c_int, libc::sigaction)>,
1023    }
1024
1025    impl Guard {
1026        /// Install the handlers, before spawning: a signal between here and
1027        /// [`Guard::spawned`] is held until the group is known.
1028        pub fn install() -> Guard {
1029            STATE.begin();
1030            let mut previous = Vec::new();
1031            for sig in SIGNALS {
1032                // SAFETY: plain-data structs, filled in before use; the
1033                // handler is an `extern "C" fn(c_int)`, as sa_sigaction
1034                // expects without SA_SIGINFO.
1035                unsafe {
1036                    let mut new: libc::sigaction = std::mem::zeroed();
1037                    new.sa_sigaction = forward as extern "C" fn(libc::c_int) as libc::sighandler_t;
1038                    libc::sigemptyset(&mut new.sa_mask);
1039                    let mut old: libc::sigaction = std::mem::zeroed();
1040                    if libc::sigaction(sig, &new, &mut old) == 0 {
1041                        previous.push((sig, old));
1042                    }
1043                }
1044            }
1045            Guard { previous }
1046        }
1047
1048        /// The spawn returned: `pid` leads the new group, or `None` if the
1049        /// spawn failed. A signal that arrived during it is acted on now.
1050        pub fn spawned(pid: Option<u32>) {
1051            if let Some((sig, pgid)) = STATE.spawned(pid) {
1052                die(sig, pgid);
1053            }
1054        }
1055    }
1056
1057    impl Drop for Guard {
1058        fn drop(&mut self) {
1059            // Before the previous handlers come back, so a signal one of ours
1060            // deferred late is still acted on.
1061            if let Some(sig) = STATE.end() {
1062                die(sig, 0);
1063            }
1064            for (sig, old) in &self.previous {
1065                // SAFETY: restores the action saved by `install`.
1066                unsafe {
1067                    libc::sigaction(*sig, old, std::ptr::null_mut());
1068                }
1069            }
1070        }
1071    }
1072
1073    /// Driven on a private `State`, so no real signal is sent and the
1074    /// handler's own state is untouched: every way a handler and the version
1075    /// step can interleave ends with the signal acted on.
1076    #[cfg(test)]
1077    mod tests {
1078        use super::{Act, SeqCst, State};
1079
1080        #[test]
1081        fn a_signal_during_the_spawn_is_held_until_the_group_is_known() {
1082            let s = State::new();
1083            s.begin();
1084            assert_eq!(s.on_signal(libc::SIGTERM), Act::Defer, "no group yet");
1085            assert_eq!(s.spawned(Some(42)), Some((libc::SIGTERM, 42)));
1086            assert_eq!(s.on_signal(libc::SIGINT), Act::Die { pgid: 42 });
1087            assert_eq!(s.end(), None);
1088
1089            s.begin();
1090            assert_eq!(s.spawned(Some(7)), None, "nothing arrived");
1091            assert_eq!(s.end(), None);
1092
1093            s.begin();
1094            assert_eq!(s.on_signal(libc::SIGINT), Act::Defer);
1095            assert_eq!(
1096                s.spawned(None),
1097                Some((libc::SIGINT, 0)),
1098                "a failed spawn still stops tak"
1099            );
1100            assert_eq!(s.end(), None);
1101
1102            assert_eq!(
1103                s.on_signal(libc::SIGHUP),
1104                Act::Die { pgid: 0 },
1105                "after the step"
1106            );
1107            assert!(!s.wants_to_defer(), "and it never defers there");
1108        }
1109
1110        /// A handler that decided to defer, then was preempted: whenever it
1111        /// resumes, its signal is acted on.
1112        #[test]
1113        fn a_handler_preempted_past_the_step_still_acts() {
1114            let s = State::new();
1115
1116            // Until after the step ended: it sees `done` and stops tak,
1117            // without killing a group whose id may be reused.
1118            s.begin();
1119            assert!(s.wants_to_defer());
1120            assert_eq!(s.spawned(Some(42)), None);
1121            assert_eq!(s.end(), None);
1122            assert_eq!(s.defer(libc::SIGTERM), Act::Die { pgid: 0 });
1123
1124            // Until after the spawn: it sees the group. Its write is also
1125            // left for `end`; acting twice on a signal is harmless.
1126            s.begin();
1127            assert!(s.wants_to_defer());
1128            assert_eq!(s.spawned(Some(42)), None);
1129            assert_eq!(s.defer(libc::SIGINT), Act::Die { pgid: 42 });
1130            assert_eq!(s.end(), Some(libc::SIGINT));
1131
1132            // Its write landed before `end` took `pending` (and it read the
1133            // group before `spawned` stored it): `end` acts on it.
1134            s.begin();
1135            assert_eq!(s.spawned(Some(42)), None);
1136            s.pending.store(libc::SIGHUP, SeqCst);
1137            assert_eq!(s.end(), Some(libc::SIGHUP), "acted on at teardown");
1138        }
1139    }
1140}
1141
1142/// Stop a timed-out `version_cmd` and everything it started, then reap it.
1143///
1144/// On Unix that is its whole process group, so a helper it spawned cannot go
1145/// on using CPU through the samples that follow, or hold the output pipes
1146/// open. Elsewhere only the command itself is stopped.
1147///
1148/// Only on a timeout: a command that exits on its own may have started a
1149/// daemon on purpose — a version check that launches a language server or
1150/// build daemon — and that is the tool's business, not tak's to kill.
1151fn stop_group(child: &mut std::process::Child) {
1152    #[cfg(unix)]
1153    {
1154        // The child leads its own group (`process_group(0)`), so its pid is
1155        // the group id. SAFETY: killpg only sends a signal.
1156        let pgid = child.id() as libc::pid_t;
1157        if unsafe { libc::killpg(pgid, libc::SIGKILL) } != 0 {
1158            let _ = child.kill();
1159        }
1160    }
1161    #[cfg(not(unix))]
1162    let _ = child.kill();
1163    let _ = child.wait();
1164}
1165
1166fn version_once(argv: &[String], site: &Site, timeout: Duration) -> Result<String> {
1167    let bin = argv
1168        .first()
1169        .map(String::as_str)
1170        .unwrap_or("(empty command)");
1171    let mut cmd = command(argv, site)?;
1172    cmd.stdin(Stdio::null())
1173        .stdout(Stdio::piped())
1174        .stderr(Stdio::piped());
1175    // Its own process group, so a timeout can stop everything it started:
1176    // a helper left running would compete with the samples that follow.
1177    #[cfg(unix)]
1178    std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
1179    // Being in its own group, it no longer gets the terminal's Ctrl-C; this
1180    // passes a fatal signal on to it until the guard drops.
1181    #[cfg(unix)]
1182    let _forward = forward_signals::Guard::install();
1183    let spawned = cmd.spawn();
1184    // Also when the spawn failed, so a signal held during it still stops tak.
1185    #[cfg(unix)]
1186    forward_signals::Guard::spawned(spawned.as_ref().ok().map(std::process::Child::id));
1187    let mut child = spawned.with_context(|| format!("failed to spawn `{bin}`"))?;
1188
1189    // One thread per stream, so neither pipe can fill while the other is
1190    // read. They are never joined: a background process the command started
1191    // may hold a pipe open long after it exits, and the run must not wait on
1192    // that. Each thread ends when its pipe finally closes.
1193    let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
1194    let spawn_reader = |r: Option<Box<dyn std::io::Read + Send>>| {
1195        let kept = Arc::new(Mutex::new(Vec::new()));
1196        if let Some(r) = r {
1197            let (kept, tx) = (Arc::clone(&kept), done_tx.clone());
1198            std::thread::spawn(move || {
1199                keep_prefix(r, VERSION_OUTPUT_CAP, &kept);
1200                let _ = tx.send(());
1201            });
1202        } else {
1203            let _ = done_tx.send(());
1204        }
1205        kept
1206    };
1207    let stdout = spawn_reader(child.stdout.take().map(|o| Box::new(o) as _));
1208    let stderr = spawn_reader(child.stderr.take().map(|e| Box::new(e) as _));
1209
1210    let deadline = Instant::now() + timeout;
1211    let status = loop {
1212        match child.try_wait() {
1213            Ok(Some(status)) => break status,
1214            Ok(None) if Instant::now() < deadline => {
1215                std::thread::sleep(Duration::from_millis(5));
1216            }
1217            Ok(None) => {
1218                stop_group(&mut child);
1219                bail!(
1220                    "`{bin}` did not finish within {}, so it was stopped",
1221                    crate::progress::fmt(timeout)
1222                );
1223            }
1224            Err(e) => {
1225                stop_group(&mut child);
1226                return Err(e).with_context(|| format!("failed to wait for `{bin}`"));
1227            }
1228        }
1229    };
1230    let grace = Instant::now() + VERSION_OUTPUT_GRACE;
1231    for _ in 0..2 {
1232        let left = grace.saturating_duration_since(Instant::now());
1233        if done_rx.recv_timeout(left).is_err() {
1234            break;
1235        }
1236    }
1237    let take = |kept: &Mutex<Vec<u8>>| kept.lock().map(|k| k.clone()).unwrap_or_default();
1238    let (stdout, stderr) = (take(&stdout), take(&stderr));
1239
1240    // A failing command's output is an error message or a usage dump, not a
1241    // version, however much of it there is.
1242    if !status.success() {
1243        let stderr = String::from_utf8_lossy(&stderr);
1244        bail!(
1245            "`{bin}` exited with {status}: {}",
1246            stderr
1247                .lines()
1248                .map(str::trim)
1249                .rfind(|l| !l.is_empty())
1250                .unwrap_or("(no output)")
1251        );
1252    }
1253    let first = |bytes: &[u8]| {
1254        String::from_utf8_lossy(bytes)
1255            .lines()
1256            .map(str::trim)
1257            .find(|l| !l.is_empty())
1258            .map(str::to_string)
1259    };
1260    first(&stdout)
1261        .or_else(|| first(&stderr))
1262        .with_context(|| format!("`{bin}` printed nothing"))
1263}
1264
1265/// `ok` applies to the subject under valgrind: cachegrind exits with its
1266/// client's code, and re-raises the signal a client died of.
1267fn count(
1268    cmd: &[String],
1269    prepare: Option<&[String]>,
1270    site: &Site,
1271    ok: &[i32],
1272) -> Result<Option<Counted>> {
1273    if !valgrind_available() {
1274        return Ok(None);
1275    }
1276
1277    let mut samples: Vec<u64> = Vec::with_capacity(COUNTER_RUNS as usize);
1278    for _ in 0..COUNTER_RUNS {
1279        if let Some(p) = prepare {
1280            prepare_once(p, site)?;
1281        }
1282        let mut argv: Vec<String> = [
1283            "valgrind",
1284            "--tool=cachegrind",
1285            "--cache-sim=no",
1286            "--branch-sim=no",
1287            "--cachegrind-out-file=/dev/null",
1288        ]
1289        .map(String::from)
1290        .to_vec();
1291        argv.extend_from_slice(cmd);
1292        let mut c = command(&argv, site)?;
1293        c.stdout(Stdio::null());
1294        let out = c.output().context("failed to run valgrind")?;
1295
1296        // cachegrind writes its summary to stderr as e.g. "I refs:  48,349,132".
1297        let stderr = String::from_utf8_lossy(&out.stderr);
1298        let bin = cmd.first().map(String::as_str).unwrap_or("(empty command)");
1299        accepted(bin, out.status, ok, " under valgrind")?;
1300        match parse_irefs(&stderr) {
1301            Some(n) => samples.push(n),
1302            // Valgrind is installed but produced no summary — a real failure,
1303            // not the same thing as valgrind being absent. Reporting it as
1304            // absent sends people off installing something they already have.
1305            None => bail!(
1306                "valgrind ran but emitted no `I refs` summary: {}",
1307                stderr.lines().last().unwrap_or("(no output)").trim()
1308            ),
1309        }
1310    }
1311
1312    Ok(Some(Counted {
1313        min: *samples.iter().min().expect("COUNTER_RUNS > 0"),
1314        max: *samples.iter().max().expect("COUNTER_RUNS > 0"),
1315        runs: COUNTER_RUNS,
1316    }))
1317}
1318
1319/// Extract the `I refs:` count from cachegrind's stderr summary.
1320fn parse_irefs(stderr: &str) -> Option<u64> {
1321    let line = stderr.lines().find(|l| l.contains("I refs:"))?;
1322    let digits: String = line
1323        .rsplit(':')
1324        .next()?
1325        .chars()
1326        .filter(|c| c.is_ascii_digit())
1327        .collect();
1328    digits.parse().ok()
1329}
1330
1331#[cfg(test)]
1332mod tests {
1333    use super::*;
1334
1335    #[test]
1336    fn parses_cachegrind_summary() {
1337        let s = "==12== I refs:      48,349,132\n";
1338        assert_eq!(parse_irefs(s), Some(48_349_132));
1339    }
1340
1341    #[test]
1342    fn missing_summary_is_none_not_panic() {
1343        assert_eq!(parse_irefs("valgrind: command not found"), None);
1344    }
1345
1346    /// What `subject` removes, as configured.
1347    fn removals(settings: &Settings) -> Vec<String> {
1348        subject("true", settings)
1349            .get_envs()
1350            .filter(|(_, v)| v.is_none())
1351            .map(|(k, _)| k.to_string_lossy().into_owned())
1352            .collect()
1353    }
1354
1355    /// Construction-level check. The end-to-end proof that a subject cannot see
1356    /// the token lives in `tests/subject_env.rs`, which runs the real binary.
1357    #[test]
1358    fn subject_commands_remove_the_default_denied_variables() {
1359        let removed = removals(&Settings::default());
1360        for key in Settings::default().scrubbed_env() {
1361            assert!(removed.contains(&key.to_string()), "{key} not removed");
1362        }
1363    }
1364
1365    /// The removal follows the setting rather than a compiled-in list, which is
1366    /// the whole point of routing it through `Settings`.
1367    #[test]
1368    fn the_removal_follows_the_settings() {
1369        let removed = removals(&Settings {
1370            env_deny: vec!["CUSTOM_SECRET".into()],
1371            env_allow: Vec::new(),
1372            ..Settings::default()
1373        });
1374        assert!(removed.contains(&"CUSTOM_SECRET".to_string()));
1375        assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
1376    }
1377
1378    /// An allowed variable is not removed, so a subject that genuinely needs
1379    /// one can still be measured.
1380    #[test]
1381    fn an_allowed_variable_survives() {
1382        let removed = removals(&Settings {
1383            env_deny: vec!["GITHUB_TOKEN".into(), "GH_TOKEN".into()],
1384            env_allow: vec!["GITHUB_TOKEN".into()],
1385            ..Settings::default()
1386        });
1387        assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
1388        assert!(removed.contains(&"GH_TOKEN".to_string()));
1389    }
1390
1391    #[test]
1392    fn zero_runs_is_rejected_not_a_panic() {
1393        let plan = Plan {
1394            cmd: vec!["true".into()],
1395            warmup: 0,
1396            runs: 0,
1397            dir: None,
1398            settings: Settings::default(),
1399        };
1400        assert!(wall(&plan).is_err());
1401    }
1402
1403    #[test]
1404    fn a_failed_subject_is_not_recorded_as_a_fast_run() {
1405        #[cfg(unix)]
1406        let cmd = vec!["/bin/sh".into(), "-c".into(), "exit 42".into()];
1407        #[cfg(windows)]
1408        let cmd = vec!["cmd".into(), "/C".into(), "exit /B 42".into()];
1409
1410        let err = wall(&Plan {
1411            cmd,
1412            warmup: 0,
1413            runs: 1,
1414            dir: None,
1415            settings: Settings::default(),
1416        })
1417        .unwrap_err();
1418
1419        assert!(format!("{err:#}").contains("exited with"), "{err:#}");
1420    }
1421
1422    #[test]
1423    fn wall_reports_min_le_p50_le_max() {
1424        let plan = Plan {
1425            cmd: vec!["true".into()],
1426            warmup: 1,
1427            runs: 5,
1428            dir: None,
1429            settings: Settings::default(),
1430        };
1431        let m = wall(&plan).unwrap();
1432        assert!(m["wall_min_ms"] <= m["wall_p50_ms"]);
1433        assert!(m["wall_p50_ms"] <= m["wall_max_ms"]);
1434        assert_eq!(m["wall_n"], 5.0);
1435    }
1436
1437    /// Every subject gets exactly its warmups and runs, warmups first.
1438    #[test]
1439    fn the_schedule_gives_each_subject_its_counts() {
1440        let counts = [(2, 10), (1, 5), (0, 3)];
1441        let order = schedule(&counts, 7);
1442        for (i, &(warmup, runs)) in counts.iter().enumerate() {
1443            let of = |timed| {
1444                order
1445                    .iter()
1446                    .filter(|s| s.subject == i && s.timed == timed)
1447                    .count()
1448            };
1449            assert_eq!(of(false), warmup as usize, "subject {i} warmups");
1450            assert_eq!(of(true), runs as usize, "subject {i} runs");
1451        }
1452        let first_timed = order.iter().position(|s| s.timed).unwrap();
1453        assert!(order[first_timed..].iter().all(|s| s.timed));
1454    }
1455
1456    #[test]
1457    fn the_same_seed_gives_the_same_order() {
1458        let counts = [(1, 8), (1, 8), (1, 8)];
1459        assert_eq!(schedule(&counts, 42), schedule(&counts, 42));
1460        assert_ne!(schedule(&counts, 42), schedule(&counts, 43));
1461    }
1462
1463    /// Interleaving is the point: with equal counts, every round holds each
1464    /// subject once, and the order is not the same in every round.
1465    #[test]
1466    fn each_round_runs_every_subject_once_in_a_varying_order() {
1467        let order = schedule(&[(0, 20), (0, 20), (0, 20)], 1);
1468        let rounds: Vec<Vec<usize>> = order
1469            .chunks(3)
1470            .map(|r| r.iter().map(|s| s.subject).collect())
1471            .collect();
1472        assert_eq!(rounds.len(), 20);
1473        for r in &rounds {
1474            let mut sorted = r.clone();
1475            sorted.sort();
1476            assert_eq!(sorted, [0, 1, 2], "round {r:?}");
1477        }
1478        assert!(rounds.iter().any(|r| r != &rounds[0]), "never shuffled");
1479    }
1480
1481    /// A subject with half the runs takes part in alternate rounds, not only
1482    /// the first half — otherwise drift late in the run lands on the others.
1483    #[test]
1484    fn a_subject_with_fewer_runs_is_spread_across_the_run() {
1485        let order = schedule(&[(0, 10), (0, 5)], 3);
1486        let fewer: Vec<usize> = order
1487            .iter()
1488            .enumerate()
1489            .filter(|(_, s)| s.subject == 1)
1490            .map(|(i, _)| i)
1491            .collect();
1492        assert_eq!(fewer.len(), 5);
1493        assert!(
1494            *fewer.last().unwrap() >= order.len() - 3,
1495            "last sample of the smaller subject is near the end: {fewer:?} of {}",
1496            order.len()
1497        );
1498    }
1499
1500    #[test]
1501    fn a_benchmark_seed_depends_on_its_name_and_the_run_seed() {
1502        assert_eq!(seed_for(1, "a"), seed_for(1, "a"));
1503        assert_ne!(seed_for(1, "a"), seed_for(1, "b"));
1504        assert_ne!(seed_for(1, "a"), seed_for(2, "a"));
1505    }
1506
1507    #[test]
1508    fn stats_report_the_sample_standard_deviation() {
1509        let m = stats(&[2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]);
1510        assert_eq!(m["wall_min_ms"], 2.0);
1511        assert_eq!(m["wall_max_ms"], 9.0);
1512        assert_eq!(m["wall_mean_ms"], 5.0);
1513        // sqrt(32 / 7)
1514        assert!((m["wall_stddev_ms"] - 2.138_089_935).abs() < 1e-6);
1515        assert_eq!(stats(&[3.0])["wall_stddev_ms"], 0.0);
1516    }
1517
1518    /// A failing subject is dropped; the others still get every sample.
1519    #[cfg(unix)]
1520    #[test]
1521    fn a_failing_subject_does_not_stop_the_others() {
1522        let mk = |name: &str, cmd: &[&str]| Subject {
1523            name: name.into(),
1524            cmd: cmd.iter().map(|s| s.to_string()).collect(),
1525            prepare: None,
1526            setup: None,
1527            setup_dir: None,
1528            check: None,
1529            dir: None,
1530            version_cmd: None,
1531            env: BTreeMap::new(),
1532            vars: BTreeMap::new(),
1533            when: None,
1534            runs: Runs::Fixed(4),
1535            auto: AutoRuns {
1536                budget: Duration::from_secs(30),
1537                min: 5,
1538                max: 50,
1539            },
1540            warmup: 1,
1541            counters: false,
1542            ok_exit_codes: vec![0],
1543        };
1544        let res = interleaved(
1545            &[mk("ok", &["true"]), mk("bad", &["false"])],
1546            5,
1547            &Settings::default(),
1548            &mut Quiet,
1549        );
1550        assert_eq!(res[0].as_ref().unwrap().times.len(), 4);
1551        assert!(format!("{:#}", res[1].as_ref().unwrap_err()).contains("exited with"));
1552    }
1553
1554    /// Runs `sh -c script` as a `version_cmd` with the given deadline.
1555    #[cfg(unix)]
1556    fn version_sh(script: &str, env: &[(&str, &str)], timeout: Duration) -> Result<String> {
1557        let settings = Settings::default();
1558        let env: BTreeMap<String, String> = env
1559            .iter()
1560            .map(|(k, v)| (k.to_string(), v.to_string()))
1561            .collect();
1562        let site = Site {
1563            dir: None,
1564            env: &env,
1565            settings: &settings,
1566        };
1567        version_once(&["sh".into(), "-c".into(), script.into()], &site, timeout)
1568    }
1569
1570    /// The first non-empty line, from stdout or else stderr; a failure is an
1571    /// error naming the command, which the caller turns into a warning.
1572    #[cfg(unix)]
1573    #[test]
1574    fn a_version_is_the_first_line_printed() {
1575        let sh = |script: &str| version_sh(script, &[("V", "9.9")], VERSION_TIMEOUT);
1576        assert_eq!(
1577            sh("printf '\\n  tool %s  \\nbuilt today\\n' \"$V\"").unwrap(),
1578            "tool 9.9",
1579            "first non-empty line, trimmed, in the subject's env"
1580        );
1581        assert_eq!(sh("echo 'java 21' >&2").unwrap(), "java 21");
1582        let err = format!("{:#}", sh("echo nope >&2; exit 2").unwrap_err());
1583        assert!(err.contains("`sh`") && err.contains("nope"), "{err}");
1584        assert!(sh("true").is_err(), "no output is no version");
1585    }
1586
1587    /// Output past the cap is read and dropped, so a command that prints a
1588    /// lot still finishes, and its first line is what counts.
1589    #[cfg(unix)]
1590    #[test]
1591    fn a_version_is_read_from_a_capped_prefix() {
1592        let sh = |script: &str| version_sh(script, &[], VERSION_TIMEOUT);
1593        assert_eq!(sh("yes 'tool 1.0' | head -c 10000000").unwrap(), "tool 1.0");
1594        assert_eq!(
1595            sh("yes 'java 21' | head -c 10000000 >&2").unwrap(),
1596            "java 21",
1597            "a flood on stderr"
1598        );
1599        let kept = Mutex::new(Vec::new());
1600        let mut src = std::io::Cursor::new(vec![7u8; 100]);
1601        keep_prefix(&mut src, 10, &kept);
1602        assert_eq!(kept.lock().unwrap().len(), 10, "only the cap is kept");
1603        assert_eq!(
1604            src.position(),
1605            100,
1606            "the rest is read, not left in the pipe"
1607        );
1608    }
1609
1610    /// A failing command that prints a lot — a usage dump after an unknown
1611    /// flag — is a failure, not a version, however long its output.
1612    #[cfg(unix)]
1613    #[test]
1614    fn a_failing_version_cmd_is_an_error_even_past_the_cap() {
1615        let err = version_sh(
1616            "yes 'usage: tool [flags]' | head -c 100000; echo 'unknown flag' >&2; exit 1",
1617            &[],
1618            VERSION_TIMEOUT,
1619        )
1620        .unwrap_err();
1621        let err = format!("{err:#}");
1622        assert!(
1623            err.contains("exited with") && err.contains("unknown flag"),
1624            "{err}"
1625        );
1626    }
1627
1628    /// One that never finishes, even one that only floods stderr, is stopped
1629    /// at the deadline and says so.
1630    #[cfg(unix)]
1631    #[test]
1632    fn a_version_cmd_that_never_finishes_is_stopped() {
1633        let t = Duration::from_millis(300);
1634        let began = Instant::now();
1635        // `exec`, so the process stopped at the deadline is the flood itself.
1636        for script in ["exec yes 'tool 2.0' >&2", "exec sleep 30"] {
1637            let err = format!("{:#}", version_sh(script, &[], t).unwrap_err());
1638            assert!(err.contains("did not finish"), "{script}: {err}");
1639        }
1640        assert!(
1641            began.elapsed() < Duration::from_secs(5),
1642            "{:?}",
1643            began.elapsed()
1644        );
1645    }
1646
1647    /// A timeout stops what the command started too, not just the command:
1648    /// a helper left running would compete with the samples that follow.
1649    #[cfg(unix)]
1650    #[test]
1651    fn a_timeout_stops_the_whole_process_group() {
1652        let dir = tempfile::tempdir().unwrap();
1653        let pidfile = dir.path().join("pid");
1654        let script = format!("sleep 30 & echo $! > '{}'; wait", pidfile.display());
1655        let err = version_sh(&script, &[], Duration::from_millis(300)).unwrap_err();
1656        assert!(format!("{err:#}").contains("did not finish"), "{err:#}");
1657        let pid = std::fs::read_to_string(&pidfile).unwrap();
1658        let pid = pid.trim();
1659        let until = Instant::now() + Duration::from_secs(2);
1660        while running(pid) && Instant::now() < until {
1661            std::thread::sleep(Duration::from_millis(20));
1662        }
1663        assert!(
1664            !running(pid),
1665            "the background sleep {pid} outlived the timeout"
1666        );
1667    }
1668
1669    /// Whether `pid` is still running. A zombie is not: once the shell that
1670    /// started the process is killed with it, only PID 1 can reap it, and in
1671    /// a container whose PID 1 does not reap orphans it stays a zombie —
1672    /// which `kill -0` still reports as present.
1673    #[cfg(unix)]
1674    fn running(pid: &str) -> bool {
1675        #[cfg(target_os = "linux")]
1676        {
1677            // The state follows the `)` closing the command name, which may
1678            // itself contain spaces or parentheses, so look for the last one.
1679            let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) else {
1680                return false;
1681            };
1682            let state = stat
1683                .rfind(')')
1684                .and_then(|i| stat[i + 1..].trim_start().chars().next());
1685            !matches!(state, None | Some('Z' | 'X' | 'x'))
1686        }
1687        #[cfg(not(target_os = "linux"))]
1688        {
1689            let Ok(out) = Command::new("ps")
1690                .args(["-o", "stat=", "-p", pid])
1691                .stderr(Stdio::null())
1692                .output()
1693            else {
1694                return false;
1695            };
1696            let stat = String::from_utf8_lossy(&out.stdout);
1697            let stat = stat.trim();
1698            out.status.success() && !stat.is_empty() && !stat.starts_with('Z')
1699        }
1700    }
1701
1702    /// A background process that inherits the pipes keeps them open after
1703    /// the command exits; the version it printed still comes back promptly.
1704    #[cfg(unix)]
1705    #[test]
1706    fn a_background_process_holding_the_pipe_does_not_hold_up_the_version() {
1707        let began = Instant::now();
1708        let v = version_sh("sleep 5 & echo 'tool 3.0'", &[], VERSION_TIMEOUT).unwrap();
1709        assert_eq!(v, "tool 3.0");
1710        assert!(
1711            began.elapsed() < Duration::from_secs(3),
1712            "{:?}",
1713            began.elapsed()
1714        );
1715    }
1716
1717    /// A prepare step that fails stops its subject, and says it was prepare.
1718    #[cfg(unix)]
1719    #[test]
1720    fn a_failing_prepare_is_reported_as_prepare() {
1721        let res = interleaved(
1722            &[Subject {
1723                name: "x".into(),
1724                cmd: vec!["true".into()],
1725                prepare: Some(vec![
1726                    "/bin/sh".into(),
1727                    "-c".into(),
1728                    "echo nope >&2; exit 3".into(),
1729                ]),
1730                setup: None,
1731                setup_dir: None,
1732                check: None,
1733                dir: None,
1734                version_cmd: None,
1735                env: BTreeMap::new(),
1736                vars: BTreeMap::new(),
1737                when: None,
1738                runs: Runs::Fixed(1),
1739                auto: AutoRuns {
1740                    budget: Duration::from_secs(30),
1741                    min: 5,
1742                    max: 50,
1743                },
1744                warmup: 0,
1745                counters: false,
1746                ok_exit_codes: vec![0],
1747            }],
1748            0,
1749            &Settings::default(),
1750            &mut Quiet,
1751        );
1752        let msg = format!("{:#}", res[0].as_ref().unwrap_err());
1753        assert!(msg.contains("prepare") && msg.contains("nope"), "{msg}");
1754    }
1755
1756    /// A subject whose command bumps a counter file and whose check fails on
1757    /// every even-numbered run, warmups included in the count.
1758    #[cfg(unix)]
1759    fn alternating(dir: &Path, warmup: u32, runs: u32) -> Subject {
1760        Subject {
1761            name: "alt".into(),
1762            cmd: vec![
1763                "/bin/sh".into(),
1764                "-c".into(),
1765                "echo x >> n".into(),
1766            ],
1767            prepare: None,
1768            setup: None,
1769            setup_dir: None,
1770            check: Some(vec![
1771                "/bin/sh".into(),
1772                "-c".into(),
1773                // Arithmetic strips the padding macOS `wc -l` puts before the count.
1774                "echo check >> checked; runs=$(( $(wc -l < n) )); test $(( runs % 2 )) = 1 || { echo \"run $runs is even\" >&2; exit 1; }".into(),
1775            ]),
1776            version_cmd: None,
1777            dir: Some(dir.to_path_buf()),
1778            env: BTreeMap::new(),
1779            vars: BTreeMap::new(),
1780            when: None,
1781            runs: Runs::Fixed(runs),
1782            auto: AutoRuns {
1783                budget: Duration::from_secs(30),
1784                min: 5,
1785                max: 50,
1786            },
1787            warmup,
1788            counters: false,
1789            ok_exit_codes: vec![0],
1790        }
1791    }
1792
1793    /// A failing check marks its sample and the subject keeps every one;
1794    /// warmups are never checked.
1795    #[cfg(unix)]
1796    #[test]
1797    fn a_failing_check_marks_the_sample_without_dropping_the_subject() {
1798        let dir = tempfile::tempdir().unwrap();
1799        let res = interleaved(
1800            &[alternating(dir.path(), 1, 6)],
1801            0,
1802            &Settings::default(),
1803            &mut Quiet,
1804        );
1805        let s = res[0].as_ref().unwrap();
1806        assert_eq!(s.times.len(), 6);
1807        // Run 1 is the warmup; timed runs 2..=7 fail on the even ones.
1808        assert_eq!(s.checks, [false, true, false, true, false, true]);
1809        assert_eq!(s.passed(), 3);
1810        assert!(
1811            s.first_failure
1812                .as_deref()
1813                .unwrap()
1814                .contains("run 2 is even"),
1815            "{s:?}"
1816        );
1817        let checked = std::fs::read_to_string(dir.path().join("checked")).unwrap();
1818        assert_eq!(checked.lines().count(), 6, "no check after the warmup");
1819    }
1820
1821    /// `ok_exit_codes` belong to the command, not its check: a command that
1822    /// exits 1 under `[0, 1]` is kept with its code, and a check that exits 1
1823    /// is still a failed check.
1824    #[cfg(unix)]
1825    #[test]
1826    fn ok_exit_codes_do_not_pass_a_check_that_exits_1() {
1827        let dir = tempfile::tempdir().unwrap();
1828        let mut s = alternating(dir.path(), 0, 2);
1829        s.cmd = vec!["/bin/sh".into(), "-c".into(), "exit 1".into()];
1830        s.check = Some(vec!["/bin/sh".into(), "-c".into(), "exit 1".into()]);
1831        s.ok_exit_codes = vec![0, 1];
1832        let res = interleaved(&[s], 0, &Settings::default(), &mut Quiet);
1833        let s = res[0].as_ref().unwrap();
1834        assert_eq!(s.exit_codes, [1, 1]);
1835        assert_eq!(s.checks, [false, false]);
1836        assert_eq!(s.passed(), 0);
1837    }
1838
1839    /// A check that cannot be started is a configuration mistake, not six
1840    /// failed samples.
1841    #[cfg(unix)]
1842    #[test]
1843    fn a_check_that_cannot_start_drops_the_subject() {
1844        let dir = tempfile::tempdir().unwrap();
1845        let mut s = alternating(dir.path(), 0, 2);
1846        s.check = Some(vec!["/nonexistent/tak-check".into()]);
1847        let res = interleaved(&[s], 0, &Settings::default(), &mut Quiet);
1848        let msg = format!("{:#}", res[0].as_ref().unwrap_err());
1849        assert!(msg.contains("failed to spawn check"), "{msg}");
1850    }
1851
1852    /// A passing step that leaves a process writing to stderr returns at
1853    /// once, and that process is left alone: a fixture server started by
1854    /// `setup` must survive logging after the step is done, so its later
1855    /// write to stderr must succeed rather than die of SIGPIPE (exit 141).
1856    #[cfg(unix)]
1857    #[test]
1858    fn a_process_left_by_a_passing_step_can_still_write_to_stderr() {
1859        let dir = tempfile::tempdir().unwrap();
1860        let env = BTreeMap::new();
1861        let settings = Settings::default();
1862        let site = Site {
1863            dir: Some(dir.path()),
1864            env: &env,
1865            settings: &settings,
1866        };
1867        const N: usize = 10;
1868        let start = Instant::now();
1869        for i in 0..N {
1870            let script = format!(
1871                "{{ sh -c 'sleep 1; echo late >&2'; echo $? > s{i}.tmp && mv s{i}.tmp s{i}; }} & exit 0"
1872            );
1873            let step = ["/bin/sh".to_string(), "-c".into(), script];
1874            assert_eq!(untimed("setup", &step, &site).unwrap(), None);
1875        }
1876        let took = start.elapsed();
1877        assert!(took < Duration::from_secs(2), "{N} passes took {took:?}");
1878
1879        let deadline = Instant::now() + Duration::from_secs(20);
1880        let statuses: Vec<String> = (0..N)
1881            .map(|i| {
1882                loop {
1883                    if let Ok(s) = std::fs::read_to_string(dir.path().join(format!("s{i}"))) {
1884                        break s.trim().to_string();
1885                    }
1886                    assert!(Instant::now() < deadline, "leftover {i} never finished");
1887                    std::thread::sleep(Duration::from_millis(50));
1888                }
1889            })
1890            .collect();
1891        assert!(statuses.iter().all(|s| s == "0"), "{statuses:?}");
1892    }
1893
1894    /// An observer that records what it was told.
1895    #[derive(Default)]
1896    struct Log {
1897        plans: Vec<Vec<u64>>,
1898        finished: Vec<usize>,
1899        /// Every event in order, as `setup:N`, `start:N` and `drop:N`.
1900        events: Vec<String>,
1901    }
1902    impl Observer for Log {
1903        fn planned(&mut self, remaining: &[u64]) {
1904            self.plans.push(remaining.to_vec());
1905        }
1906        fn setting_up(&mut self, subject: usize) {
1907            self.events.push(format!("setup:{subject}"));
1908        }
1909        fn started(&mut self, subject: usize) {
1910            self.events.push(format!("start:{subject}"));
1911        }
1912        fn dropped(&mut self, subject: usize) {
1913            self.events.push(format!("drop:{subject}"));
1914        }
1915        fn finished(&mut self, subject: usize, _: Duration) {
1916            self.finished.push(subject);
1917        }
1918    }
1919
1920    /// Every setup runs once, before any sample; a failing one drops its
1921    /// subject before it takes a sample, and says it was setup.
1922    #[cfg(unix)]
1923    #[test]
1924    fn setups_run_once_first_and_a_failing_one_drops_its_subject() {
1925        let sh = |script: &str| Some(["/bin/sh", "-c", script].map(String::from).to_vec());
1926        let mk = |name: &str, setup: Option<Vec<String>>| Subject {
1927            name: name.into(),
1928            cmd: vec!["true".into()],
1929            prepare: None,
1930            setup,
1931            setup_dir: None,
1932            check: None,
1933            version_cmd: None,
1934            dir: None,
1935            env: BTreeMap::new(),
1936            vars: BTreeMap::new(),
1937            when: None,
1938            runs: Runs::Auto,
1939            auto: AutoRuns {
1940                budget: Duration::from_secs(30),
1941                min: 2,
1942                max: 2,
1943            },
1944            warmup: 1,
1945            counters: false,
1946            ok_exit_codes: vec![0],
1947        };
1948        let mut log = Log::default();
1949        let res = interleaved(
1950            &[
1951                mk("ok", sh("true")),
1952                mk("bad", sh("echo no fixture >&2; exit 2")),
1953                mk("none", None),
1954            ],
1955            3,
1956            &Settings::default(),
1957            &mut log,
1958        );
1959        assert_eq!(log.events[..3], ["setup:0", "setup:1", "drop:1"]);
1960        assert!(!log.events[3..].iter().any(|e| e.starts_with("setup:")));
1961        assert!(!log.events.contains(&"start:1".to_string()));
1962        assert_eq!(res[0].as_ref().unwrap().times.len(), 2);
1963        assert_eq!(res[2].as_ref().unwrap().times.len(), 2);
1964        let msg = format!("{:#}", res[1].as_ref().unwrap_err());
1965        assert!(msg.contains("setup") && msg.contains("no fixture"), "{msg}");
1966        // Setup is not a sample: only warmups and runs finish.
1967        assert_eq!(log.finished.len(), 2 * (1 + 2));
1968    }
1969
1970    /// `runs = "auto"` sizes each subject from its own speed: a subject too
1971    /// slow for the budget gets the floor, a faster one gets more. Uses real
1972    /// sleeps, so the fast count is only bounded, not exact.
1973    #[cfg(unix)]
1974    #[test]
1975    fn auto_runs_give_a_slow_subject_the_floor_and_a_fast_one_more() {
1976        let mk = |name: &str, secs: &str, warmup: u32| Subject {
1977            name: name.into(),
1978            cmd: vec!["sleep".into(), secs.into()],
1979            prepare: None,
1980            setup: None,
1981            setup_dir: None,
1982            check: None,
1983            dir: None,
1984            version_cmd: None,
1985            env: BTreeMap::new(),
1986            vars: BTreeMap::new(),
1987            when: None,
1988            runs: Runs::Auto,
1989            auto: AutoRuns {
1990                budget: Duration::from_millis(400),
1991                min: 2,
1992                max: 6,
1993            },
1994            warmup,
1995            counters: false,
1996            ok_exit_codes: vec![0],
1997        };
1998        let mut log = Log::default();
1999        // The slow one has no warmup, so its first kept sample sizes it.
2000        let res = interleaved(
2001            &[mk("fast", "0.02", 1), mk("slow", "0.3", 0)],
2002            9,
2003            &Settings::default(),
2004            &mut log,
2005        );
2006        let fast = res[0].as_ref().unwrap().times.len();
2007        let slow = res[1].as_ref().unwrap().times.len();
2008        assert_eq!(slow, 2, "0.4s budget / 0.3s sample is below the floor");
2009        assert!(fast > slow && fast <= 6, "fast got {fast}");
2010        // Planned on the floors first, then on the settled counts.
2011        assert_eq!(log.plans[0], [1 + 2, 2]);
2012        assert_eq!(log.plans.len(), 2);
2013        assert_eq!(log.finished.len(), 1 + fast + slow);
2014    }
2015
2016    #[test]
2017    fn steady_samples_raise_no_warning() {
2018        assert!(warnings(&[10.0, 10.2, 9.9, 10.1, 10.0, 10.3]).is_empty());
2019        assert!(warnings(&[10.0, 50.0]).is_empty(), "too few to judge");
2020    }
2021
2022    #[test]
2023    fn a_spike_is_an_outlier() {
2024        let w = warnings(&[10.0, 10.2, 9.9, 10.1, 40.0, 10.0, 10.1]);
2025        assert_eq!(w.len(), 1, "{w:?}");
2026        assert!(
2027            w[0].starts_with("1 of 7 samples are slow outliers"),
2028            "{w:?}"
2029        );
2030    }
2031
2032    #[test]
2033    fn a_slow_first_sample_is_called_out() {
2034        let w = warnings(&[35.0, 10.0, 10.2, 9.9, 10.1, 10.0]);
2035        assert!(
2036            w.iter().any(|m| m.contains("first sample took 3.5x")),
2037            "{w:?}"
2038        );
2039    }
2040
2041    /// With most samples identical the median deviation is zero; a spike
2042    /// must still be reported.
2043    #[test]
2044    fn a_spike_among_identical_samples_is_still_an_outlier() {
2045        let w = warnings(&[10.0, 10.0, 10.0, 100.0, 10.0]);
2046        assert!(w.iter().any(|m| m.contains("slow outliers")), "{w:?}");
2047        assert!(
2048            warnings(&[10.0; 6]).is_empty(),
2049            "identical samples are fine"
2050        );
2051    }
2052
2053    /// A fast outlier is the minimum, so it is reported as such rather than
2054    /// reassured away.
2055    #[test]
2056    fn a_fast_outlier_is_flagged_as_possibly_the_minimum() {
2057        let w = warnings(&[100.0, 101.0, 99.0, 102.0, 10.0, 100.0]);
2058        assert!(
2059            w.iter()
2060                .any(|m| m.contains("fast outliers") && m.contains("minimum")),
2061            "{w:?}"
2062        );
2063    }
2064
2065    /// Several identical spikes over a flat majority are all caught, not
2066    /// hidden by a spread they themselves inflate.
2067    #[test]
2068    fn several_spikes_over_a_flat_majority_are_caught() {
2069        let w = warnings(&[10.0, 10.0, 10.0, 10.0, 40.0, 45.0]);
2070        assert!(
2071            w.iter()
2072                .any(|m| m.starts_with("2 of 6 samples are slow outliers")),
2073            "{w:?}"
2074        );
2075        assert!(
2076            warnings(&[10.0, 10.0, 10.0, 11.0, 10.0]).is_empty(),
2077            "10% is not a spike"
2078        );
2079    }
2080}