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//!
16//! Heap allocations (`alloc_*`, from DHAT) are counted rather than timed. Their
17//! totals have repeated exactly for every hermetic subject measured so far, but
18//! that is five programs, not a demonstrated property, so they are recorded
19//! and reported and do not gate. Their peak moves with thread scheduling.
20
21use crate::config::{
22    AutoRuns, CountUntil, DEFAULT_OK_EXIT_CODES, MetricSource, Runs, SELF_TOOL, Subject,
23};
24use crate::settings::Settings;
25use anyhow::{Context, Result, bail};
26use std::collections::BTreeMap;
27use std::path::Path;
28use std::process::{Command, Stdio};
29use std::sync::{Arc, Mutex};
30use std::time::Duration;
31use std::time::Instant;
32
33#[derive(Debug, Clone)]
34pub struct Plan {
35    pub cmd: Vec<String>,
36    pub warmup: u32,
37    pub runs: u32,
38    /// Directory to run in. Declared benchmarks resolve relative commands
39    /// against `tak.toml`'s directory, not the caller's — otherwise the same
40    /// benchmark measures different things depending on where you stood.
41    pub dir: Option<std::path::PathBuf>,
42    /// Resolved settings. Carried on the plan rather than read from a global so
43    /// a test can measure under a different configuration without touching the
44    /// environment of the whole test binary.
45    pub settings: Settings,
46}
47
48/// A command for running a benchmark subject, with the scrubbed variables
49/// removed.
50///
51/// Every subject spawn goes through here. Under cachegrind the removal is
52/// applied to valgrind itself, which the subject inherits from.
53///
54/// What gets removed is [`Settings::scrubbed_env`] — `env_deny` less
55/// `env_allow`, both declared on the `Settings` registry. The default is the
56/// forge tokens because a CLI that finds one often does more with it than
57/// without, so a measurement would move depending on whether CI happened to
58/// export one.
59///
60/// This controls direct inheritance, not hostile-code isolation. A subject can
61/// still inspect accessible same-user processes and files, so `backfill` must
62/// run without credentials when its release binaries are not trusted.
63///
64/// tak's own network calls are unaffected — `backfill` authenticates with
65/// `curl` directly rather than through this path.
66fn subject(bin: &str, settings: &Settings) -> Command {
67    let mut c = Command::new(bin);
68    for key in settings.scrubbed_env() {
69        c.env_remove(key);
70    }
71    c
72}
73
74/// Where a command runs and what it sees, beyond its argv.
75#[derive(Debug, Clone, Copy)]
76struct Site<'a> {
77    dir: Option<&'a Path>,
78    env: &'a BTreeMap<String, String>,
79    settings: &'a Settings,
80}
81
82/// Build a spawn of `argv` at `site`.
83///
84/// Declared variables are applied after the scrub. A variable written into
85/// `tak.toml` for a subject is an explicit choice, not something inherited by
86/// accident, which is the only thing the scrub exists to stop.
87fn command(argv: &[String], site: &Site) -> Result<Command> {
88    let (bin, args) = argv.split_first().context("empty command")?;
89    let mut c = subject(bin, site.settings);
90    c.args(args).envs(site.env);
91    if let Some(d) = site.dir {
92        c.current_dir(d);
93    }
94    #[cfg(unix)]
95    if tracked::OWN_GROUPS.load(std::sync::atomic::Ordering::SeqCst) {
96        std::os::unix::process::CommandExt::process_group(&mut c, 0);
97    }
98    Ok(c)
99}
100
101/// Spawn `c`, wait for it, and keep its process group known to
102/// [`stop_running`] meanwhile. `Command::status` split in two: the same
103/// stdio defaults, and only an uncontended lock between the spawn and the wait.
104fn run_tracked(c: &mut Command) -> std::io::Result<std::process::ExitStatus> {
105    let mut child = c.spawn()?;
106    tracked::started(child.id());
107    let status = child.wait();
108    tracked::finished();
109    status
110}
111
112/// Put every measured command in a process group of its own, so that
113/// [`stop_running`] can stop it and whatever it started, and nothing else.
114///
115/// For `tak backfill --commits`, whose interrupt handler has to stop the
116/// command before deleting the checkout it runs in. A SIGTERM sent to tak
117/// alone, as when CI cancels a job, never reaches a command in tak's own
118/// group, and signalling that group instead would also stop whatever shares
119/// it with tak, such as `tee` at the other end of a pipeline. `tak run`
120/// leaves commands in its group, where a terminal's Ctrl-C reaches them.
121///
122/// The group is set in the child before it runs the program, so it is inside
123/// the timed window, as one `setpgid` against a fork and exec that already
124/// cost hundreds of microseconds; and the program's own instructions, which
125/// cachegrind counts from exec, do not include it. Wall time is not gated.
126#[cfg(unix)]
127pub fn use_own_groups() {
128    tracked::OWN_GROUPS.store(true, std::sync::atomic::Ordering::SeqCst);
129}
130
131/// Kill the measured command running now, any started after this, and
132/// whatever earlier ones left running, each with its whole process group.
133/// Only effective after [`use_own_groups`]: a command in tak's own group is
134/// left alone.
135#[cfg(unix)]
136pub fn stop_running() {
137    use std::sync::atomic::Ordering::SeqCst;
138    tracked::STOPPED.store(true, SeqCst);
139    tracked::kill_all();
140}
141
142/// The one measured command running at a time — samples, setup, prepare,
143/// check and valgrind all run one after another — as its process group.
144mod tracked {
145    use std::sync::Mutex;
146    use std::sync::atomic::{AtomicBool, Ordering::SeqCst};
147
148    pub(super) static OWN_GROUPS: AtomicBool = AtomicBool::new(false);
149    pub(super) static STOPPED: AtomicBool = AtomicBool::new(false);
150
151    /// Every group an interrupt must kill, behind one lock.
152    ///
153    /// One lock for both, so that moving a group from running to left
154    /// behind is a single step. With the running group in an atomic and the
155    /// others in a list, `finished` cleared the one before adding to the
156    /// other, and an interrupt landing between the two found the group in
157    /// neither: its leftover process then outlived the checkout it ran in.
158    static GROUPS: Mutex<Groups> = Mutex::new(Groups::new());
159
160    /// The state behind [`GROUPS`], with the transitions as plain methods so
161    /// they can be tested without real processes.
162    #[derive(Debug, Default, PartialEq)]
163    pub(super) struct Groups {
164        /// The group of the command running now, or 0.
165        running: i32,
166        /// Groups whose leader has exited but where something it started is
167        /// still running: a server a `setup` started on purpose, a daemon a
168        /// tool leaves behind. Left alone while the backfill runs, as `tak
169        /// run` leaves them, and killed with the running command on
170        /// interrupt, since the checkout they run in is about to be deleted.
171        left: Vec<i32>,
172    }
173
174    impl Groups {
175        pub(super) const fn new() -> Groups {
176            Groups {
177                running: 0,
178                left: Vec::new(),
179            }
180        }
181
182        pub(super) fn start(&mut self, pgid: i32) {
183            self.running = pgid;
184        }
185
186        /// The running command has been reaped. Its group moves to `left`
187        /// while it still has members, and groups that have emptied are
188        /// dropped: a group id is only kept while it cannot be reused. A
189        /// group that empties between this and an interrupt leaves a window
190        /// in which its id could be reused, which would take the kernel
191        /// handing out that exact pid again first.
192        pub(super) fn finish(&mut self, alive: impl Fn(i32) -> bool) {
193            self.left.retain(|g| alive(*g));
194            if self.running > 0 && alive(self.running) {
195                self.left.push(self.running);
196            }
197            self.running = 0;
198        }
199
200        /// Every group an interrupt kills now.
201        pub(super) fn targets(&self) -> Vec<i32> {
202            std::iter::once(self.running)
203                .filter(|g| *g > 0)
204                .chain(self.left.iter().copied())
205                .collect()
206        }
207    }
208
209    fn groups() -> std::sync::MutexGuard<'static, Groups> {
210        // A poisoned lock still holds the groups; an interrupt must not
211        // skip them.
212        GROUPS.lock().unwrap_or_else(|e| e.into_inner())
213    }
214
215    /// `pid` leads its own group. If [`super::stop_running`] already ran it
216    /// may have looked before this was stored, so the group is killed here:
217    /// each side stores before it loads, all `SeqCst`, so one of them acts.
218    /// The uncontended lock this takes is inside the timed window, and costs
219    /// tens of nanoseconds against a fork and exec.
220    pub(super) fn started(pid: u32) {
221        if !OWN_GROUPS.load(SeqCst) {
222            return;
223        }
224        groups().start(pid as i32);
225        if STOPPED.load(SeqCst) {
226            kill(pid as i32);
227        }
228    }
229
230    /// The running command has been reaped; see [`Groups::finish`]. Called
231    /// after the clock stops, since checking the groups costs a syscall each.
232    pub(super) fn finished() {
233        if OWN_GROUPS.load(SeqCst) {
234            groups().finish(alive);
235        }
236    }
237
238    /// Kill the running command's group and every group left behind, under
239    /// the same lock `finished` moves them with.
240    pub(super) fn kill_all() {
241        for g in groups().targets() {
242            kill(g);
243        }
244    }
245
246    #[cfg(unix)]
247    fn alive(pgid: i32) -> bool {
248        // SAFETY: signal 0 only checks that the group exists.
249        unsafe { libc::killpg(pgid, 0) == 0 }
250    }
251
252    #[cfg(not(unix))]
253    fn alive(_pgid: i32) -> bool {
254        false
255    }
256
257    #[cfg(unix)]
258    pub(super) fn kill(pgid: i32) {
259        if pgid > 0 {
260            // SAFETY: killpg has no memory-safety preconditions.
261            unsafe {
262                libc::killpg(pgid, libc::SIGKILL);
263            }
264        }
265    }
266
267    #[cfg(not(unix))]
268    pub(super) fn kill(_pgid: i32) {}
269
270    #[cfg(test)]
271    mod tests {
272        use super::Groups;
273
274        /// A group is always somewhere an interrupt looks: running while its
275        /// command runs, left behind once it exits with a member still there,
276        /// and forgotten only when it is empty.
277        #[test]
278        fn a_group_is_never_untracked_while_it_has_members() {
279            let mut g = Groups::new();
280            assert!(g.targets().is_empty());
281            g.start(10);
282            assert_eq!(g.targets(), [10]);
283
284            // Exits, with a helper still in its group.
285            g.finish(|p| p == 10);
286            assert_eq!(g.targets(), [10]);
287            g.start(20);
288            assert_eq!(g.targets(), [20, 10]);
289
290            // 20 exits empty; 10's helper is still there.
291            g.finish(|p| p == 10);
292            assert_eq!(g.targets(), [10]);
293
294            // 10's helper exits too, and is forgotten at the next finish.
295            g.start(30);
296            g.finish(|_| false);
297            assert!(g.targets().is_empty());
298            assert_eq!(g, Groups::new());
299        }
300    }
301}
302
303/// One successful run of a subject's timed command.
304#[derive(Debug, Clone, Copy, PartialEq)]
305pub struct Sample {
306    /// Elapsed wall time in milliseconds.
307    pub ms: f64,
308    /// What the command exited with: one of its `ok_exit_codes`, kept so the
309    /// export shows what actually happened rather than assuming 0.
310    pub exit_code: i32,
311}
312
313/// The exit code of a sample that counts, or the error that drops its
314/// subject.
315///
316/// A death by signal has no exit code and always fails: a subject that
317/// crashed or was killed did not do the work being measured, whatever its
318/// `ok_exit_codes` allow.
319fn accepted(bin: &str, status: std::process::ExitStatus, ok: &[i32], via: &str) -> Result<i32> {
320    match status.code() {
321        Some(code) if ok.contains(&code) => Ok(code),
322        // Name the accepted codes only when they are not the default, where
323        // "exited with 1" alone would leave the reader wondering why that
324        // was a failure.
325        _ if ok == DEFAULT_OK_EXIT_CODES => {
326            bail!("benchmark subject `{bin}` exited with {status}{via}")
327        }
328        _ => bail!(
329            "benchmark subject `{bin}` exited with {status}{via}, and ok_exit_codes is {}",
330            ok.iter().map(i32::to_string).collect::<Vec<_>>().join(", ")
331        ),
332    }
333}
334
335/// Run once, discarding output, returning elapsed wall time and exit code.
336///
337/// No shell. Spawning a shell adds its own startup cost and variance to every
338/// sample, which for commands in the 10ms range is a large fraction of the
339/// measurement — the same reasoning behind poop's refusal to support one.
340fn time_once(cmd: &[String], site: &Site, ok: &[i32]) -> Result<Sample> {
341    let mut c = command(cmd, site)?;
342    c.stdout(Stdio::null()).stderr(Stdio::null());
343    let bin = &cmd[0];
344    let start = Instant::now();
345    let mut child = c
346        .spawn()
347        .with_context(|| format!("failed to spawn `{bin}`"))?;
348    // An uncontended lock inside the timed window; see `tracked::started`.
349    tracked::started(child.id());
350    let status = child.wait();
351    let ms = start.elapsed().as_secs_f64() * 1000.0;
352    tracked::finished();
353    let status = status.with_context(|| format!("failed to wait for `{bin}`"))?;
354    let exit_code = accepted(bin, status, ok, "")?;
355    Ok(Sample { ms, exit_code })
356}
357
358/// How much of a failing prepare, setup or check step's stderr to keep for
359/// the message. Enough for the last few lines; a verbose reset command's full
360/// output would otherwise sit in memory before every sample.
361const UNTIMED_STDERR_TAIL: usize = 4096;
362
363/// Run a subject's prepare step. Untimed, so reading its stderr for the error
364/// message costs the measurement nothing.
365fn prepare_once(cmd: &[String], site: &Site) -> Result<()> {
366    required("prepare", cmd, site)
367}
368
369/// Run an untimed step that must succeed: `prepare` or `setup`.
370fn required(what: &str, cmd: &[String], site: &Site) -> Result<()> {
371    match untimed(what, cmd, site)? {
372        None => Ok(()),
373        Some(failure) => bail!("{failure}"),
374    }
375}
376
377/// Run a subject's check step after a timed sample. `Ok(None)` is a pass and
378/// `Ok(Some(why))` a failed sample. Only a check that cannot be started at
379/// all is an error: that is a mistake in `tak.toml`, not a finding about the
380/// subject, and would otherwise read as every sample having failed.
381fn check_once(cmd: &[String], site: &Site) -> Result<Option<String>> {
382    untimed("check", cmd, site)
383}
384
385/// Run an untimed step — `prepare`, `setup` or `check`, named by `step` in
386/// messages. `Ok(Some(why))` when it exits non-zero, naming the step and the
387/// last line of its stderr.
388///
389/// Its output is not passed through: on a terminal it would tear up the
390/// progress bar, and in a log a setup that clones a fixture could bury the
391/// results. The tail of stderr is kept for the message.
392///
393/// Always judged by exit 0, whatever the subject's `ok_exit_codes` say: those
394/// describe the program being measured. A setup or reset that failed leaves
395/// every later sample starting from the wrong state, and a check passes only
396/// by exiting 0.
397///
398/// stderr goes to an anonymous temporary file, not a pipe, and the step is
399/// done when its process exits. With a pipe, a step that starts something in
400/// the background — a fixture server, a daemon, a build server, `sleep 600 &`
401/// — leaves that process holding the write end: waiting for EOF hung the
402/// whole run, and closing the read end instead would kill the process with
403/// SIGPIPE the next time it logged. A file has neither problem. tak neither
404/// waits for nor kills such processes, since a server started by `setup` may
405/// be exactly the point; one still running while samples are timed competes
406/// with them, and the timings show it.
407///
408/// The cost is disk: whatever a leftover process writes to stderr lands in
409/// the file, in the temp directory, for as long as it runs. The file has no
410/// name on Unix and is deleted when its last handle closes on Windows, so the
411/// space comes back once tak has dropped its handle and the process exits. A
412/// step whose background process logs heavily should redirect that output.
413///
414/// There is deliberately no overall deadline: a setup that builds or clones a
415/// fixture can legitimately take minutes.
416fn untimed(step: &str, cmd: &[String], site: &Site) -> Result<Option<String>> {
417    let mut c = command(cmd, site)?;
418    let bin = &cmd[0];
419    let err = tempfile::tempfile()
420        .with_context(|| format!("failed to create a file for {step} `{bin}`'s stderr"))?;
421    let reader = err
422        .try_clone()
423        .with_context(|| format!("failed to create a file for {step} `{bin}`'s stderr"))?;
424    c.stdin(Stdio::null())
425        .stdout(Stdio::null())
426        .stderr(Stdio::from(err));
427    let status = run_tracked(&mut c).with_context(|| format!("failed to spawn {step} `{bin}`"))?;
428    if status.success() {
429        return Ok(None);
430    }
431    // A check like `git diff --quiet` says nothing on failure by design, so
432    // silence is reported as the status alone. An unreadable file is treated
433    // the same way: the status is the finding, the stderr only decoration.
434    let tail = stderr_tail(&reader).unwrap_or_default();
435    let stderr = String::from_utf8_lossy(&tail);
436    Ok(Some(match stderr.lines().rfind(|l| !l.trim().is_empty()) {
437        Some(last) => format!("{step} `{bin}` exited with {status}: {}", last.trim()),
438        None => format!("{step} `{bin}` exited with {status}"),
439    }))
440}
441
442/// The most a metric command may print. One number and a newline is a few
443/// dozen bytes; anything near this is a log or a report, not a value, and
444/// guessing which part of it was meant would record the wrong thing.
445const METRIC_OUTPUT_MAX: usize = 1024;
446
447/// A subject's custom metric: a file's size in bytes, or the one number a
448/// command prints.
449///
450/// Taken once, after the subject's samples and instruction counts, and not
451/// part of either. After, because `setup` or the samples themselves may be
452/// what produces the file or the output being measured.
453///
454/// A file is `stat`ed, following symlinks, and must be a regular file: a
455/// directory's size is filesystem bookkeeping, not the size of what is in it.
456///
457/// A command runs in the subject's `dir` and `env`, with the same variables
458/// removed, no shell, and no deadline, like `setup` or `check`. It must exit 0
459/// and print exactly one number; see [`parse_metric_value`]. Its output is
460/// captured the way `version_cmd`'s is, through [`capture`]: bounded while it
461/// is read, so a script that dumps a report is stopped at
462/// [`METRIC_OUTPUT_MAX`] instead of filling memory or a disk, and not waited
463/// on past its exit, so one that leaves something running in the background
464/// holding the pipe open does not hang the run.
465pub fn custom_metric(source: &MetricSource, s: &Subject, settings: &Settings) -> Result<f64> {
466    match source {
467        MetricSource::File(path) => {
468            let meta = std::fs::metadata(path)
469                .with_context(|| format!("could not read the size of {}", path.display()))?;
470            if !meta.is_file() {
471                bail!("{} is not a regular file", path.display());
472            }
473            Ok(meta.len() as f64)
474        }
475        MetricSource::Cmd(argv) => {
476            let site = Site {
477                dir: s.dir.as_deref(),
478                env: &s.env,
479                settings,
480            };
481            metric_cmd_once(argv, &site)
482        }
483    }
484}
485
486fn metric_cmd_once(argv: &[String], site: &Site) -> Result<f64> {
487    let bin = &argv[0];
488    let out = capture(argv, site, None, METRIC_OUTPUT_MAX, true)?;
489    // Either way the metric is lost, and whatever the command started is
490    // stopped, unlike after a `version_cmd`: a metric is taken between
491    // benchmarks, and a leftover would compete with the next one's samples.
492    // `capture` stops the group only while the command itself runs, so a
493    // background writer that crosses the cap after it exited, or that still
494    // holds stdout, is stopped here. Harmless when nothing is left.
495    if out.overflowed || out.stdout_open {
496        stop_leftovers(out.pgid);
497    }
498    // Before the status: a command stopped for printing too much died of
499    // tak's signal, and saying so would hide why it was stopped.
500    if out.overflowed {
501        bail!(
502            "`{bin}` and what it started printed more than {METRIC_OUTPUT_MAX} bytes, so they were \
503             stopped; a metric command prints one number and nothing else"
504        );
505    }
506    // Something the command left running still holds its stdout and may
507    // print more, so what arrived so far is not known to be the whole answer.
508    if out.stdout_open {
509        bail!(
510            "`{bin}` exited but left a process holding its stdout open, so that was stopped; \
511             a metric command must finish its output before it exits"
512        );
513    }
514    if !out.status.success() {
515        bail!(
516            "`{bin}` exited with {}: {}",
517            out.status,
518            last_line(&out.stderr_tail)
519        );
520    }
521    let text = std::str::from_utf8(&out.stdout)
522        .map_err(|_| anyhow::anyhow!("`{bin}` printed something that is not UTF-8"))?;
523    parse_metric_value(text).with_context(|| format!("`{bin}`"))
524}
525
526/// Read a metric command's stdout as one number.
527///
528/// Deliberately strict. Surrounding whitespace, a trailing newline included,
529/// is ignored; what is left must be a single non-negative decimal: digits,
530/// optionally a fraction, optionally an exponent — `1234`, `12.5`, `1.2e6`.
531/// No sign, no `inf` or `nan`, no hex, no thousands separators, no unit, and
532/// nothing else on the line or on another one. A script that prints
533/// `bundle: 42 kB` or two numbers has a bug worth hearing about, and pulling
534/// the first number out of it would record whichever one happened to come
535/// first. Negative values are refused because `compare` reports a change as a
536/// percentage of the base, which is meaningless against a negative one, and
537/// nothing a size or a count measures goes below zero.
538pub fn parse_metric_value(text: &str) -> Result<f64> {
539    let t = text.trim_matches(|c: char| c.is_ascii_whitespace());
540    if t.is_empty() {
541        bail!("printed nothing; a metric command prints one number");
542    }
543    let bytes = t.as_bytes();
544    let digits = |i: &mut usize| {
545        let start = *i;
546        while *i < bytes.len() && bytes[*i].is_ascii_digit() {
547            *i += 1;
548        }
549        *i > start
550    };
551    let mut i = 0;
552    let mut ok = digits(&mut i);
553    if ok && i < bytes.len() && bytes[i] == b'.' {
554        i += 1;
555        ok = digits(&mut i);
556    }
557    if ok && i < bytes.len() && (bytes[i] == b'e' || bytes[i] == b'E') {
558        i += 1;
559        if i < bytes.len() && (bytes[i] == b'+' || bytes[i] == b'-') {
560            i += 1;
561        }
562        ok = digits(&mut i);
563    }
564    if !ok || i != bytes.len() {
565        bail!(
566            "printed {t:?}, not one number; a metric command prints a single non-negative \
567             number such as `1234` or `12.5`, and nothing else"
568        );
569    }
570    let v: f64 = t
571        .parse()
572        .with_context(|| format!("printed {t:?}, which is not a number"))?;
573    if !v.is_finite() {
574        bail!("printed {t:?}, which is too large to record");
575    }
576    Ok(v)
577}
578
579/// The last [`UNTIMED_STDERR_TAIL`] bytes of a step's stderr file.
580///
581/// Read by position, not through the file cursor: the handle is a duplicate
582/// of the one a leftover process may still be writing through, and on Unix
583/// they share the cursor, so seeking would move where that process writes.
584/// Windows has no positional read that leaves the cursor alone; there a
585/// leftover writer may overwrite part of a file nobody reads again.
586fn stderr_tail(f: &std::fs::File) -> std::io::Result<Vec<u8>> {
587    let len = f.metadata()?.len();
588    let start = len.saturating_sub(UNTIMED_STDERR_TAIL as u64);
589    let mut buf = vec![0u8; (len - start) as usize];
590    let mut filled = 0;
591    while filled < buf.len() {
592        let n = read_at(f, &mut buf[filled..], start + filled as u64)?;
593        if n == 0 {
594            break;
595        }
596        filled += n;
597    }
598    buf.truncate(filled);
599    Ok(buf)
600}
601
602#[cfg(unix)]
603fn read_at(f: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result<usize> {
604    std::os::unix::fs::FileExt::read_at(f, buf, offset)
605}
606
607#[cfg(windows)]
608fn read_at(f: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result<usize> {
609    std::os::windows::fs::FileExt::seek_read(f, buf, offset)
610}
611
612/// One entry in a run's sample order.
613#[derive(Debug, Clone, Copy, PartialEq, Eq)]
614pub struct Slot {
615    /// Index into the subjects being measured.
616    pub subject: usize,
617    /// Whether this sample is kept. Warmup samples run through the same
618    /// prepare-then-run path and are discarded.
619    pub timed: bool,
620}
621
622/// The order in which to take samples: every warmup round, then every timed
623/// round, each round a fresh shuffle of the subjects due in it.
624///
625/// Measuring one subject to completion before starting the next puts any
626/// drift over the run — contention on a shared host, thermal throttling, a
627/// cache filling up — entirely on whichever subjects ran while it happened,
628/// where it reads as a difference between them. One sample of each per round
629/// spreads that drift across all of them, and shuffling each round stops any
630/// subject from systematically running first (cold) or right after a
631/// particular other one (whose leftovers it inherits).
632///
633/// A subject with fewer samples than there are rounds sits out evenly spaced
634/// rounds rather than dropping out at the end, which would leave the late
635/// part of the run — and its drift — to the others.
636///
637/// `counts` is `(warmup, runs)` per subject. The same seed gives the same
638/// order for the same subjects.
639pub fn schedule(counts: &[(u32, u32)], seed: u64) -> Vec<Slot> {
640    let mut rng = fastrand::Rng::with_seed(seed);
641    let warmups: Vec<u64> = counts.iter().map(|&(w, _)| u64::from(w)).collect();
642    let runs: Vec<u64> = counts.iter().map(|&(_, r)| u64::from(r)).collect();
643    let mut out = rounds(&warmups, false, &mut rng);
644    out.extend(rounds(&runs, true, &mut rng));
645    out
646}
647
648/// Shuffled rounds taking `count[i]` samples of subject `i`.
649fn rounds(count: &[u64], timed: bool, rng: &mut fastrand::Rng) -> Vec<Slot> {
650    let total = count.iter().copied().max().unwrap_or(0);
651    let mut out = Vec::new();
652    for round in 0..total {
653        // Subject i is due in the rounds where floor(r * k / R) steps up:
654        // exactly k of the R rounds, as evenly spaced as integers allow.
655        let mut due: Vec<usize> = (0..count.len())
656            .filter(|&i| (round + 1) * count[i] / total > round * count[i] / total)
657            .collect();
658        rng.shuffle(&mut due);
659        out.extend(due.into_iter().map(|subject| Slot { subject, timed }));
660    }
661    out
662}
663
664/// Derive a benchmark's seed from the run's, so `--bench x --seed n` takes
665/// the same order for `x` as the full run with `--seed n` did.
666pub fn seed_for(seed: u64, bench: &str) -> u64 {
667    // FNV-1a: a fixed function, unlike std's randomly keyed hasher.
668    bench.bytes().fold(seed ^ 0xcbf2_9ce4_8422_2325, |h, b| {
669        (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)
670    })
671}
672
673/// Told about a run as it happens, to report progress.
674pub trait Observer {
675    /// Samples still to take per subject, warmups included. Called before the
676    /// first sample and again once `runs = "auto"` has settled its counts.
677    fn planned(&mut self, _remaining: &[u64]) {}
678    /// `subject`'s setup step is starting. Untimed and not a sample, so it
679    /// counts toward neither the samples taken nor their average.
680    fn setting_up(&mut self, _subject: usize) {}
681    /// Every setup has run, and `subject`'s succeeded; nothing of it has run
682    /// yet, not its version, not a warmup. Asked after *all* setups rather
683    /// than after its own, since a later subject's setup can change the
684    /// paths an earlier one runs in. An error drops the subject as a failed
685    /// setup would. `tak backfill --commits` checks here that the old tree's
686    /// code has not left a path leading out of the checkout.
687    fn set_up(&mut self, _subject: usize) -> Result<()> {
688        Ok(())
689    }
690    /// A step of `subject` that runs from its paths is about to start: its
691    /// setup, the prepare before a sample, the sample itself (after that
692    /// prepare), or the check after it. Asked before each of them, warmups
693    /// included, since any earlier step, of this subject or another, can
694    /// change the paths the next one runs with. Never inside the timed
695    /// window. An error drops the subject.
696    fn before_run(&mut self, _subject: usize) -> Result<()> {
697        Ok(())
698    }
699    /// A sample of `subject` is starting.
700    fn started(&mut self, _subject: usize) {}
701    /// A sample of `subject` finished; `elapsed` covers its prepare step too.
702    fn finished(&mut self, _subject: usize, _elapsed: Duration) {}
703    /// `subject` failed and takes no more samples.
704    fn dropped(&mut self, _subject: usize) {}
705}
706
707/// An observer that reports nothing.
708pub struct Quiet;
709impl Observer for Quiet {}
710
711/// What one subject's run produced.
712#[derive(Debug, Clone, Default, PartialEq)]
713pub struct Samples {
714    /// Timed samples in milliseconds, in the order taken.
715    pub times: Vec<f64>,
716    /// Whether the subject's `check` passed after each timed sample, aligned
717    /// with `times`. Empty when the subject has no check.
718    pub checks: Vec<bool>,
719    /// What each timed sample exited with, aligned with `times`: always one
720    /// of the subject's `ok_exit_codes`.
721    pub exit_codes: Vec<i32>,
722    /// Why the first failing check failed, for the warning that reports it.
723    pub first_failure: Option<String>,
724}
725
726impl Samples {
727    /// Checks that passed.
728    pub fn passed(&self) -> usize {
729        self.checks.iter().filter(|&&ok| ok).count()
730    }
731}
732
733/// Measure several subjects against each other, interleaved.
734///
735/// Returns each subject's timed samples in the order they were taken, with
736/// the outcome of its check after each one, or the error that stopped it. A failing subject is dropped from the remaining
737/// rounds and the others carry on: one competitor breaking should not throw
738/// away a long run's worth of everyone else's samples. Subject directories
739/// are used as given, so the caller resolves them first.
740///
741/// Every subject's `setup` runs first, once, in the order given: before
742/// any warmup, so a subject's first sample never shares the machine with
743/// another's setup and none of it is counted toward an auto run count. A
744/// subject whose setup fails is dropped like one whose prepare does.
745///
746/// Sampling then runs in two phases. The warmups come first, plus one kept
747/// sample of every `runs = "auto"` subject that has no warmups, so each auto
748/// subject has been timed at least once. Its run count is then fixed from the
749/// fastest of those samples, and every remaining timed sample is taken in
750/// shuffled rounds.
751///
752/// A subject's `check` runs after each of its timed samples, pilots included,
753/// and never after a warmup: a warmup is discarded, so whether it did the
754/// right work says nothing about any result. A failing check is recorded
755/// against its sample and the subject carries on — how often it fails is the
756/// finding — so only a check that cannot be started drops the subject.
757pub fn interleaved(
758    subjects: &[Subject],
759    seed: u64,
760    settings: &Settings,
761    observer: &mut dyn Observer,
762) -> Vec<Result<Samples>> {
763    interleaved_with_versions(subjects, seed, settings, observer).0
764}
765
766/// A subject's `version_cmd` result: `None` when it declares none or never
767/// got that far, otherwise what it printed or why it could not tell.
768pub type Version = Option<Result<String>>;
769
770/// [`interleaved`], also returning each subject's version.
771///
772/// Versions are asked for after every `setup` and before any warmup: setup
773/// may be what installs or builds the subject, so asking earlier would name
774/// the wrong program or none, and a tool that warms a cache or checks for
775/// updates on `--version` does so before the first sample rather than
776/// between samples. A subject whose setup failed is not asked.
777pub fn interleaved_with_versions(
778    subjects: &[Subject],
779    seed: u64,
780    settings: &Settings,
781    observer: &mut dyn Observer,
782) -> (Vec<Result<Samples>>, Vec<Version>) {
783    let mut rng = fastrand::Rng::with_seed(seed);
784    let mut results: Vec<Result<Samples>> = subjects
785        .iter()
786        .map(|s| {
787            // Zero runs would leave nothing to report on.
788            if s.runs == Runs::Fixed(0) {
789                bail!("runs must be at least 1");
790            }
791            Ok(Samples::default())
792        })
793        .collect();
794    // The fastest whole sample of each subject so far, prepare included —
795    // what an auto count is sized from. The fastest, because a warmup is
796    // often a cold outlier and would shrink the count for no reason.
797    let mut fastest: Vec<Option<Duration>> = vec![None; subjects.len()];
798
799    let warmups: Vec<u64> = subjects.iter().map(|s| u64::from(s.warmup)).collect();
800    let pilots: Vec<u64> = subjects
801        .iter()
802        .map(|s| u64::from(s.runs == Runs::Auto && s.warmup == 0))
803        .collect();
804    // Until the auto counts are known, plan on each one's floor.
805    let provisional: Vec<u64> = subjects
806        .iter()
807        .zip(&warmups)
808        .map(|(s, w)| {
809            w + u64::from(match s.runs {
810                Runs::Fixed(n) => n,
811                Runs::Auto => s.auto.min,
812            })
813        })
814        .collect();
815    observer.planned(&provisional);
816
817    for (i, s) in subjects.iter().enumerate() {
818        let (Some(setup), Ok(_)) = (&s.setup, &results[i]) else {
819            continue;
820        };
821        observer.setting_up(i);
822        let site = Site {
823            dir: s.setup_dir.as_deref(),
824            env: &s.env,
825            settings,
826        };
827        // Before as well as after: an earlier subject's setup may have
828        // changed the paths this one runs with.
829        if let Err(e) = observer
830            .before_run(i)
831            .and_then(|()| required("setup", setup, &site))
832        {
833            results[i] = Err(e);
834            observer.dropped(i);
835        }
836    }
837    for (i, result) in results.iter_mut().enumerate() {
838        if result.is_ok()
839            && let Err(e) = observer.set_up(i)
840        {
841            *result = Err(e);
842            observer.dropped(i);
843        }
844    }
845
846    let versions: Vec<Version> = subjects
847        .iter()
848        .zip(&results)
849        .map(|(s, r)| r.as_ref().ok().and_then(|_| subject_version(s, settings)))
850        .collect();
851
852    let mut first = rounds(&warmups, false, &mut rng);
853    first.extend(rounds(&pilots, true, &mut rng));
854    run_slots(
855        &first,
856        subjects,
857        settings,
858        &mut results,
859        &mut fastest,
860        observer,
861    );
862
863    let remaining: Vec<u64> = subjects
864        .iter()
865        .enumerate()
866        .map(|(i, s)| match (&results[i], s.runs) {
867            (Err(_), _) => 0,
868            (Ok(_), Runs::Fixed(n)) => u64::from(n),
869            (Ok(taken), Runs::Auto) => {
870                let n = auto_runs(&s.auto, fastest[i]);
871                u64::from(n).saturating_sub(taken.times.len() as u64)
872            }
873        })
874        .collect();
875    observer.planned(&remaining);
876    let second = rounds(&remaining, true, &mut rng);
877    run_slots(
878        &second,
879        subjects,
880        settings,
881        &mut results,
882        &mut fastest,
883        observer,
884    );
885    (results, versions)
886}
887
888/// An auto subject's run count. One that was never timed — its every sample
889/// failed, so it is being dropped anyway — gets the floor.
890fn auto_runs(auto: &AutoRuns, fastest: Option<Duration>) -> u32 {
891    fastest.map_or(auto.min, |d| auto.runs_for(d))
892}
893
894/// Take the given samples, recording timed ones and the fastest slot seen.
895///
896/// `fastest` covers prepare and the command but not the check, so an auto
897/// count is sized from the same kind of sample whether it was a warmup (which
898/// runs no check) or a pilot. The observer is told the whole slot, check
899/// included, because that is what its time estimate has to cover.
900fn run_slots(
901    slots: &[Slot],
902    subjects: &[Subject],
903    settings: &Settings,
904    results: &mut [Result<Samples>],
905    fastest: &mut [Option<Duration>],
906    observer: &mut dyn Observer,
907) {
908    for slot in slots {
909        let Ok(samples) = &mut results[slot.subject] else {
910            continue;
911        };
912        let s = &subjects[slot.subject];
913        let site = Site {
914            dir: s.dir.as_deref(),
915            env: &s.env,
916            settings,
917        };
918        observer.started(slot.subject);
919        // Before the prepare as well as after it, and outside `began`, which
920        // sizes auto runs: the previous sample, of any subject, may have
921        // changed the paths this prepare runs with.
922        let vetted = if s.prepare.is_some() {
923            observer.before_run(slot.subject)
924        } else {
925            Ok(())
926        };
927        let began = Instant::now();
928        let taken = vetted
929            .and_then(|()| {
930                s.prepare
931                    .as_deref()
932                    .map_or(Ok(()), |p| prepare_once(p, &site))
933            })
934            .and_then(|()| observer.before_run(slot.subject))
935            .and_then(|()| time_once(&s.cmd, &site, &s.ok_exit_codes));
936        let elapsed = began.elapsed();
937        // Only after the clock has stopped: the check is outside the
938        // measurement, however long it takes.
939        let checked = match (&taken, &s.check) {
940            // Asked again first: the sample just run can have changed the
941            // paths the check runs with.
942            (Ok(_), Some(check)) if slot.timed => observer
943                .before_run(slot.subject)
944                .and_then(|()| check_once(check, &site))
945                .map(Some),
946            _ => Ok(None),
947        };
948        match taken.and_then(|sample| checked.map(|c| (sample, c))) {
949            Ok((sample, check)) => {
950                if slot.timed {
951                    samples.times.push(sample.ms);
952                    samples.exit_codes.push(sample.exit_code);
953                }
954                if let Some(failure) = check {
955                    samples.checks.push(failure.is_none());
956                    if samples.first_failure.is_none() {
957                        samples.first_failure = failure;
958                    }
959                }
960                let f = &mut fastest[slot.subject];
961                *f = Some(f.map_or(elapsed, |f| f.min(elapsed)));
962                observer.finished(slot.subject, began.elapsed());
963            }
964            Err(e) => {
965                results[slot.subject] = Err(e);
966                observer.dropped(slot.subject);
967            }
968        }
969    }
970}
971
972/// Wall-clock statistics over a set of samples, in milliseconds.
973///
974/// Reports `min` alongside the mean because contention is one-sided — a busy
975/// machine can only make a run slower, never faster — so the minimum is a far
976/// more robust estimator than the mean on shared CI hardware. The standard
977/// deviation is there to show how noisy the run was, not to be compared.
978pub fn stats(samples: &[f64]) -> BTreeMap<String, f64> {
979    let mut sorted = samples.to_vec();
980    sorted.sort_by(f64::total_cmp);
981    let n = sorted.len();
982    let mean = sorted.iter().sum::<f64>() / n as f64;
983    // Sample (n - 1) deviation, as hyperfine reports; a single sample has none.
984    let stddev = if n > 1 {
985        (sorted.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64).sqrt()
986    } else {
987        0.0
988    };
989    BTreeMap::from([
990        ("wall_min_ms".to_string(), sorted[0]),
991        ("wall_p50_ms".to_string(), sorted[n / 2]),
992        ("wall_mean_ms".to_string(), mean),
993        ("wall_max_ms".to_string(), sorted[n - 1]),
994        ("wall_stddev_ms".to_string(), stddev),
995        ("wall_n".to_string(), n as f64),
996    ])
997}
998
999/// Signs a subject's samples should not be taken at face value, as
1000/// sentences for stderr. `samples` must be in the order they were taken.
1001///
1002/// Two, both from hyperfine's experience of what goes wrong:
1003///
1004/// - **Outliers**, by modified z-score (0.6745 x distance from the median /
1005///   median absolute deviation) above 3.5, the usual cut-off. Something else
1006///   on the machine ran, or the command's own work varies from run to run.
1007/// - **A slow first sample**, over twice the median of the rest: a cache the
1008///   warmup did not fill. The first timed sample should look like the others.
1009///
1010/// Nothing is dropped or corrected; the point is to say when a comparison
1011/// deserves a second run. Slow outliers leave the minimum alone, but a fast
1012/// one may be the minimum, so the two are reported apart.
1013pub fn warnings(samples: &[f64]) -> Vec<String> {
1014    let mut out = Vec::new();
1015    let n = samples.len();
1016    if n < 5 {
1017        return out;
1018    }
1019    let median = |v: &mut Vec<f64>| {
1020        v.sort_by(f64::total_cmp);
1021        let m = v.len();
1022        if m.is_multiple_of(2) {
1023            (v[m / 2 - 1] + v[m / 2]) / 2.0
1024        } else {
1025            v[m / 2]
1026        }
1027    };
1028    let med = median(&mut samples.to_vec());
1029    let mad = median(&mut samples.iter().map(|x| (x - med).abs()).collect());
1030    // The modified z-score needs a spread to divide by. When over half the
1031    // samples equal the median the median deviation is zero, and any
1032    // stand-in computed from all the samples would be inflated by the very
1033    // spikes it should catch. With a flat majority there is no noise to
1034    // measure against, so anything over a quarter away from the median
1035    // counts. Identical samples still raise nothing.
1036    let outlier = |x: f64| {
1037        if mad > 0.0 {
1038            0.6745 * (x - med).abs() / mad > 3.5
1039        } else {
1040            med > 0.0 && (x - med).abs() > 0.25 * med
1041        }
1042    };
1043    {
1044        let (fast, slow) = samples
1045            .iter()
1046            .filter(|&&x| outlier(x))
1047            .fold(
1048                (0, 0),
1049                |(f, s), &x| if x < med { (f + 1, s) } else { (f, s + 1) },
1050            );
1051        if slow > 0 {
1052            out.push(format!(
1053                "{slow} of {n} samples are slow outliers; something else was running, or the \
1054                 command's work varies. Consider a quieter machine or more runs."
1055            ));
1056        }
1057        // A fast outlier is not harmless the way a slow one is: it is the
1058        // minimum tak reports, so the headline number may rest on it.
1059        if fast > 0 {
1060            out.push(format!(
1061                "{fast} of {n} samples are fast outliers, and the reported minimum may be one of \
1062                 them; check the command did the same work every time."
1063            ));
1064        }
1065    }
1066    let rest = median(&mut samples[1..].to_vec());
1067    if rest > 0.0 && samples[0] > 2.0 * rest {
1068        out.push(format!(
1069            "the first sample took {:.1}x the median of the rest; the warmup did not fill some \
1070             cache. Consider more warmup runs.",
1071            samples[0] / rest
1072        ));
1073    }
1074    out
1075}
1076
1077/// Wall-clock statistics over `plan.runs` samples of one command.
1078pub fn wall(plan: &Plan) -> Result<BTreeMap<String, f64>> {
1079    let subject = Subject {
1080        name: SELF_TOOL.to_string(),
1081        cmd: plan.cmd.clone(),
1082        prepare: None,
1083        setup: None,
1084        setup_dir: None,
1085        check: None,
1086        dir: plan.dir.clone(),
1087        version_cmd: None,
1088        env: BTreeMap::new(),
1089        vars: BTreeMap::new(),
1090        when: None,
1091        runs: Runs::Fixed(plan.runs),
1092        auto: AutoRuns {
1093            budget: crate::config::DEFAULT_BUDGET,
1094            min: crate::config::DEFAULT_MIN_RUNS,
1095            max: crate::config::DEFAULT_MAX_RUNS,
1096        },
1097        warmup: plan.warmup,
1098        counters: false,
1099        allocations: false,
1100        count_until: Default::default(),
1101        ok_exit_codes: DEFAULT_OK_EXIT_CODES.to_vec(),
1102        metrics: BTreeMap::new(),
1103    };
1104    // One subject has one possible order, so the seed is irrelevant.
1105    let samples = interleaved(
1106        std::slice::from_ref(&subject),
1107        0,
1108        &plan.settings,
1109        &mut Quiet,
1110    )
1111    .pop()
1112    .expect("one result per subject")?;
1113    Ok(stats(&samples.times))
1114}
1115
1116/// Is cachegrind usable on this machine?
1117///
1118/// Exposed so callers can tell "no counters because valgrind is missing" from
1119/// "no counters because the measurement failed" — two problems with entirely
1120/// different fixes.
1121pub fn valgrind_available() -> bool {
1122    Command::new("valgrind")
1123        .arg("--version")
1124        .stdout(Stdio::null())
1125        .stderr(Stdio::null())
1126        .status()
1127        .map(|s| s.success())
1128        .unwrap_or(false)
1129}
1130
1131/// Repeats of the cachegrind run. Three is enough to catch a bimodal subject
1132/// without tripling the cost of a measurement that is already ~50x slowed.
1133const COUNTER_RUNS: u32 = 3;
1134
1135/// A subject varying by more than this is doing environment-dependent work, and
1136/// its instruction count is not a usable gate. Well above the ~0.005% observed
1137/// for a genuinely hermetic command, far below the 16% seen from one that
1138/// touches the network.
1139const SPREAD_WARN_PCT: f64 = 0.5;
1140
1141/// Instruction counts from repeated cachegrind runs.
1142#[derive(Debug, Clone, Copy)]
1143pub struct Counted {
1144    pub min: u64,
1145    pub max: u64,
1146    pub runs: u32,
1147}
1148
1149impl Counted {
1150    /// Relative spread across runs, as a percentage of the minimum.
1151    pub fn spread_pct(&self) -> f64 {
1152        if self.min == 0 {
1153            return 0.0;
1154        }
1155        (self.max - self.min) as f64 / self.min as f64 * 100.0
1156    }
1157
1158    /// Whether this subject looks non-hermetic.
1159    ///
1160    /// The metric is deterministic; the program being measured need not be. A
1161    /// CLI that checks for updates, reads a cache it may have just created, or
1162    /// resolves DNS retires a different number of instructions depending on
1163    /// conditions that have nothing to do with the code under test.
1164    pub fn is_suspect(&self) -> bool {
1165        self.spread_pct() > SPREAD_WARN_PCT
1166    }
1167}
1168
1169/// Instruction count via `valgrind --tool=cachegrind`, repeated.
1170///
1171/// Reports the **minimum**, for the same reason wall clock does: the extra work
1172/// a subject sometimes performs is one-sided. A run that consults the network or
1173/// populates a cache can only retire *more* instructions than the quiet path,
1174/// never fewer, so the floor is the stable estimator.
1175///
1176/// Returns `Ok(None)` when valgrind is unavailable rather than failing: this is
1177/// the expected state on macOS (no usable Apple Silicon support) and Windows.
1178/// Those platforms record timing only, and the CI gate lives on the Linux job.
1179/// Locally, a container gets you counters on any host.
1180pub fn instructions(
1181    cmd: &[String],
1182    dir: Option<&std::path::Path>,
1183    settings: &Settings,
1184) -> Result<Option<Counted>> {
1185    count(
1186        cmd,
1187        None,
1188        &Site {
1189            dir,
1190            env: &BTreeMap::new(),
1191            settings,
1192        },
1193        &DEFAULT_OK_EXIT_CODES,
1194        CountUntil::Exit,
1195        false,
1196        &|| Ok(()),
1197    )
1198    .map(|c| c.map(|(c, _)| c))
1199}
1200
1201/// [`instructions`] for a declared subject: its environment, its
1202/// `ok_exit_codes`, and its prepare step before every cachegrind run, since
1203/// each run has to start from the same state the timed samples did.
1204pub fn subject_instructions(s: &Subject, settings: &Settings) -> Result<Option<Counted>> {
1205    subject_count(s, settings, false, &|| Ok(())).map(|c| c.map(|(c, _)| c))
1206}
1207
1208/// [`subject_instructions`], asking `vet` before each counted run, after its
1209/// `prepare`, as [`Observer::before_run`] is asked before each sample.
1210pub fn subject_instructions_vetted(
1211    s: &Subject,
1212    settings: &Settings,
1213    vet: &dyn Fn() -> Result<()>,
1214) -> Result<Option<Counted>> {
1215    subject_count(s, settings, false, vet).map(|c| c.map(|(c, _)| c))
1216}
1217
1218/// [`subject_instructions`], also returning the cachegrind profile of the run
1219/// whose count is reported. That is the minimum, so the profile's total is
1220/// the number recorded, and attributing a change to its functions explains
1221/// exactly the change the gate saw.
1222///
1223/// The profile is a separate result: failing to keep it must not cost the
1224/// count, which is the one metric that gates.
1225pub fn subject_profile(s: &Subject, settings: &Settings) -> Result<Option<(Counted, Profiled)>> {
1226    subject_profile_vetted(s, settings, &|| Ok(()))
1227}
1228
1229/// [`subject_profile`], asking `vet` as [`subject_instructions_vetted`] does.
1230pub fn subject_profile_vetted(
1231    s: &Subject,
1232    settings: &Settings,
1233    vet: &dyn Fn() -> Result<()>,
1234) -> Result<Option<(Counted, Profiled)>> {
1235    Ok(subject_count(s, settings, true, vet)?
1236        .map(|(c, p)| (c, p.expect("a profile was asked for"))))
1237}
1238
1239/// The raw cachegrind profile behind a count, or why it could not be kept.
1240pub type Profiled = Result<Vec<u8>>;
1241
1242fn subject_count(
1243    s: &Subject,
1244    settings: &Settings,
1245    profile: bool,
1246    vet: &dyn Fn() -> Result<()>,
1247) -> Result<Option<(Counted, Option<Profiled>)>> {
1248    count(
1249        &s.cmd,
1250        s.prepare.as_deref(),
1251        &Site {
1252            dir: s.dir.as_deref(),
1253            env: &s.env,
1254            settings,
1255        },
1256        &s.ok_exit_codes,
1257        s.count_until,
1258        profile,
1259        vet,
1260    )
1261}
1262
1263/// Run a subject's `version_cmd` once and return the version it reports, or
1264/// `None` when the subject declares none.
1265///
1266/// It runs where the subject does — its directory, its environment, the same
1267/// scrub — because that decides which binary a bare name resolves to, and the
1268/// point is to name the program that was measured. The result is the first
1269/// non-empty line of stdout, or of stderr when stdout has none: `java
1270/// -version` and some older tools print only there. Only one line, because a
1271/// version is a label on a results page, and several tools follow it with a
1272/// licence or build banner.
1273pub fn subject_version(s: &Subject, settings: &Settings) -> Option<Result<String>> {
1274    let argv = s.version_cmd.as_ref()?;
1275    let site = Site {
1276        dir: s.dir.as_deref(),
1277        env: &s.env,
1278        settings,
1279    };
1280    Some(version_once(argv, &site, VERSION_TIMEOUT))
1281}
1282
1283/// How much of each stream a `version_cmd` keeps. A version is its first
1284/// non-empty line; a tool that follows it with a banner, or a help dump,
1285/// must not be held in memory for the rest.
1286const VERSION_OUTPUT_CAP: usize = 8192;
1287
1288/// How long a `version_cmd` may take. Asking a tool its version should be
1289/// instant; one that stalls on a network or licence check must cost a
1290/// warning, not hang the run before its first sample with nothing on
1291/// screen. Fixed rather than a setting until a real tool needs longer.
1292const VERSION_TIMEOUT: Duration = Duration::from_secs(10);
1293
1294/// After the command exits, how long to wait for its output to finish
1295/// arriving. Anything it wrote is already in the pipe by then, so this only
1296/// ends up mattering when a process it started in the background still
1297/// holds the pipe open — and that must not hold up the run.
1298const VERSION_OUTPUT_GRACE: Duration = Duration::from_millis(500);
1299
1300/// Read `r` to the end, keeping the first `cap` bytes in `kept` and
1301/// discarding the rest. Draining it all means the writer never blocks on a
1302/// full pipe, so the command can finish and report its real exit status.
1303/// `overflow` is set once anything past `cap` arrives, for a caller that
1304/// treats more output than that as a failure and stops the command.
1305///
1306/// With `tail`, the last [`UNTIMED_STDERR_TAIL`] bytes are kept there too:
1307/// an error message is at the end of a log, and a long one pushes it past
1308/// any prefix.
1309fn keep_prefix(
1310    mut r: impl std::io::Read,
1311    cap: usize,
1312    kept: &Mutex<Vec<u8>>,
1313    overflow: &std::sync::atomic::AtomicBool,
1314    tail: Option<&Mutex<Vec<u8>>>,
1315) {
1316    let mut buf = [0u8; 8192];
1317    loop {
1318        match r.read(&mut buf) {
1319            Ok(0) => return,
1320            Ok(n) => {
1321                let Ok(mut k) = kept.lock() else { return };
1322                let room = cap.saturating_sub(k.len());
1323                if n > room {
1324                    overflow.store(true, std::sync::atomic::Ordering::SeqCst);
1325                }
1326                k.extend_from_slice(&buf[..n.min(room)]);
1327                if let Some(Ok(mut t)) = tail.map(Mutex::lock) {
1328                    t.extend_from_slice(&buf[..n]);
1329                    let excess = t.len().saturating_sub(UNTIMED_STDERR_TAIL);
1330                    t.drain(..excess);
1331                }
1332            }
1333            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
1334            Err(_) => return,
1335        }
1336    }
1337}
1338
1339/// Passing a fatal signal on to a running `version_cmd`'s process group.
1340///
1341/// The group is what lets a timeout stop everything the command started,
1342/// but it also takes the command out of the terminal's foreground group, so
1343/// a Ctrl-C — or a SIGTERM from CI cancelling the job — would stop tak and
1344/// leave the command running, however long it would otherwise have hung.
1345/// While a guard is alive, SIGINT, SIGTERM and SIGHUP kill that group and
1346/// then stop tak exactly as they would have without the handler. The
1347/// previous handlers come back when the guard drops, so the rest of a run
1348/// behaves as before: the measured commands share tak's group and get the
1349/// terminal's signals directly.
1350#[cfg(unix)]
1351mod forward_signals {
1352    use std::sync::atomic::{AtomicBool, AtomicI32, Ordering::SeqCst};
1353
1354    const SIGNALS: [libc::c_int; 3] = [libc::SIGINT, libc::SIGTERM, libc::SIGHUP];
1355
1356    /// What the handler knows, as atomics alone: nothing else is safe to
1357    /// touch from a signal handler.
1358    ///
1359    /// A handler can run on any thread and be preempted anywhere, so every
1360    /// path that records a signal in `pending` must end with someone acting
1361    /// on it. All accesses are `SeqCst`, which puts them in one order:
1362    ///
1363    /// - The handler writes `pending`, then reads `done` and `pgid`.
1364    ///   [`State::spawned`] writes `pgid` and then takes `pending`;
1365    ///   [`State::end`] writes `done` and then takes `pending`. Either a take
1366    ///   comes after the handler's write, and the spawning thread acts on the
1367    ///   signal, or every take that could have collected it came before, and
1368    ///   so did the store preceding it, which the handler's later read sees,
1369    ///   so the handler acts on the signal itself.
1370    /// - The handler reads `spawning` before `pgid`, and `spawned` writes
1371    ///   them in the opposite order, so a handler that sees `spawning`
1372    ///   cleared also sees the group.
1373    ///
1374    /// A handler that starts after [`State::end`] sees `spawning` cleared and
1375    /// never writes `pending`; one that started earlier and was preempted
1376    /// sees `done` and stops tak itself, without killing a group whose id may
1377    /// have been reused by then.
1378    pub(super) struct State {
1379        /// Between installing the handlers and recording the group: a
1380        /// command may exist whose group the handler cannot know yet.
1381        spawning: AtomicBool,
1382        /// The group to kill, or 0 when there is none.
1383        pgid: AtomicI32,
1384        /// A signal that arrived while `spawning`, for the spawning thread
1385        /// to act on once the group is known.
1386        pending: AtomicI32,
1387        /// The version step is over and nothing will look at `pending`
1388        /// again, so a late handler must act on its signal itself.
1389        done: AtomicBool,
1390    }
1391
1392    /// What the handler should do with a signal.
1393    #[derive(Debug, PartialEq, Eq)]
1394    pub(super) enum Act {
1395        /// Leave it for [`State::spawned`] or [`State::end`].
1396        Defer,
1397        /// Kill this group (0 for none) and stop tak.
1398        Die { pgid: i32 },
1399    }
1400
1401    impl State {
1402        pub(super) const fn new() -> State {
1403            State {
1404                spawning: AtomicBool::new(false),
1405                pgid: AtomicI32::new(0),
1406                pending: AtomicI32::new(0),
1407                done: AtomicBool::new(true),
1408            }
1409        }
1410
1411        pub(super) fn begin(&self) {
1412            self.pending.store(0, SeqCst);
1413            self.pgid.store(0, SeqCst);
1414            self.done.store(false, SeqCst);
1415            self.spawning.store(true, SeqCst);
1416        }
1417
1418        /// The handler's decision.
1419        pub(super) fn on_signal(&self, sig: libc::c_int) -> Act {
1420            if self.wants_to_defer() {
1421                self.defer(sig)
1422            } else {
1423                Act::Die {
1424                    pgid: self.pgid.load(SeqCst),
1425                }
1426            }
1427        }
1428
1429        /// First half of [`State::on_signal`]: still spawning, group not yet
1430        /// known. Separate so a test can pause a handler between the halves.
1431        fn wants_to_defer(&self) -> bool {
1432            let spawning = self.spawning.load(SeqCst);
1433            spawning && self.pgid.load(SeqCst) == 0
1434        }
1435
1436        /// Second half: record the signal, then check whether whoever would
1437        /// have collected it already has.
1438        fn defer(&self, sig: libc::c_int) -> Act {
1439            self.pending.store(sig, SeqCst);
1440            if self.done.load(SeqCst) {
1441                return Act::Die { pgid: 0 };
1442            }
1443            match self.pgid.load(SeqCst) {
1444                0 => Act::Defer,
1445                pgid => Act::Die { pgid },
1446            }
1447        }
1448
1449        /// Record the group once the spawn returns (`None` if it failed),
1450        /// and hand back any signal that arrived meanwhile with the group
1451        /// to kill for it.
1452        pub(super) fn spawned(&self, pid: Option<u32>) -> Option<(libc::c_int, i32)> {
1453            let pgid = pid.map_or(0, |p| p as i32);
1454            self.pgid.store(pgid, SeqCst);
1455            self.spawning.store(false, SeqCst);
1456            let sig = self.pending.swap(0, SeqCst);
1457            (sig != 0).then_some((sig, pgid))
1458        }
1459
1460        /// The step is over. Returns a signal a late handler deferred, which
1461        /// the caller must still act on; its group is not killed, since the
1462        /// command has been reaped and the id may be reused.
1463        pub(super) fn end(&self) -> Option<libc::c_int> {
1464            self.spawning.store(false, SeqCst);
1465            self.done.store(true, SeqCst);
1466            self.pgid.store(0, SeqCst);
1467            let sig = self.pending.swap(0, SeqCst);
1468            (sig != 0).then_some(sig)
1469        }
1470    }
1471
1472    static STATE: State = State::new();
1473
1474    /// Kill the group, then stop tak the way `sig` would have. The signal is
1475    /// blocked while a handler runs, so from there the raise takes effect —
1476    /// with the default action — as soon as the handler returns.
1477    fn die(sig: libc::c_int, pgid: i32) {
1478        // SAFETY: killpg, signal and raise are async-signal-safe.
1479        unsafe {
1480            if pgid > 0 {
1481                libc::killpg(pgid, libc::SIGKILL);
1482            }
1483            libc::signal(sig, libc::SIG_DFL);
1484            libc::raise(sig);
1485        }
1486    }
1487
1488    extern "C" fn forward(sig: libc::c_int) {
1489        if let Act::Die { pgid } = STATE.on_signal(sig) {
1490            die(sig, pgid);
1491        }
1492    }
1493
1494    pub struct Guard {
1495        previous: Vec<(libc::c_int, libc::sigaction)>,
1496    }
1497
1498    impl Guard {
1499        /// Install the handlers, before spawning: a signal between here and
1500        /// [`Guard::spawned`] is held until the group is known.
1501        pub fn install() -> Guard {
1502            STATE.begin();
1503            let mut previous = Vec::new();
1504            for sig in SIGNALS {
1505                // SAFETY: plain-data structs, filled in before use; the
1506                // handler is an `extern "C" fn(c_int)`, as sa_sigaction
1507                // expects without SA_SIGINFO.
1508                unsafe {
1509                    let mut new: libc::sigaction = std::mem::zeroed();
1510                    new.sa_sigaction = forward as extern "C" fn(libc::c_int) as libc::sighandler_t;
1511                    libc::sigemptyset(&mut new.sa_mask);
1512                    let mut old: libc::sigaction = std::mem::zeroed();
1513                    if libc::sigaction(sig, &new, &mut old) == 0 {
1514                        previous.push((sig, old));
1515                    }
1516                }
1517            }
1518            Guard { previous }
1519        }
1520
1521        /// The spawn returned: `pid` leads the new group, or `None` if the
1522        /// spawn failed. A signal that arrived during it is acted on now.
1523        pub fn spawned(pid: Option<u32>) {
1524            if let Some((sig, pgid)) = STATE.spawned(pid) {
1525                die(sig, pgid);
1526            }
1527        }
1528    }
1529
1530    impl Drop for Guard {
1531        fn drop(&mut self) {
1532            // Before the previous handlers come back, so a signal one of ours
1533            // deferred late is still acted on.
1534            if let Some(sig) = STATE.end() {
1535                die(sig, 0);
1536            }
1537            for (sig, old) in &self.previous {
1538                // SAFETY: restores the action saved by `install`.
1539                unsafe {
1540                    libc::sigaction(*sig, old, std::ptr::null_mut());
1541                }
1542            }
1543        }
1544    }
1545
1546    /// Driven on a private `State`, so no real signal is sent and the
1547    /// handler's own state is untouched: every way a handler and the version
1548    /// step can interleave ends with the signal acted on.
1549    #[cfg(test)]
1550    mod tests {
1551        use super::{Act, SeqCst, State};
1552
1553        #[test]
1554        fn a_signal_during_the_spawn_is_held_until_the_group_is_known() {
1555            let s = State::new();
1556            s.begin();
1557            assert_eq!(s.on_signal(libc::SIGTERM), Act::Defer, "no group yet");
1558            assert_eq!(s.spawned(Some(42)), Some((libc::SIGTERM, 42)));
1559            assert_eq!(s.on_signal(libc::SIGINT), Act::Die { pgid: 42 });
1560            assert_eq!(s.end(), None);
1561
1562            s.begin();
1563            assert_eq!(s.spawned(Some(7)), None, "nothing arrived");
1564            assert_eq!(s.end(), None);
1565
1566            s.begin();
1567            assert_eq!(s.on_signal(libc::SIGINT), Act::Defer);
1568            assert_eq!(
1569                s.spawned(None),
1570                Some((libc::SIGINT, 0)),
1571                "a failed spawn still stops tak"
1572            );
1573            assert_eq!(s.end(), None);
1574
1575            assert_eq!(
1576                s.on_signal(libc::SIGHUP),
1577                Act::Die { pgid: 0 },
1578                "after the step"
1579            );
1580            assert!(!s.wants_to_defer(), "and it never defers there");
1581        }
1582
1583        /// A handler that decided to defer, then was preempted: whenever it
1584        /// resumes, its signal is acted on.
1585        #[test]
1586        fn a_handler_preempted_past_the_step_still_acts() {
1587            let s = State::new();
1588
1589            // Until after the step ended: it sees `done` and stops tak,
1590            // without killing a group whose id may be reused.
1591            s.begin();
1592            assert!(s.wants_to_defer());
1593            assert_eq!(s.spawned(Some(42)), None);
1594            assert_eq!(s.end(), None);
1595            assert_eq!(s.defer(libc::SIGTERM), Act::Die { pgid: 0 });
1596
1597            // Until after the spawn: it sees the group. Its write is also
1598            // left for `end`; acting twice on a signal is harmless.
1599            s.begin();
1600            assert!(s.wants_to_defer());
1601            assert_eq!(s.spawned(Some(42)), None);
1602            assert_eq!(s.defer(libc::SIGINT), Act::Die { pgid: 42 });
1603            assert_eq!(s.end(), Some(libc::SIGINT));
1604
1605            // Its write landed before `end` took `pending` (and it read the
1606            // group before `spawned` stored it): `end` acts on it.
1607            s.begin();
1608            assert_eq!(s.spawned(Some(42)), None);
1609            s.pending.store(libc::SIGHUP, SeqCst);
1610            assert_eq!(s.end(), Some(libc::SIGHUP), "acted on at teardown");
1611        }
1612    }
1613}
1614
1615/// Stop a command run by [`capture`] and everything it started, then reap it:
1616/// a `version_cmd` past its deadline, or a metric command past its output cap.
1617///
1618/// On Unix that is its whole process group, so a helper it spawned cannot go
1619/// on using CPU through the samples that follow, or hold the output pipes
1620/// open. Elsewhere only the command itself is stopped.
1621///
1622/// Only then: a command that exits on its own may have started a
1623/// daemon on purpose — a version check that launches a language server or
1624/// build daemon — and that is the tool's business, not tak's to kill.
1625fn stop_group(child: &mut std::process::Child) {
1626    #[cfg(unix)]
1627    {
1628        // The child leads its own group (`process_group(0)`), so its pid is
1629        // the group id. SAFETY: killpg only sends a signal.
1630        let pgid = child.id() as libc::pid_t;
1631        if unsafe { libc::killpg(pgid, libc::SIGKILL) } != 0 {
1632            let _ = child.kill();
1633        }
1634    }
1635    #[cfg(not(unix))]
1636    let _ = child.kill();
1637    let _ = child.wait();
1638}
1639
1640fn version_once(argv: &[String], site: &Site, timeout: Duration) -> Result<String> {
1641    let bin = argv
1642        .first()
1643        .map(String::as_str)
1644        .unwrap_or("(empty command)");
1645    let Captured {
1646        status,
1647        stdout,
1648        stderr,
1649        stderr_tail,
1650        ..
1651    } = capture(argv, site, Some(timeout), VERSION_OUTPUT_CAP, false)?;
1652
1653    // A failing command's output is an error message or a usage dump, not a
1654    // version, however much of it there is.
1655    if !status.success() {
1656        bail!("`{bin}` exited with {status}: {}", last_line(&stderr_tail));
1657    }
1658    let first = |bytes: &[u8]| {
1659        String::from_utf8_lossy(bytes)
1660            .lines()
1661            .map(str::trim)
1662            .find(|l| !l.is_empty())
1663            .map(str::to_string)
1664    };
1665    first(&stdout)
1666        .or_else(|| first(&stderr))
1667        .with_context(|| format!("`{bin}` printed nothing"))
1668}
1669
1670/// The last non-empty line of a captured stream, for an error message.
1671fn last_line(bytes: &[u8]) -> String {
1672    String::from_utf8_lossy(bytes)
1673        .lines()
1674        .map(str::trim)
1675        .rfind(|l| !l.is_empty())
1676        .unwrap_or("(no output)")
1677        .to_string()
1678}
1679
1680/// What [`capture`] got from a command that finished.
1681struct Captured {
1682    status: std::process::ExitStatus,
1683    /// At most the cap passed to [`capture`].
1684    stdout: Vec<u8>,
1685    /// The first [`VERSION_OUTPUT_CAP`] bytes, where a version is.
1686    stderr: Vec<u8>,
1687    /// The last [`UNTIMED_STDERR_TAIL`] bytes, where an error is.
1688    stderr_tail: Vec<u8>,
1689    /// stdout went past the cap. With `stop_past_cap`, the command was
1690    /// stopped as soon as that was seen, and `status` is how it died.
1691    overflowed: bool,
1692    /// stdout was still open when the grace period after the command's exit
1693    /// ran out: something it left running holds it and may yet write to it.
1694    stdout_open: bool,
1695    /// The command's process group on Unix, which is also its pid, for a
1696    /// caller that has to stop what it left behind.
1697    pgid: u32,
1698}
1699
1700/// Stop whatever is left of a finished command's process group: a caller's
1701/// decision, since leaving a daemon running can be the point; see
1702/// [`stop_group`]. The command itself has been reaped, but its group id
1703/// cannot be handed to a new process while any member of the group lives,
1704/// so this reaches only what the command started. Elsewhere there is no
1705/// group to reach. When nothing is left, `killpg` fails with ESRCH, which
1706/// is expected and ignored. It is called only when the output was rejected,
1707/// which is when something may be left.
1708fn stop_leftovers(pgid: u32) {
1709    #[cfg(unix)]
1710    // SAFETY: killpg only sends a signal.
1711    unsafe {
1712        libc::killpg(pgid as libc::pid_t, libc::SIGKILL);
1713    }
1714    #[cfg(not(unix))]
1715    let _ = pgid;
1716}
1717
1718/// Run `argv` at `site` with both streams piped, keeping the first
1719/// `stdout_cap` bytes of stdout and [`VERSION_OUTPUT_CAP`] of stderr, and
1720/// reading and discarding the rest so the command never blocks on a full
1721/// pipe. Memory and disk stay bounded however much it prints.
1722///
1723/// It runs in its own process group, so a `timeout` or `stop_past_cap` can
1724/// stop everything it started. With `stop_past_cap`, output beyond the cap
1725/// is a failure the caller will report anyway, so the command is stopped the
1726/// moment it arrives rather than left to print for as long as it likes.
1727/// `timeout: None` waits as long as the command takes, as `setup` does.
1728///
1729/// Once the command exits, its output is waited for only briefly: a process
1730/// it left in the background may hold a pipe open indefinitely.
1731fn capture(
1732    argv: &[String],
1733    site: &Site,
1734    timeout: Option<Duration>,
1735    stdout_cap: usize,
1736    stop_past_cap: bool,
1737) -> Result<Captured> {
1738    use std::sync::atomic::{AtomicBool, Ordering::SeqCst};
1739    let bin = argv
1740        .first()
1741        .map(String::as_str)
1742        .unwrap_or("(empty command)");
1743    let mut cmd = command(argv, site)?;
1744    cmd.stdin(Stdio::null())
1745        .stdout(Stdio::piped())
1746        .stderr(Stdio::piped());
1747    // Its own process group, so a timeout can stop everything it started:
1748    // a helper left running would compete with the samples that follow.
1749    #[cfg(unix)]
1750    std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
1751    // Being in its own group, it no longer gets the terminal's Ctrl-C; this
1752    // passes a fatal signal on to it until the guard drops.
1753    #[cfg(unix)]
1754    let _forward = forward_signals::Guard::install();
1755    let spawned = cmd.spawn();
1756    // Also when the spawn failed, so a signal held during it still stops tak.
1757    #[cfg(unix)]
1758    forward_signals::Guard::spawned(spawned.as_ref().ok().map(std::process::Child::id));
1759    let mut child = spawned.with_context(|| format!("failed to spawn `{bin}`"))?;
1760    // Known to `stop_running` like every other command tak runs, so a
1761    // backfill's interrupt stops it, and anything it leaves behind, before
1762    // deleting the checkout it ran in. Finished on every way out, early
1763    // returns included.
1764    tracked::started(child.id());
1765    struct Finished;
1766    impl Drop for Finished {
1767        fn drop(&mut self) {
1768            tracked::finished();
1769        }
1770    }
1771    let _finished = Finished;
1772
1773    // One thread per stream, so neither pipe can fill while the other is
1774    // read. They are never joined: a background process the command started
1775    // may hold a pipe open long after it exits, and the run must not wait on
1776    // that. Each thread ends when its pipe finally closes.
1777    let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
1778    let overflow = Arc::new(AtomicBool::new(false));
1779    // stderr's overflow is never acted on: it only feeds an error message.
1780    let ignored = Arc::new(AtomicBool::new(false));
1781    let stdout_done = Arc::new(AtomicBool::new(false));
1782    let unused = Arc::new(AtomicBool::new(false));
1783    let spawn_reader = |r: Option<Box<dyn std::io::Read + Send>>,
1784                        cap: usize,
1785                        flag: &Arc<AtomicBool>,
1786                        done: &Arc<AtomicBool>,
1787                        tail: Option<&Arc<Mutex<Vec<u8>>>>| {
1788        let kept = Arc::new(Mutex::new(Vec::new()));
1789        if let Some(r) = r {
1790            let (kept, tx, flag, done) = (
1791                Arc::clone(&kept),
1792                done_tx.clone(),
1793                Arc::clone(flag),
1794                Arc::clone(done),
1795            );
1796            let tail = tail.map(Arc::clone);
1797            std::thread::spawn(move || {
1798                keep_prefix(r, cap, &kept, &flag, tail.as_deref());
1799                done.store(true, SeqCst);
1800                let _ = tx.send(());
1801            });
1802        } else {
1803            done.store(true, SeqCst);
1804            let _ = done_tx.send(());
1805        }
1806        kept
1807    };
1808    let stdout = spawn_reader(
1809        child.stdout.take().map(|o| Box::new(o) as _),
1810        stdout_cap,
1811        &overflow,
1812        &stdout_done,
1813        None,
1814    );
1815    let stderr_tail = Arc::new(Mutex::new(Vec::new()));
1816    let stderr = spawn_reader(
1817        child.stderr.take().map(|e| Box::new(e) as _),
1818        VERSION_OUTPUT_CAP,
1819        &ignored,
1820        &unused,
1821        Some(&stderr_tail),
1822    );
1823
1824    let deadline = timeout.map(|t| Instant::now() + t);
1825    let status = loop {
1826        if stop_past_cap && overflow.load(SeqCst) {
1827            stop_group(&mut child);
1828            // Reaped by `stop_group`; this only reads the status it left.
1829            break child
1830                .wait()
1831                .with_context(|| format!("failed to wait for `{bin}`"))?;
1832        }
1833        match child.try_wait() {
1834            Ok(Some(status)) => break status,
1835            Ok(None) if deadline.is_none_or(|d| Instant::now() < d) => {
1836                std::thread::sleep(Duration::from_millis(5));
1837            }
1838            Ok(None) => {
1839                stop_group(&mut child);
1840                bail!(
1841                    "`{bin}` did not finish within {}, so it was stopped",
1842                    crate::progress::fmt(timeout.unwrap_or_default())
1843                );
1844            }
1845            Err(e) => {
1846                stop_group(&mut child);
1847                return Err(e).with_context(|| format!("failed to wait for `{bin}`"));
1848            }
1849        }
1850    };
1851    let grace = Instant::now() + VERSION_OUTPUT_GRACE;
1852    for _ in 0..2 {
1853        let left = grace.saturating_duration_since(Instant::now());
1854        if done_rx.recv_timeout(left).is_err() {
1855            break;
1856        }
1857    }
1858    let take = |kept: &Mutex<Vec<u8>>| kept.lock().map(|k| k.clone()).unwrap_or_default();
1859    Ok(Captured {
1860        status,
1861        stdout: take(&stdout),
1862        stderr: take(&stderr),
1863        stderr_tail: take(&stderr_tail),
1864        overflowed: overflow.load(SeqCst),
1865        stdout_open: !stdout_done.load(SeqCst),
1866        pgid: child.id(),
1867    })
1868}
1869
1870/// How much of valgrind's log to read. Only valgrind writes it, so it holds
1871/// a banner and a summary and is a few kilobytes; the cap is there so a
1872/// tool that turned verbose could not make tak read without limit.
1873const VALGRIND_LOG_CAP: u64 = 1 << 20;
1874
1875/// Run `cmd` under valgrind with `tool` options to completion, returning its
1876/// exit status and the lines of valgrind's log that belong to the subject's
1877/// own process, where the tool's summary is.
1878///
1879/// valgrind writes its messages to a file of its own (`--log-fd`), and the
1880/// subject's stdout and stderr go to `/dev/null`, as they do for timed
1881/// samples. Mixing the two on one stream, as valgrind does by default,
1882/// caused every problem a subject's background process could cause: reading
1883/// the stream to EOF waited for that process and hung the run; a file for
1884/// it grew for as long as the process logged; a bounded tail of it could
1885/// have the summary pushed out by the process's output; and the subject
1886/// could print a line that read as the summary. With the log apart, nothing
1887/// the subject leaves behind can reach it, and the run is over when the
1888/// process spawned here exits.
1889///
1890/// The log is an anonymous temporary file — unlinked from the start, so a
1891/// subject that clears its temporary directory, as `rm -rf "$TMPDIR"/*`
1892/// does, cannot take the log with it. It reaches valgrind by descriptor:
1893/// close-on-exec is cleared for it in the child alone, and valgrind moves it
1894/// out of the client's sight and marks it close-on-exec again, so programs
1895/// the subject runs never hold it. A process the subject forks without exec
1896/// stays under valgrind and writes to the same file, under its own
1897/// `==PID==` prefix, which is why only the subject's pid's lines are
1898/// returned: valgrind replaces itself with the tool rather than forking, so
1899/// that is the pid spawned here.
1900///
1901/// Creating the file can fail — a full or read-only temporary directory —
1902/// and that is an error naming it, which the caller reports as a failed
1903/// measurement, never as valgrind being absent.
1904///
1905/// The pid is returned with the log: it is the subject's own, and names the
1906/// files a tool writes with `%p` in their path.
1907#[cfg(unix)]
1908fn under_valgrind(
1909    tool: &[&str],
1910    cmd: &[String],
1911    site: &Site,
1912) -> Result<(std::process::ExitStatus, String, u32)> {
1913    use std::io::{Read, Seek};
1914    use std::os::fd::AsRawFd;
1915    use std::os::unix::process::CommandExt;
1916    let mut log = tempfile::tempfile().context("failed to create a file for valgrind's log")?;
1917    let fd = log.as_raw_fd();
1918    let mut argv: Vec<String> = std::iter::once("valgrind")
1919        .chain(tool.iter().copied())
1920        .map(String::from)
1921        .collect();
1922    argv.push(format!("--log-fd={fd}"));
1923    argv.extend_from_slice(cmd);
1924    let mut c = command(&argv, site)?;
1925    c.stdin(Stdio::null())
1926        .stdout(Stdio::null())
1927        .stderr(Stdio::null());
1928    // SAFETY: runs in the child between fork and exec, and only calls fcntl,
1929    // which is async-signal-safe, on a descriptor this function owns.
1930    unsafe {
1931        c.pre_exec(move || {
1932            if libc::fcntl(fd, libc::F_SETFD, 0) == -1 {
1933                return Err(std::io::Error::last_os_error());
1934            }
1935            Ok(())
1936        });
1937    }
1938    // Spawned and waited for as `run_tracked` does, so under `tak backfill
1939    // --commits` the run is in its own process group (set by `command`) and
1940    // an interrupt stops it with everything it started. The group is set by
1941    // std, not by the hook above, which is the only `pre_exec` here.
1942    let mut child = c.spawn().context("failed to run valgrind")?;
1943    let pid = child.id();
1944    tracked::started(pid);
1945    let status = child.wait();
1946    tracked::finished();
1947    let status = status.context("failed to run valgrind")?;
1948    // An empty log is what a valgrind that could not start the subject
1949    // leaves: its launcher reports that on stderr, before the log is used.
1950    // The caller's "no summary" error says so rather than this one guessing.
1951    let mut raw = Vec::new();
1952    log.rewind().context("failed to read valgrind's log")?;
1953    log.take(VALGRIND_LOG_CAP)
1954        .read_to_end(&mut raw)
1955        .context("failed to read valgrind's log")?;
1956    let prefix = format!("=={pid}==");
1957    let own: String = String::from_utf8_lossy(&raw)
1958        .lines()
1959        .filter(|l| l.starts_with(&prefix))
1960        .flat_map(|l| [l, "\n"])
1961        .collect();
1962    Ok((status, own, pid))
1963}
1964
1965/// There is no valgrind to run on other platforms, and [`valgrind_available`]
1966/// says so before this is reached.
1967#[cfg(not(unix))]
1968fn under_valgrind(
1969    _tool: &[&str],
1970    _cmd: &[String],
1971    _site: &Site,
1972) -> Result<(std::process::ExitStatus, String, u32)> {
1973    bail!("valgrind runs only on Unix")
1974}
1975
1976/// The last line of valgrind's log with something on it past the `==PID==`
1977/// prefix, for an error that has no summary to show. valgrind ends its
1978/// output with a bare `==PID==` line, which says nothing.
1979fn last_log_line(log: &str) -> &str {
1980    log.lines()
1981        .map(|l| valgrind_line(l).unwrap_or(l).trim())
1982        .rfind(|l| !l.is_empty())
1983        .unwrap_or("(valgrind wrote no log; it may not have been able to start the command)")
1984}
1985
1986/// `ok` applies to the subject under valgrind: cachegrind exits with its
1987/// client's code, and re-raises the signal a client died of.
1988///
1989/// With `profile`, each run writes its per-function profile to a scratch
1990/// file, and the one from the run at the minimum is returned. Without it the
1991/// profile goes to `/dev/null` as it always has. cachegrind writes it after
1992/// the client exits, so keeping it cannot move the count.
1993///
1994/// Anything that stops the profile being kept is returned in its place
1995/// rather than failing the count: an instruction count is still the gate
1996/// with or without the profile that explains it.
1997///
1998/// `until` [`CountUntil::Exec`] counts under callgrind instead, which can
1999/// report the count at a point inside the run; see [`callgrind_total`]. Its
2000/// profiles are in a format `tak profile` does not read, so none is kept.
2001fn count(
2002    cmd: &[String],
2003    prepare: Option<&[String]>,
2004    site: &Site,
2005    ok: &[i32],
2006    until: CountUntil,
2007    profile: bool,
2008    vet: &dyn Fn() -> Result<()>,
2009) -> Result<Option<(Counted, Option<Profiled>)>> {
2010    if !valgrind_available() {
2011        return Ok(None);
2012    }
2013    let exec = until == CountUntil::Exec;
2014
2015    // An absolute path, since the subject may run in its own `dir`; removed
2016    // with the directory on every exit path. When it cannot be created the
2017    // runs go to `/dev/null` as they would without `profile`, unless the
2018    // count itself is read from it.
2019    let (scratch, unkept) = match (profile || exec).then(tempfile::tempdir) {
2020        Some(Ok(d)) => (Some(d), None),
2021        Some(Err(e)) if exec => {
2022            return Err(anyhow::Error::new(e)
2023                .context("could not create a directory for callgrind's counts"));
2024        }
2025        Some(Err(e)) => (
2026            None,
2027            Some(
2028                anyhow::Error::new(e)
2029                    .context("could not create a directory for cachegrind profiles"),
2030            ),
2031        ),
2032        None => (None, None),
2033    };
2034    let mut samples: Vec<u64> = Vec::with_capacity(COUNTER_RUNS as usize);
2035    for run in 0..COUNTER_RUNS {
2036        // Before each step that runs from the subject's paths, as for a
2037        // timed sample: the previous run may have changed them.
2038        if let Some(p) = prepare {
2039            vet()?;
2040            prepare_once(p, site)?;
2041        }
2042        vet()?;
2043        let out_file = match &scratch {
2044            // valgrind expands `%p` and `%q{VAR}` in this path and reads `%%`
2045            // as a literal one. A temporary directory seldom holds a `%`, but
2046            // TMPDIR is the user's to set.
2047            Some(d) => d
2048                .path()
2049                .join(format!("run-{run}"))
2050                .to_string_lossy()
2051                .replace('%', "%%"),
2052            None => "/dev/null".to_string(),
2053        };
2054        let bin = cmd.first().map(String::as_str).unwrap_or("(empty command)");
2055        if exec {
2056            // `%p`, since a process the subject forks stays under valgrind
2057            // and dumps its own counts; only the subject's are read.
2058            let out_arg = format!("--callgrind-out-file={out_file}.%p");
2059            let (status, log, pid) = under_valgrind(
2060                &["--tool=callgrind", "--dump-before=*execve*", &out_arg],
2061                cmd,
2062                site,
2063            )?;
2064            accepted(bin, status, ok, " under valgrind")?;
2065            let dir = scratch
2066                .as_ref()
2067                .expect("an exec count has a scratch directory");
2068            samples.push(callgrind_total(
2069                dir.path(),
2070                &format!("run-{run}"),
2071                pid,
2072                &log,
2073            )?);
2074            continue;
2075        }
2076        let out_arg = format!("--cachegrind-out-file={out_file}");
2077        let (status, log, _) = under_valgrind(
2078            &[
2079                "--tool=cachegrind",
2080                "--cache-sim=no",
2081                "--branch-sim=no",
2082                &out_arg,
2083            ],
2084            cmd,
2085            site,
2086        )?;
2087
2088        // cachegrind writes its summary to its log as e.g. "I refs:  48,349,132".
2089        accepted(bin, status, ok, " under valgrind")?;
2090        match parse_irefs(&log) {
2091            // cachegrind that cannot open its output file still exits with
2092            // the client's code, and reports `I refs: 0` — a count that would
2093            // record as the largest improvement ever measured. Seen with
2094            // valgrind 3.24 when the subject removed the directory the profile
2095            // was going to. Decided on the count, not on the message, which
2096            // only names the cause: no process retires zero instructions, so
2097            // zero is never a measurement.
2098            Some(0) => {
2099                let unwritable =
2100                    valgrind_lines(&log).any(|l| l.contains("can't open output data file"));
2101                if unwritable {
2102                    bail!(
2103                        "cachegrind could not write its profile to {out_file}, and counts nothing when that happens"
2104                    );
2105                }
2106                bail!("cachegrind counted no instructions");
2107            }
2108            Some(n) => samples.push(n),
2109            // Valgrind is installed but produced no summary — a real failure,
2110            // not the same thing as valgrind being absent. Reporting it as
2111            // absent sends people off installing something they already have.
2112            None => bail!(
2113                "valgrind ran but emitted no `I refs` summary: {}",
2114                last_log_line(&log)
2115            ),
2116        }
2117    }
2118
2119    let counted = Counted {
2120        min: *samples.iter().min().expect("COUNTER_RUNS > 0"),
2121        max: *samples.iter().max().expect("COUNTER_RUNS > 0"),
2122        runs: COUNTER_RUNS,
2123    };
2124    // The first run at the minimum. A hermetic subject's runs are identical,
2125    // and for one that is not, the minimum is the quiet path the recorded
2126    // count describes.
2127    let best = samples
2128        .iter()
2129        .position(|n| *n == counted.min)
2130        .expect("the minimum is one of the samples");
2131    let kept = match (scratch, unkept) {
2132        _ if exec => profile.then(|| {
2133            Err(anyhow::anyhow!(
2134                "no profile is kept for count_until = \"exec\": the count comes from callgrind, whose profile tak profile does not read"
2135            ))
2136        }),
2137        (Some(d), _) => {
2138            let path = d.path().join(format!("run-{best}"));
2139            Some(
2140                std::fs::read(&path)
2141                    .with_context(|| format!("cachegrind wrote no profile to {}", path.display()))
2142                    .and_then(|raw| {
2143                        if raw.is_empty() {
2144                            bail!("cachegrind wrote an empty profile to {}", path.display());
2145                        }
2146                        Ok(raw)
2147                    }),
2148            )
2149        }
2150        (None, Some(e)) => Some(Err(e)),
2151        (None, None) => None,
2152    };
2153    Ok(Some((counted, kept)))
2154}
2155
2156/// The instructions one callgrind run counted for the subject, up to its
2157/// last `execve`, or to its exit when it never execs.
2158///
2159/// `--dump-before=*execve*` has callgrind write the counts so far, and
2160/// start again from zero, each time the process enters a function named
2161/// like `execve` — the C library's, and any wrapper around it. A successful
2162/// exec ends the process valgrind was counting without its exit dump, so the
2163/// part written before it is the last; a process that never execs leaves
2164/// the one dump callgrind writes at exit. Summing every part the subject's
2165/// pid wrote gives the same total either way, and one that tries several
2166/// paths, as `execvp` does along PATH, has each failed attempt added in.
2167///
2168/// Files are `{stem}.{pid}` and `{stem}.{pid}.{part}`; the first exists from
2169/// the start and stays empty when the run dumped in parts. Each holds its
2170/// count on a `totals:` line, which older callgrind wrote as `summary:`.
2171fn callgrind_total(dir: &Path, stem: &str, pid: u32, log: &str) -> Result<u64> {
2172    let base = format!("{stem}.{pid}");
2173    let mut total: u64 = 0;
2174    let entries = std::fs::read_dir(dir)
2175        .with_context(|| format!("could not read callgrind's counts in {}", dir.display()))?;
2176    for entry in entries {
2177        let entry = entry
2178            .with_context(|| format!("could not read callgrind's counts in {}", dir.display()))?;
2179        let name = entry.file_name();
2180        let name = name.to_string_lossy();
2181        let ours = name == base
2182            || name
2183                .strip_prefix(&base)
2184                .and_then(|r| r.strip_prefix('.'))
2185                .is_some_and(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()));
2186        if !ours {
2187            continue;
2188        }
2189        let path = entry.path();
2190        let text = std::fs::read_to_string(&path)
2191            .with_context(|| format!("could not read callgrind's counts in {}", path.display()))?;
2192        total += callgrind_part(&text)
2193            .with_context(|| format!("callgrind wrote no total to {}", path.display()))?;
2194    }
2195    if total == 0 {
2196        bail!(
2197            "callgrind counted no instructions before the process exited or exec'd; \
2198             count_until = \"exec\" needs the exec to go through a function named execve, \
2199             as the C library's does: {}",
2200            last_log_line(log)
2201        );
2202    }
2203    Ok(total)
2204}
2205
2206/// The count in one callgrind output file: 0 for the empty file callgrind
2207/// leaves when it dumped in parts, `None` for one with no total at all.
2208fn callgrind_part(text: &str) -> Option<u64> {
2209    if text.trim().is_empty() {
2210        return Some(0);
2211    }
2212    let number = |key: &str| {
2213        text.lines()
2214            .find_map(|l| l.strip_prefix(key))
2215            .and_then(|rest| rest.split_whitespace().next())
2216            .and_then(|n| n.parse::<u64>().ok())
2217    };
2218    number("totals:").or_else(|| number("summary:"))
2219}
2220
2221/// Extract the `I refs:` count from cachegrind's summary in its log.
2222///
2223/// Only valgrind's own `==PID==` lines are read, and the last summary among
2224/// them. [`under_valgrind`] keeps the subject's output out of the log
2225/// altogether; the prefix check is what would still hold if that ever
2226/// changed, since a subject printing `I refs:` must not supply its own count.
2227fn parse_irefs(log: &str) -> Option<u64> {
2228    let line = valgrind_lines(log)
2229        .filter(|l| l.contains("I refs:"))
2230        .last()?;
2231    let digits: String = line
2232        .rsplit(':')
2233        .next()?
2234        .chars()
2235        .filter(|c| c.is_ascii_digit())
2236        .collect();
2237    digits.parse().ok()
2238}
2239
2240/// What DHAT reports about one run's heap use.
2241#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2242pub struct Heap {
2243    /// Blocks allocated over the whole run, freed or not.
2244    pub blocks: u64,
2245    /// Bytes allocated over the whole run, freed or not.
2246    pub bytes: u64,
2247    /// Bytes live at the global peak (DHAT's `t-gmax`).
2248    pub peak_bytes: u64,
2249}
2250
2251impl Heap {
2252    /// As recorded metrics. The `alloc_` prefix keeps them together in the
2253    /// sorted metrics map and apart from the gated `instructions`.
2254    pub fn metrics(&self) -> [(&'static str, u64); 3] {
2255        [
2256            ("alloc_blocks", self.blocks),
2257            ("alloc_bytes", self.bytes),
2258            ("alloc_peak_bytes", self.peak_bytes),
2259        ]
2260    }
2261}
2262
2263/// Heap allocations from repeated DHAT runs: each metric's floor and ceiling,
2264/// taken independently, as [`Counted`] does for instructions.
2265#[derive(Debug, Clone, Copy)]
2266pub struct Allocated {
2267    pub min: Heap,
2268    pub max: Heap,
2269    pub runs: u32,
2270}
2271
2272/// Relative spread of one metric across runs, as a percentage of its
2273/// minimum. A minimum of zero under a maximum that is not has no percentage,
2274/// and counts as infinitely spread: something allocated on one run and not on
2275/// another.
2276fn spread(lo: u64, hi: u64) -> f64 {
2277    match (lo, hi) {
2278        (0, 0) => 0.0,
2279        (0, _) => f64::INFINITY,
2280        (lo, hi) => (hi - lo) as f64 / lo as f64 * 100.0,
2281    }
2282}
2283
2284impl Allocated {
2285    /// The wider spread of the two totals, blocks and bytes.
2286    pub fn totals_spread_pct(&self) -> f64 {
2287        spread(self.min.blocks, self.max.blocks).max(spread(self.min.bytes, self.max.bytes))
2288    }
2289
2290    /// The spread of the peak.
2291    pub fn peak_spread_pct(&self) -> f64 {
2292        spread(self.min.peak_bytes, self.max.peak_bytes)
2293    }
2294
2295    /// Whether the totals moved between runs, which says the program's work
2296    /// did. Same threshold as instructions. The totals of every hermetic
2297    /// subject measured, threaded ones included, repeated exactly; the one
2298    /// that moved was `git status` refreshing its index on the first run.
2299    pub fn is_suspect(&self) -> bool {
2300        self.totals_spread_pct() > SPREAD_WARN_PCT
2301    }
2302
2303    /// Whether the peak moved while the totals did not. That is how a
2304    /// threaded subject looks: every thread does the same work, but how much
2305    /// of it is live at once depends on how valgrind interleaves them, which
2306    /// moved an 8-thread subject's peak by up to 2.5%.
2307    pub fn peak_is_unsteady(&self) -> bool {
2308        self.peak_spread_pct() > SPREAD_WARN_PCT
2309    }
2310
2311    /// Whether DHAT saw no heap allocation at all. Nearly always blindness
2312    /// rather than a finding: DHAT counts only calls it can intercept, so a
2313    /// statically linked binary, or one with its own allocator compiled in
2314    /// (jemalloc, mimalloc), reports zero however much it allocates.
2315    pub fn saw_nothing(&self) -> bool {
2316        self.max.blocks == 0
2317    }
2318}
2319
2320/// Heap allocations via `valgrind --tool=dhat`, repeated [`COUNTER_RUNS`]
2321/// times, with the subject's prepare step before each run as for
2322/// [`subject_instructions`].
2323///
2324/// Reported, never gated — not yet. In the measurements on the methodology
2325/// page the totals repeated exactly for every hermetic subject, threaded ones
2326/// and a 32-way CPU contention run included. The peak did not: valgrind runs
2327/// one thread at a time and switches by its own schedule, so how much a
2328/// threaded program has live at once moves with it, in both directions. Its
2329/// minimum drifted 0.7% under contention, so for the peak the floor is not
2330/// the one-sided estimator it is for everything else.
2331///
2332/// `Ok(None)` when valgrind is unavailable, like [`instructions`].
2333pub fn subject_allocations(s: &Subject, settings: &Settings) -> Result<Option<Allocated>> {
2334    subject_allocations_vetted(s, settings, &|| Ok(()))
2335}
2336
2337/// [`subject_allocations`], asking `vet` before each DHAT run, after its
2338/// `prepare`, as [`subject_instructions_vetted`] does before each counted
2339/// run.
2340pub fn subject_allocations_vetted(
2341    s: &Subject,
2342    settings: &Settings,
2343    vet: &dyn Fn() -> Result<()>,
2344) -> Result<Option<Allocated>> {
2345    let site = Site {
2346        dir: s.dir.as_deref(),
2347        env: &s.env,
2348        settings,
2349    };
2350    allocations(&s.cmd, s.prepare.as_deref(), &site, &s.ok_exit_codes, vet)
2351}
2352
2353/// `ok` applies to the subject under valgrind: DHAT, like cachegrind, exits
2354/// with its client's code.
2355fn allocations(
2356    cmd: &[String],
2357    prepare: Option<&[String]>,
2358    site: &Site,
2359    ok: &[i32],
2360    vet: &dyn Fn() -> Result<()>,
2361) -> Result<Option<Allocated>> {
2362    if !valgrind_available() {
2363        return Ok(None);
2364    }
2365    let bin = cmd.first().map(String::as_str).unwrap_or("(empty command)");
2366    let mut runs: Vec<Heap> = Vec::with_capacity(COUNTER_RUNS as usize);
2367    for _ in 0..COUNTER_RUNS {
2368        // Before each step that runs from the subject's paths, as for a
2369        // counted cachegrind run: the previous run may have changed them,
2370        // and the prepare may change them again.
2371        if let Some(p) = prepare {
2372            vet()?;
2373            prepare_once(p, site)?;
2374        }
2375        vet()?;
2376        // The profile DHAT would write is for its viewer, and tak reads only
2377        // the summary; without this every run leaves a `dhat.out.PID` in the
2378        // subject's directory.
2379        let (status, log, _) =
2380            under_valgrind(&["--tool=dhat", "--dhat-out-file=/dev/null"], cmd, site)?;
2381        accepted(bin, status, ok, " under valgrind")?;
2382        match parse_dhat(&log) {
2383            Some(h) => runs.push(h),
2384            None => bail!(
2385                "valgrind ran but emitted no DHAT summary: {}",
2386                last_log_line(&log)
2387            ),
2388        }
2389    }
2390    let fold = |f: fn(u64, u64) -> u64| {
2391        runs.iter()
2392            .copied()
2393            .reduce(|a, b| Heap {
2394                blocks: f(a.blocks, b.blocks),
2395                bytes: f(a.bytes, b.bytes),
2396                peak_bytes: f(a.peak_bytes, b.peak_bytes),
2397            })
2398            .expect("COUNTER_RUNS > 0")
2399    };
2400    Ok(Some(Allocated {
2401        min: fold(u64::min),
2402        max: fold(u64::max),
2403        runs: COUNTER_RUNS,
2404    }))
2405}
2406
2407/// Extract DHAT's summary from valgrind's log, e.g.
2408///
2409/// ```text
2410/// ==8== Total:     4,140 bytes in 3 blocks
2411/// ==8== At t-gmax: 4,140 bytes in 3 blocks
2412/// ```
2413///
2414/// Only lines with valgrind's `==PID==` prefix count. The log holds nothing
2415/// else when it is written by [`under_valgrind`], but the summary's own
2416/// words are too ordinary — "Total: 5 bytes in 1 blocks" could be any
2417/// progress line — to match wherever they appear. The format is the one
2418/// valgrind 3.15 introduced with `--tool=dhat`; before that it was
2419/// `exp-dhat`, which no longer exists.
2420fn parse_dhat(log: &str) -> Option<Heap> {
2421    let field = |name: &str| {
2422        let rest = valgrind_lines(log).find_map(|l| l.trim_start().strip_prefix(name))?;
2423        let (bytes, rest) = rest.trim().split_once(" bytes in ")?;
2424        let blocks = rest.split_whitespace().next()?;
2425        Some((dhat_number(bytes)?, dhat_number(blocks)?))
2426    };
2427    let (bytes, blocks) = field("Total:")?;
2428    let (peak_bytes, _) = field("At t-gmax:")?;
2429    Some(Heap {
2430        blocks,
2431        bytes,
2432        peak_bytes,
2433    })
2434}
2435
2436/// A line of valgrind's own output, without its `==PID==` prefix.
2437fn valgrind_line(line: &str) -> Option<&str> {
2438    let rest = line.strip_prefix("==")?;
2439    let (pid, rest) = rest.split_once("==")?;
2440    (!pid.is_empty() && pid.chars().all(|c| c.is_ascii_digit())).then_some(rest)
2441}
2442
2443/// A count as valgrind prints it, with commas every three digits.
2444fn dhat_number(s: &str) -> Option<u64> {
2445    let digits: String = s.trim().chars().filter(|&c| c != ',').collect();
2446    if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
2447        return None;
2448    }
2449    digits.parse().ok()
2450}
2451
2452/// valgrind's own lines in its log, with their `==<pid>==` prefix removed.
2453fn valgrind_lines(log: &str) -> impl Iterator<Item = &str> {
2454    log.lines().filter_map(valgrind_line)
2455}
2456
2457#[cfg(test)]
2458mod tests {
2459    use super::*;
2460
2461    /// Every part the subject's pid dumped is added up — the empty base file
2462    /// callgrind leaves when it dumped in parts included — and the files of
2463    /// another run or a forked child are left out.
2464    #[test]
2465    fn a_callgrind_total_sums_the_subjects_parts_alone() {
2466        let d = tempfile::tempdir().unwrap();
2467        let write = |name: &str, text: &str| std::fs::write(d.path().join(name), text).unwrap();
2468        write("run-0.41", "");
2469        write(
2470            "run-0.41.1",
2471            "version: 1\nevents: Ir\npart: 1\nsummary: 1000\ntotals: 1000\n",
2472        );
2473        write("run-0.41.2", "part: 2\ntotals: 20\n");
2474        write("run-0.410", "totals: 5\n");
2475        write("run-0.42.1", "totals: 300\n");
2476        write("run-1.41.1", "totals: 7\n");
2477        assert_eq!(callgrind_total(d.path(), "run-0", 41, "").unwrap(), 1020);
2478        assert_eq!(callgrind_total(d.path(), "run-0", 42, "").unwrap(), 300);
2479        assert_eq!(callgrind_part("summary: 9\n"), Some(9), "older callgrind");
2480        assert_eq!(callgrind_part("events: Ir\n"), None);
2481    }
2482
2483    /// No dump at all — a process that exec'd through something other than
2484    /// an `execve` callgrind could name — is an error, never a count of 0.
2485    #[test]
2486    fn a_callgrind_run_that_dumped_nothing_is_not_a_count() {
2487        let d = tempfile::tempdir().unwrap();
2488        std::fs::write(d.path().join("run-0.41"), "").unwrap();
2489        let err = callgrind_total(d.path(), "run-0", 41, "").unwrap_err();
2490        assert!(format!("{err:#}").contains("execve"), "{err:#}");
2491    }
2492
2493    /// Captured from valgrind 3.22.0 (Ubuntu 24.04) running `git --version`.
2494    /// 3.24.0 (Debian trixie) prints the same summary lines.
2495    const DHAT_3_22: &str = "\
2496==9== DHAT, a dynamic heap analysis tool
2497==9== Copyright (C) 2010-2018, and GNU GPL'd, by Mozilla Foundation
2498==9== Using Valgrind-3.22.0 and LibVEX; rerun with -h for copyright info
2499==9== Command: git --version
2500==9==
2501git version 2.43.0
2502==9==
2503==9== Total:     7,119 bytes in 31 blocks
2504==9== At t-gmax: 6,847 bytes in 25 blocks
2505==9== At t-end:  2,379 bytes in 15 blocks
2506==9== Reads:     1,067 bytes
2507==9== Writes:    1,546 bytes
2508==9==
2509==9== To view the resulting profile, open
2510==9==   file:///usr/libexec/valgrind/dh_view.html
2511==9== in a web browser, click on \"Load...\", and then select the file
2512==9==   /dev/null
2513==9== The text at the bottom explains the abbreviations used in the output.
2514";
2515
2516    #[test]
2517    fn parses_a_dhat_summary() {
2518        assert_eq!(
2519            parse_dhat(DHAT_3_22),
2520            Some(Heap {
2521                blocks: 31,
2522                bytes: 7_119,
2523                peak_bytes: 6_847,
2524            })
2525        );
2526    }
2527
2528    /// Captured from valgrind 3.24.0 running a threaded Python script: the
2529    /// separators matter once counts pass a million.
2530    #[test]
2531    fn parses_counts_past_a_million() {
2532        let s = "==21== Total:     2,626,313 bytes in 2,833 blocks\n\
2533                 ==21== At t-gmax: 1,185,686 bytes in 1,661 blocks\n";
2534        assert_eq!(
2535            parse_dhat(s),
2536            Some(Heap {
2537                blocks: 2_833,
2538                bytes: 2_626_313,
2539                peak_bytes: 1_185_686,
2540            })
2541        );
2542    }
2543
2544    /// Only valgrind's own lines are read: a line without its `==PID==`
2545    /// prefix is never the measurement, however much it looks like one.
2546    #[test]
2547    fn only_valgrinds_own_lines_are_read() {
2548        let s = "Total: 5 bytes in 1 blocks\n\
2549                 ==12== \n\
2550                 ==12== Total:     8,748 bytes in 17 blocks\n\
2551                 ==12== At t-gmax: 8,748 bytes in 17 blocks\n";
2552        assert_eq!(parse_dhat(s).unwrap().blocks, 17);
2553        assert_eq!(
2554            parse_dhat("Total: 5 bytes in 1 blocks\nAt t-gmax: 5 bytes in 1 blocks\n"),
2555            None
2556        );
2557        assert_eq!(valgrind_line("==x== Total:"), None);
2558        assert_eq!(valgrind_line("==== Total:"), None);
2559    }
2560
2561    #[test]
2562    fn a_missing_or_truncated_dhat_summary_is_none() {
2563        assert_eq!(parse_dhat(""), None);
2564        // A run that died before the summary's second line.
2565        assert_eq!(parse_dhat("==3== Total:     1 bytes in 1 blocks\n"), None);
2566        assert_eq!(
2567            parse_dhat(
2568                "==3== Total:     lots bytes in 1 blocks\n==3== At t-gmax: 1 bytes in 1 blocks\n"
2569            ),
2570            None
2571        );
2572    }
2573
2574    /// Totals and peak are judged apart: moving totals mean the work
2575    /// changed, a moving peak alone means threads interleaved differently.
2576    #[test]
2577    fn totals_and_peak_spread_are_judged_apart() {
2578        let h = |blocks, bytes, peak_bytes| Heap {
2579            blocks,
2580            bytes,
2581            peak_bytes,
2582        };
2583        let a = |min, max| Allocated { min, max, runs: 3 };
2584        let steady = a(h(10, 1000, 500), h(10, 1000, 500));
2585        assert_eq!(steady.totals_spread_pct(), 0.0);
2586        assert!(!steady.is_suspect() && !steady.peak_is_unsteady());
2587
2588        let threaded = a(h(10, 1000, 500), h(10, 1000, 510));
2589        assert!((threaded.peak_spread_pct() - 2.0).abs() < 1e-9);
2590        assert!(threaded.peak_is_unsteady() && !threaded.is_suspect());
2591
2592        // The first run refreshed a cache: 1140 blocks, then 496.
2593        let first_run = a(h(496, 2_077_237, 1_790_738), h(1140, 2_227_102, 1_888_914));
2594        assert!(first_run.is_suspect());
2595        assert!((first_run.totals_spread_pct() - 129.84).abs() < 0.01);
2596
2597        // Nothing on one run and something on another has no percentage.
2598        assert!(a(h(0, 0, 0), h(1, 8, 8)).totals_spread_pct().is_infinite());
2599        assert!(a(h(0, 0, 0), h(0, 0, 0)).saw_nothing());
2600        assert!(!steady.saw_nothing());
2601    }
2602
2603    /// The subject's stderr is interleaved with valgrind's; only valgrind's
2604    /// prefixed lines are its summary.
2605    #[test]
2606    fn a_count_printed_by_the_subject_is_not_the_count() {
2607        let s = "I refs: 5\n==7== error: can't open output data file\n==7== I refs:      1,234\nI refs: 9\n";
2608        assert_eq!(parse_irefs(s), Some(1_234));
2609        assert_eq!(parse_irefs("I refs: 5\n"), None);
2610        assert_eq!(
2611            valgrind_lines("==x== no\n== 1== no\n==12== yes\n").collect::<Vec<_>>(),
2612            [" yes"]
2613        );
2614    }
2615
2616    #[test]
2617    fn parses_cachegrind_summary() {
2618        let s = "==12== I refs:      48,349,132\n";
2619        assert_eq!(parse_irefs(s), Some(48_349_132));
2620    }
2621
2622    #[test]
2623    fn missing_summary_is_none_not_panic() {
2624        assert_eq!(parse_irefs("valgrind: command not found"), None);
2625    }
2626
2627    /// What `subject` removes, as configured.
2628    fn removals(settings: &Settings) -> Vec<String> {
2629        subject("true", settings)
2630            .get_envs()
2631            .filter(|(_, v)| v.is_none())
2632            .map(|(k, _)| k.to_string_lossy().into_owned())
2633            .collect()
2634    }
2635
2636    /// Construction-level check. The end-to-end proof that a subject cannot see
2637    /// the token lives in `tests/subject_env.rs`, which runs the real binary.
2638    #[test]
2639    fn subject_commands_remove_the_default_denied_variables() {
2640        let removed = removals(&Settings::default());
2641        for key in Settings::default().scrubbed_env() {
2642            assert!(removed.contains(&key.to_string()), "{key} not removed");
2643        }
2644    }
2645
2646    /// The removal follows the setting rather than a compiled-in list, which is
2647    /// the whole point of routing it through `Settings`.
2648    #[test]
2649    fn the_removal_follows_the_settings() {
2650        let removed = removals(&Settings {
2651            env_deny: vec!["CUSTOM_SECRET".into()],
2652            env_allow: Vec::new(),
2653            ..Settings::default()
2654        });
2655        assert!(removed.contains(&"CUSTOM_SECRET".to_string()));
2656        assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
2657    }
2658
2659    /// An allowed variable is not removed, so a subject that genuinely needs
2660    /// one can still be measured.
2661    #[test]
2662    fn an_allowed_variable_survives() {
2663        let removed = removals(&Settings {
2664            env_deny: vec!["GITHUB_TOKEN".into(), "GH_TOKEN".into()],
2665            env_allow: vec!["GITHUB_TOKEN".into()],
2666            ..Settings::default()
2667        });
2668        assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
2669        assert!(removed.contains(&"GH_TOKEN".to_string()));
2670    }
2671
2672    #[test]
2673    fn zero_runs_is_rejected_not_a_panic() {
2674        let plan = Plan {
2675            cmd: vec!["true".into()],
2676            warmup: 0,
2677            runs: 0,
2678            dir: None,
2679            settings: Settings::default(),
2680        };
2681        assert!(wall(&plan).is_err());
2682    }
2683
2684    #[test]
2685    fn a_failed_subject_is_not_recorded_as_a_fast_run() {
2686        #[cfg(unix)]
2687        let cmd = vec!["/bin/sh".into(), "-c".into(), "exit 42".into()];
2688        #[cfg(windows)]
2689        let cmd = vec!["cmd".into(), "/C".into(), "exit /B 42".into()];
2690
2691        let err = wall(&Plan {
2692            cmd,
2693            warmup: 0,
2694            runs: 1,
2695            dir: None,
2696            settings: Settings::default(),
2697        })
2698        .unwrap_err();
2699
2700        assert!(format!("{err:#}").contains("exited with"), "{err:#}");
2701    }
2702
2703    #[test]
2704    fn wall_reports_min_le_p50_le_max() {
2705        let plan = Plan {
2706            cmd: vec!["true".into()],
2707            warmup: 1,
2708            runs: 5,
2709            dir: None,
2710            settings: Settings::default(),
2711        };
2712        let m = wall(&plan).unwrap();
2713        assert!(m["wall_min_ms"] <= m["wall_p50_ms"]);
2714        assert!(m["wall_p50_ms"] <= m["wall_max_ms"]);
2715        assert_eq!(m["wall_n"], 5.0);
2716    }
2717
2718    /// Every subject gets exactly its warmups and runs, warmups first.
2719    #[test]
2720    fn the_schedule_gives_each_subject_its_counts() {
2721        let counts = [(2, 10), (1, 5), (0, 3)];
2722        let order = schedule(&counts, 7);
2723        for (i, &(warmup, runs)) in counts.iter().enumerate() {
2724            let of = |timed| {
2725                order
2726                    .iter()
2727                    .filter(|s| s.subject == i && s.timed == timed)
2728                    .count()
2729            };
2730            assert_eq!(of(false), warmup as usize, "subject {i} warmups");
2731            assert_eq!(of(true), runs as usize, "subject {i} runs");
2732        }
2733        let first_timed = order.iter().position(|s| s.timed).unwrap();
2734        assert!(order[first_timed..].iter().all(|s| s.timed));
2735    }
2736
2737    #[test]
2738    fn the_same_seed_gives_the_same_order() {
2739        let counts = [(1, 8), (1, 8), (1, 8)];
2740        assert_eq!(schedule(&counts, 42), schedule(&counts, 42));
2741        assert_ne!(schedule(&counts, 42), schedule(&counts, 43));
2742    }
2743
2744    /// Interleaving is the point: with equal counts, every round holds each
2745    /// subject once, and the order is not the same in every round.
2746    #[test]
2747    fn each_round_runs_every_subject_once_in_a_varying_order() {
2748        let order = schedule(&[(0, 20), (0, 20), (0, 20)], 1);
2749        let rounds: Vec<Vec<usize>> = order
2750            .chunks(3)
2751            .map(|r| r.iter().map(|s| s.subject).collect())
2752            .collect();
2753        assert_eq!(rounds.len(), 20);
2754        for r in &rounds {
2755            let mut sorted = r.clone();
2756            sorted.sort();
2757            assert_eq!(sorted, [0, 1, 2], "round {r:?}");
2758        }
2759        assert!(rounds.iter().any(|r| r != &rounds[0]), "never shuffled");
2760    }
2761
2762    /// A subject with half the runs takes part in alternate rounds, not only
2763    /// the first half — otherwise drift late in the run lands on the others.
2764    #[test]
2765    fn a_subject_with_fewer_runs_is_spread_across_the_run() {
2766        let order = schedule(&[(0, 10), (0, 5)], 3);
2767        let fewer: Vec<usize> = order
2768            .iter()
2769            .enumerate()
2770            .filter(|(_, s)| s.subject == 1)
2771            .map(|(i, _)| i)
2772            .collect();
2773        assert_eq!(fewer.len(), 5);
2774        assert!(
2775            *fewer.last().unwrap() >= order.len() - 3,
2776            "last sample of the smaller subject is near the end: {fewer:?} of {}",
2777            order.len()
2778        );
2779    }
2780
2781    #[test]
2782    fn a_benchmark_seed_depends_on_its_name_and_the_run_seed() {
2783        assert_eq!(seed_for(1, "a"), seed_for(1, "a"));
2784        assert_ne!(seed_for(1, "a"), seed_for(1, "b"));
2785        assert_ne!(seed_for(1, "a"), seed_for(2, "a"));
2786    }
2787
2788    #[test]
2789    fn stats_report_the_sample_standard_deviation() {
2790        let m = stats(&[2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]);
2791        assert_eq!(m["wall_min_ms"], 2.0);
2792        assert_eq!(m["wall_max_ms"], 9.0);
2793        assert_eq!(m["wall_mean_ms"], 5.0);
2794        // sqrt(32 / 7)
2795        assert!((m["wall_stddev_ms"] - 2.138_089_935).abs() < 1e-6);
2796        assert_eq!(stats(&[3.0])["wall_stddev_ms"], 0.0);
2797    }
2798
2799    /// A failing subject is dropped; the others still get every sample.
2800    #[cfg(unix)]
2801    #[test]
2802    fn a_failing_subject_does_not_stop_the_others() {
2803        let mk = |name: &str, cmd: &[&str]| Subject {
2804            name: name.into(),
2805            cmd: cmd.iter().map(|s| s.to_string()).collect(),
2806            prepare: None,
2807            setup: None,
2808            setup_dir: None,
2809            check: None,
2810            dir: None,
2811            version_cmd: None,
2812            env: BTreeMap::new(),
2813            vars: BTreeMap::new(),
2814            when: None,
2815            runs: Runs::Fixed(4),
2816            auto: AutoRuns {
2817                budget: Duration::from_secs(30),
2818                min: 5,
2819                max: 50,
2820            },
2821            warmup: 1,
2822            counters: false,
2823            allocations: false,
2824            count_until: Default::default(),
2825            ok_exit_codes: vec![0],
2826            metrics: BTreeMap::new(),
2827        };
2828        let res = interleaved(
2829            &[mk("ok", &["true"]), mk("bad", &["false"])],
2830            5,
2831            &Settings::default(),
2832            &mut Quiet,
2833        );
2834        assert_eq!(res[0].as_ref().unwrap().times.len(), 4);
2835        assert!(format!("{:#}", res[1].as_ref().unwrap_err()).contains("exited with"));
2836    }
2837
2838    /// One number and nothing else; anything a script might print around it
2839    /// is refused rather than picked apart.
2840    #[test]
2841    fn a_metric_value_is_exactly_one_non_negative_number() {
2842        for (text, want) in [
2843            ("1234", 1234.0),
2844            ("1234\n", 1234.0),
2845            ("  \t12.5\r\n", 12.5),
2846            ("0", 0.0),
2847            ("1.5e3", 1500.0),
2848            ("2E-2", 0.02),
2849            ("007", 7.0),
2850        ] {
2851            assert_eq!(parse_metric_value(text).unwrap(), want, "{text:?}");
2852        }
2853        for bad in [
2854            "", "\n", "-1", "+1", ".5", "5.", "1e", "1e+", "nan", "inf", "0x10", "1,234", "12 kB",
2855            "1 2", "1\n2", "size: 3", "1e999",
2856        ] {
2857            assert!(parse_metric_value(bad).is_err(), "accepted {bad:?}");
2858        }
2859    }
2860
2861    fn with_metrics(dir: &Path, env: &[(&str, &str)]) -> Subject {
2862        Subject {
2863            name: "s".into(),
2864            cmd: vec!["true".into()],
2865            prepare: None,
2866            setup: None,
2867            setup_dir: None,
2868            check: None,
2869            dir: Some(dir.to_path_buf()),
2870            version_cmd: None,
2871            env: env
2872                .iter()
2873                .map(|(k, v)| (k.to_string(), v.to_string()))
2874                .collect(),
2875            vars: BTreeMap::new(),
2876            when: None,
2877            runs: Runs::Fixed(1),
2878            auto: AutoRuns {
2879                budget: Duration::from_secs(30),
2880                min: 5,
2881                max: 50,
2882            },
2883            warmup: 0,
2884            counters: false,
2885            allocations: false,
2886            count_until: Default::default(),
2887            ok_exit_codes: vec![0],
2888            metrics: BTreeMap::new(),
2889        }
2890    }
2891
2892    /// A file's size is its length in bytes; a directory has none worth
2893    /// recording, and a missing file is an error that names it.
2894    #[test]
2895    fn a_file_metric_is_its_size_in_bytes() {
2896        let dir = tempfile::tempdir().unwrap();
2897        let file = dir.path().join("bin");
2898        std::fs::write(&file, vec![0u8; 4321]).unwrap();
2899        let s = with_metrics(dir.path(), &[]);
2900        let settings = Settings::default();
2901        assert_eq!(
2902            custom_metric(&MetricSource::File(file), &s, &settings).unwrap(),
2903            4321.0
2904        );
2905        let err = custom_metric(&MetricSource::File(dir.path().into()), &s, &settings).unwrap_err();
2906        assert!(format!("{err:#}").contains("not a regular file"), "{err:#}");
2907        let missing = dir.path().join("missing");
2908        let err = custom_metric(&MetricSource::File(missing), &s, &settings).unwrap_err();
2909        assert!(format!("{err:#}").contains("missing"), "{err:#}");
2910    }
2911
2912    /// A metric command runs where the subject does, with its env, and must
2913    /// exit 0 and print one number. The scrub is checked end to end in
2914    /// `tests/subjects.rs`, which can set a token for tak without touching
2915    /// this test binary's environment.
2916    #[cfg(unix)]
2917    #[test]
2918    fn a_cmd_metric_runs_in_the_subjects_dir_and_env() {
2919        let dir = tempfile::tempdir().unwrap();
2920        std::fs::write(dir.path().join("here"), "").unwrap();
2921        let s = with_metrics(dir.path(), &[("N", "42")]);
2922        let settings = Settings::default();
2923        let sh = |script: &str| {
2924            custom_metric(
2925                &MetricSource::Cmd(vec!["sh".into(), "-c".into(), script.into()]),
2926                &s,
2927                &settings,
2928            )
2929        };
2930        assert_eq!(sh("test -e here && echo $N").unwrap(), 42.0);
2931        let err = format!("{:#}", sh("echo 5; echo broke >&2; exit 3").unwrap_err());
2932        assert!(
2933            err.contains("exit status: 3") && err.contains("broke"),
2934            "{err}"
2935        );
2936        let err = format!("{:#}", sh("echo 'bundle: 12 kB'").unwrap_err());
2937        assert!(err.contains("not one number"), "{err}");
2938        let err = format!("{:#}", sh("yes 1 | head -c 4096").unwrap_err());
2939        assert!(err.contains("more than 1024 bytes"), "{err}");
2940        // Exactly at the cap is still judged as output, not as too much.
2941        let err = format!("{:#}", sh("yes 1 | head -c 1024").unwrap_err());
2942        assert!(err.contains("not one number"), "{err}");
2943        // A command that never stops printing is stopped at the cap, not
2944        // left to fill memory or a disk; `exec` so it is the command itself.
2945        let start = Instant::now();
2946        let err = format!("{:#}", sh("exec yes 1").unwrap_err());
2947        assert!(err.contains("so they were stopped"), "{err}");
2948        assert!(start.elapsed() < Duration::from_secs(4));
2949        // The error at the end of a long log is the one reported, not a line
2950        // from its start.
2951        let err = format!(
2952            "{:#}",
2953            sh("yes 'noise line' | head -c 20000 >&2; echo 'the real error' >&2; exit 2")
2954                .unwrap_err()
2955        );
2956        assert!(err.ends_with("the real error"), "{err}");
2957        assert!(!err.contains("noise"), "{err}");
2958    }
2959
2960    /// A metric command that exits while something it started still holds
2961    /// its stdout has not finished its answer: that is an error rather than
2962    /// whatever number arrived first, it does not hold up the run, and the
2963    /// leftover is stopped rather than left running into the next samples.
2964    #[cfg(unix)]
2965    #[test]
2966    fn a_metric_cmd_leaving_stdout_open_fails_and_is_stopped() {
2967        let err = leftover_metric("sleep 30 & echo $! > pid; echo 7");
2968        assert!(err.contains("stdout open"), "{err}");
2969    }
2970
2971    /// A background writer that goes past the cap only after the command has
2972    /// exited — too late for `capture` to stop the command itself — is still
2973    /// stopped, and the error says what happened.
2974    #[cfg(unix)]
2975    #[test]
2976    fn a_leftover_that_floods_stdout_after_exit_is_stopped() {
2977        let err = leftover_metric("(sleep 0.1; exec yes 1) & echo $! > pid; echo 7");
2978        assert!(
2979            err.contains("more than 1024 bytes") && err.contains("what it started"),
2980            "{err}"
2981        );
2982    }
2983
2984    /// Runs `script` as a metric command whose background process writes its
2985    /// pid to `pid`, and checks that the metric fails promptly and the
2986    /// background process does not outlive it. Returns the error.
2987    #[cfg(unix)]
2988    fn leftover_metric(script: &str) -> String {
2989        let dir = tempfile::tempdir().unwrap();
2990        let s = with_metrics(dir.path(), &[]);
2991        let start = Instant::now();
2992        let err = custom_metric(
2993            &MetricSource::Cmd(vec!["sh".into(), "-c".into(), script.into()]),
2994            &s,
2995            &Settings::default(),
2996        )
2997        .unwrap_err();
2998        assert!(start.elapsed() < Duration::from_secs(4));
2999        let pid = std::fs::read_to_string(dir.path().join("pid")).unwrap();
3000        let pid = pid.trim();
3001        // SIGKILL is delivered asynchronously; give it a moment to land.
3002        // `running`, not `kill -0`: the orphan may linger as a zombie.
3003        let until = Instant::now() + Duration::from_secs(2);
3004        while running(pid) && Instant::now() < until {
3005            std::thread::sleep(Duration::from_millis(20));
3006        }
3007        assert!(
3008            !running(pid),
3009            "the background process {pid} was left running"
3010        );
3011        format!("{err:#}")
3012    }
3013
3014    /// Runs `sh -c script` as a `version_cmd` with the given deadline.
3015    #[cfg(unix)]
3016    fn version_sh(script: &str, env: &[(&str, &str)], timeout: Duration) -> Result<String> {
3017        let settings = Settings::default();
3018        let env: BTreeMap<String, String> = env
3019            .iter()
3020            .map(|(k, v)| (k.to_string(), v.to_string()))
3021            .collect();
3022        let site = Site {
3023            dir: None,
3024            env: &env,
3025            settings: &settings,
3026        };
3027        version_once(&["sh".into(), "-c".into(), script.into()], &site, timeout)
3028    }
3029
3030    /// The first non-empty line, from stdout or else stderr; a failure is an
3031    /// error naming the command, which the caller turns into a warning.
3032    #[cfg(unix)]
3033    #[test]
3034    fn a_version_is_the_first_line_printed() {
3035        let sh = |script: &str| version_sh(script, &[("V", "9.9")], VERSION_TIMEOUT);
3036        assert_eq!(
3037            sh("printf '\\n  tool %s  \\nbuilt today\\n' \"$V\"").unwrap(),
3038            "tool 9.9",
3039            "first non-empty line, trimmed, in the subject's env"
3040        );
3041        assert_eq!(sh("echo 'java 21' >&2").unwrap(), "java 21");
3042        let err = format!("{:#}", sh("echo nope >&2; exit 2").unwrap_err());
3043        assert!(err.contains("`sh`") && err.contains("nope"), "{err}");
3044        assert!(sh("true").is_err(), "no output is no version");
3045    }
3046
3047    /// Output past the cap is read and dropped, so a command that prints a
3048    /// lot still finishes, and its first line is what counts.
3049    #[cfg(unix)]
3050    #[test]
3051    fn a_version_is_read_from_a_capped_prefix() {
3052        let sh = |script: &str| version_sh(script, &[], VERSION_TIMEOUT);
3053        assert_eq!(sh("yes 'tool 1.0' | head -c 10000000").unwrap(), "tool 1.0");
3054        assert_eq!(
3055            sh("yes 'java 21' | head -c 10000000 >&2").unwrap(),
3056            "java 21",
3057            "a flood on stderr"
3058        );
3059        let kept = Mutex::new(Vec::new());
3060        let mut src = std::io::Cursor::new(vec![7u8; 100]);
3061        let overflow = std::sync::atomic::AtomicBool::new(false);
3062        keep_prefix(&mut src, 10, &kept, &overflow, None);
3063        assert_eq!(kept.lock().unwrap().len(), 10, "only the cap is kept");
3064        assert_eq!(
3065            src.position(),
3066            100,
3067            "the rest is read, not left in the pipe"
3068        );
3069        assert!(overflow.into_inner(), "and going past the cap is noticed");
3070
3071        let (kept, overflow) = (
3072            Mutex::new(Vec::new()),
3073            std::sync::atomic::AtomicBool::new(false),
3074        );
3075        keep_prefix(
3076            std::io::Cursor::new(vec![7u8; 10]),
3077            10,
3078            &kept,
3079            &overflow,
3080            None,
3081        );
3082        assert!(!overflow.into_inner(), "exactly the cap is not past it");
3083    }
3084
3085    /// A failing command that prints a lot — a usage dump after an unknown
3086    /// flag — is a failure, not a version, however long its output.
3087    #[cfg(unix)]
3088    #[test]
3089    fn a_failing_version_cmd_is_an_error_even_past_the_cap() {
3090        let err = version_sh(
3091            "yes 'usage: tool [flags]' | head -c 100000; echo 'unknown flag' >&2; exit 1",
3092            &[],
3093            VERSION_TIMEOUT,
3094        )
3095        .unwrap_err();
3096        let err = format!("{err:#}");
3097        assert!(
3098            err.contains("exited with") && err.contains("unknown flag"),
3099            "{err}"
3100        );
3101    }
3102
3103    /// One that never finishes, even one that only floods stderr, is stopped
3104    /// at the deadline and says so.
3105    #[cfg(unix)]
3106    #[test]
3107    fn a_version_cmd_that_never_finishes_is_stopped() {
3108        let t = Duration::from_millis(300);
3109        let began = Instant::now();
3110        // `exec`, so the process stopped at the deadline is the flood itself.
3111        for script in ["exec yes 'tool 2.0' >&2", "exec sleep 30"] {
3112            let err = format!("{:#}", version_sh(script, &[], t).unwrap_err());
3113            assert!(err.contains("did not finish"), "{script}: {err}");
3114        }
3115        assert!(
3116            began.elapsed() < Duration::from_secs(5),
3117            "{:?}",
3118            began.elapsed()
3119        );
3120    }
3121
3122    /// A timeout stops what the command started too, not just the command:
3123    /// a helper left running would compete with the samples that follow.
3124    #[cfg(unix)]
3125    #[test]
3126    fn a_timeout_stops_the_whole_process_group() {
3127        let dir = tempfile::tempdir().unwrap();
3128        let pidfile = dir.path().join("pid");
3129        let script = format!("sleep 30 & echo $! > '{}'; wait", pidfile.display());
3130        let err = version_sh(&script, &[], Duration::from_millis(300)).unwrap_err();
3131        assert!(format!("{err:#}").contains("did not finish"), "{err:#}");
3132        let pid = std::fs::read_to_string(&pidfile).unwrap();
3133        let pid = pid.trim();
3134        let until = Instant::now() + Duration::from_secs(2);
3135        while running(pid) && Instant::now() < until {
3136            std::thread::sleep(Duration::from_millis(20));
3137        }
3138        assert!(
3139            !running(pid),
3140            "the background sleep {pid} outlived the timeout"
3141        );
3142    }
3143
3144    /// Whether `pid` is still running. A zombie is not: once the shell that
3145    /// started the process is killed with it, only PID 1 can reap it, and in
3146    /// a container whose PID 1 does not reap orphans it stays a zombie —
3147    /// which `kill -0` still reports as present.
3148    #[cfg(unix)]
3149    fn running(pid: &str) -> bool {
3150        #[cfg(target_os = "linux")]
3151        {
3152            // The state follows the `)` closing the command name, which may
3153            // itself contain spaces or parentheses, so look for the last one.
3154            let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) else {
3155                return false;
3156            };
3157            let state = stat
3158                .rfind(')')
3159                .and_then(|i| stat[i + 1..].trim_start().chars().next());
3160            !matches!(state, None | Some('Z' | 'X' | 'x'))
3161        }
3162        #[cfg(not(target_os = "linux"))]
3163        {
3164            let Ok(out) = Command::new("ps")
3165                .args(["-o", "stat=", "-p", pid])
3166                .stderr(Stdio::null())
3167                .output()
3168            else {
3169                return false;
3170            };
3171            let stat = String::from_utf8_lossy(&out.stdout);
3172            let stat = stat.trim();
3173            out.status.success() && !stat.is_empty() && !stat.starts_with('Z')
3174        }
3175    }
3176
3177    /// A background process that inherits the pipes keeps them open after
3178    /// the command exits; the version it printed still comes back promptly.
3179    #[cfg(unix)]
3180    #[test]
3181    fn a_background_process_holding_the_pipe_does_not_hold_up_the_version() {
3182        let began = Instant::now();
3183        let v = version_sh("sleep 5 & echo 'tool 3.0'", &[], VERSION_TIMEOUT).unwrap();
3184        assert_eq!(v, "tool 3.0");
3185        assert!(
3186            began.elapsed() < Duration::from_secs(3),
3187            "{:?}",
3188            began.elapsed()
3189        );
3190    }
3191
3192    /// A prepare step that fails stops its subject, and says it was prepare.
3193    #[cfg(unix)]
3194    #[test]
3195    fn a_failing_prepare_is_reported_as_prepare() {
3196        let res = interleaved(
3197            &[Subject {
3198                name: "x".into(),
3199                cmd: vec!["true".into()],
3200                prepare: Some(vec![
3201                    "/bin/sh".into(),
3202                    "-c".into(),
3203                    "echo nope >&2; exit 3".into(),
3204                ]),
3205                setup: None,
3206                setup_dir: None,
3207                check: None,
3208                dir: None,
3209                version_cmd: None,
3210                env: BTreeMap::new(),
3211                vars: BTreeMap::new(),
3212                when: None,
3213                runs: Runs::Fixed(1),
3214                auto: AutoRuns {
3215                    budget: Duration::from_secs(30),
3216                    min: 5,
3217                    max: 50,
3218                },
3219                warmup: 0,
3220                counters: false,
3221                allocations: false,
3222                count_until: Default::default(),
3223                ok_exit_codes: vec![0],
3224                metrics: BTreeMap::new(),
3225            }],
3226            0,
3227            &Settings::default(),
3228            &mut Quiet,
3229        );
3230        let msg = format!("{:#}", res[0].as_ref().unwrap_err());
3231        assert!(msg.contains("prepare") && msg.contains("nope"), "{msg}");
3232    }
3233
3234    /// A subject whose command bumps a counter file and whose check fails on
3235    /// every even-numbered run, warmups included in the count.
3236    #[cfg(unix)]
3237    fn alternating(dir: &Path, warmup: u32, runs: u32) -> Subject {
3238        Subject {
3239            name: "alt".into(),
3240            cmd: vec![
3241                "/bin/sh".into(),
3242                "-c".into(),
3243                "echo x >> n".into(),
3244            ],
3245            prepare: None,
3246            setup: None,
3247            setup_dir: None,
3248            check: Some(vec![
3249                "/bin/sh".into(),
3250                "-c".into(),
3251                // Arithmetic strips the padding macOS `wc -l` puts before the count.
3252                "echo check >> checked; runs=$(( $(wc -l < n) )); test $(( runs % 2 )) = 1 || { echo \"run $runs is even\" >&2; exit 1; }".into(),
3253            ]),
3254            version_cmd: None,
3255            dir: Some(dir.to_path_buf()),
3256            env: BTreeMap::new(),
3257            vars: BTreeMap::new(),
3258            when: None,
3259            runs: Runs::Fixed(runs),
3260            auto: AutoRuns {
3261                budget: Duration::from_secs(30),
3262                min: 5,
3263                max: 50,
3264            },
3265            warmup,
3266            counters: false,
3267            allocations: false,
3268            count_until: Default::default(),
3269            ok_exit_codes: vec![0],
3270            metrics: BTreeMap::new(),
3271        }
3272    }
3273
3274    /// A failing check marks its sample and the subject keeps every one;
3275    /// warmups are never checked.
3276    #[cfg(unix)]
3277    #[test]
3278    fn a_failing_check_marks_the_sample_without_dropping_the_subject() {
3279        let dir = tempfile::tempdir().unwrap();
3280        let res = interleaved(
3281            &[alternating(dir.path(), 1, 6)],
3282            0,
3283            &Settings::default(),
3284            &mut Quiet,
3285        );
3286        let s = res[0].as_ref().unwrap();
3287        assert_eq!(s.times.len(), 6);
3288        // Run 1 is the warmup; timed runs 2..=7 fail on the even ones.
3289        assert_eq!(s.checks, [false, true, false, true, false, true]);
3290        assert_eq!(s.passed(), 3);
3291        assert!(
3292            s.first_failure
3293                .as_deref()
3294                .unwrap()
3295                .contains("run 2 is even"),
3296            "{s:?}"
3297        );
3298        let checked = std::fs::read_to_string(dir.path().join("checked")).unwrap();
3299        assert_eq!(checked.lines().count(), 6, "no check after the warmup");
3300    }
3301
3302    /// `ok_exit_codes` belong to the command, not its check: a command that
3303    /// exits 1 under `[0, 1]` is kept with its code, and a check that exits 1
3304    /// is still a failed check.
3305    #[cfg(unix)]
3306    #[test]
3307    fn ok_exit_codes_do_not_pass_a_check_that_exits_1() {
3308        let dir = tempfile::tempdir().unwrap();
3309        let mut s = alternating(dir.path(), 0, 2);
3310        s.cmd = vec!["/bin/sh".into(), "-c".into(), "exit 1".into()];
3311        s.check = Some(vec!["/bin/sh".into(), "-c".into(), "exit 1".into()]);
3312        s.ok_exit_codes = vec![0, 1];
3313        let res = interleaved(&[s], 0, &Settings::default(), &mut Quiet);
3314        let s = res[0].as_ref().unwrap();
3315        assert_eq!(s.exit_codes, [1, 1]);
3316        assert_eq!(s.checks, [false, false]);
3317        assert_eq!(s.passed(), 0);
3318    }
3319
3320    /// A check that cannot be started is a configuration mistake, not six
3321    /// failed samples.
3322    #[cfg(unix)]
3323    #[test]
3324    fn a_check_that_cannot_start_drops_the_subject() {
3325        let dir = tempfile::tempdir().unwrap();
3326        let mut s = alternating(dir.path(), 0, 2);
3327        s.check = Some(vec!["/nonexistent/tak-check".into()]);
3328        let res = interleaved(&[s], 0, &Settings::default(), &mut Quiet);
3329        let msg = format!("{:#}", res[0].as_ref().unwrap_err());
3330        assert!(msg.contains("failed to spawn check"), "{msg}");
3331    }
3332
3333    /// A passing step that leaves a process writing to stderr returns at
3334    /// once, and that process is left alone: a fixture server started by
3335    /// `setup` must survive logging after the step is done, so its later
3336    /// write to stderr must succeed rather than die of SIGPIPE (exit 141).
3337    #[cfg(unix)]
3338    #[test]
3339    fn a_process_left_by_a_passing_step_can_still_write_to_stderr() {
3340        let dir = tempfile::tempdir().unwrap();
3341        let env = BTreeMap::new();
3342        let settings = Settings::default();
3343        let site = Site {
3344            dir: Some(dir.path()),
3345            env: &env,
3346            settings: &settings,
3347        };
3348        const N: usize = 10;
3349        let start = Instant::now();
3350        for i in 0..N {
3351            let script = format!(
3352                "{{ sh -c 'sleep 1; echo late >&2'; echo $? > s{i}.tmp && mv s{i}.tmp s{i}; }} & exit 0"
3353            );
3354            let step = ["/bin/sh".to_string(), "-c".into(), script];
3355            assert_eq!(untimed("setup", &step, &site).unwrap(), None);
3356        }
3357        let took = start.elapsed();
3358        assert!(took < Duration::from_secs(2), "{N} passes took {took:?}");
3359
3360        let deadline = Instant::now() + Duration::from_secs(20);
3361        let statuses: Vec<String> = (0..N)
3362            .map(|i| {
3363                loop {
3364                    if let Ok(s) = std::fs::read_to_string(dir.path().join(format!("s{i}"))) {
3365                        break s.trim().to_string();
3366                    }
3367                    assert!(Instant::now() < deadline, "leftover {i} never finished");
3368                    std::thread::sleep(Duration::from_millis(50));
3369                }
3370            })
3371            .collect();
3372        assert!(statuses.iter().all(|s| s == "0"), "{statuses:?}");
3373    }
3374
3375    /// An observer that records what it was told.
3376    #[derive(Default)]
3377    struct Log {
3378        plans: Vec<Vec<u64>>,
3379        finished: Vec<usize>,
3380        /// Every event in order, as `setup:N`, `start:N` and `drop:N`.
3381        events: Vec<String>,
3382    }
3383    impl Observer for Log {
3384        fn planned(&mut self, remaining: &[u64]) {
3385            self.plans.push(remaining.to_vec());
3386        }
3387        fn setting_up(&mut self, subject: usize) {
3388            self.events.push(format!("setup:{subject}"));
3389        }
3390        fn started(&mut self, subject: usize) {
3391            self.events.push(format!("start:{subject}"));
3392        }
3393        fn dropped(&mut self, subject: usize) {
3394            self.events.push(format!("drop:{subject}"));
3395        }
3396        fn finished(&mut self, subject: usize, _: Duration) {
3397            self.finished.push(subject);
3398        }
3399    }
3400
3401    /// Every setup runs once, before any sample; a failing one drops its
3402    /// subject before it takes a sample, and says it was setup.
3403    #[cfg(unix)]
3404    #[test]
3405    fn setups_run_once_first_and_a_failing_one_drops_its_subject() {
3406        let sh = |script: &str| Some(["/bin/sh", "-c", script].map(String::from).to_vec());
3407        let mk = |name: &str, setup: Option<Vec<String>>| Subject {
3408            name: name.into(),
3409            cmd: vec!["true".into()],
3410            prepare: None,
3411            setup,
3412            setup_dir: None,
3413            check: None,
3414            version_cmd: None,
3415            dir: None,
3416            env: BTreeMap::new(),
3417            vars: BTreeMap::new(),
3418            when: None,
3419            runs: Runs::Auto,
3420            auto: AutoRuns {
3421                budget: Duration::from_secs(30),
3422                min: 2,
3423                max: 2,
3424            },
3425            warmup: 1,
3426            counters: false,
3427            allocations: false,
3428            count_until: Default::default(),
3429            ok_exit_codes: vec![0],
3430            metrics: BTreeMap::new(),
3431        };
3432        let mut log = Log::default();
3433        let res = interleaved(
3434            &[
3435                mk("ok", sh("true")),
3436                mk("bad", sh("echo no fixture >&2; exit 2")),
3437                mk("none", None),
3438            ],
3439            3,
3440            &Settings::default(),
3441            &mut log,
3442        );
3443        assert_eq!(log.events[..3], ["setup:0", "setup:1", "drop:1"]);
3444        assert!(!log.events[3..].iter().any(|e| e.starts_with("setup:")));
3445        assert!(!log.events.contains(&"start:1".to_string()));
3446        assert_eq!(res[0].as_ref().unwrap().times.len(), 2);
3447        assert_eq!(res[2].as_ref().unwrap().times.len(), 2);
3448        let msg = format!("{:#}", res[1].as_ref().unwrap_err());
3449        assert!(msg.contains("setup") && msg.contains("no fixture"), "{msg}");
3450        // Setup is not a sample: only warmups and runs finish.
3451        assert_eq!(log.finished.len(), 2 * (1 + 2));
3452    }
3453
3454    /// `runs = "auto"` sizes each subject from its own speed: a subject too
3455    /// slow for the budget gets the floor, a faster one gets more. Uses real
3456    /// sleeps, so the fast count is only bounded, not exact. The fast subject
3457    /// needs a sample under budget/3 to beat the floor, so the margin is 20x:
3458    /// at 6.5x a loaded macOS runner pushed it to the floor of 2 and failed CI.
3459    #[cfg(unix)]
3460    #[test]
3461    fn auto_runs_give_a_slow_subject_the_floor_and_a_fast_one_more() {
3462        let mk = |name: &str, secs: &str, warmup: u32| Subject {
3463            name: name.into(),
3464            cmd: vec!["sleep".into(), secs.into()],
3465            prepare: None,
3466            setup: None,
3467            setup_dir: None,
3468            check: None,
3469            dir: None,
3470            version_cmd: None,
3471            env: BTreeMap::new(),
3472            vars: BTreeMap::new(),
3473            when: None,
3474            runs: Runs::Auto,
3475            auto: AutoRuns {
3476                budget: Duration::from_millis(600),
3477                min: 2,
3478                max: 6,
3479            },
3480            warmup,
3481            counters: false,
3482            allocations: false,
3483            count_until: Default::default(),
3484            ok_exit_codes: vec![0],
3485            metrics: BTreeMap::new(),
3486        };
3487        let mut log = Log::default();
3488        // The slow one has no warmup, so its first kept sample sizes it.
3489        let res = interleaved(
3490            &[mk("fast", "0.01", 1), mk("slow", "0.5", 0)],
3491            9,
3492            &Settings::default(),
3493            &mut log,
3494        );
3495        let fast = res[0].as_ref().unwrap().times.len();
3496        let slow = res[1].as_ref().unwrap().times.len();
3497        assert_eq!(slow, 2, "0.6s budget / 0.5s sample is below the floor");
3498        assert!(fast > slow && fast <= 6, "fast got {fast}");
3499        // Planned on the floors first, then on the settled counts.
3500        assert_eq!(log.plans[0], [1 + 2, 2]);
3501        assert_eq!(log.plans.len(), 2);
3502        assert_eq!(log.finished.len(), 1 + fast + slow);
3503    }
3504
3505    #[test]
3506    fn steady_samples_raise_no_warning() {
3507        assert!(warnings(&[10.0, 10.2, 9.9, 10.1, 10.0, 10.3]).is_empty());
3508        assert!(warnings(&[10.0, 50.0]).is_empty(), "too few to judge");
3509    }
3510
3511    #[test]
3512    fn a_spike_is_an_outlier() {
3513        let w = warnings(&[10.0, 10.2, 9.9, 10.1, 40.0, 10.0, 10.1]);
3514        assert_eq!(w.len(), 1, "{w:?}");
3515        assert!(
3516            w[0].starts_with("1 of 7 samples are slow outliers"),
3517            "{w:?}"
3518        );
3519    }
3520
3521    #[test]
3522    fn a_slow_first_sample_is_called_out() {
3523        let w = warnings(&[35.0, 10.0, 10.2, 9.9, 10.1, 10.0]);
3524        assert!(
3525            w.iter().any(|m| m.contains("first sample took 3.5x")),
3526            "{w:?}"
3527        );
3528    }
3529
3530    /// With most samples identical the median deviation is zero; a spike
3531    /// must still be reported.
3532    #[test]
3533    fn a_spike_among_identical_samples_is_still_an_outlier() {
3534        let w = warnings(&[10.0, 10.0, 10.0, 100.0, 10.0]);
3535        assert!(w.iter().any(|m| m.contains("slow outliers")), "{w:?}");
3536        assert!(
3537            warnings(&[10.0; 6]).is_empty(),
3538            "identical samples are fine"
3539        );
3540    }
3541
3542    /// A fast outlier is the minimum, so it is reported as such rather than
3543    /// reassured away.
3544    #[test]
3545    fn a_fast_outlier_is_flagged_as_possibly_the_minimum() {
3546        let w = warnings(&[100.0, 101.0, 99.0, 102.0, 10.0, 100.0]);
3547        assert!(
3548            w.iter()
3549                .any(|m| m.contains("fast outliers") && m.contains("minimum")),
3550            "{w:?}"
3551        );
3552    }
3553
3554    /// Several identical spikes over a flat majority are all caught, not
3555    /// hidden by a spread they themselves inflate.
3556    #[test]
3557    fn several_spikes_over_a_flat_majority_are_caught() {
3558        let w = warnings(&[10.0, 10.0, 10.0, 10.0, 40.0, 45.0]);
3559        assert!(
3560            w.iter()
3561                .any(|m| m.starts_with("2 of 6 samples are slow outliers")),
3562            "{w:?}"
3563        );
3564        assert!(
3565            warnings(&[10.0, 10.0, 10.0, 11.0, 10.0]).is_empty(),
3566            "10% is not a spike"
3567        );
3568    }
3569}