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