tak-cli 0.0.11

Pre-v1 command-line benchmarking and performance tracking
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
//! Measurement backends.
//!
//! Two tiers, deliberately separated:
//!
//! - **Deterministic** (`instructions`) — reproducible to ~0.02% run-to-run and
//!   ~0.035% across wildly different machine load. This is the only tier that may
//!   gate CI.
//! - **Timing** (`wall_*`) — recorded and charted, never gated. On a quiet 32-core
//!   host wall clock still shows 4–20% coefficient of variation; under contention
//!   the median moves ~150%.
//!
//! Syscall counts and peak RSS sit awkwardly between the two: better than wall
//! clock (~1%) but not deterministic, because they move with thread scheduling.
//! They are recorded, and may be flagged, but must not gate at a tight threshold.

use crate::config::{SELF_TOOL, Subject};
use crate::settings::Settings;
use anyhow::{Context, Result, bail};
use std::collections::BTreeMap;
use std::path::Path;
use std::process::{Command, Stdio};
use std::time::Instant;

#[derive(Debug, Clone)]
pub struct Plan {
    pub cmd: Vec<String>,
    pub warmup: u32,
    pub runs: u32,
    /// Directory to run in. Declared benchmarks resolve relative commands
    /// against `tak.toml`'s directory, not the caller's — otherwise the same
    /// benchmark measures different things depending on where you stood.
    pub dir: Option<std::path::PathBuf>,
    /// Resolved settings. Carried on the plan rather than read from a global so
    /// a test can measure under a different configuration without touching the
    /// environment of the whole test binary.
    pub settings: Settings,
}

/// A command for running a benchmark subject, with the scrubbed variables
/// removed.
///
/// Every subject spawn goes through here. Under cachegrind the removal is
/// applied to valgrind itself, which the subject inherits from.
///
/// What gets removed is [`Settings::scrubbed_env`] — `env_deny` less
/// `env_allow`, both declared on the `Settings` registry. The default is the
/// forge tokens because a CLI that finds one often does more with it than
/// without, so a measurement would move depending on whether CI happened to
/// export one.
///
/// This controls direct inheritance, not hostile-code isolation. A subject can
/// still inspect accessible same-user processes and files, so `backfill` must
/// run without credentials when its release binaries are not trusted.
///
/// tak's own network calls are unaffected — `backfill` authenticates with
/// `curl` directly rather than through this path.
fn subject(bin: &str, settings: &Settings) -> Command {
    let mut c = Command::new(bin);
    for key in settings.scrubbed_env() {
        c.env_remove(key);
    }
    c
}

/// Where a command runs and what it sees, beyond its argv.
#[derive(Debug, Clone, Copy)]
struct Site<'a> {
    dir: Option<&'a Path>,
    env: &'a BTreeMap<String, String>,
    settings: &'a Settings,
}

/// Build a spawn of `argv` at `site`.
///
/// Declared variables are applied after the scrub. A variable written into
/// `tak.toml` for a subject is an explicit choice, not something inherited by
/// accident, which is the only thing the scrub exists to stop.
fn command(argv: &[String], site: &Site) -> Result<Command> {
    let (bin, args) = argv.split_first().context("empty command")?;
    let mut c = subject(bin, site.settings);
    c.args(args).envs(site.env);
    if let Some(d) = site.dir {
        c.current_dir(d);
    }
    Ok(c)
}

/// Run once, discarding output, returning elapsed wall time in milliseconds.
///
/// No shell. Spawning a shell adds its own startup cost and variance to every
/// sample, which for commands in the 10ms range is a large fraction of the
/// measurement — the same reasoning behind poop's refusal to support one.
fn time_once(cmd: &[String], site: &Site) -> Result<f64> {
    let mut c = command(cmd, site)?;
    c.stdout(Stdio::null()).stderr(Stdio::null());
    let bin = &cmd[0];
    let start = Instant::now();
    let status = c
        .status()
        .with_context(|| format!("failed to spawn `{bin}`"))?;
    let elapsed = start.elapsed().as_secs_f64() * 1000.0;
    if !status.success() {
        bail!("benchmark subject `{bin}` exited with {status}");
    }
    Ok(elapsed)
}

