use crate::config::{AutoRuns, DEFAULT_OK_EXIT_CODES, MetricSource, Runs, SELF_TOOL, Subject};
use crate::settings::Settings;
use anyhow::{Context, Result, bail};
use std::collections::BTreeMap;
use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use std::time::Instant;
#[derive(Debug, Clone)]
pub struct Plan {
pub cmd: Vec<String>,
pub warmup: u32,
pub runs: u32,
pub dir: Option<std::path::PathBuf>,
pub settings: Settings,
}
fn subject(bin: &str, settings: &Settings) -> Command {
let mut c = Command::new(bin);
for key in settings.scrubbed_env() {
c.env_remove(key);
}
c
}
#[derive(Debug, Clone, Copy)]
struct Site<'a> {
dir: Option<&'a Path>,
env: &'a BTreeMap<String, String>,
settings: &'a Settings,
}
fn command(argv: &[String], site: &Site) -> Result<Command> {
let (bin, args) = argv.split_first().context("empty command")?;
let mut c = subject(bin, site.settings);
c.args(args).envs(site.env);
if let Some(d) = site.dir {
c.current_dir(d);
}
#[cfg(unix)]
if tracked::OWN_GROUPS.load(std::sync::atomic::Ordering::SeqCst) {
std::os::unix::process::CommandExt::process_group(&mut c, 0);
}
Ok(c)
}
fn run_tracked(c: &mut Command) -> std::io::Result<std::process::ExitStatus> {
let mut child = c.spawn()?;
tracked::started(child.id());
let status = child.wait();
tracked::finished();
status
}
#[cfg(unix)]
pub fn use_own_groups() {
tracked::OWN_GROUPS.store(true, std::sync::atomic::Ordering::SeqCst);
}
#[cfg(unix)]
pub fn stop_running() {
use std::sync::atomic::Ordering::SeqCst;
tracked::STOPPED.store(true, SeqCst);
tracked::kill_all();
}
mod tracked {
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering::SeqCst};
pub(super) static OWN_GROUPS: AtomicBool = AtomicBool::new(false);
pub(super) static STOPPED: AtomicBool = AtomicBool::new(false);
static GROUPS: Mutex<Groups> = Mutex::new(Groups::new());
#[derive(Debug, Default, PartialEq)]
pub(super) struct Groups {
running: i32,
left: Vec<i32>,
}
impl Groups {
pub(super) const fn new() -> Groups {
Groups {
running: 0,
left: Vec::new(),
}
}
pub(super) fn start(&mut self, pgid: i32) {
self.running = pgid;
}
pub(super) fn finish(&mut self, alive: impl Fn(i32) -> bool) {
self.left.retain(|g| alive(*g));
if self.running > 0 && alive(self.running) {
self.left.push(self.running);
}
self.running = 0;
}
pub(super) fn targets(&self) -> Vec<i32> {
std::iter::once(self.running)
.filter(|g| *g > 0)
.chain(self.left.iter().copied())
.collect()
}
}
fn groups() -> std::sync::MutexGuard<'static, Groups> {
GROUPS.lock().unwrap_or_else(|e| e.into_inner())
}
pub(super) fn started(pid: u32) {
if !OWN_GROUPS.load(SeqCst) {
return;
}
groups().start(pid as i32);
if STOPPED.load(SeqCst) {
kill(pid as i32);
}
}
pub(super) fn finished() {
if OWN_GROUPS.load(SeqCst) {
groups().finish(alive);
}
}
pub(super) fn kill_all() {
for g in groups().targets() {
kill(g);
}
}
#[cfg(unix)]
fn alive(pgid: i32) -> bool {
unsafe { libc::killpg(pgid, 0) == 0 }
}
#[cfg(not(unix))]
fn alive(_pgid: i32) -> bool {
false
}
#[cfg(unix)]
pub(super) fn kill(pgid: i32) {
if pgid > 0 {
unsafe {
libc::killpg(pgid, libc::SIGKILL);
}
}
}
#[cfg(not(unix))]
pub(super) fn kill(_pgid: i32) {}
#[cfg(test)]
mod tests {
use super::Groups;
#[test]
fn a_group_is_never_untracked_while_it_has_members() {
let mut g = Groups::new();
assert!(g.targets().is_empty());
g.start(10);
assert_eq!(g.targets(), [10]);
g.finish(|p| p == 10);
assert_eq!(g.targets(), [10]);
g.start(20);
assert_eq!(g.targets(), [20, 10]);
g.finish(|p| p == 10);
assert_eq!(g.targets(), [10]);
g.start(30);
g.finish(|_| false);
assert!(g.targets().is_empty());
assert_eq!(g, Groups::new());
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Sample {
pub ms: f64,
pub exit_code: i32,
}
fn accepted(bin: &str, status: std::process::ExitStatus, ok: &[i32], via: &str) -> Result<i32> {
match status.code() {
Some(code) if ok.contains(&code) => Ok(code),
_ if ok == DEFAULT_OK_EXIT_CODES => {
bail!("benchmark subject `{bin}` exited with {status}{via}")
}
_ => bail!(
"benchmark subject `{bin}` exited with {status}{via}, and ok_exit_codes is {}",
ok.iter().map(i32::to_string).collect::<Vec<_>>().join(", ")
),
}
}
fn time_once(cmd: &[String], site: &Site, ok: &[i32]) -> Result<Sample> {
let mut c = command(cmd, site)?;
c.stdout(Stdio::null()).stderr(Stdio::null());
let bin = &cmd[0];
let start = Instant::now();
let mut child = c
.spawn()
.with_context(|| format!("failed to spawn `{bin}`"))?;
tracked::started(child.id());
let status = child.wait();
let ms = start.elapsed().as_secs_f64() * 1000.0;
tracked::finished();
let status = status.with_context(|| format!("failed to wait for `{bin}`"))?;
let exit_code = accepted(bin, status, ok, "")?;
Ok(Sample { ms, exit_code })
}
const UNTIMED_STDERR_TAIL: usize = 4096;
fn prepare_once(cmd: &[String], site: &Site) -> Result<()> {
required("prepare", cmd, site)
}
fn required(what: &str, cmd: &[String], site: &Site) -> Result<()> {
match untimed(what, cmd, site)? {
None => Ok(()),
Some(failure) => bail!("{failure}"),
}
}
fn check_once(cmd: &[String], site: &Site) -> Result<Option<String>> {
untimed("check", cmd, site)
}
fn untimed(step: &str, cmd: &[String], site: &Site) -> Result<Option<String>> {
let mut c = command(cmd, site)?;
let bin = &cmd[0];
let err = tempfile::tempfile()
.with_context(|| format!("failed to create a file for {step} `{bin}`'s stderr"))?;
let reader = err
.try_clone()
.with_context(|| format!("failed to create a file for {step} `{bin}`'s stderr"))?;
c.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::from(err));
let status = run_tracked(&mut c).with_context(|| format!("failed to spawn {step} `{bin}`"))?;
if status.success() {
return Ok(None);
}
let tail = stderr_tail(&reader).unwrap_or_default();
let stderr = String::from_utf8_lossy(&tail);
Ok(Some(match stderr.lines().rfind(|l| !l.trim().is_empty()) {
Some(last) => format!("{step} `{bin}` exited with {status}: {}", last.trim()),
None => format!("{step} `{bin}` exited with {status}"),
}))
}
const METRIC_OUTPUT_MAX: usize = 1024;
pub fn custom_metric(source: &MetricSource, s: &Subject, settings: &Settings) -> Result<f64> {
match source {
MetricSource::File(path) => {
let meta = std::fs::metadata(path)
.with_context(|| format!("could not read the size of {}", path.display()))?;
if !meta.is_file() {
bail!("{} is not a regular file", path.display());
}
Ok(meta.len() as f64)
}
MetricSource::Cmd(argv) => {
let site = Site {
dir: s.dir.as_deref(),
env: &s.env,
settings,
};
metric_cmd_once(argv, &site)
}
}
}
fn metric_cmd_once(argv: &[String], site: &Site) -> Result<f64> {
let bin = &argv[0];
let out = capture(argv, site, None, METRIC_OUTPUT_MAX, true)?;
if out.overflowed || out.stdout_open {
stop_leftovers(out.pgid);
}
if out.overflowed {
bail!(
"`{bin}` and what it started printed more than {METRIC_OUTPUT_MAX} bytes, so they were \
stopped; a metric command prints one number and nothing else"
);
}
if out.stdout_open {
bail!(
"`{bin}` exited but left a process holding its stdout open, so that was stopped; \
a metric command must finish its output before it exits"
);
}
if !out.status.success() {
bail!(
"`{bin}` exited with {}: {}",
out.status,
last_line(&out.stderr_tail)
);
}
let text = std::str::from_utf8(&out.stdout)
.map_err(|_| anyhow::anyhow!("`{bin}` printed something that is not UTF-8"))?;
parse_metric_value(text).with_context(|| format!("`{bin}`"))
}
pub fn parse_metric_value(text: &str) -> Result<f64> {
let t = text.trim_matches(|c: char| c.is_ascii_whitespace());
if t.is_empty() {
bail!("printed nothing; a metric command prints one number");
}
let bytes = t.as_bytes();
let digits = |i: &mut usize| {
let start = *i;
while *i < bytes.len() && bytes[*i].is_ascii_digit() {
*i += 1;
}
*i > start
};
let mut i = 0;
let mut ok = digits(&mut i);
if ok && i < bytes.len() && bytes[i] == b'.' {
i += 1;
ok = digits(&mut i);
}
if ok && i < bytes.len() && (bytes[i] == b'e' || bytes[i] == b'E') {
i += 1;
if i < bytes.len() && (bytes[i] == b'+' || bytes[i] == b'-') {
i += 1;
}
ok = digits(&mut i);
}
if !ok || i != bytes.len() {
bail!(
"printed {t:?}, not one number; a metric command prints a single non-negative \
number such as `1234` or `12.5`, and nothing else"
);
}
let v: f64 = t
.parse()
.with_context(|| format!("printed {t:?}, which is not a number"))?;
if !v.is_finite() {
bail!("printed {t:?}, which is too large to record");
}
Ok(v)
}
fn stderr_tail(f: &std::fs::File) -> std::io::Result<Vec<u8>> {
let len = f.metadata()?.len();
let start = len.saturating_sub(UNTIMED_STDERR_TAIL as u64);
let mut buf = vec![0u8; (len - start) as usize];
let mut filled = 0;
while filled < buf.len() {
let n = read_at(f, &mut buf[filled..], start + filled as u64)?;
if n == 0 {
break;
}
filled += n;
}
buf.truncate(filled);
Ok(buf)
}
#[cfg(unix)]
fn read_at(f: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result<usize> {
std::os::unix::fs::FileExt::read_at(f, buf, offset)
}
#[cfg(windows)]
fn read_at(f: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result<usize> {
std::os::windows::fs::FileExt::seek_read(f, buf, offset)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Slot {
pub subject: usize,
pub timed: bool,
}
pub fn schedule(counts: &[(u32, u32)], seed: u64) -> Vec<Slot> {
let mut rng = fastrand::Rng::with_seed(seed);
let warmups: Vec<u64> = counts.iter().map(|&(w, _)| u64::from(w)).collect();
let runs: Vec<u64> = counts.iter().map(|&(_, r)| u64::from(r)).collect();
let mut out = rounds(&warmups, false, &mut rng);
out.extend(rounds(&runs, true, &mut rng));
out
}
fn rounds(count: &[u64], timed: bool, rng: &mut fastrand::Rng) -> Vec<Slot> {
let total = count.iter().copied().max().unwrap_or(0);
let mut out = Vec::new();
for round in 0..total {
let mut due: Vec<usize> = (0..count.len())
.filter(|&i| (round + 1) * count[i] / total > round * count[i] / total)
.collect();
rng.shuffle(&mut due);
out.extend(due.into_iter().map(|subject| Slot { subject, timed }));
}
out
}
pub fn seed_for(seed: u64, bench: &str) -> u64 {
bench.bytes().fold(seed ^ 0xcbf2_9ce4_8422_2325, |h, b| {
(h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)
})
}
pub trait Observer {
fn planned(&mut self, _remaining: &[u64]) {}
fn setting_up(&mut self, _subject: usize) {}
fn set_up(&mut self, _subject: usize) -> Result<()> {
Ok(())
}
fn before_run(&mut self, _subject: usize) -> Result<()> {
Ok(())
}
fn started(&mut self, _subject: usize) {}
fn finished(&mut self, _subject: usize, _elapsed: Duration) {}
fn dropped(&mut self, _subject: usize) {}
}
pub struct Quiet;
impl Observer for Quiet {}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Samples {
pub times: Vec<f64>,
pub checks: Vec<bool>,
pub exit_codes: Vec<i32>,
pub first_failure: Option<String>,
}
impl Samples {
pub fn passed(&self) -> usize {
self.checks.iter().filter(|&&ok| ok).count()
}
}
pub fn interleaved(
subjects: &[Subject],
seed: u64,
settings: &Settings,
observer: &mut dyn Observer,
) -> Vec<Result<Samples>> {
interleaved_with_versions(subjects, seed, settings, observer).0
}
pub type Version = Option<Result<String>>;
pub fn interleaved_with_versions(
subjects: &[Subject],
seed: u64,
settings: &Settings,
observer: &mut dyn Observer,
) -> (Vec<Result<Samples>>, Vec<Version>) {
let mut rng = fastrand::Rng::with_seed(seed);
let mut results: Vec<Result<Samples>> = subjects
.iter()
.map(|s| {
if s.runs == Runs::Fixed(0) {
bail!("runs must be at least 1");
}
Ok(Samples::default())
})
.collect();
let mut fastest: Vec<Option<Duration>> = vec![None; subjects.len()];
let warmups: Vec<u64> = subjects.iter().map(|s| u64::from(s.warmup)).collect();
let pilots: Vec<u64> = subjects
.iter()
.map(|s| u64::from(s.runs == Runs::Auto && s.warmup == 0))
.collect();
let provisional: Vec<u64> = subjects
.iter()
.zip(&warmups)
.map(|(s, w)| {
w + u64::from(match s.runs {
Runs::Fixed(n) => n,
Runs::Auto => s.auto.min,
})
})
.collect();
observer.planned(&provisional);
for (i, s) in subjects.iter().enumerate() {
let (Some(setup), Ok(_)) = (&s.setup, &results[i]) else {
continue;
};
observer.setting_up(i);
let site = Site {
dir: s.setup_dir.as_deref(),
env: &s.env,
settings,
};
if let Err(e) = observer
.before_run(i)
.and_then(|()| required("setup", setup, &site))
{
results[i] = Err(e);
observer.dropped(i);
}
}
for (i, result) in results.iter_mut().enumerate() {
if result.is_ok()
&& let Err(e) = observer.set_up(i)
{
*result = Err(e);
observer.dropped(i);
}
}
let versions: Vec<Version> = subjects
.iter()
.zip(&results)
.map(|(s, r)| r.as_ref().ok().and_then(|_| subject_version(s, settings)))
.collect();
let mut first = rounds(&warmups, false, &mut rng);
first.extend(rounds(&pilots, true, &mut rng));
run_slots(
&first,
subjects,
settings,
&mut results,
&mut fastest,
observer,
);
let remaining: Vec<u64> = subjects
.iter()
.enumerate()
.map(|(i, s)| match (&results[i], s.runs) {
(Err(_), _) => 0,
(Ok(_), Runs::Fixed(n)) => u64::from(n),
(Ok(taken), Runs::Auto) => {
let n = auto_runs(&s.auto, fastest[i]);
u64::from(n).saturating_sub(taken.times.len() as u64)
}
})
.collect();
observer.planned(&remaining);
let second = rounds(&remaining, true, &mut rng);
run_slots(
&second,
subjects,
settings,
&mut results,
&mut fastest,
observer,
);
(results, versions)
}
fn auto_runs(auto: &AutoRuns, fastest: Option<Duration>) -> u32 {
fastest.map_or(auto.min, |d| auto.runs_for(d))
}
fn run_slots(
slots: &[Slot],
subjects: &[Subject],
settings: &Settings,
results: &mut [Result<Samples>],
fastest: &mut [Option<Duration>],
observer: &mut dyn Observer,
) {
for slot in slots {
let Ok(samples) = &mut results[slot.subject] else {
continue;
};
let s = &subjects[slot.subject];
let site = Site {
dir: s.dir.as_deref(),
env: &s.env,
settings,
};
observer.started(slot.subject);
let vetted = if s.prepare.is_some() {
observer.before_run(slot.subject)
} else {
Ok(())
};
let began = Instant::now();
let taken = vetted
.and_then(|()| {
s.prepare
.as_deref()
.map_or(Ok(()), |p| prepare_once(p, &site))
})
.and_then(|()| observer.before_run(slot.subject))
.and_then(|()| time_once(&s.cmd, &site, &s.ok_exit_codes));
let elapsed = began.elapsed();
let checked = match (&taken, &s.check) {
(Ok(_), Some(check)) if slot.timed => observer
.before_run(slot.subject)
.and_then(|()| check_once(check, &site))
.map(Some),
_ => Ok(None),
};
match taken.and_then(|sample| checked.map(|c| (sample, c))) {
Ok((sample, check)) => {
if slot.timed {
samples.times.push(sample.ms);
samples.exit_codes.push(sample.exit_code);
}
if let Some(failure) = check {
samples.checks.push(failure.is_none());
if samples.first_failure.is_none() {
samples.first_failure = failure;
}
}
let f = &mut fastest[slot.subject];
*f = Some(f.map_or(elapsed, |f| f.min(elapsed)));
observer.finished(slot.subject, began.elapsed());
}
Err(e) => {
results[slot.subject] = Err(e);
observer.dropped(slot.subject);
}
}
}
}
pub fn stats(samples: &[f64]) -> BTreeMap<String, f64> {
let mut sorted = samples.to_vec();
sorted.sort_by(f64::total_cmp);
let n = sorted.len();
let mean = sorted.iter().sum::<f64>() / n as f64;
let stddev = if n > 1 {
(sorted.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64).sqrt()
} else {
0.0
};
BTreeMap::from([
("wall_min_ms".to_string(), sorted[0]),
("wall_p50_ms".to_string(), sorted[n / 2]),
("wall_mean_ms".to_string(), mean),
("wall_max_ms".to_string(), sorted[n - 1]),
("wall_stddev_ms".to_string(), stddev),
("wall_n".to_string(), n as f64),
])
}
pub fn warnings(samples: &[f64]) -> Vec<String> {
let mut out = Vec::new();
let n = samples.len();
if n < 5 {
return out;
}
let median = |v: &mut Vec<f64>| {
v.sort_by(f64::total_cmp);
let m = v.len();
if m.is_multiple_of(2) {
(v[m / 2 - 1] + v[m / 2]) / 2.0
} else {
v[m / 2]
}
};
let med = median(&mut samples.to_vec());
let mad = median(&mut samples.iter().map(|x| (x - med).abs()).collect());
let outlier = |x: f64| {
if mad > 0.0 {
0.6745 * (x - med).abs() / mad > 3.5
} else {
med > 0.0 && (x - med).abs() > 0.25 * med
}
};
{
let (fast, slow) = samples
.iter()
.filter(|&&x| outlier(x))
.fold(
(0, 0),
|(f, s), &x| if x < med { (f + 1, s) } else { (f, s + 1) },
);
if slow > 0 {
out.push(format!(
"{slow} of {n} samples are slow outliers; something else was running, or the \
command's work varies. Consider a quieter machine or more runs."
));
}
if fast > 0 {
out.push(format!(
"{fast} of {n} samples are fast outliers, and the reported minimum may be one of \
them; check the command did the same work every time."
));
}
}
let rest = median(&mut samples[1..].to_vec());
if rest > 0.0 && samples[0] > 2.0 * rest {
out.push(format!(
"the first sample took {:.1}x the median of the rest; the warmup did not fill some \
cache. Consider more warmup runs.",
samples[0] / rest
));
}
out
}
pub fn wall(plan: &Plan) -> Result<BTreeMap<String, f64>> {
let subject = Subject {
name: SELF_TOOL.to_string(),
cmd: plan.cmd.clone(),
prepare: None,
setup: None,
setup_dir: None,
check: None,
dir: plan.dir.clone(),
version_cmd: None,
env: BTreeMap::new(),
vars: BTreeMap::new(),
when: None,
runs: Runs::Fixed(plan.runs),
auto: AutoRuns {
budget: crate::config::DEFAULT_BUDGET,
min: crate::config::DEFAULT_MIN_RUNS,
max: crate::config::DEFAULT_MAX_RUNS,
},
warmup: plan.warmup,
counters: false,
allocations: false,
ok_exit_codes: DEFAULT_OK_EXIT_CODES.to_vec(),
metrics: BTreeMap::new(),
};
let samples = interleaved(
std::slice::from_ref(&subject),
0,
&plan.settings,
&mut Quiet,
)
.pop()
.expect("one result per subject")?;
Ok(stats(&samples.times))
}
pub fn valgrind_available() -> bool {
Command::new("valgrind")
.arg("--version")
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
const COUNTER_RUNS: u32 = 3;
const SPREAD_WARN_PCT: f64 = 0.5;
#[derive(Debug, Clone, Copy)]
pub struct Counted {
pub min: u64,
pub max: u64,
pub runs: u32,
}
impl Counted {
pub fn spread_pct(&self) -> f64 {
if self.min == 0 {
return 0.0;
}
(self.max - self.min) as f64 / self.min as f64 * 100.0
}
pub fn is_suspect(&self) -> bool {
self.spread_pct() > SPREAD_WARN_PCT
}
}
pub fn instructions(
cmd: &[String],
dir: Option<&std::path::Path>,
settings: &Settings,
) -> Result<Option<Counted>> {
count(
cmd,
None,
&Site {
dir,
env: &BTreeMap::new(),
settings,
},
&DEFAULT_OK_EXIT_CODES,
false,
&|| Ok(()),
)
.map(|c| c.map(|(c, _)| c))
}
pub fn subject_instructions(s: &Subject, settings: &Settings) -> Result<Option<Counted>> {
subject_count(s, settings, false, &|| Ok(())).map(|c| c.map(|(c, _)| c))
}
pub fn subject_instructions_vetted(
s: &Subject,
settings: &Settings,
vet: &dyn Fn() -> Result<()>,
) -> Result<Option<Counted>> {
subject_count(s, settings, false, vet).map(|c| c.map(|(c, _)| c))
}
pub fn subject_profile(s: &Subject, settings: &Settings) -> Result<Option<(Counted, Profiled)>> {
subject_profile_vetted(s, settings, &|| Ok(()))
}
pub fn subject_profile_vetted(
s: &Subject,
settings: &Settings,
vet: &dyn Fn() -> Result<()>,
) -> Result<Option<(Counted, Profiled)>> {
Ok(subject_count(s, settings, true, vet)?
.map(|(c, p)| (c, p.expect("a profile was asked for"))))
}
pub type Profiled = Result<Vec<u8>>;
fn subject_count(
s: &Subject,
settings: &Settings,
profile: bool,
vet: &dyn Fn() -> Result<()>,
) -> Result<Option<(Counted, Option<Profiled>)>> {
count(
&s.cmd,
s.prepare.as_deref(),
&Site {
dir: s.dir.as_deref(),
env: &s.env,
settings,
},
&s.ok_exit_codes,
profile,
vet,
)
}
pub fn subject_version(s: &Subject, settings: &Settings) -> Option<Result<String>> {
let argv = s.version_cmd.as_ref()?;
let site = Site {
dir: s.dir.as_deref(),
env: &s.env,
settings,
};
Some(version_once(argv, &site, VERSION_TIMEOUT))
}
const VERSION_OUTPUT_CAP: usize = 8192;
const VERSION_TIMEOUT: Duration = Duration::from_secs(10);
const VERSION_OUTPUT_GRACE: Duration = Duration::from_millis(500);
fn keep_prefix(
mut r: impl std::io::Read,
cap: usize,
kept: &Mutex<Vec<u8>>,
overflow: &std::sync::atomic::AtomicBool,
tail: Option<&Mutex<Vec<u8>>>,
) {
let mut buf = [0u8; 8192];
loop {
match r.read(&mut buf) {
Ok(0) => return,
Ok(n) => {
let Ok(mut k) = kept.lock() else { return };
let room = cap.saturating_sub(k.len());
if n > room {
overflow.store(true, std::sync::atomic::Ordering::SeqCst);
}
k.extend_from_slice(&buf[..n.min(room)]);
if let Some(Ok(mut t)) = tail.map(Mutex::lock) {
t.extend_from_slice(&buf[..n]);
let excess = t.len().saturating_sub(UNTIMED_STDERR_TAIL);
t.drain(..excess);
}
}
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(_) => return,
}
}
}
#[cfg(unix)]
mod forward_signals {
use std::sync::atomic::{AtomicBool, AtomicI32, Ordering::SeqCst};
const SIGNALS: [libc::c_int; 3] = [libc::SIGINT, libc::SIGTERM, libc::SIGHUP];
pub(super) struct State {
spawning: AtomicBool,
pgid: AtomicI32,
pending: AtomicI32,
done: AtomicBool,
}
#[derive(Debug, PartialEq, Eq)]
pub(super) enum Act {
Defer,
Die { pgid: i32 },
}
impl State {
pub(super) const fn new() -> State {
State {
spawning: AtomicBool::new(false),
pgid: AtomicI32::new(0),
pending: AtomicI32::new(0),
done: AtomicBool::new(true),
}
}
pub(super) fn begin(&self) {
self.pending.store(0, SeqCst);
self.pgid.store(0, SeqCst);
self.done.store(false, SeqCst);
self.spawning.store(true, SeqCst);
}
pub(super) fn on_signal(&self, sig: libc::c_int) -> Act {
if self.wants_to_defer() {
self.defer(sig)
} else {
Act::Die {
pgid: self.pgid.load(SeqCst),
}
}
}
fn wants_to_defer(&self) -> bool {
let spawning = self.spawning.load(SeqCst);
spawning && self.pgid.load(SeqCst) == 0
}
fn defer(&self, sig: libc::c_int) -> Act {
self.pending.store(sig, SeqCst);
if self.done.load(SeqCst) {
return Act::Die { pgid: 0 };
}
match self.pgid.load(SeqCst) {
0 => Act::Defer,
pgid => Act::Die { pgid },
}
}
pub(super) fn spawned(&self, pid: Option<u32>) -> Option<(libc::c_int, i32)> {
let pgid = pid.map_or(0, |p| p as i32);
self.pgid.store(pgid, SeqCst);
self.spawning.store(false, SeqCst);
let sig = self.pending.swap(0, SeqCst);
(sig != 0).then_some((sig, pgid))
}
pub(super) fn end(&self) -> Option<libc::c_int> {
self.spawning.store(false, SeqCst);
self.done.store(true, SeqCst);
self.pgid.store(0, SeqCst);
let sig = self.pending.swap(0, SeqCst);
(sig != 0).then_some(sig)
}
}
static STATE: State = State::new();
fn die(sig: libc::c_int, pgid: i32) {
unsafe {
if pgid > 0 {
libc::killpg(pgid, libc::SIGKILL);
}
libc::signal(sig, libc::SIG_DFL);
libc::raise(sig);
}
}
extern "C" fn forward(sig: libc::c_int) {
if let Act::Die { pgid } = STATE.on_signal(sig) {
die(sig, pgid);
}
}
pub struct Guard {
previous: Vec<(libc::c_int, libc::sigaction)>,
}
impl Guard {
pub fn install() -> Guard {
STATE.begin();
let mut previous = Vec::new();
for sig in SIGNALS {
unsafe {
let mut new: libc::sigaction = std::mem::zeroed();
new.sa_sigaction = forward as extern "C" fn(libc::c_int) as libc::sighandler_t;
libc::sigemptyset(&mut new.sa_mask);
let mut old: libc::sigaction = std::mem::zeroed();
if libc::sigaction(sig, &new, &mut old) == 0 {
previous.push((sig, old));
}
}
}
Guard { previous }
}
pub fn spawned(pid: Option<u32>) {
if let Some((sig, pgid)) = STATE.spawned(pid) {
die(sig, pgid);
}
}
}
impl Drop for Guard {
fn drop(&mut self) {
if let Some(sig) = STATE.end() {
die(sig, 0);
}
for (sig, old) in &self.previous {
unsafe {
libc::sigaction(*sig, old, std::ptr::null_mut());
}
}
}
}
#[cfg(test)]
mod tests {
use super::{Act, SeqCst, State};
#[test]
fn a_signal_during_the_spawn_is_held_until_the_group_is_known() {
let s = State::new();
s.begin();
assert_eq!(s.on_signal(libc::SIGTERM), Act::Defer, "no group yet");
assert_eq!(s.spawned(Some(42)), Some((libc::SIGTERM, 42)));
assert_eq!(s.on_signal(libc::SIGINT), Act::Die { pgid: 42 });
assert_eq!(s.end(), None);
s.begin();
assert_eq!(s.spawned(Some(7)), None, "nothing arrived");
assert_eq!(s.end(), None);
s.begin();
assert_eq!(s.on_signal(libc::SIGINT), Act::Defer);
assert_eq!(
s.spawned(None),
Some((libc::SIGINT, 0)),
"a failed spawn still stops tak"
);
assert_eq!(s.end(), None);
assert_eq!(
s.on_signal(libc::SIGHUP),
Act::Die { pgid: 0 },
"after the step"
);
assert!(!s.wants_to_defer(), "and it never defers there");
}
#[test]
fn a_handler_preempted_past_the_step_still_acts() {
let s = State::new();
s.begin();
assert!(s.wants_to_defer());
assert_eq!(s.spawned(Some(42)), None);
assert_eq!(s.end(), None);
assert_eq!(s.defer(libc::SIGTERM), Act::Die { pgid: 0 });
s.begin();
assert!(s.wants_to_defer());
assert_eq!(s.spawned(Some(42)), None);
assert_eq!(s.defer(libc::SIGINT), Act::Die { pgid: 42 });
assert_eq!(s.end(), Some(libc::SIGINT));
s.begin();
assert_eq!(s.spawned(Some(42)), None);
s.pending.store(libc::SIGHUP, SeqCst);
assert_eq!(s.end(), Some(libc::SIGHUP), "acted on at teardown");
}
}
}
fn stop_group(child: &mut std::process::Child) {
#[cfg(unix)]
{
let pgid = child.id() as libc::pid_t;
if unsafe { libc::killpg(pgid, libc::SIGKILL) } != 0 {
let _ = child.kill();
}
}
#[cfg(not(unix))]
let _ = child.kill();
let _ = child.wait();
}
fn version_once(argv: &[String], site: &Site, timeout: Duration) -> Result<String> {
let bin = argv
.first()
.map(String::as_str)
.unwrap_or("(empty command)");
let Captured {
status,
stdout,
stderr,
stderr_tail,
..
} = capture(argv, site, Some(timeout), VERSION_OUTPUT_CAP, false)?;
if !status.success() {
bail!("`{bin}` exited with {status}: {}", last_line(&stderr_tail));
}
let first = |bytes: &[u8]| {
String::from_utf8_lossy(bytes)
.lines()
.map(str::trim)
.find(|l| !l.is_empty())
.map(str::to_string)
};
first(&stdout)
.or_else(|| first(&stderr))
.with_context(|| format!("`{bin}` printed nothing"))
}
fn last_line(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes)
.lines()
.map(str::trim)
.rfind(|l| !l.is_empty())
.unwrap_or("(no output)")
.to_string()
}
struct Captured {
status: std::process::ExitStatus,
stdout: Vec<u8>,
stderr: Vec<u8>,
stderr_tail: Vec<u8>,
overflowed: bool,
stdout_open: bool,
pgid: u32,
}
fn stop_leftovers(pgid: u32) {
#[cfg(unix)]
unsafe {
libc::killpg(pgid as libc::pid_t, libc::SIGKILL);
}
#[cfg(not(unix))]
let _ = pgid;
}
fn capture(
argv: &[String],
site: &Site,
timeout: Option<Duration>,
stdout_cap: usize,
stop_past_cap: bool,
) -> Result<Captured> {
use std::sync::atomic::{AtomicBool, Ordering::SeqCst};
let bin = argv
.first()
.map(String::as_str)
.unwrap_or("(empty command)");
let mut cmd = command(argv, site)?;
cmd.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
#[cfg(unix)]
std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
#[cfg(unix)]
let _forward = forward_signals::Guard::install();
let spawned = cmd.spawn();
#[cfg(unix)]
forward_signals::Guard::spawned(spawned.as_ref().ok().map(std::process::Child::id));
let mut child = spawned.with_context(|| format!("failed to spawn `{bin}`"))?;
tracked::started(child.id());
struct Finished;
impl Drop for Finished {
fn drop(&mut self) {
tracked::finished();
}
}
let _finished = Finished;
let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
let overflow = Arc::new(AtomicBool::new(false));
let ignored = Arc::new(AtomicBool::new(false));
let stdout_done = Arc::new(AtomicBool::new(false));
let unused = Arc::new(AtomicBool::new(false));
let spawn_reader = |r: Option<Box<dyn std::io::Read + Send>>,
cap: usize,
flag: &Arc<AtomicBool>,
done: &Arc<AtomicBool>,
tail: Option<&Arc<Mutex<Vec<u8>>>>| {
let kept = Arc::new(Mutex::new(Vec::new()));
if let Some(r) = r {
let (kept, tx, flag, done) = (
Arc::clone(&kept),
done_tx.clone(),
Arc::clone(flag),
Arc::clone(done),
);
let tail = tail.map(Arc::clone);
std::thread::spawn(move || {
keep_prefix(r, cap, &kept, &flag, tail.as_deref());
done.store(true, SeqCst);
let _ = tx.send(());
});
} else {
done.store(true, SeqCst);
let _ = done_tx.send(());
}
kept
};
let stdout = spawn_reader(
child.stdout.take().map(|o| Box::new(o) as _),
stdout_cap,
&overflow,
&stdout_done,
None,
);
let stderr_tail = Arc::new(Mutex::new(Vec::new()));
let stderr = spawn_reader(
child.stderr.take().map(|e| Box::new(e) as _),
VERSION_OUTPUT_CAP,
&ignored,
&unused,
Some(&stderr_tail),
);
let deadline = timeout.map(|t| Instant::now() + t);
let status = loop {
if stop_past_cap && overflow.load(SeqCst) {
stop_group(&mut child);
break child
.wait()
.with_context(|| format!("failed to wait for `{bin}`"))?;
}
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) if deadline.is_none_or(|d| Instant::now() < d) => {
std::thread::sleep(Duration::from_millis(5));
}
Ok(None) => {
stop_group(&mut child);
bail!(
"`{bin}` did not finish within {}, so it was stopped",
crate::progress::fmt(timeout.unwrap_or_default())
);
}
Err(e) => {
stop_group(&mut child);
return Err(e).with_context(|| format!("failed to wait for `{bin}`"));
}
}
};
let grace = Instant::now() + VERSION_OUTPUT_GRACE;
for _ in 0..2 {
let left = grace.saturating_duration_since(Instant::now());
if done_rx.recv_timeout(left).is_err() {
break;
}
}
let take = |kept: &Mutex<Vec<u8>>| kept.lock().map(|k| k.clone()).unwrap_or_default();
Ok(Captured {
status,
stdout: take(&stdout),
stderr: take(&stderr),
stderr_tail: take(&stderr_tail),
overflowed: overflow.load(SeqCst),
stdout_open: !stdout_done.load(SeqCst),
pgid: child.id(),
})
}
const VALGRIND_LOG_CAP: u64 = 1 << 20;
#[cfg(unix)]
fn under_valgrind(
tool: &[&str],
cmd: &[String],
site: &Site,
) -> Result<(std::process::ExitStatus, String)> {
use std::io::{Read, Seek};
use std::os::fd::AsRawFd;
use std::os::unix::process::CommandExt;
let mut log = tempfile::tempfile().context("failed to create a file for valgrind's log")?;
let fd = log.as_raw_fd();
let mut argv: Vec<String> = std::iter::once("valgrind")
.chain(tool.iter().copied())
.map(String::from)
.collect();
argv.push(format!("--log-fd={fd}"));
argv.extend_from_slice(cmd);
let mut c = command(&argv, site)?;
c.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
unsafe {
c.pre_exec(move || {
if libc::fcntl(fd, libc::F_SETFD, 0) == -1 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
let mut child = c.spawn().context("failed to run valgrind")?;
let pid = child.id();
tracked::started(pid);
let status = child.wait();
tracked::finished();
let status = status.context("failed to run valgrind")?;
let mut raw = Vec::new();
log.rewind().context("failed to read valgrind's log")?;
log.take(VALGRIND_LOG_CAP)
.read_to_end(&mut raw)
.context("failed to read valgrind's log")?;
let prefix = format!("=={pid}==");
let own: String = String::from_utf8_lossy(&raw)
.lines()
.filter(|l| l.starts_with(&prefix))
.flat_map(|l| [l, "\n"])
.collect();
Ok((status, own))
}
#[cfg(not(unix))]
fn under_valgrind(
_tool: &[&str],
_cmd: &[String],
_site: &Site,
) -> Result<(std::process::ExitStatus, String)> {
bail!("valgrind runs only on Unix")
}
fn last_log_line(log: &str) -> &str {
log.lines()
.map(|l| valgrind_line(l).unwrap_or(l).trim())
.rfind(|l| !l.is_empty())
.unwrap_or("(valgrind wrote no log; it may not have been able to start the command)")
}
fn count(
cmd: &[String],
prepare: Option<&[String]>,
site: &Site,
ok: &[i32],
profile: bool,
vet: &dyn Fn() -> Result<()>,
) -> Result<Option<(Counted, Option<Profiled>)>> {
if !valgrind_available() {
return Ok(None);
}
let (scratch, unkept) = match profile.then(tempfile::tempdir) {
Some(Ok(d)) => (Some(d), None),
Some(Err(e)) => (
None,
Some(
anyhow::Error::new(e)
.context("could not create a directory for cachegrind profiles"),
),
),
None => (None, None),
};
let mut samples: Vec<u64> = Vec::with_capacity(COUNTER_RUNS as usize);
for run in 0..COUNTER_RUNS {
if let Some(p) = prepare {
vet()?;
prepare_once(p, site)?;
}
vet()?;
let out_file = match &scratch {
Some(d) => d
.path()
.join(format!("run-{run}"))
.to_string_lossy()
.replace('%', "%%"),
None => "/dev/null".to_string(),
};
let out_arg = format!("--cachegrind-out-file={out_file}");
let (status, log) = under_valgrind(
&[
"--tool=cachegrind",
"--cache-sim=no",
"--branch-sim=no",
&out_arg,
],
cmd,
site,
)?;
let bin = cmd.first().map(String::as_str).unwrap_or("(empty command)");
accepted(bin, status, ok, " under valgrind")?;
match parse_irefs(&log) {
Some(0) => {
let unwritable =
valgrind_lines(&log).any(|l| l.contains("can't open output data file"));
if unwritable {
bail!(
"cachegrind could not write its profile to {out_file}, and counts nothing when that happens"
);
}
bail!("cachegrind counted no instructions");
}
Some(n) => samples.push(n),
None => bail!(
"valgrind ran but emitted no `I refs` summary: {}",
last_log_line(&log)
),
}
}
let counted = Counted {
min: *samples.iter().min().expect("COUNTER_RUNS > 0"),
max: *samples.iter().max().expect("COUNTER_RUNS > 0"),
runs: COUNTER_RUNS,
};
let best = samples
.iter()
.position(|n| *n == counted.min)
.expect("the minimum is one of the samples");
let kept = match (scratch, unkept) {
(Some(d), _) => {
let path = d.path().join(format!("run-{best}"));
Some(
std::fs::read(&path)
.with_context(|| format!("cachegrind wrote no profile to {}", path.display()))
.and_then(|raw| {
if raw.is_empty() {
bail!("cachegrind wrote an empty profile to {}", path.display());
}
Ok(raw)
}),
)
}
(None, Some(e)) => Some(Err(e)),
(None, None) => None,
};
Ok(Some((counted, kept)))
}
fn parse_irefs(log: &str) -> Option<u64> {
let line = valgrind_lines(log)
.filter(|l| l.contains("I refs:"))
.last()?;
let digits: String = line
.rsplit(':')
.next()?
.chars()
.filter(|c| c.is_ascii_digit())
.collect();
digits.parse().ok()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Heap {
pub blocks: u64,
pub bytes: u64,
pub peak_bytes: u64,
}
impl Heap {
pub fn metrics(&self) -> [(&'static str, u64); 3] {
[
("alloc_blocks", self.blocks),
("alloc_bytes", self.bytes),
("alloc_peak_bytes", self.peak_bytes),
]
}
}
#[derive(Debug, Clone, Copy)]
pub struct Allocated {
pub min: Heap,
pub max: Heap,
pub runs: u32,
}
fn spread(lo: u64, hi: u64) -> f64 {
match (lo, hi) {
(0, 0) => 0.0,
(0, _) => f64::INFINITY,
(lo, hi) => (hi - lo) as f64 / lo as f64 * 100.0,
}
}
impl Allocated {
pub fn totals_spread_pct(&self) -> f64 {
spread(self.min.blocks, self.max.blocks).max(spread(self.min.bytes, self.max.bytes))
}
pub fn peak_spread_pct(&self) -> f64 {
spread(self.min.peak_bytes, self.max.peak_bytes)
}
pub fn is_suspect(&self) -> bool {
self.totals_spread_pct() > SPREAD_WARN_PCT
}
pub fn peak_is_unsteady(&self) -> bool {
self.peak_spread_pct() > SPREAD_WARN_PCT
}
pub fn saw_nothing(&self) -> bool {
self.max.blocks == 0
}
}
pub fn subject_allocations(s: &Subject, settings: &Settings) -> Result<Option<Allocated>> {
subject_allocations_vetted(s, settings, &|| Ok(()))
}
pub fn subject_allocations_vetted(
s: &Subject,
settings: &Settings,
vet: &dyn Fn() -> Result<()>,
) -> Result<Option<Allocated>> {
let site = Site {
dir: s.dir.as_deref(),
env: &s.env,
settings,
};
allocations(&s.cmd, s.prepare.as_deref(), &site, &s.ok_exit_codes, vet)
}
fn allocations(
cmd: &[String],
prepare: Option<&[String]>,
site: &Site,
ok: &[i32],
vet: &dyn Fn() -> Result<()>,
) -> Result<Option<Allocated>> {
if !valgrind_available() {
return Ok(None);
}
let bin = cmd.first().map(String::as_str).unwrap_or("(empty command)");
let mut runs: Vec<Heap> = Vec::with_capacity(COUNTER_RUNS as usize);
for _ in 0..COUNTER_RUNS {
if let Some(p) = prepare {
vet()?;
prepare_once(p, site)?;
}
vet()?;
let (status, log) =
under_valgrind(&["--tool=dhat", "--dhat-out-file=/dev/null"], cmd, site)?;
accepted(bin, status, ok, " under valgrind")?;
match parse_dhat(&log) {
Some(h) => runs.push(h),
None => bail!(
"valgrind ran but emitted no DHAT summary: {}",
last_log_line(&log)
),
}
}
let fold = |f: fn(u64, u64) -> u64| {
runs.iter()
.copied()
.reduce(|a, b| Heap {
blocks: f(a.blocks, b.blocks),
bytes: f(a.bytes, b.bytes),
peak_bytes: f(a.peak_bytes, b.peak_bytes),
})
.expect("COUNTER_RUNS > 0")
};
Ok(Some(Allocated {
min: fold(u64::min),
max: fold(u64::max),
runs: COUNTER_RUNS,
}))
}
fn parse_dhat(log: &str) -> Option<Heap> {
let field = |name: &str| {
let rest = valgrind_lines(log).find_map(|l| l.trim_start().strip_prefix(name))?;
let (bytes, rest) = rest.trim().split_once(" bytes in ")?;
let blocks = rest.split_whitespace().next()?;
Some((dhat_number(bytes)?, dhat_number(blocks)?))
};
let (bytes, blocks) = field("Total:")?;
let (peak_bytes, _) = field("At t-gmax:")?;
Some(Heap {
blocks,
bytes,
peak_bytes,
})
}
fn valgrind_line(line: &str) -> Option<&str> {
let rest = line.strip_prefix("==")?;
let (pid, rest) = rest.split_once("==")?;
(!pid.is_empty() && pid.chars().all(|c| c.is_ascii_digit())).then_some(rest)
}
fn dhat_number(s: &str) -> Option<u64> {
let digits: String = s.trim().chars().filter(|&c| c != ',').collect();
if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
return None;
}
digits.parse().ok()
}
fn valgrind_lines(log: &str) -> impl Iterator<Item = &str> {
log.lines().filter_map(valgrind_line)
}
#[cfg(test)]
mod tests {
use super::*;
const DHAT_3_22: &str = "\
==9== DHAT, a dynamic heap analysis tool
==9== Copyright (C) 2010-2018, and GNU GPL'd, by Mozilla Foundation
==9== Using Valgrind-3.22.0 and LibVEX; rerun with -h for copyright info
==9== Command: git --version
==9==
git version 2.43.0
==9==
==9== Total: 7,119 bytes in 31 blocks
==9== At t-gmax: 6,847 bytes in 25 blocks
==9== At t-end: 2,379 bytes in 15 blocks
==9== Reads: 1,067 bytes
==9== Writes: 1,546 bytes
==9==
==9== To view the resulting profile, open
==9== file:///usr/libexec/valgrind/dh_view.html
==9== in a web browser, click on \"Load...\", and then select the file
==9== /dev/null
==9== The text at the bottom explains the abbreviations used in the output.
";
#[test]
fn parses_a_dhat_summary() {
assert_eq!(
parse_dhat(DHAT_3_22),
Some(Heap {
blocks: 31,
bytes: 7_119,
peak_bytes: 6_847,
})
);
}
#[test]
fn parses_counts_past_a_million() {
let s = "==21== Total: 2,626,313 bytes in 2,833 blocks\n\
==21== At t-gmax: 1,185,686 bytes in 1,661 blocks\n";
assert_eq!(
parse_dhat(s),
Some(Heap {
blocks: 2_833,
bytes: 2_626_313,
peak_bytes: 1_185_686,
})
);
}
#[test]
fn only_valgrinds_own_lines_are_read() {
let s = "Total: 5 bytes in 1 blocks\n\
==12== \n\
==12== Total: 8,748 bytes in 17 blocks\n\
==12== At t-gmax: 8,748 bytes in 17 blocks\n";
assert_eq!(parse_dhat(s).unwrap().blocks, 17);
assert_eq!(
parse_dhat("Total: 5 bytes in 1 blocks\nAt t-gmax: 5 bytes in 1 blocks\n"),
None
);
assert_eq!(valgrind_line("==x== Total:"), None);
assert_eq!(valgrind_line("==== Total:"), None);
}
#[test]
fn a_missing_or_truncated_dhat_summary_is_none() {
assert_eq!(parse_dhat(""), None);
assert_eq!(parse_dhat("==3== Total: 1 bytes in 1 blocks\n"), None);
assert_eq!(
parse_dhat(
"==3== Total: lots bytes in 1 blocks\n==3== At t-gmax: 1 bytes in 1 blocks\n"
),
None
);
}
#[test]
fn totals_and_peak_spread_are_judged_apart() {
let h = |blocks, bytes, peak_bytes| Heap {
blocks,
bytes,
peak_bytes,
};
let a = |min, max| Allocated { min, max, runs: 3 };
let steady = a(h(10, 1000, 500), h(10, 1000, 500));
assert_eq!(steady.totals_spread_pct(), 0.0);
assert!(!steady.is_suspect() && !steady.peak_is_unsteady());
let threaded = a(h(10, 1000, 500), h(10, 1000, 510));
assert!((threaded.peak_spread_pct() - 2.0).abs() < 1e-9);
assert!(threaded.peak_is_unsteady() && !threaded.is_suspect());
let first_run = a(h(496, 2_077_237, 1_790_738), h(1140, 2_227_102, 1_888_914));
assert!(first_run.is_suspect());
assert!((first_run.totals_spread_pct() - 129.84).abs() < 0.01);
assert!(a(h(0, 0, 0), h(1, 8, 8)).totals_spread_pct().is_infinite());
assert!(a(h(0, 0, 0), h(0, 0, 0)).saw_nothing());
assert!(!steady.saw_nothing());
}
#[test]
fn a_count_printed_by_the_subject_is_not_the_count() {
let s = "I refs: 5\n==7== error: can't open output data file\n==7== I refs: 1,234\nI refs: 9\n";
assert_eq!(parse_irefs(s), Some(1_234));
assert_eq!(parse_irefs("I refs: 5\n"), None);
assert_eq!(
valgrind_lines("==x== no\n== 1== no\n==12== yes\n").collect::<Vec<_>>(),
[" yes"]
);
}
#[test]
fn parses_cachegrind_summary() {
let s = "==12== I refs: 48,349,132\n";
assert_eq!(parse_irefs(s), Some(48_349_132));
}
#[test]
fn missing_summary_is_none_not_panic() {
assert_eq!(parse_irefs("valgrind: command not found"), None);
}
fn removals(settings: &Settings) -> Vec<String> {
subject("true", settings)
.get_envs()
.filter(|(_, v)| v.is_none())
.map(|(k, _)| k.to_string_lossy().into_owned())
.collect()
}
#[test]
fn subject_commands_remove_the_default_denied_variables() {
let removed = removals(&Settings::default());
for key in Settings::default().scrubbed_env() {
assert!(removed.contains(&key.to_string()), "{key} not removed");
}
}
#[test]
fn the_removal_follows_the_settings() {
let removed = removals(&Settings {
env_deny: vec!["CUSTOM_SECRET".into()],
env_allow: Vec::new(),
..Settings::default()
});
assert!(removed.contains(&"CUSTOM_SECRET".to_string()));
assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
}
#[test]
fn an_allowed_variable_survives() {
let removed = removals(&Settings {
env_deny: vec!["GITHUB_TOKEN".into(), "GH_TOKEN".into()],
env_allow: vec!["GITHUB_TOKEN".into()],
..Settings::default()
});
assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
assert!(removed.contains(&"GH_TOKEN".to_string()));
}
#[test]
fn zero_runs_is_rejected_not_a_panic() {
let plan = Plan {
cmd: vec!["true".into()],
warmup: 0,
runs: 0,
dir: None,
settings: Settings::default(),
};
assert!(wall(&plan).is_err());
}
#[test]
fn a_failed_subject_is_not_recorded_as_a_fast_run() {
#[cfg(unix)]
let cmd = vec!["/bin/sh".into(), "-c".into(), "exit 42".into()];
#[cfg(windows)]
let cmd = vec!["cmd".into(), "/C".into(), "exit /B 42".into()];
let err = wall(&Plan {
cmd,
warmup: 0,
runs: 1,
dir: None,
settings: Settings::default(),
})
.unwrap_err();
assert!(format!("{err:#}").contains("exited with"), "{err:#}");
}
#[test]
fn wall_reports_min_le_p50_le_max() {
let plan = Plan {
cmd: vec!["true".into()],
warmup: 1,
runs: 5,
dir: None,
settings: Settings::default(),
};
let m = wall(&plan).unwrap();
assert!(m["wall_min_ms"] <= m["wall_p50_ms"]);
assert!(m["wall_p50_ms"] <= m["wall_max_ms"]);
assert_eq!(m["wall_n"], 5.0);
}
#[test]
fn the_schedule_gives_each_subject_its_counts() {
let counts = [(2, 10), (1, 5), (0, 3)];
let order = schedule(&counts, 7);
for (i, &(warmup, runs)) in counts.iter().enumerate() {
let of = |timed| {
order
.iter()
.filter(|s| s.subject == i && s.timed == timed)
.count()
};
assert_eq!(of(false), warmup as usize, "subject {i} warmups");
assert_eq!(of(true), runs as usize, "subject {i} runs");
}
let first_timed = order.iter().position(|s| s.timed).unwrap();
assert!(order[first_timed..].iter().all(|s| s.timed));
}
#[test]
fn the_same_seed_gives_the_same_order() {
let counts = [(1, 8), (1, 8), (1, 8)];
assert_eq!(schedule(&counts, 42), schedule(&counts, 42));
assert_ne!(schedule(&counts, 42), schedule(&counts, 43));
}
#[test]
fn each_round_runs_every_subject_once_in_a_varying_order() {
let order = schedule(&[(0, 20), (0, 20), (0, 20)], 1);
let rounds: Vec<Vec<usize>> = order
.chunks(3)
.map(|r| r.iter().map(|s| s.subject).collect())
.collect();
assert_eq!(rounds.len(), 20);
for r in &rounds {
let mut sorted = r.clone();
sorted.sort();
assert_eq!(sorted, [0, 1, 2], "round {r:?}");
}
assert!(rounds.iter().any(|r| r != &rounds[0]), "never shuffled");
}
#[test]
fn a_subject_with_fewer_runs_is_spread_across_the_run() {
let order = schedule(&[(0, 10), (0, 5)], 3);
let fewer: Vec<usize> = order
.iter()
.enumerate()
.filter(|(_, s)| s.subject == 1)
.map(|(i, _)| i)
.collect();
assert_eq!(fewer.len(), 5);
assert!(
*fewer.last().unwrap() >= order.len() - 3,
"last sample of the smaller subject is near the end: {fewer:?} of {}",
order.len()
);
}
#[test]
fn a_benchmark_seed_depends_on_its_name_and_the_run_seed() {
assert_eq!(seed_for(1, "a"), seed_for(1, "a"));
assert_ne!(seed_for(1, "a"), seed_for(1, "b"));
assert_ne!(seed_for(1, "a"), seed_for(2, "a"));
}
#[test]
fn stats_report_the_sample_standard_deviation() {
let m = stats(&[2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]);
assert_eq!(m["wall_min_ms"], 2.0);
assert_eq!(m["wall_max_ms"], 9.0);
assert_eq!(m["wall_mean_ms"], 5.0);
assert!((m["wall_stddev_ms"] - 2.138_089_935).abs() < 1e-6);
assert_eq!(stats(&[3.0])["wall_stddev_ms"], 0.0);
}
#[cfg(unix)]
#[test]
fn a_failing_subject_does_not_stop_the_others() {
let mk = |name: &str, cmd: &[&str]| Subject {
name: name.into(),
cmd: cmd.iter().map(|s| s.to_string()).collect(),
prepare: None,
setup: None,
setup_dir: None,
check: None,
dir: None,
version_cmd: None,
env: BTreeMap::new(),
vars: BTreeMap::new(),
when: None,
runs: Runs::Fixed(4),
auto: AutoRuns {
budget: Duration::from_secs(30),
min: 5,
max: 50,
},
warmup: 1,
counters: false,
allocations: false,
ok_exit_codes: vec![0],
metrics: BTreeMap::new(),
};
let res = interleaved(
&[mk("ok", &["true"]), mk("bad", &["false"])],
5,
&Settings::default(),
&mut Quiet,
);
assert_eq!(res[0].as_ref().unwrap().times.len(), 4);
assert!(format!("{:#}", res[1].as_ref().unwrap_err()).contains("exited with"));
}
#[test]
fn a_metric_value_is_exactly_one_non_negative_number() {
for (text, want) in [
("1234", 1234.0),
("1234\n", 1234.0),
(" \t12.5\r\n", 12.5),
("0", 0.0),
("1.5e3", 1500.0),
("2E-2", 0.02),
("007", 7.0),
] {
assert_eq!(parse_metric_value(text).unwrap(), want, "{text:?}");
}
for bad in [
"", "\n", "-1", "+1", ".5", "5.", "1e", "1e+", "nan", "inf", "0x10", "1,234", "12 kB",
"1 2", "1\n2", "size: 3", "1e999",
] {
assert!(parse_metric_value(bad).is_err(), "accepted {bad:?}");
}
}
fn with_metrics(dir: &Path, env: &[(&str, &str)]) -> Subject {
Subject {
name: "s".into(),
cmd: vec!["true".into()],
prepare: None,
setup: None,
setup_dir: None,
check: None,
dir: Some(dir.to_path_buf()),
version_cmd: None,
env: env
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect(),
vars: BTreeMap::new(),
when: None,
runs: Runs::Fixed(1),
auto: AutoRuns {
budget: Duration::from_secs(30),
min: 5,
max: 50,
},
warmup: 0,
counters: false,
allocations: false,
ok_exit_codes: vec![0],
metrics: BTreeMap::new(),
}
}
#[test]
fn a_file_metric_is_its_size_in_bytes() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("bin");
std::fs::write(&file, vec![0u8; 4321]).unwrap();
let s = with_metrics(dir.path(), &[]);
let settings = Settings::default();
assert_eq!(
custom_metric(&MetricSource::File(file), &s, &settings).unwrap(),
4321.0
);
let err = custom_metric(&MetricSource::File(dir.path().into()), &s, &settings).unwrap_err();
assert!(format!("{err:#}").contains("not a regular file"), "{err:#}");
let missing = dir.path().join("missing");
let err = custom_metric(&MetricSource::File(missing), &s, &settings).unwrap_err();
assert!(format!("{err:#}").contains("missing"), "{err:#}");
}
#[cfg(unix)]
#[test]
fn a_cmd_metric_runs_in_the_subjects_dir_and_env() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("here"), "").unwrap();
let s = with_metrics(dir.path(), &[("N", "42")]);
let settings = Settings::default();
let sh = |script: &str| {
custom_metric(
&MetricSource::Cmd(vec!["sh".into(), "-c".into(), script.into()]),
&s,
&settings,
)
};
assert_eq!(sh("test -e here && echo $N").unwrap(), 42.0);
let err = format!("{:#}", sh("echo 5; echo broke >&2; exit 3").unwrap_err());
assert!(
err.contains("exit status: 3") && err.contains("broke"),
"{err}"
);
let err = format!("{:#}", sh("echo 'bundle: 12 kB'").unwrap_err());
assert!(err.contains("not one number"), "{err}");
let err = format!("{:#}", sh("yes 1 | head -c 4096").unwrap_err());
assert!(err.contains("more than 1024 bytes"), "{err}");
let err = format!("{:#}", sh("yes 1 | head -c 1024").unwrap_err());
assert!(err.contains("not one number"), "{err}");
let start = Instant::now();
let err = format!("{:#}", sh("exec yes 1").unwrap_err());
assert!(err.contains("so they were stopped"), "{err}");
assert!(start.elapsed() < Duration::from_secs(4));
let err = format!(
"{:#}",
sh("yes 'noise line' | head -c 20000 >&2; echo 'the real error' >&2; exit 2")
.unwrap_err()
);
assert!(err.ends_with("the real error"), "{err}");
assert!(!err.contains("noise"), "{err}");
}
#[cfg(unix)]
#[test]
fn a_metric_cmd_leaving_stdout_open_fails_and_is_stopped() {
let err = leftover_metric("sleep 30 & echo $! > pid; echo 7");
assert!(err.contains("stdout open"), "{err}");
}
#[cfg(unix)]
#[test]
fn a_leftover_that_floods_stdout_after_exit_is_stopped() {
let err = leftover_metric("(sleep 0.1; exec yes 1) & echo $! > pid; echo 7");
assert!(
err.contains("more than 1024 bytes") && err.contains("what it started"),
"{err}"
);
}
#[cfg(unix)]
fn leftover_metric(script: &str) -> String {
let dir = tempfile::tempdir().unwrap();
let s = with_metrics(dir.path(), &[]);
let start = Instant::now();
let err = custom_metric(
&MetricSource::Cmd(vec!["sh".into(), "-c".into(), script.into()]),
&s,
&Settings::default(),
)
.unwrap_err();
assert!(start.elapsed() < Duration::from_secs(4));
let pid = std::fs::read_to_string(dir.path().join("pid")).unwrap();
let pid = pid.trim();
let until = Instant::now() + Duration::from_secs(2);
while running(pid) && Instant::now() < until {
std::thread::sleep(Duration::from_millis(20));
}
assert!(
!running(pid),
"the background process {pid} was left running"
);
format!("{err:#}")
}
#[cfg(unix)]
fn version_sh(script: &str, env: &[(&str, &str)], timeout: Duration) -> Result<String> {
let settings = Settings::default();
let env: BTreeMap<String, String> = env
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
let site = Site {
dir: None,
env: &env,
settings: &settings,
};
version_once(&["sh".into(), "-c".into(), script.into()], &site, timeout)
}
#[cfg(unix)]
#[test]
fn a_version_is_the_first_line_printed() {
let sh = |script: &str| version_sh(script, &[("V", "9.9")], VERSION_TIMEOUT);
assert_eq!(
sh("printf '\\n tool %s \\nbuilt today\\n' \"$V\"").unwrap(),
"tool 9.9",
"first non-empty line, trimmed, in the subject's env"
);
assert_eq!(sh("echo 'java 21' >&2").unwrap(), "java 21");
let err = format!("{:#}", sh("echo nope >&2; exit 2").unwrap_err());
assert!(err.contains("`sh`") && err.contains("nope"), "{err}");
assert!(sh("true").is_err(), "no output is no version");
}
#[cfg(unix)]
#[test]
fn a_version_is_read_from_a_capped_prefix() {
let sh = |script: &str| version_sh(script, &[], VERSION_TIMEOUT);
assert_eq!(sh("yes 'tool 1.0' | head -c 10000000").unwrap(), "tool 1.0");
assert_eq!(
sh("yes 'java 21' | head -c 10000000 >&2").unwrap(),
"java 21",
"a flood on stderr"
);
let kept = Mutex::new(Vec::new());
let mut src = std::io::Cursor::new(vec![7u8; 100]);
let overflow = std::sync::atomic::AtomicBool::new(false);
keep_prefix(&mut src, 10, &kept, &overflow, None);
assert_eq!(kept.lock().unwrap().len(), 10, "only the cap is kept");
assert_eq!(
src.position(),
100,
"the rest is read, not left in the pipe"
);
assert!(overflow.into_inner(), "and going past the cap is noticed");
let (kept, overflow) = (
Mutex::new(Vec::new()),
std::sync::atomic::AtomicBool::new(false),
);
keep_prefix(
std::io::Cursor::new(vec![7u8; 10]),
10,
&kept,
&overflow,
None,
);
assert!(!overflow.into_inner(), "exactly the cap is not past it");
}
#[cfg(unix)]
#[test]
fn a_failing_version_cmd_is_an_error_even_past_the_cap() {
let err = version_sh(
"yes 'usage: tool [flags]' | head -c 100000; echo 'unknown flag' >&2; exit 1",
&[],
VERSION_TIMEOUT,
)
.unwrap_err();
let err = format!("{err:#}");
assert!(
err.contains("exited with") && err.contains("unknown flag"),
"{err}"
);
}
#[cfg(unix)]
#[test]
fn a_version_cmd_that_never_finishes_is_stopped() {
let t = Duration::from_millis(300);
let began = Instant::now();
for script in ["exec yes 'tool 2.0' >&2", "exec sleep 30"] {
let err = format!("{:#}", version_sh(script, &[], t).unwrap_err());
assert!(err.contains("did not finish"), "{script}: {err}");
}
assert!(
began.elapsed() < Duration::from_secs(5),
"{:?}",
began.elapsed()
);
}
#[cfg(unix)]
#[test]
fn a_timeout_stops_the_whole_process_group() {
let dir = tempfile::tempdir().unwrap();
let pidfile = dir.path().join("pid");
let script = format!("sleep 30 & echo $! > '{}'; wait", pidfile.display());
let err = version_sh(&script, &[], Duration::from_millis(300)).unwrap_err();
assert!(format!("{err:#}").contains("did not finish"), "{err:#}");
let pid = std::fs::read_to_string(&pidfile).unwrap();
let pid = pid.trim();
let until = Instant::now() + Duration::from_secs(2);
while running(pid) && Instant::now() < until {
std::thread::sleep(Duration::from_millis(20));
}
assert!(
!running(pid),
"the background sleep {pid} outlived the timeout"
);
}
#[cfg(unix)]
fn running(pid: &str) -> bool {
#[cfg(target_os = "linux")]
{
let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) else {
return false;
};
let state = stat
.rfind(')')
.and_then(|i| stat[i + 1..].trim_start().chars().next());
!matches!(state, None | Some('Z' | 'X' | 'x'))
}
#[cfg(not(target_os = "linux"))]
{
let Ok(out) = Command::new("ps")
.args(["-o", "stat=", "-p", pid])
.stderr(Stdio::null())
.output()
else {
return false;
};
let stat = String::from_utf8_lossy(&out.stdout);
let stat = stat.trim();
out.status.success() && !stat.is_empty() && !stat.starts_with('Z')
}
}
#[cfg(unix)]
#[test]
fn a_background_process_holding_the_pipe_does_not_hold_up_the_version() {
let began = Instant::now();
let v = version_sh("sleep 5 & echo 'tool 3.0'", &[], VERSION_TIMEOUT).unwrap();
assert_eq!(v, "tool 3.0");
assert!(
began.elapsed() < Duration::from_secs(3),
"{:?}",
began.elapsed()
);
}
#[cfg(unix)]
#[test]
fn a_failing_prepare_is_reported_as_prepare() {
let res = interleaved(
&[Subject {
name: "x".into(),
cmd: vec!["true".into()],
prepare: Some(vec![
"/bin/sh".into(),
"-c".into(),
"echo nope >&2; exit 3".into(),
]),
setup: None,
setup_dir: None,
check: None,
dir: None,
version_cmd: None,
env: BTreeMap::new(),
vars: BTreeMap::new(),
when: None,
runs: Runs::Fixed(1),
auto: AutoRuns {
budget: Duration::from_secs(30),
min: 5,
max: 50,
},
warmup: 0,
counters: false,
allocations: false,
ok_exit_codes: vec![0],
metrics: BTreeMap::new(),
}],
0,
&Settings::default(),
&mut Quiet,
);
let msg = format!("{:#}", res[0].as_ref().unwrap_err());
assert!(msg.contains("prepare") && msg.contains("nope"), "{msg}");
}
#[cfg(unix)]
fn alternating(dir: &Path, warmup: u32, runs: u32) -> Subject {
Subject {
name: "alt".into(),
cmd: vec![
"/bin/sh".into(),
"-c".into(),
"echo x >> n".into(),
],
prepare: None,
setup: None,
setup_dir: None,
check: Some(vec![
"/bin/sh".into(),
"-c".into(),
"echo check >> checked; runs=$(( $(wc -l < n) )); test $(( runs % 2 )) = 1 || { echo \"run $runs is even\" >&2; exit 1; }".into(),
]),
version_cmd: None,
dir: Some(dir.to_path_buf()),
env: BTreeMap::new(),
vars: BTreeMap::new(),
when: None,
runs: Runs::Fixed(runs),
auto: AutoRuns {
budget: Duration::from_secs(30),
min: 5,
max: 50,
},
warmup,
counters: false,
allocations: false,
ok_exit_codes: vec![0],
metrics: BTreeMap::new(),
}
}
#[cfg(unix)]
#[test]
fn a_failing_check_marks_the_sample_without_dropping_the_subject() {
let dir = tempfile::tempdir().unwrap();
let res = interleaved(
&[alternating(dir.path(), 1, 6)],
0,
&Settings::default(),
&mut Quiet,
);
let s = res[0].as_ref().unwrap();
assert_eq!(s.times.len(), 6);
assert_eq!(s.checks, [false, true, false, true, false, true]);
assert_eq!(s.passed(), 3);
assert!(
s.first_failure
.as_deref()
.unwrap()
.contains("run 2 is even"),
"{s:?}"
);
let checked = std::fs::read_to_string(dir.path().join("checked")).unwrap();
assert_eq!(checked.lines().count(), 6, "no check after the warmup");
}
#[cfg(unix)]
#[test]
fn ok_exit_codes_do_not_pass_a_check_that_exits_1() {
let dir = tempfile::tempdir().unwrap();
let mut s = alternating(dir.path(), 0, 2);
s.cmd = vec!["/bin/sh".into(), "-c".into(), "exit 1".into()];
s.check = Some(vec!["/bin/sh".into(), "-c".into(), "exit 1".into()]);
s.ok_exit_codes = vec![0, 1];
let res = interleaved(&[s], 0, &Settings::default(), &mut Quiet);
let s = res[0].as_ref().unwrap();
assert_eq!(s.exit_codes, [1, 1]);
assert_eq!(s.checks, [false, false]);
assert_eq!(s.passed(), 0);
}
#[cfg(unix)]
#[test]
fn a_check_that_cannot_start_drops_the_subject() {
let dir = tempfile::tempdir().unwrap();
let mut s = alternating(dir.path(), 0, 2);
s.check = Some(vec!["/nonexistent/tak-check".into()]);
let res = interleaved(&[s], 0, &Settings::default(), &mut Quiet);
let msg = format!("{:#}", res[0].as_ref().unwrap_err());
assert!(msg.contains("failed to spawn check"), "{msg}");
}
#[cfg(unix)]
#[test]
fn a_process_left_by_a_passing_step_can_still_write_to_stderr() {
let dir = tempfile::tempdir().unwrap();
let env = BTreeMap::new();
let settings = Settings::default();
let site = Site {
dir: Some(dir.path()),
env: &env,
settings: &settings,
};
const N: usize = 10;
let start = Instant::now();
for i in 0..N {
let script = format!(
"{{ sh -c 'sleep 1; echo late >&2'; echo $? > s{i}.tmp && mv s{i}.tmp s{i}; }} & exit 0"
);
let step = ["/bin/sh".to_string(), "-c".into(), script];
assert_eq!(untimed("setup", &step, &site).unwrap(), None);
}
let took = start.elapsed();
assert!(took < Duration::from_secs(2), "{N} passes took {took:?}");
let deadline = Instant::now() + Duration::from_secs(20);
let statuses: Vec<String> = (0..N)
.map(|i| {
loop {
if let Ok(s) = std::fs::read_to_string(dir.path().join(format!("s{i}"))) {
break s.trim().to_string();
}
assert!(Instant::now() < deadline, "leftover {i} never finished");
std::thread::sleep(Duration::from_millis(50));
}
})
.collect();
assert!(statuses.iter().all(|s| s == "0"), "{statuses:?}");
}
#[derive(Default)]
struct Log {
plans: Vec<Vec<u64>>,
finished: Vec<usize>,
events: Vec<String>,
}
impl Observer for Log {
fn planned(&mut self, remaining: &[u64]) {
self.plans.push(remaining.to_vec());
}
fn setting_up(&mut self, subject: usize) {
self.events.push(format!("setup:{subject}"));
}
fn started(&mut self, subject: usize) {
self.events.push(format!("start:{subject}"));
}
fn dropped(&mut self, subject: usize) {
self.events.push(format!("drop:{subject}"));
}
fn finished(&mut self, subject: usize, _: Duration) {
self.finished.push(subject);
}
}
#[cfg(unix)]
#[test]
fn setups_run_once_first_and_a_failing_one_drops_its_subject() {
let sh = |script: &str| Some(["/bin/sh", "-c", script].map(String::from).to_vec());
let mk = |name: &str, setup: Option<Vec<String>>| Subject {
name: name.into(),
cmd: vec!["true".into()],
prepare: None,
setup,
setup_dir: None,
check: None,
version_cmd: None,
dir: None,
env: BTreeMap::new(),
vars: BTreeMap::new(),
when: None,
runs: Runs::Auto,
auto: AutoRuns {
budget: Duration::from_secs(30),
min: 2,
max: 2,
},
warmup: 1,
counters: false,
allocations: false,
ok_exit_codes: vec![0],
metrics: BTreeMap::new(),
};
let mut log = Log::default();
let res = interleaved(
&[
mk("ok", sh("true")),
mk("bad", sh("echo no fixture >&2; exit 2")),
mk("none", None),
],
3,
&Settings::default(),
&mut log,
);
assert_eq!(log.events[..3], ["setup:0", "setup:1", "drop:1"]);
assert!(!log.events[3..].iter().any(|e| e.starts_with("setup:")));
assert!(!log.events.contains(&"start:1".to_string()));
assert_eq!(res[0].as_ref().unwrap().times.len(), 2);
assert_eq!(res[2].as_ref().unwrap().times.len(), 2);
let msg = format!("{:#}", res[1].as_ref().unwrap_err());
assert!(msg.contains("setup") && msg.contains("no fixture"), "{msg}");
assert_eq!(log.finished.len(), 2 * (1 + 2));
}
#[cfg(unix)]
#[test]
fn auto_runs_give_a_slow_subject_the_floor_and_a_fast_one_more() {
let mk = |name: &str, secs: &str, warmup: u32| Subject {
name: name.into(),
cmd: vec!["sleep".into(), secs.into()],
prepare: None,
setup: None,
setup_dir: None,
check: None,
dir: None,
version_cmd: None,
env: BTreeMap::new(),
vars: BTreeMap::new(),
when: None,
runs: Runs::Auto,
auto: AutoRuns {
budget: Duration::from_millis(600),
min: 2,
max: 6,
},
warmup,
counters: false,
allocations: false,
ok_exit_codes: vec![0],
metrics: BTreeMap::new(),
};
let mut log = Log::default();
let res = interleaved(
&[mk("fast", "0.01", 1), mk("slow", "0.5", 0)],
9,
&Settings::default(),
&mut log,
);
let fast = res[0].as_ref().unwrap().times.len();
let slow = res[1].as_ref().unwrap().times.len();
assert_eq!(slow, 2, "0.6s budget / 0.5s sample is below the floor");
assert!(fast > slow && fast <= 6, "fast got {fast}");
assert_eq!(log.plans[0], [1 + 2, 2]);
assert_eq!(log.plans.len(), 2);
assert_eq!(log.finished.len(), 1 + fast + slow);
}
#[test]
fn steady_samples_raise_no_warning() {
assert!(warnings(&[10.0, 10.2, 9.9, 10.1, 10.0, 10.3]).is_empty());
assert!(warnings(&[10.0, 50.0]).is_empty(), "too few to judge");
}
#[test]
fn a_spike_is_an_outlier() {
let w = warnings(&[10.0, 10.2, 9.9, 10.1, 40.0, 10.0, 10.1]);
assert_eq!(w.len(), 1, "{w:?}");
assert!(
w[0].starts_with("1 of 7 samples are slow outliers"),
"{w:?}"
);
}
#[test]
fn a_slow_first_sample_is_called_out() {
let w = warnings(&[35.0, 10.0, 10.2, 9.9, 10.1, 10.0]);
assert!(
w.iter().any(|m| m.contains("first sample took 3.5x")),
"{w:?}"
);
}
#[test]
fn a_spike_among_identical_samples_is_still_an_outlier() {
let w = warnings(&[10.0, 10.0, 10.0, 100.0, 10.0]);
assert!(w.iter().any(|m| m.contains("slow outliers")), "{w:?}");
assert!(
warnings(&[10.0; 6]).is_empty(),
"identical samples are fine"
);
}
#[test]
fn a_fast_outlier_is_flagged_as_possibly_the_minimum() {
let w = warnings(&[100.0, 101.0, 99.0, 102.0, 10.0, 100.0]);
assert!(
w.iter()
.any(|m| m.contains("fast outliers") && m.contains("minimum")),
"{w:?}"
);
}
#[test]
fn several_spikes_over_a_flat_majority_are_caught() {
let w = warnings(&[10.0, 10.0, 10.0, 10.0, 40.0, 45.0]);
assert!(
w.iter()
.any(|m| m.starts_with("2 of 6 samples are slow outliers")),
"{w:?}"
);
assert!(
warnings(&[10.0, 10.0, 10.0, 11.0, 10.0]).is_empty(),
"10% is not a spike"
);
}
}