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