/// How much of a failing prepare step's stderr to keep for the error message.
/// Enough for the last few lines; a verbose reset command's full output would
/// otherwise sit in memory before every sample.
const PREPARE_STDERR_TAIL: usize = 4096;

/// Run a subject's prepare step. Untimed, so reading its stderr for the error
/// message costs the measurement nothing.
fn prepare_once(cmd: &[String], site: &Site) -> Result<()> {
    use std::io::Read;

    let mut c = command(cmd, site)?;
    let bin = &cmd[0];
    let mut child = c
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .spawn()
        .with_context(|| format!("failed to spawn prepare `{bin}`"))?;
    // Keep only the tail, reading as it arrives so the child never blocks on a
    // full pipe.
    let mut tail: Vec<u8> = Vec::new();
    if let Some(mut err) = child.stderr.take() {
        let mut buf = [0u8; 8192];
        loop {
            let n = err.read(&mut buf).unwrap_or(0);
            if n == 0 {
                break;
            }
            tail.extend_from_slice(&buf[..n]);
            if tail.len() > PREPARE_STDERR_TAIL {
                tail.drain(..tail.len() - PREPARE_STDERR_TAIL);
            }
        }
    }
    let status = child
        .wait()
        .with_context(|| format!("failed to wait for prepare `{bin}`"))?;
    if !status.success() {
        let stderr = String::from_utf8_lossy(&tail);
        bail!(
            "prepare `{bin}` exited with {status}: {}",
            stderr.lines().last().unwrap_or("(no output)").trim()
        );
    }
    Ok(())
}

/// One entry in a run's sample order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Slot {
    /// Index into the subjects being measured.
    pub subject: usize,
    /// Whether this sample is kept. Warmup samples run through the same
    /// prepare-then-run path and are discarded.
    pub timed: bool,
}

/// The order in which to take samples: every warmup round, then every timed
/// round, each round a fresh shuffle of the subjects due in it.
///
/// Measuring one subject to completion before starting the next puts any
/// drift over the run — contention on a shared host, thermal throttling, a
/// cache filling up — entirely on whichever subjects ran while it happened,
/// where it reads as a difference between them. One sample of each per round
/// spreads that drift across all of them, and shuffling each round stops any
/// subject from systematically running first (cold) or right after a
/// particular other one (whose leftovers it inherits).
///
/// A subject with fewer samples than there are rounds sits out evenly spaced
/// rounds rather than dropping out at the end, which would leave the late
/// part of the run — and its drift — to the others.
///
/// `counts` is `(warmup, runs)` per subject. The same seed gives the same
/// order for the same subjects.
pub fn schedule(counts: &[(u32, u32)], seed: u64) -> Vec<Slot> {
    let mut rng = fastrand::Rng::with_seed(seed);
    let mut out = Vec::new();
    for timed in [false, true] {
        let count = |i: usize| {
            let (warmup, runs) = counts[i];
            u64::from(if timed { runs } else { warmup })
        };
        let rounds = (0..counts.len()).map(count).max().unwrap_or(0);
        for round in 0..rounds {
            // Subject i is due in the rounds where floor(r * k / R) steps up:
            // exactly k of the R rounds, as evenly spaced as integers allow.
            let mut due: Vec<usize> = (0..counts.len())
                .filter(|&i| (round + 1) * count(i) / rounds > round * count(i) / rounds)
                .collect();
            rng.shuffle(&mut due);
            out.extend(due.into_iter().map(|subject| Slot { subject, timed }));
        }
    }
    out
}

/// Derive a benchmark's seed from the run's, so `--bench x --seed n` takes
/// the same order for `x` as the full run with `--seed n` did.
pub fn seed_for(seed: u64, bench: &str) -> u64 {
    // FNV-1a: a fixed function, unlike std's randomly keyed hasher.
    bench.bytes().fold(seed ^ 0xcbf2_9ce4_8422_2325, |h, b| {
        (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)
    })
}

