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, 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::time::Duration;
23use std::time::Instant;
24
25#[derive(Debug, Clone)]
26pub struct Plan {
27    pub cmd: Vec<String>,
28    pub warmup: u32,
29    pub runs: u32,
30    /// Directory to run in. Declared benchmarks resolve relative commands
31    /// against `tak.toml`'s directory, not the caller's — otherwise the same
32    /// benchmark measures different things depending on where you stood.
33    pub dir: Option<std::path::PathBuf>,
34    /// Resolved settings. Carried on the plan rather than read from a global so
35    /// a test can measure under a different configuration without touching the
36    /// environment of the whole test binary.
37    pub settings: Settings,
38}
39
40/// A command for running a benchmark subject, with the scrubbed variables
41/// removed.
42///
43/// Every subject spawn goes through here. Under cachegrind the removal is
44/// applied to valgrind itself, which the subject inherits from.
45///
46/// What gets removed is [`Settings::scrubbed_env`] — `env_deny` less
47/// `env_allow`, both declared on the `Settings` registry. The default is the
48/// forge tokens because a CLI that finds one often does more with it than
49/// without, so a measurement would move depending on whether CI happened to
50/// export one.
51///
52/// This controls direct inheritance, not hostile-code isolation. A subject can
53/// still inspect accessible same-user processes and files, so `backfill` must
54/// run without credentials when its release binaries are not trusted.
55///
56/// tak's own network calls are unaffected — `backfill` authenticates with
57/// `curl` directly rather than through this path.
58fn subject(bin: &str, settings: &Settings) -> Command {
59    let mut c = Command::new(bin);
60    for key in settings.scrubbed_env() {
61        c.env_remove(key);
62    }
63    c
64}
65
66/// Where a command runs and what it sees, beyond its argv.
67#[derive(Debug, Clone, Copy)]
68struct Site<'a> {
69    dir: Option<&'a Path>,
70    env: &'a BTreeMap<String, String>,
71    settings: &'a Settings,
72}
73
74/// Build a spawn of `argv` at `site`.
75///
76/// Declared variables are applied after the scrub. A variable written into
77/// `tak.toml` for a subject is an explicit choice, not something inherited by
78/// accident, which is the only thing the scrub exists to stop.
79fn command(argv: &[String], site: &Site) -> Result<Command> {
80    let (bin, args) = argv.split_first().context("empty command")?;
81    let mut c = subject(bin, site.settings);
82    c.args(args).envs(site.env);
83    if let Some(d) = site.dir {
84        c.current_dir(d);
85    }
86    Ok(c)
87}
88
89/// Run once, discarding output, returning elapsed wall time in milliseconds.
90///
91/// No shell. Spawning a shell adds its own startup cost and variance to every
92/// sample, which for commands in the 10ms range is a large fraction of the
93/// measurement — the same reasoning behind poop's refusal to support one.
94fn time_once(cmd: &[String], site: &Site) -> Result<f64> {
95    let mut c = command(cmd, site)?;
96    c.stdout(Stdio::null()).stderr(Stdio::null());
97    let bin = &cmd[0];
98    let start = Instant::now();
99    let status = c
100        .status()
101        .with_context(|| format!("failed to spawn `{bin}`"))?;
102    let elapsed = start.elapsed().as_secs_f64() * 1000.0;
103    if !status.success() {
104        bail!("benchmark subject `{bin}` exited with {status}");
105    }
106    Ok(elapsed)
107}
108
109/// How much of a failing prepare step's stderr to keep for the error message.
110/// Enough for the last few lines; a verbose reset command's full output would
111/// otherwise sit in memory before every sample.
112const PREPARE_STDERR_TAIL: usize = 4096;
113
114/// Run a subject's prepare step. Untimed, so reading its stderr for the error
115/// message costs the measurement nothing.
116fn prepare_once(cmd: &[String], site: &Site) -> Result<()> {
117    use std::io::Read;
118
119    let mut c = command(cmd, site)?;
120    let bin = &cmd[0];
121    let mut child = c
122        .stdin(Stdio::null())
123        .stdout(Stdio::null())
124        .stderr(Stdio::piped())
125        .spawn()
126        .with_context(|| format!("failed to spawn prepare `{bin}`"))?;
127    // Keep only the tail, reading as it arrives so the child never blocks on a
128    // full pipe.
129    let mut tail: Vec<u8> = Vec::new();
130    if let Some(mut err) = child.stderr.take() {
131        let mut buf = [0u8; 8192];
132        loop {
133            let n = err.read(&mut buf).unwrap_or(0);
134            if n == 0 {
135                break;
136            }
137            tail.extend_from_slice(&buf[..n]);
138            if tail.len() > PREPARE_STDERR_TAIL {
139                tail.drain(..tail.len() - PREPARE_STDERR_TAIL);
140            }
141        }
142    }
143    let status = child
144        .wait()
145        .with_context(|| format!("failed to wait for prepare `{bin}`"))?;
146    if !status.success() {
147        let stderr = String::from_utf8_lossy(&tail);
148        bail!(
149            "prepare `{bin}` exited with {status}: {}",
150            stderr.lines().last().unwrap_or("(no output)").trim()
151        );
152    }
153    Ok(())
154}
155
156/// One entry in a run's sample order.
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub struct Slot {
159    /// Index into the subjects being measured.
160    pub subject: usize,
161    /// Whether this sample is kept. Warmup samples run through the same
162    /// prepare-then-run path and are discarded.
163    pub timed: bool,
164}
165
166/// The order in which to take samples: every warmup round, then every timed
167/// round, each round a fresh shuffle of the subjects due in it.
168///
169/// Measuring one subject to completion before starting the next puts any
170/// drift over the run — contention on a shared host, thermal throttling, a
171/// cache filling up — entirely on whichever subjects ran while it happened,
172/// where it reads as a difference between them. One sample of each per round
173/// spreads that drift across all of them, and shuffling each round stops any
174/// subject from systematically running first (cold) or right after a
175/// particular other one (whose leftovers it inherits).
176///
177/// A subject with fewer samples than there are rounds sits out evenly spaced
178/// rounds rather than dropping out at the end, which would leave the late
179/// part of the run — and its drift — to the others.
180///
181/// `counts` is `(warmup, runs)` per subject. The same seed gives the same
182/// order for the same subjects.
183pub fn schedule(counts: &[(u32, u32)], seed: u64) -> Vec<Slot> {
184    let mut rng = fastrand::Rng::with_seed(seed);
185    let warmups: Vec<u64> = counts.iter().map(|&(w, _)| u64::from(w)).collect();
186    let runs: Vec<u64> = counts.iter().map(|&(_, r)| u64::from(r)).collect();
187    let mut out = rounds(&warmups, false, &mut rng);
188    out.extend(rounds(&runs, true, &mut rng));
189    out
190}
191
192/// Shuffled rounds taking `count[i]` samples of subject `i`.
193fn rounds(count: &[u64], timed: bool, rng: &mut fastrand::Rng) -> Vec<Slot> {
194    let total = count.iter().copied().max().unwrap_or(0);
195    let mut out = Vec::new();
196    for round in 0..total {
197        // Subject i is due in the rounds where floor(r * k / R) steps up:
198        // exactly k of the R rounds, as evenly spaced as integers allow.
199        let mut due: Vec<usize> = (0..count.len())
200            .filter(|&i| (round + 1) * count[i] / total > round * count[i] / total)
201            .collect();
202        rng.shuffle(&mut due);
203        out.extend(due.into_iter().map(|subject| Slot { subject, timed }));
204    }
205    out
206}
207
208/// Derive a benchmark's seed from the run's, so `--bench x --seed n` takes
209/// the same order for `x` as the full run with `--seed n` did.
210pub fn seed_for(seed: u64, bench: &str) -> u64 {
211    // FNV-1a: a fixed function, unlike std's randomly keyed hasher.
212    bench.bytes().fold(seed ^ 0xcbf2_9ce4_8422_2325, |h, b| {
213        (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)
214    })
215}
216
217/// Told about a run as it happens, to report progress.
218pub trait Observer {
219    /// Samples still to take per subject, warmups included. Called before the
220    /// first sample and again once `runs = "auto"` has settled its counts.
221    fn planned(&mut self, _remaining: &[u64]) {}
222    /// A sample of `subject` is starting.
223    fn started(&mut self, _subject: usize) {}
224    /// A sample of `subject` finished; `elapsed` covers its prepare step too.
225    fn finished(&mut self, _subject: usize, _elapsed: Duration) {}
226    /// `subject` failed and takes no more samples.
227    fn dropped(&mut self, _subject: usize) {}
228}
229
230/// An observer that reports nothing.
231pub struct Quiet;
232impl Observer for Quiet {}
233
234/// Measure several subjects against each other, interleaved.
235///
236/// Returns each subject's timed samples in the order they were taken, or the
237/// error that stopped it. A failing subject is dropped from the remaining
238/// rounds and the others carry on: one competitor breaking should not throw
239/// away a long run's worth of everyone else's samples. Subject directories
240/// are used as given, so the caller resolves them first.
241///
242/// Runs in two phases. The warmups come first, plus one kept sample of every
243/// `runs = "auto"` subject that has no warmups, so each auto subject has been
244/// timed at least once. Its run count is then fixed from the fastest of those
245/// samples, and every remaining timed sample is taken in shuffled rounds.
246pub fn interleaved(
247    subjects: &[Subject],
248    seed: u64,
249    settings: &Settings,
250    observer: &mut dyn Observer,
251) -> Vec<Result<Vec<f64>>> {
252    let mut rng = fastrand::Rng::with_seed(seed);
253    let mut results: Vec<Result<Vec<f64>>> = subjects
254        .iter()
255        .map(|s| {
256            // Zero runs would leave nothing to report on.
257            if s.runs == Runs::Fixed(0) {
258                bail!("runs must be at least 1");
259            }
260            Ok(Vec::new())
261        })
262        .collect();
263    // The fastest whole sample of each subject so far, prepare included —
264    // what an auto count is sized from. The fastest, because a warmup is
265    // often a cold outlier and would shrink the count for no reason.
266    let mut fastest: Vec<Option<Duration>> = vec![None; subjects.len()];
267
268    let warmups: Vec<u64> = subjects.iter().map(|s| u64::from(s.warmup)).collect();
269    let pilots: Vec<u64> = subjects
270        .iter()
271        .map(|s| u64::from(s.runs == Runs::Auto && s.warmup == 0))
272        .collect();
273    // Until the auto counts are known, plan on each one's floor.
274    let provisional: Vec<u64> = subjects
275        .iter()
276        .zip(&warmups)
277        .map(|(s, w)| {
278            w + u64::from(match s.runs {
279                Runs::Fixed(n) => n,
280                Runs::Auto => s.auto.min,
281            })
282        })
283        .collect();
284    observer.planned(&provisional);
285
286    let mut first = rounds(&warmups, false, &mut rng);
287    first.extend(rounds(&pilots, true, &mut rng));
288    run_slots(
289        &first,
290        subjects,
291        settings,
292        &mut results,
293        &mut fastest,
294        observer,
295    );
296
297    let remaining: Vec<u64> = subjects
298        .iter()
299        .enumerate()
300        .map(|(i, s)| match (&results[i], s.runs) {
301            (Err(_), _) => 0,
302            (Ok(_), Runs::Fixed(n)) => u64::from(n),
303            (Ok(taken), Runs::Auto) => {
304                let n = auto_runs(&s.auto, fastest[i]);
305                u64::from(n).saturating_sub(taken.len() as u64)
306            }
307        })
308        .collect();
309    observer.planned(&remaining);
310    let second = rounds(&remaining, true, &mut rng);
311    run_slots(
312        &second,
313        subjects,
314        settings,
315        &mut results,
316        &mut fastest,
317        observer,
318    );
319    results
320}
321
322/// An auto subject's run count. One that was never timed — its every sample
323/// failed, so it is being dropped anyway — gets the floor.
324fn auto_runs(auto: &AutoRuns, fastest: Option<Duration>) -> u32 {
325    fastest.map_or(auto.min, |d| auto.runs_for(d))
326}
327
328/// Take the given samples, recording timed ones and the fastest slot seen.
329fn run_slots(
330    slots: &[Slot],
331    subjects: &[Subject],
332    settings: &Settings,
333    results: &mut [Result<Vec<f64>>],
334    fastest: &mut [Option<Duration>],
335    observer: &mut dyn Observer,
336) {
337    for slot in slots {
338        let Ok(samples) = &mut results[slot.subject] else {
339            continue;
340        };
341        let s = &subjects[slot.subject];
342        let site = Site {
343            dir: s.dir.as_deref(),
344            env: &s.env,
345            settings,
346        };
347        observer.started(slot.subject);
348        let began = Instant::now();
349        let taken = s
350            .prepare
351            .as_deref()
352            .map_or(Ok(()), |p| prepare_once(p, &site))
353            .and_then(|()| time_once(&s.cmd, &site));
354        let elapsed = began.elapsed();
355        match taken {
356            Ok(ms) => {
357                if slot.timed {
358                    samples.push(ms);
359                }
360                let f = &mut fastest[slot.subject];
361                *f = Some(f.map_or(elapsed, |f| f.min(elapsed)));
362                observer.finished(slot.subject, elapsed);
363            }
364            Err(e) => {
365                results[slot.subject] = Err(e);
366                observer.dropped(slot.subject);
367            }
368        }
369    }
370}
371
372/// Wall-clock statistics over a set of samples, in milliseconds.
373///
374/// Reports `min` alongside the mean because contention is one-sided — a busy
375/// machine can only make a run slower, never faster — so the minimum is a far
376/// more robust estimator than the mean on shared CI hardware. The standard
377/// deviation is there to show how noisy the run was, not to be compared.
378pub fn stats(samples: &[f64]) -> BTreeMap<String, f64> {
379    let mut sorted = samples.to_vec();
380    sorted.sort_by(f64::total_cmp);
381    let n = sorted.len();
382    let mean = sorted.iter().sum::<f64>() / n as f64;
383    // Sample (n - 1) deviation, as hyperfine reports; a single sample has none.
384    let stddev = if n > 1 {
385        (sorted.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64).sqrt()
386    } else {
387        0.0
388    };
389    BTreeMap::from([
390        ("wall_min_ms".to_string(), sorted[0]),
391        ("wall_p50_ms".to_string(), sorted[n / 2]),
392        ("wall_mean_ms".to_string(), mean),
393        ("wall_max_ms".to_string(), sorted[n - 1]),
394        ("wall_stddev_ms".to_string(), stddev),
395        ("wall_n".to_string(), n as f64),
396    ])
397}
398
399/// Wall-clock statistics over `plan.runs` samples of one command.
400pub fn wall(plan: &Plan) -> Result<BTreeMap<String, f64>> {
401    let subject = Subject {
402        name: SELF_TOOL.to_string(),
403        cmd: plan.cmd.clone(),
404        prepare: None,
405        dir: plan.dir.clone(),
406        env: BTreeMap::new(),
407        runs: Runs::Fixed(plan.runs),
408        auto: AutoRuns {
409            budget: crate::config::DEFAULT_BUDGET,
410            min: crate::config::DEFAULT_MIN_RUNS,
411            max: crate::config::DEFAULT_MAX_RUNS,
412        },
413        warmup: plan.warmup,
414        counters: false,
415    };
416    // One subject has one possible order, so the seed is irrelevant.
417    let samples = interleaved(
418        std::slice::from_ref(&subject),
419        0,
420        &plan.settings,
421        &mut Quiet,
422    )
423    .pop()
424    .expect("one result per subject")?;
425    Ok(stats(&samples))
426}
427
428/// Is cachegrind usable on this machine?
429///
430/// Exposed so callers can tell "no counters because valgrind is missing" from
431/// "no counters because the measurement failed" — two problems with entirely
432/// different fixes.
433pub fn valgrind_available() -> bool {
434    Command::new("valgrind")
435        .arg("--version")
436        .stdout(Stdio::null())
437        .stderr(Stdio::null())
438        .status()
439        .map(|s| s.success())
440        .unwrap_or(false)
441}
442
443/// Repeats of the cachegrind run. Three is enough to catch a bimodal subject
444/// without tripling the cost of a measurement that is already ~50x slowed.
445const COUNTER_RUNS: u32 = 3;
446
447/// A subject varying by more than this is doing environment-dependent work, and
448/// its instruction count is not a usable gate. Well above the ~0.005% observed
449/// for a genuinely hermetic command, far below the 16% seen from one that
450/// touches the network.
451const SPREAD_WARN_PCT: f64 = 0.5;
452
453/// Instruction counts from repeated cachegrind runs.
454#[derive(Debug, Clone, Copy)]
455pub struct Counted {
456    pub min: u64,
457    pub max: u64,
458    pub runs: u32,
459}
460
461impl Counted {
462    /// Relative spread across runs, as a percentage of the minimum.
463    pub fn spread_pct(&self) -> f64 {
464        if self.min == 0 {
465            return 0.0;
466        }
467        (self.max - self.min) as f64 / self.min as f64 * 100.0
468    }
469
470    /// Whether this subject looks non-hermetic.
471    ///
472    /// The metric is deterministic; the program being measured need not be. A
473    /// CLI that checks for updates, reads a cache it may have just created, or
474    /// resolves DNS retires a different number of instructions depending on
475    /// conditions that have nothing to do with the code under test.
476    pub fn is_suspect(&self) -> bool {
477        self.spread_pct() > SPREAD_WARN_PCT
478    }
479}
480
481/// Instruction count via `valgrind --tool=cachegrind`, repeated.
482///
483/// Reports the **minimum**, for the same reason wall clock does: the extra work
484/// a subject sometimes performs is one-sided. A run that consults the network or
485/// populates a cache can only retire *more* instructions than the quiet path,
486/// never fewer, so the floor is the stable estimator.
487///
488/// Returns `Ok(None)` when valgrind is unavailable rather than failing: this is
489/// the expected state on macOS (no usable Apple Silicon support) and Windows.
490/// Those platforms record timing only, and the CI gate lives on the Linux job.
491/// Locally, a container gets you counters on any host.
492pub fn instructions(
493    cmd: &[String],
494    dir: Option<&std::path::Path>,
495    settings: &Settings,
496) -> Result<Option<Counted>> {
497    count(
498        cmd,
499        None,
500        &Site {
501            dir,
502            env: &BTreeMap::new(),
503            settings,
504        },
505    )
506}
507
508/// [`instructions`] for a declared subject: its environment, and its prepare
509/// step before every cachegrind run, since each run has to start from the
510/// same state the timed samples did.
511pub fn subject_instructions(s: &Subject, settings: &Settings) -> Result<Option<Counted>> {
512    count(
513        &s.cmd,
514        s.prepare.as_deref(),
515        &Site {
516            dir: s.dir.as_deref(),
517            env: &s.env,
518            settings,
519        },
520    )
521}
522
523fn count(cmd: &[String], prepare: Option<&[String]>, site: &Site) -> Result<Option<Counted>> {
524    if !valgrind_available() {
525        return Ok(None);
526    }
527
528    let mut samples: Vec<u64> = Vec::with_capacity(COUNTER_RUNS as usize);
529    for _ in 0..COUNTER_RUNS {
530        if let Some(p) = prepare {
531            prepare_once(p, site)?;
532        }
533        let mut argv: Vec<String> = [
534            "valgrind",
535            "--tool=cachegrind",
536            "--cache-sim=no",
537            "--branch-sim=no",
538            "--cachegrind-out-file=/dev/null",
539        ]
540        .map(String::from)
541        .to_vec();
542        argv.extend_from_slice(cmd);
543        let mut c = command(&argv, site)?;
544        c.stdout(Stdio::null());
545        let out = c.output().context("failed to run valgrind")?;
546
547        // cachegrind writes its summary to stderr as e.g. "I refs:  48,349,132".
548        let stderr = String::from_utf8_lossy(&out.stderr);
549        if !out.status.success() {
550            let bin = cmd.first().map(String::as_str).unwrap_or("(empty command)");
551            bail!(
552                "benchmark subject `{bin}` exited with {} under valgrind",
553                out.status
554            );
555        }
556        match parse_irefs(&stderr) {
557            Some(n) => samples.push(n),
558            // Valgrind is installed but produced no summary — a real failure,
559            // not the same thing as valgrind being absent. Reporting it as
560            // absent sends people off installing something they already have.
561            None => bail!(
562                "valgrind ran but emitted no `I refs` summary: {}",
563                stderr.lines().last().unwrap_or("(no output)").trim()
564            ),
565        }
566    }
567
568    Ok(Some(Counted {
569        min: *samples.iter().min().expect("COUNTER_RUNS > 0"),
570        max: *samples.iter().max().expect("COUNTER_RUNS > 0"),
571        runs: COUNTER_RUNS,
572    }))
573}
574
575/// Extract the `I refs:` count from cachegrind's stderr summary.
576fn parse_irefs(stderr: &str) -> Option<u64> {
577    let line = stderr.lines().find(|l| l.contains("I refs:"))?;
578    let digits: String = line
579        .rsplit(':')
580        .next()?
581        .chars()
582        .filter(|c| c.is_ascii_digit())
583        .collect();
584    digits.parse().ok()
585}
586
587#[cfg(test)]
588mod tests {
589    use super::*;
590
591    #[test]
592    fn parses_cachegrind_summary() {
593        let s = "==12== I refs:      48,349,132\n";
594        assert_eq!(parse_irefs(s), Some(48_349_132));
595    }
596
597    #[test]
598    fn missing_summary_is_none_not_panic() {
599        assert_eq!(parse_irefs("valgrind: command not found"), None);
600    }
601
602    /// What `subject` removes, as configured.
603    fn removals(settings: &Settings) -> Vec<String> {
604        subject("true", settings)
605            .get_envs()
606            .filter(|(_, v)| v.is_none())
607            .map(|(k, _)| k.to_string_lossy().into_owned())
608            .collect()
609    }
610
611    /// Construction-level check. The end-to-end proof that a subject cannot see
612    /// the token lives in `tests/subject_env.rs`, which runs the real binary.
613    #[test]
614    fn subject_commands_remove_the_default_denied_variables() {
615        let removed = removals(&Settings::default());
616        for key in Settings::default().scrubbed_env() {
617            assert!(removed.contains(&key.to_string()), "{key} not removed");
618        }
619    }
620
621    /// The removal follows the setting rather than a compiled-in list, which is
622    /// the whole point of routing it through `Settings`.
623    #[test]
624    fn the_removal_follows_the_settings() {
625        let removed = removals(&Settings {
626            env_deny: vec!["CUSTOM_SECRET".into()],
627            env_allow: Vec::new(),
628            ..Settings::default()
629        });
630        assert!(removed.contains(&"CUSTOM_SECRET".to_string()));
631        assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
632    }
633
634    /// An allowed variable is not removed, so a subject that genuinely needs
635    /// one can still be measured.
636    #[test]
637    fn an_allowed_variable_survives() {
638        let removed = removals(&Settings {
639            env_deny: vec!["GITHUB_TOKEN".into(), "GH_TOKEN".into()],
640            env_allow: vec!["GITHUB_TOKEN".into()],
641            ..Settings::default()
642        });
643        assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
644        assert!(removed.contains(&"GH_TOKEN".to_string()));
645    }
646
647    #[test]
648    fn zero_runs_is_rejected_not_a_panic() {
649        let plan = Plan {
650            cmd: vec!["true".into()],
651            warmup: 0,
652            runs: 0,
653            dir: None,
654            settings: Settings::default(),
655        };
656        assert!(wall(&plan).is_err());
657    }
658
659    #[test]
660    fn a_failed_subject_is_not_recorded_as_a_fast_run() {
661        #[cfg(unix)]
662        let cmd = vec!["/bin/sh".into(), "-c".into(), "exit 42".into()];
663        #[cfg(windows)]
664        let cmd = vec!["cmd".into(), "/C".into(), "exit /B 42".into()];
665
666        let err = wall(&Plan {
667            cmd,
668            warmup: 0,
669            runs: 1,
670            dir: None,
671            settings: Settings::default(),
672        })
673        .unwrap_err();
674
675        assert!(format!("{err:#}").contains("exited with"), "{err:#}");
676    }
677
678    #[test]
679    fn wall_reports_min_le_p50_le_max() {
680        let plan = Plan {
681            cmd: vec!["true".into()],
682            warmup: 1,
683            runs: 5,
684            dir: None,
685            settings: Settings::default(),
686        };
687        let m = wall(&plan).unwrap();
688        assert!(m["wall_min_ms"] <= m["wall_p50_ms"]);
689        assert!(m["wall_p50_ms"] <= m["wall_max_ms"]);
690        assert_eq!(m["wall_n"], 5.0);
691    }
692
693    /// Every subject gets exactly its warmups and runs, warmups first.
694    #[test]
695    fn the_schedule_gives_each_subject_its_counts() {
696        let counts = [(2, 10), (1, 5), (0, 3)];
697        let order = schedule(&counts, 7);
698        for (i, &(warmup, runs)) in counts.iter().enumerate() {
699            let of = |timed| {
700                order
701                    .iter()
702                    .filter(|s| s.subject == i && s.timed == timed)
703                    .count()
704            };
705            assert_eq!(of(false), warmup as usize, "subject {i} warmups");
706            assert_eq!(of(true), runs as usize, "subject {i} runs");
707        }
708        let first_timed = order.iter().position(|s| s.timed).unwrap();
709        assert!(order[first_timed..].iter().all(|s| s.timed));
710    }
711
712    #[test]
713    fn the_same_seed_gives_the_same_order() {
714        let counts = [(1, 8), (1, 8), (1, 8)];
715        assert_eq!(schedule(&counts, 42), schedule(&counts, 42));
716        assert_ne!(schedule(&counts, 42), schedule(&counts, 43));
717    }
718
719    /// Interleaving is the point: with equal counts, every round holds each
720    /// subject once, and the order is not the same in every round.
721    #[test]
722    fn each_round_runs_every_subject_once_in_a_varying_order() {
723        let order = schedule(&[(0, 20), (0, 20), (0, 20)], 1);
724        let rounds: Vec<Vec<usize>> = order
725            .chunks(3)
726            .map(|r| r.iter().map(|s| s.subject).collect())
727            .collect();
728        assert_eq!(rounds.len(), 20);
729        for r in &rounds {
730            let mut sorted = r.clone();
731            sorted.sort();
732            assert_eq!(sorted, [0, 1, 2], "round {r:?}");
733        }
734        assert!(rounds.iter().any(|r| r != &rounds[0]), "never shuffled");
735    }
736
737    /// A subject with half the runs takes part in alternate rounds, not only
738    /// the first half — otherwise drift late in the run lands on the others.
739    #[test]
740    fn a_subject_with_fewer_runs_is_spread_across_the_run() {
741        let order = schedule(&[(0, 10), (0, 5)], 3);
742        let fewer: Vec<usize> = order
743            .iter()
744            .enumerate()
745            .filter(|(_, s)| s.subject == 1)
746            .map(|(i, _)| i)
747            .collect();
748        assert_eq!(fewer.len(), 5);
749        assert!(
750            *fewer.last().unwrap() >= order.len() - 3,
751            "last sample of the smaller subject is near the end: {fewer:?} of {}",
752            order.len()
753        );
754    }
755
756    #[test]
757    fn a_benchmark_seed_depends_on_its_name_and_the_run_seed() {
758        assert_eq!(seed_for(1, "a"), seed_for(1, "a"));
759        assert_ne!(seed_for(1, "a"), seed_for(1, "b"));
760        assert_ne!(seed_for(1, "a"), seed_for(2, "a"));
761    }
762
763    #[test]
764    fn stats_report_the_sample_standard_deviation() {
765        let m = stats(&[2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]);
766        assert_eq!(m["wall_min_ms"], 2.0);
767        assert_eq!(m["wall_max_ms"], 9.0);
768        assert_eq!(m["wall_mean_ms"], 5.0);
769        // sqrt(32 / 7)
770        assert!((m["wall_stddev_ms"] - 2.138_089_935).abs() < 1e-6);
771        assert_eq!(stats(&[3.0])["wall_stddev_ms"], 0.0);
772    }
773
774    /// A failing subject is dropped; the others still get every sample.
775    #[cfg(unix)]
776    #[test]
777    fn a_failing_subject_does_not_stop_the_others() {
778        let mk = |name: &str, cmd: &[&str]| Subject {
779            name: name.into(),
780            cmd: cmd.iter().map(|s| s.to_string()).collect(),
781            prepare: None,
782            dir: None,
783            env: BTreeMap::new(),
784            runs: Runs::Fixed(4),
785            auto: AutoRuns {
786                budget: Duration::from_secs(30),
787                min: 5,
788                max: 50,
789            },
790            warmup: 1,
791            counters: false,
792        };
793        let res = interleaved(
794            &[mk("ok", &["true"]), mk("bad", &["false"])],
795            5,
796            &Settings::default(),
797            &mut Quiet,
798        );
799        assert_eq!(res[0].as_ref().unwrap().len(), 4);
800        assert!(format!("{:#}", res[1].as_ref().unwrap_err()).contains("exited with"));
801    }
802
803    /// A prepare step that fails stops its subject, and says it was prepare.
804    #[cfg(unix)]
805    #[test]
806    fn a_failing_prepare_is_reported_as_prepare() {
807        let res = interleaved(
808            &[Subject {
809                name: "x".into(),
810                cmd: vec!["true".into()],
811                prepare: Some(vec![
812                    "/bin/sh".into(),
813                    "-c".into(),
814                    "echo nope >&2; exit 3".into(),
815                ]),
816                dir: None,
817                env: BTreeMap::new(),
818                runs: Runs::Fixed(1),
819                auto: AutoRuns {
820                    budget: Duration::from_secs(30),
821                    min: 5,
822                    max: 50,
823                },
824                warmup: 0,
825                counters: false,
826            }],
827            0,
828            &Settings::default(),
829            &mut Quiet,
830        );
831        let msg = format!("{:#}", res[0].as_ref().unwrap_err());
832        assert!(msg.contains("prepare") && msg.contains("nope"), "{msg}");
833    }
834
835    /// An observer that records what it was told.
836    #[derive(Default)]
837    struct Log {
838        plans: Vec<Vec<u64>>,
839        finished: Vec<usize>,
840    }
841    impl Observer for Log {
842        fn planned(&mut self, remaining: &[u64]) {
843            self.plans.push(remaining.to_vec());
844        }
845        fn finished(&mut self, subject: usize, _: Duration) {
846            self.finished.push(subject);
847        }
848    }
849
850    /// `runs = "auto"` sizes each subject from its own speed: a subject too
851    /// slow for the budget gets the floor, a faster one gets more. Uses real
852    /// sleeps, so the fast count is only bounded, not exact.
853    #[cfg(unix)]
854    #[test]
855    fn auto_runs_give_a_slow_subject_the_floor_and_a_fast_one_more() {
856        let mk = |name: &str, secs: &str, warmup: u32| Subject {
857            name: name.into(),
858            cmd: vec!["sleep".into(), secs.into()],
859            prepare: None,
860            dir: None,
861            env: BTreeMap::new(),
862            runs: Runs::Auto,
863            auto: AutoRuns {
864                budget: Duration::from_millis(400),
865                min: 2,
866                max: 6,
867            },
868            warmup,
869            counters: false,
870        };
871        let mut log = Log::default();
872        // The slow one has no warmup, so its first kept sample sizes it.
873        let res = interleaved(
874            &[mk("fast", "0.02", 1), mk("slow", "0.3", 0)],
875            9,
876            &Settings::default(),
877            &mut log,
878        );
879        let fast = res[0].as_ref().unwrap().len();
880        let slow = res[1].as_ref().unwrap().len();
881        assert_eq!(slow, 2, "0.4s budget / 0.3s sample is below the floor");
882        assert!(fast > slow && fast <= 6, "fast got {fast}");
883        // Planned on the floors first, then on the settled counts.
884        assert_eq!(log.plans[0], [1 + 2, 2]);
885        assert_eq!(log.plans.len(), 2);
886        assert_eq!(log.finished.len(), 1 + fast + slow);
887    }
888}