/// Measure several subjects against each other, interleaved.
///
/// Returns each subject's timed samples in the order they were taken, or the
/// error that stopped it. A failing subject is dropped from the remaining
/// rounds and the others carry on: one competitor breaking should not throw
/// away a long run's worth of everyone else's samples. Subject directories
/// are used as given, so the caller resolves them first.
pub fn interleaved(subjects: &[Subject], seed: u64, settings: &Settings) -> Vec<Result<Vec<f64>>> {
    let counts: Vec<_> = subjects.iter().map(|s| (s.warmup, s.runs)).collect();
    let mut results: Vec<Result<Vec<f64>>> = subjects
        .iter()
        .map(|s| {
            // Zero runs would leave nothing to report on.
            if s.runs == 0 {
                bail!("runs must be at least 1");
            }
            Ok(Vec::with_capacity(s.runs as usize))
        })
        .collect();
    for slot in schedule(&counts, seed) {
        let Ok(samples) = &mut results[slot.subject] else {
            continue;
        };
        let s = &subjects[slot.subject];
        let site = Site {
            dir: s.dir.as_deref(),
            env: &s.env,
            settings,
        };
        let taken = s
            .prepare
            .as_deref()
            .map_or(Ok(()), |p| prepare_once(p, &site))
            .and_then(|()| time_once(&s.cmd, &site));
        match taken {
            Ok(ms) if slot.timed => samples.push(ms),
            Ok(_) => {}
            Err(e) => results[slot.subject] = Err(e),
        }
    }
    results
}

/// Wall-clock statistics over a set of samples, in milliseconds.
///
/// Reports `min` alongside the mean because contention is one-sided — a busy
/// machine can only make a run slower, never faster — so the minimum is a far
/// more robust estimator than the mean on shared CI hardware. The standard
/// deviation is there to show how noisy the run was, not to be compared.
pub fn stats(samples: &[f64]) -> BTreeMap<String, f64> {
    let mut sorted = samples.to_vec();
    sorted.sort_by(f64::total_cmp);
    let n = sorted.len();
    let mean = sorted.iter().sum::<f64>() / n as f64;
    // Sample (n - 1) deviation, as hyperfine reports; a single sample has none.
    let stddev = if n > 1 {
        (sorted.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64).sqrt()
    } else {
        0.0
    };
    BTreeMap::from([
        ("wall_min_ms".to_string(), sorted[0]),
        ("wall_p50_ms".to_string(), sorted[n / 2]),
        ("wall_mean_ms".to_string(), mean),
        ("wall_max_ms".to_string(), sorted[n - 1]),
        ("wall_stddev_ms".to_string(), stddev),
        ("wall_n".to_string(), n as f64),
    ])
}

/// Wall-clock statistics over `plan.runs` samples of one command.
pub fn wall(plan: &Plan) -> Result<BTreeMap<String, f64>> {
    let subject = Subject {
        name: SELF_TOOL.to_string(),
        cmd: plan.cmd.clone(),
        prepare: None,
        dir: plan.dir.clone(),
        env: BTreeMap::new(),
        runs: plan.runs,
        warmup: plan.warmup,
        counters: false,
    };
    // One subject has one possible order, so the seed is irrelevant.
    let samples = interleaved(std::slice::from_ref(&subject), 0, &plan.settings)
        .pop()
        .expect("one result per subject")?;
    Ok(stats(&samples))
}

/// Is cachegrind usable on this machine?
///
/// Exposed so callers can tell "no counters because valgrind is missing" from
/// "no counters because the measurement failed" — two problems with entirely
/// different fixes.
pub fn valgrind_available() -> bool {
    Command::new("valgrind")
        .arg("--version")
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

/// Repeats of the cachegrind run. Three is enough to catch a bimodal subject
/// without tripling the cost of a measurement that is already ~50x slowed.
const COUNTER_RUNS: u32 = 3;

/// A subject varying by more than this is doing environment-dependent work, and
/// its instruction count is not a usable gate. Well above the ~0.005% observed
/// for a genuinely hermetic command, far below the 16% seen from one that
/// touches the network.
const SPREAD_WARN_PCT: f64 = 0.5;

/// Instruction counts from repeated cachegrind runs.
#[derive(Debug, Clone, Copy)]
pub struct Counted {
    pub min: u64,
    pub max: u64,
    pub runs: u32,
}

impl Counted {
    /// Relative spread across runs, as a percentage of the minimum.
    pub fn spread_pct(&self) -> f64 {
        if self.min == 0 {
            return 0.0;
        }
        (self.max - self.min) as f64 / self.min as f64 * 100.0
    }

    /// Whether this subject looks non-hermetic.
    ///
    /// The metric is deterministic; the program being measured need not be. A
    /// CLI that checks for updates, reads a cache it may have just created, or
    /// resolves DNS retires a different number of instructions depending on
    /// conditions that have nothing to do with the code under test.
    pub fn is_suspect(&self) -> bool {
        self.spread_pct() > SPREAD_WARN_PCT
    }
}

/// Instruction count via `valgrind --tool=cachegrind`, repeated.
///
/// Reports the **minimum**, for the same reason wall clock does: the extra work
/// a subject sometimes performs is one-sided. A run that consults the network or
/// populates a cache can only retire *more* instructions than the quiet path,
/// never fewer, so the floor is the stable estimator.
///
/// Returns `Ok(None)` when valgrind is unavailable rather than failing: this is
/// the expected state on macOS (no usable Apple Silicon support) and Windows.
/// Those platforms record timing only, and the CI gate lives on the Linux job.
/// Locally, a container gets you counters on any host.
pub fn instructions(
    cmd: &[String],
    dir: Option<&std::path::Path>,
    settings: &Settings,
) -> Result<Option<Counted>> {
    count(
        cmd,
        None,
        &Site {
            dir,
            env: &BTreeMap::new(),
            settings,
        },
    )
}

/// [`instructions`] for a declared subject: its environment, and its prepare
/// step before every cachegrind run, since each run has to start from the
/// same state the timed samples did.
pub fn subject_instructions(s: &Subject, settings: &Settings) -> Result<Option<Counted>> {
    count(
        &s.cmd,
        s.prepare.as_deref(),
        &Site {
            dir: s.dir.as_deref(),
            env: &s.env,
            settings,
        },
    )
}

fn count(cmd: &[String], prepare: Option<&[String]>, site: &Site) -> Result<Option<Counted>> {
    if !valgrind_available() {
        return Ok(None);
    }

    let mut samples: Vec<u64> = Vec::with_capacity(COUNTER_RUNS as usize);
    for _ in 0..COUNTER_RUNS {
        if let Some(p) = prepare {
            prepare_once(p, site)?;
        }
        let mut argv: Vec<String> = [
            "valgrind",
            "--tool=cachegrind",
            "--cache-sim=no",
            "--branch-sim=no",
            "--cachegrind-out-file=/dev/null",
        ]
        .map(String::from)
        .to_vec();
        argv.extend_from_slice(cmd);
        let mut c = command(&argv, site)?;
        c.stdout(Stdio::null());
        let out = c.output().context("failed to run valgrind")?;

        // cachegrind writes its summary to stderr as e.g. "I refs:  48,349,132".
        let stderr = String::from_utf8_lossy(&out.stderr);
        if !out.status.success() {
            let bin = cmd.first().map(String::as_str).unwrap_or("(empty command)");
            bail!(
                "benchmark subject `{bin}` exited with {} under valgrind",
                out.status
            );
        }
        match parse_irefs(&stderr) {
            Some(n) => samples.push(n),
            // Valgrind is installed but produced no summary — a real failure,
            // not the same thing as valgrind being absent. Reporting it as
            // absent sends people off installing something they already have.
            None => bail!(
                "valgrind ran but emitted no `I refs` summary: {}",
                stderr.lines().last().unwrap_or("(no output)").trim()
            ),
        }
    }

    Ok(Some(Counted {
        min: *samples.iter().min().expect("COUNTER_RUNS > 0"),
        max: *samples.iter().max().expect("COUNTER_RUNS > 0"),
        runs: COUNTER_RUNS,
    }))
}

/// Extract the `I refs:` count from cachegrind's stderr summary.
fn parse_irefs(stderr: &str) -> Option<u64> {
    let line = stderr.lines().find(|l| l.contains("I refs:"))?;
    let digits: String = line
        .rsplit(':')
        .next()?
        .chars()
        .filter(|c| c.is_ascii_digit())
        .collect();
    digits.parse().ok()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_cachegrind_summary() {
        let s = "==12== I refs:      48,349,132\n";
        assert_eq!(parse_irefs(s), Some(48_349_132));
    }

    #[test]
    fn missing_summary_is_none_not_panic() {
        assert_eq!(parse_irefs("valgrind: command not found"), None);
    }

    /// What `subject` removes, as configured.
    fn removals(settings: &Settings) -> Vec<String> {
        subject("true", settings)
            .get_envs()
            .filter(|(_, v)| v.is_none())
            .map(|(k, _)| k.to_string_lossy().into_owned())
            .collect()
    }

    /// Construction-level check. The end-to-end proof that a subject cannot see
    /// the token lives in `tests/subject_env.rs`, which runs the real binary.
    #[test]
    fn subject_commands_remove_the_default_denied_variables() {
        let removed = removals(&Settings::default());
        for key in Settings::default().scrubbed_env() {
            assert!(removed.contains(&key.to_string()), "{key} not removed");
        }
    }

    /// The removal follows the setting rather than a compiled-in list, which is
    /// the whole point of routing it through `Settings`.
    #[test]
    fn the_removal_follows_the_settings() {
        let removed = removals(&Settings {
            env_deny: vec!["CUSTOM_SECRET".into()],
            env_allow: Vec::new(),
            ..Settings::default()
        });
        assert!(removed.contains(&"CUSTOM_SECRET".to_string()));
        assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
    }

    /// An allowed variable is not removed, so a subject that genuinely needs
    /// one can still be measured.
    #[test]
    fn an_allowed_variable_survives() {
        let removed = removals(&Settings {
            env_deny: vec!["GITHUB_TOKEN".into(), "GH_TOKEN".into()],
            env_allow: vec!["GITHUB_TOKEN".into()],
            ..Settings::default()
        });
        assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
        assert!(removed.contains(&"GH_TOKEN".to_string()));
    }

    #[test]
    fn zero_runs_is_rejected_not_a_panic() {
        let plan = Plan {
            cmd: vec!["true".into()],
            warmup: 0,
            runs: 0,
            dir: None,
            settings: Settings::default(),
        };
        assert!(wall(&plan).is_err());
    }

    #[test]
    fn a_failed_subject_is_not_recorded_as_a_fast_run() {
        #[cfg(unix)]
        let cmd = vec!["/bin/sh".into(), "-c".into(), "exit 42".into()];
        #[cfg(windows)]
        let cmd = vec!["cmd".into(), "/C".into(), "exit /B 42".into()];

        let err = wall(&Plan {
            cmd,
            warmup: 0,
            runs: 1,
            dir: None,
            settings: Settings::default(),
        })
        .unwrap_err();

        assert!(format!("{err:#}").contains("exited with"), "{err:#}");
    }

    #[test]
    fn wall_reports_min_le_p50_le_max() {
        let plan = Plan {
            cmd: vec!["true".into()],
            warmup: 1,
            runs: 5,
            dir: None,
            settings: Settings::default(),
        };
        let m = wall(&plan).unwrap();
        assert!(m["wall_min_ms"] <= m["wall_p50_ms"]);
        assert!(m["wall_p50_ms"] <= m["wall_max_ms"]);
        assert_eq!(m["wall_n"], 5.0);
    }

    /// Every subject gets exactly its warmups and runs, warmups first.
    #[test]
    fn the_schedule_gives_each_subject_its_counts() {
        let counts = [(2, 10), (1, 5), (0, 3)];
        let order = schedule(&counts, 7);
        for (i, &(warmup, runs)) in counts.iter().enumerate() {
            let of = |timed| {
                order
                    .iter()
                    .filter(|s| s.subject == i && s.timed == timed)
                    .count()
            };
            assert_eq!(of(false), warmup as usize, "subject {i} warmups");
            assert_eq!(of(true), runs as usize, "subject {i} runs");
        }
        let first_timed = order.iter().position(|s| s.timed).unwrap();
        assert!(order[first_timed..].iter().all(|s| s.timed));
    }

    #[test]
    fn the_same_seed_gives_the_same_order() {
        let counts = [(1, 8), (1, 8), (1, 8)];
        assert_eq!(schedule(&counts, 42), schedule(&counts, 42));
        assert_ne!(schedule(&counts, 42), schedule(&counts, 43));
    }

    /// Interleaving is the point: with equal counts, every round holds each
    /// subject once, and the order is not the same in every round.
    #[test]
    fn each_round_runs_every_subject_once_in_a_varying_order() {
        let order = schedule(&[(0, 20), (0, 20), (0, 20)], 1);
        let rounds: Vec<Vec<usize>> = order
            .chunks(3)
            .map(|r| r.iter().map(|s| s.subject).collect())
            .collect();
        assert_eq!(rounds.len(), 20);
        for r in &rounds {
            let mut sorted = r.clone();
            sorted.sort();
            assert_eq!(sorted, [0, 1, 2], "round {r:?}");
        }
        assert!(rounds.iter().any(|r| r != &rounds[0]), "never shuffled");
    }

    /// A subject with half the runs takes part in alternate rounds, not only
    /// the first half — otherwise drift late in the run lands on the others.
    #[test]
    fn a_subject_with_fewer_runs_is_spread_across_the_run() {
        let order = schedule(&[(0, 10), (0, 5)], 3);
        let fewer: Vec<usize> = order
            .iter()
            .enumerate()
            .filter(|(_, s)| s.subject == 1)
            .map(|(i, _)| i)
            .collect();
        assert_eq!(fewer.len(), 5);
        assert!(
            *fewer.last().unwrap() >= order.len() - 3,
            "last sample of the smaller subject is near the end: {fewer:?} of {}",
            order.len()
        );
    }

    #[test]
    fn a_benchmark_seed_depends_on_its_name_and_the_run_seed() {
        assert_eq!(seed_for(1, "a"), seed_for(1, "a"));
        assert_ne!(seed_for(1, "a"), seed_for(1, "b"));
        assert_ne!(seed_for(1, "a"), seed_for(2, "a"));
    }

    #[test]
    fn stats_report_the_sample_standard_deviation() {
        let m = stats(&[2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]);
        assert_eq!(m["wall_min_ms"], 2.0);
        assert_eq!(m["wall_max_ms"], 9.0);
        assert_eq!(m["wall_mean_ms"], 5.0);
        // sqrt(32 / 7)
        assert!((m["wall_stddev_ms"] - 2.138_089_935).abs() < 1e-6);
        assert_eq!(stats(&[3.0])["wall_stddev_ms"], 0.0);
    }

    /// A failing subject is dropped; the others still get every sample.
    #[cfg(unix)]
    #[test]
    fn a_failing_subject_does_not_stop_the_others() {
        let mk = |name: &str, cmd: &[&str]| Subject {
            name: name.into(),
            cmd: cmd.iter().map(|s| s.to_string()).collect(),
            prepare: None,
            dir: None,
            env: BTreeMap::new(),
            runs: 4,
            warmup: 1,
            counters: false,
        };
        let res = interleaved(
            &[mk("ok", &["true"]), mk("bad", &["false"])],
            5,
            &Settings::default(),
        );
        assert_eq!(res[0].as_ref().unwrap().len(), 4);
        assert!(format!("{:#}", res[1].as_ref().unwrap_err()).contains("exited with"));
    }

    /// A prepare step that fails stops its subject, and says it was prepare.
    #[cfg(unix)]
    #[test]
    fn a_failing_prepare_is_reported_as_prepare() {
        let res = interleaved(
            &[Subject {
                name: "x".into(),
                cmd: vec!["true".into()],
                prepare: Some(vec![
                    "/bin/sh".into(),
                    "-c".into(),
                    "echo nope >&2; exit 3".into(),
                ]),
                dir: None,
                env: BTreeMap::new(),
                runs: 1,
                warmup: 0,
                counters: false,
            }],
            0,
            &Settings::default(),
        );
        let msg = format!("{:#}", res[0].as_ref().unwrap_err());
        assert!(msg.contains("prepare") && msg.contains("nope"), "{msg}");
    }
}