1use crate::config::{AutoRuns, DEFAULT_OK_EXIT_CODES, Runs, SELF_TOOL, Subject};
17use crate::settings::Settings;
18use anyhow::{Context, Result, bail};
19use std::collections::BTreeMap;
20use std::path::Path;
21use std::process::{Command, Stdio};
22use std::sync::{Arc, Mutex};
23use std::time::Duration;
24use std::time::Instant;
25
26#[derive(Debug, Clone)]
27pub struct Plan {
28 pub cmd: Vec<String>,
29 pub warmup: u32,
30 pub runs: u32,
31 pub dir: Option<std::path::PathBuf>,
35 pub settings: Settings,
39}
40
41fn subject(bin: &str, settings: &Settings) -> Command {
60 let mut c = Command::new(bin);
61 for key in settings.scrubbed_env() {
62 c.env_remove(key);
63 }
64 c
65}
66
67#[derive(Debug, Clone, Copy)]
69struct Site<'a> {
70 dir: Option<&'a Path>,
71 env: &'a BTreeMap<String, String>,
72 settings: &'a Settings,
73}
74
75fn command(argv: &[String], site: &Site) -> Result<Command> {
81 let (bin, args) = argv.split_first().context("empty command")?;
82 let mut c = subject(bin, site.settings);
83 c.args(args).envs(site.env);
84 if let Some(d) = site.dir {
85 c.current_dir(d);
86 }
87 Ok(c)
88}
89
90#[derive(Debug, Clone, Copy, PartialEq)]
92pub struct Sample {
93 pub ms: f64,
95 pub exit_code: i32,
98}
99
100fn accepted(bin: &str, status: std::process::ExitStatus, ok: &[i32], via: &str) -> Result<i32> {
107 match status.code() {
108 Some(code) if ok.contains(&code) => Ok(code),
109 _ if ok == DEFAULT_OK_EXIT_CODES => {
113 bail!("benchmark subject `{bin}` exited with {status}{via}")
114 }
115 _ => bail!(
116 "benchmark subject `{bin}` exited with {status}{via}, and ok_exit_codes is {}",
117 ok.iter().map(i32::to_string).collect::<Vec<_>>().join(", ")
118 ),
119 }
120}
121
122fn time_once(cmd: &[String], site: &Site, ok: &[i32]) -> Result<Sample> {
128 let mut c = command(cmd, site)?;
129 c.stdout(Stdio::null()).stderr(Stdio::null());
130 let bin = &cmd[0];
131 let start = Instant::now();
132 let status = c
133 .status()
134 .with_context(|| format!("failed to spawn `{bin}`"))?;
135 let ms = start.elapsed().as_secs_f64() * 1000.0;
136 let exit_code = accepted(bin, status, ok, "")?;
137 Ok(Sample { ms, exit_code })
138}
139
140const UNTIMED_STDERR_TAIL: usize = 4096;
144
145fn prepare_once(cmd: &[String], site: &Site) -> Result<()> {
148 required("prepare", cmd, site)
149}
150
151fn required(what: &str, cmd: &[String], site: &Site) -> Result<()> {
153 match untimed(what, cmd, site)? {
154 None => Ok(()),
155 Some(failure) => bail!("{failure}"),
156 }
157}
158
159fn check_once(cmd: &[String], site: &Site) -> Result<Option<String>> {
164 untimed("check", cmd, site)
165}
166
167fn untimed(step: &str, cmd: &[String], site: &Site) -> Result<Option<String>> {
199 let mut c = command(cmd, site)?;
200 let bin = &cmd[0];
201 let err = tempfile::tempfile()
202 .with_context(|| format!("failed to create a file for {step} `{bin}`'s stderr"))?;
203 let reader = err
204 .try_clone()
205 .with_context(|| format!("failed to create a file for {step} `{bin}`'s stderr"))?;
206 let status = c
207 .stdin(Stdio::null())
208 .stdout(Stdio::null())
209 .stderr(Stdio::from(err))
210 .status()
211 .with_context(|| format!("failed to spawn {step} `{bin}`"))?;
212 if status.success() {
213 return Ok(None);
214 }
215 let tail = stderr_tail(&reader).unwrap_or_default();
219 let stderr = String::from_utf8_lossy(&tail);
220 Ok(Some(match stderr.lines().rfind(|l| !l.trim().is_empty()) {
221 Some(last) => format!("{step} `{bin}` exited with {status}: {}", last.trim()),
222 None => format!("{step} `{bin}` exited with {status}"),
223 }))
224}
225
226fn stderr_tail(f: &std::fs::File) -> std::io::Result<Vec<u8>> {
234 let len = f.metadata()?.len();
235 let start = len.saturating_sub(UNTIMED_STDERR_TAIL as u64);
236 let mut buf = vec![0u8; (len - start) as usize];
237 let mut filled = 0;
238 while filled < buf.len() {
239 let n = read_at(f, &mut buf[filled..], start + filled as u64)?;
240 if n == 0 {
241 break;
242 }
243 filled += n;
244 }
245 buf.truncate(filled);
246 Ok(buf)
247}
248
249#[cfg(unix)]
250fn read_at(f: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result<usize> {
251 std::os::unix::fs::FileExt::read_at(f, buf, offset)
252}
253
254#[cfg(windows)]
255fn read_at(f: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result<usize> {
256 std::os::windows::fs::FileExt::seek_read(f, buf, offset)
257}
258
259#[derive(Debug, Clone, Copy, PartialEq, Eq)]
261pub struct Slot {
262 pub subject: usize,
264 pub timed: bool,
267}
268
269pub fn schedule(counts: &[(u32, u32)], seed: u64) -> Vec<Slot> {
287 let mut rng = fastrand::Rng::with_seed(seed);
288 let warmups: Vec<u64> = counts.iter().map(|&(w, _)| u64::from(w)).collect();
289 let runs: Vec<u64> = counts.iter().map(|&(_, r)| u64::from(r)).collect();
290 let mut out = rounds(&warmups, false, &mut rng);
291 out.extend(rounds(&runs, true, &mut rng));
292 out
293}
294
295fn rounds(count: &[u64], timed: bool, rng: &mut fastrand::Rng) -> Vec<Slot> {
297 let total = count.iter().copied().max().unwrap_or(0);
298 let mut out = Vec::new();
299 for round in 0..total {
300 let mut due: Vec<usize> = (0..count.len())
303 .filter(|&i| (round + 1) * count[i] / total > round * count[i] / total)
304 .collect();
305 rng.shuffle(&mut due);
306 out.extend(due.into_iter().map(|subject| Slot { subject, timed }));
307 }
308 out
309}
310
311pub fn seed_for(seed: u64, bench: &str) -> u64 {
314 bench.bytes().fold(seed ^ 0xcbf2_9ce4_8422_2325, |h, b| {
316 (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)
317 })
318}
319
320pub trait Observer {
322 fn planned(&mut self, _remaining: &[u64]) {}
325 fn setting_up(&mut self, _subject: usize) {}
328 fn started(&mut self, _subject: usize) {}
330 fn finished(&mut self, _subject: usize, _elapsed: Duration) {}
332 fn dropped(&mut self, _subject: usize) {}
334}
335
336pub struct Quiet;
338impl Observer for Quiet {}
339
340#[derive(Debug, Clone, Default, PartialEq)]
342pub struct Samples {
343 pub times: Vec<f64>,
345 pub checks: Vec<bool>,
348 pub exit_codes: Vec<i32>,
351 pub first_failure: Option<String>,
353}
354
355impl Samples {
356 pub fn passed(&self) -> usize {
358 self.checks.iter().filter(|&&ok| ok).count()
359 }
360}
361
362pub fn interleaved(
387 subjects: &[Subject],
388 seed: u64,
389 settings: &Settings,
390 observer: &mut dyn Observer,
391) -> Vec<Result<Samples>> {
392 interleaved_with_versions(subjects, seed, settings, observer).0
393}
394
395pub type Version = Option<Result<String>>;
398
399pub fn interleaved_with_versions(
407 subjects: &[Subject],
408 seed: u64,
409 settings: &Settings,
410 observer: &mut dyn Observer,
411) -> (Vec<Result<Samples>>, Vec<Version>) {
412 let mut rng = fastrand::Rng::with_seed(seed);
413 let mut results: Vec<Result<Samples>> = subjects
414 .iter()
415 .map(|s| {
416 if s.runs == Runs::Fixed(0) {
418 bail!("runs must be at least 1");
419 }
420 Ok(Samples::default())
421 })
422 .collect();
423 let mut fastest: Vec<Option<Duration>> = vec![None; subjects.len()];
427
428 let warmups: Vec<u64> = subjects.iter().map(|s| u64::from(s.warmup)).collect();
429 let pilots: Vec<u64> = subjects
430 .iter()
431 .map(|s| u64::from(s.runs == Runs::Auto && s.warmup == 0))
432 .collect();
433 let provisional: Vec<u64> = subjects
435 .iter()
436 .zip(&warmups)
437 .map(|(s, w)| {
438 w + u64::from(match s.runs {
439 Runs::Fixed(n) => n,
440 Runs::Auto => s.auto.min,
441 })
442 })
443 .collect();
444 observer.planned(&provisional);
445
446 for (i, s) in subjects.iter().enumerate() {
447 let (Some(setup), Ok(_)) = (&s.setup, &results[i]) else {
448 continue;
449 };
450 observer.setting_up(i);
451 let site = Site {
452 dir: s.setup_dir.as_deref(),
453 env: &s.env,
454 settings,
455 };
456 if let Err(e) = required("setup", setup, &site) {
457 results[i] = Err(e);
458 observer.dropped(i);
459 }
460 }
461
462 let versions: Vec<Version> = subjects
463 .iter()
464 .zip(&results)
465 .map(|(s, r)| r.as_ref().ok().and_then(|_| subject_version(s, settings)))
466 .collect();
467
468 let mut first = rounds(&warmups, false, &mut rng);
469 first.extend(rounds(&pilots, true, &mut rng));
470 run_slots(
471 &first,
472 subjects,
473 settings,
474 &mut results,
475 &mut fastest,
476 observer,
477 );
478
479 let remaining: Vec<u64> = subjects
480 .iter()
481 .enumerate()
482 .map(|(i, s)| match (&results[i], s.runs) {
483 (Err(_), _) => 0,
484 (Ok(_), Runs::Fixed(n)) => u64::from(n),
485 (Ok(taken), Runs::Auto) => {
486 let n = auto_runs(&s.auto, fastest[i]);
487 u64::from(n).saturating_sub(taken.times.len() as u64)
488 }
489 })
490 .collect();
491 observer.planned(&remaining);
492 let second = rounds(&remaining, true, &mut rng);
493 run_slots(
494 &second,
495 subjects,
496 settings,
497 &mut results,
498 &mut fastest,
499 observer,
500 );
501 (results, versions)
502}
503
504fn auto_runs(auto: &AutoRuns, fastest: Option<Duration>) -> u32 {
507 fastest.map_or(auto.min, |d| auto.runs_for(d))
508}
509
510fn run_slots(
517 slots: &[Slot],
518 subjects: &[Subject],
519 settings: &Settings,
520 results: &mut [Result<Samples>],
521 fastest: &mut [Option<Duration>],
522 observer: &mut dyn Observer,
523) {
524 for slot in slots {
525 let Ok(samples) = &mut results[slot.subject] else {
526 continue;
527 };
528 let s = &subjects[slot.subject];
529 let site = Site {
530 dir: s.dir.as_deref(),
531 env: &s.env,
532 settings,
533 };
534 observer.started(slot.subject);
535 let began = Instant::now();
536 let taken = s
537 .prepare
538 .as_deref()
539 .map_or(Ok(()), |p| prepare_once(p, &site))
540 .and_then(|()| time_once(&s.cmd, &site, &s.ok_exit_codes));
541 let elapsed = began.elapsed();
542 let checked = match (&taken, &s.check) {
545 (Ok(_), Some(check)) if slot.timed => check_once(check, &site).map(Some),
546 _ => Ok(None),
547 };
548 match taken.and_then(|sample| checked.map(|c| (sample, c))) {
549 Ok((sample, check)) => {
550 if slot.timed {
551 samples.times.push(sample.ms);
552 samples.exit_codes.push(sample.exit_code);
553 }
554 if let Some(failure) = check {
555 samples.checks.push(failure.is_none());
556 if samples.first_failure.is_none() {
557 samples.first_failure = failure;
558 }
559 }
560 let f = &mut fastest[slot.subject];
561 *f = Some(f.map_or(elapsed, |f| f.min(elapsed)));
562 observer.finished(slot.subject, began.elapsed());
563 }
564 Err(e) => {
565 results[slot.subject] = Err(e);
566 observer.dropped(slot.subject);
567 }
568 }
569 }
570}
571
572pub fn stats(samples: &[f64]) -> BTreeMap<String, f64> {
579 let mut sorted = samples.to_vec();
580 sorted.sort_by(f64::total_cmp);
581 let n = sorted.len();
582 let mean = sorted.iter().sum::<f64>() / n as f64;
583 let stddev = if n > 1 {
585 (sorted.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64).sqrt()
586 } else {
587 0.0
588 };
589 BTreeMap::from([
590 ("wall_min_ms".to_string(), sorted[0]),
591 ("wall_p50_ms".to_string(), sorted[n / 2]),
592 ("wall_mean_ms".to_string(), mean),
593 ("wall_max_ms".to_string(), sorted[n - 1]),
594 ("wall_stddev_ms".to_string(), stddev),
595 ("wall_n".to_string(), n as f64),
596 ])
597}
598
599pub fn warnings(samples: &[f64]) -> Vec<String> {
614 let mut out = Vec::new();
615 let n = samples.len();
616 if n < 5 {
617 return out;
618 }
619 let median = |v: &mut Vec<f64>| {
620 v.sort_by(f64::total_cmp);
621 let m = v.len();
622 if m.is_multiple_of(2) {
623 (v[m / 2 - 1] + v[m / 2]) / 2.0
624 } else {
625 v[m / 2]
626 }
627 };
628 let med = median(&mut samples.to_vec());
629 let mad = median(&mut samples.iter().map(|x| (x - med).abs()).collect());
630 let outlier = |x: f64| {
637 if mad > 0.0 {
638 0.6745 * (x - med).abs() / mad > 3.5
639 } else {
640 med > 0.0 && (x - med).abs() > 0.25 * med
641 }
642 };
643 {
644 let (fast, slow) = samples
645 .iter()
646 .filter(|&&x| outlier(x))
647 .fold(
648 (0, 0),
649 |(f, s), &x| if x < med { (f + 1, s) } else { (f, s + 1) },
650 );
651 if slow > 0 {
652 out.push(format!(
653 "{slow} of {n} samples are slow outliers; something else was running, or the \
654 command's work varies. Consider a quieter machine or more runs."
655 ));
656 }
657 if fast > 0 {
660 out.push(format!(
661 "{fast} of {n} samples are fast outliers, and the reported minimum may be one of \
662 them; check the command did the same work every time."
663 ));
664 }
665 }
666 let rest = median(&mut samples[1..].to_vec());
667 if rest > 0.0 && samples[0] > 2.0 * rest {
668 out.push(format!(
669 "the first sample took {:.1}x the median of the rest; the warmup did not fill some \
670 cache. Consider more warmup runs.",
671 samples[0] / rest
672 ));
673 }
674 out
675}
676
677pub fn wall(plan: &Plan) -> Result<BTreeMap<String, f64>> {
679 let subject = Subject {
680 name: SELF_TOOL.to_string(),
681 cmd: plan.cmd.clone(),
682 prepare: None,
683 setup: None,
684 setup_dir: None,
685 check: None,
686 dir: plan.dir.clone(),
687 version_cmd: None,
688 env: BTreeMap::new(),
689 vars: BTreeMap::new(),
690 when: None,
691 runs: Runs::Fixed(plan.runs),
692 auto: AutoRuns {
693 budget: crate::config::DEFAULT_BUDGET,
694 min: crate::config::DEFAULT_MIN_RUNS,
695 max: crate::config::DEFAULT_MAX_RUNS,
696 },
697 warmup: plan.warmup,
698 counters: false,
699 ok_exit_codes: DEFAULT_OK_EXIT_CODES.to_vec(),
700 };
701 let samples = interleaved(
703 std::slice::from_ref(&subject),
704 0,
705 &plan.settings,
706 &mut Quiet,
707 )
708 .pop()
709 .expect("one result per subject")?;
710 Ok(stats(&samples.times))
711}
712
713pub fn valgrind_available() -> bool {
719 Command::new("valgrind")
720 .arg("--version")
721 .stdout(Stdio::null())
722 .stderr(Stdio::null())
723 .status()
724 .map(|s| s.success())
725 .unwrap_or(false)
726}
727
728const COUNTER_RUNS: u32 = 3;
731
732const SPREAD_WARN_PCT: f64 = 0.5;
737
738#[derive(Debug, Clone, Copy)]
740pub struct Counted {
741 pub min: u64,
742 pub max: u64,
743 pub runs: u32,
744}
745
746impl Counted {
747 pub fn spread_pct(&self) -> f64 {
749 if self.min == 0 {
750 return 0.0;
751 }
752 (self.max - self.min) as f64 / self.min as f64 * 100.0
753 }
754
755 pub fn is_suspect(&self) -> bool {
762 self.spread_pct() > SPREAD_WARN_PCT
763 }
764}
765
766pub fn instructions(
778 cmd: &[String],
779 dir: Option<&std::path::Path>,
780 settings: &Settings,
781) -> Result<Option<Counted>> {
782 count(
783 cmd,
784 None,
785 &Site {
786 dir,
787 env: &BTreeMap::new(),
788 settings,
789 },
790 &DEFAULT_OK_EXIT_CODES,
791 )
792}
793
794pub fn subject_instructions(s: &Subject, settings: &Settings) -> Result<Option<Counted>> {
798 count(
799 &s.cmd,
800 s.prepare.as_deref(),
801 &Site {
802 dir: s.dir.as_deref(),
803 env: &s.env,
804 settings,
805 },
806 &s.ok_exit_codes,
807 )
808}
809
810pub fn subject_version(s: &Subject, settings: &Settings) -> Option<Result<String>> {
821 let argv = s.version_cmd.as_ref()?;
822 let site = Site {
823 dir: s.dir.as_deref(),
824 env: &s.env,
825 settings,
826 };
827 Some(version_once(argv, &site, VERSION_TIMEOUT))
828}
829
830const VERSION_OUTPUT_CAP: usize = 8192;
834
835const VERSION_TIMEOUT: Duration = Duration::from_secs(10);
840
841const VERSION_OUTPUT_GRACE: Duration = Duration::from_millis(500);
846
847fn keep_prefix(mut r: impl std::io::Read, cap: usize, kept: &Mutex<Vec<u8>>) {
851 let mut buf = [0u8; 8192];
852 loop {
853 match r.read(&mut buf) {
854 Ok(0) => return,
855 Ok(n) => {
856 let Ok(mut k) = kept.lock() else { return };
857 let room = cap.saturating_sub(k.len());
858 k.extend_from_slice(&buf[..n.min(room)]);
859 }
860 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
861 Err(_) => return,
862 }
863 }
864}
865
866#[cfg(unix)]
878mod forward_signals {
879 use std::sync::atomic::{AtomicBool, AtomicI32, Ordering::SeqCst};
880
881 const SIGNALS: [libc::c_int; 3] = [libc::SIGINT, libc::SIGTERM, libc::SIGHUP];
882
883 pub(super) struct State {
906 spawning: AtomicBool,
909 pgid: AtomicI32,
911 pending: AtomicI32,
914 done: AtomicBool,
917 }
918
919 #[derive(Debug, PartialEq, Eq)]
921 pub(super) enum Act {
922 Defer,
924 Die { pgid: i32 },
926 }
927
928 impl State {
929 pub(super) const fn new() -> State {
930 State {
931 spawning: AtomicBool::new(false),
932 pgid: AtomicI32::new(0),
933 pending: AtomicI32::new(0),
934 done: AtomicBool::new(true),
935 }
936 }
937
938 pub(super) fn begin(&self) {
939 self.pending.store(0, SeqCst);
940 self.pgid.store(0, SeqCst);
941 self.done.store(false, SeqCst);
942 self.spawning.store(true, SeqCst);
943 }
944
945 pub(super) fn on_signal(&self, sig: libc::c_int) -> Act {
947 if self.wants_to_defer() {
948 self.defer(sig)
949 } else {
950 Act::Die {
951 pgid: self.pgid.load(SeqCst),
952 }
953 }
954 }
955
956 fn wants_to_defer(&self) -> bool {
959 let spawning = self.spawning.load(SeqCst);
960 spawning && self.pgid.load(SeqCst) == 0
961 }
962
963 fn defer(&self, sig: libc::c_int) -> Act {
966 self.pending.store(sig, SeqCst);
967 if self.done.load(SeqCst) {
968 return Act::Die { pgid: 0 };
969 }
970 match self.pgid.load(SeqCst) {
971 0 => Act::Defer,
972 pgid => Act::Die { pgid },
973 }
974 }
975
976 pub(super) fn spawned(&self, pid: Option<u32>) -> Option<(libc::c_int, i32)> {
980 let pgid = pid.map_or(0, |p| p as i32);
981 self.pgid.store(pgid, SeqCst);
982 self.spawning.store(false, SeqCst);
983 let sig = self.pending.swap(0, SeqCst);
984 (sig != 0).then_some((sig, pgid))
985 }
986
987 pub(super) fn end(&self) -> Option<libc::c_int> {
991 self.spawning.store(false, SeqCst);
992 self.done.store(true, SeqCst);
993 self.pgid.store(0, SeqCst);
994 let sig = self.pending.swap(0, SeqCst);
995 (sig != 0).then_some(sig)
996 }
997 }
998
999 static STATE: State = State::new();
1000
1001 fn die(sig: libc::c_int, pgid: i32) {
1005 unsafe {
1007 if pgid > 0 {
1008 libc::killpg(pgid, libc::SIGKILL);
1009 }
1010 libc::signal(sig, libc::SIG_DFL);
1011 libc::raise(sig);
1012 }
1013 }
1014
1015 extern "C" fn forward(sig: libc::c_int) {
1016 if let Act::Die { pgid } = STATE.on_signal(sig) {
1017 die(sig, pgid);
1018 }
1019 }
1020
1021 pub struct Guard {
1022 previous: Vec<(libc::c_int, libc::sigaction)>,
1023 }
1024
1025 impl Guard {
1026 pub fn install() -> Guard {
1029 STATE.begin();
1030 let mut previous = Vec::new();
1031 for sig in SIGNALS {
1032 unsafe {
1036 let mut new: libc::sigaction = std::mem::zeroed();
1037 new.sa_sigaction = forward as extern "C" fn(libc::c_int) as libc::sighandler_t;
1038 libc::sigemptyset(&mut new.sa_mask);
1039 let mut old: libc::sigaction = std::mem::zeroed();
1040 if libc::sigaction(sig, &new, &mut old) == 0 {
1041 previous.push((sig, old));
1042 }
1043 }
1044 }
1045 Guard { previous }
1046 }
1047
1048 pub fn spawned(pid: Option<u32>) {
1051 if let Some((sig, pgid)) = STATE.spawned(pid) {
1052 die(sig, pgid);
1053 }
1054 }
1055 }
1056
1057 impl Drop for Guard {
1058 fn drop(&mut self) {
1059 if let Some(sig) = STATE.end() {
1062 die(sig, 0);
1063 }
1064 for (sig, old) in &self.previous {
1065 unsafe {
1067 libc::sigaction(*sig, old, std::ptr::null_mut());
1068 }
1069 }
1070 }
1071 }
1072
1073 #[cfg(test)]
1077 mod tests {
1078 use super::{Act, SeqCst, State};
1079
1080 #[test]
1081 fn a_signal_during_the_spawn_is_held_until_the_group_is_known() {
1082 let s = State::new();
1083 s.begin();
1084 assert_eq!(s.on_signal(libc::SIGTERM), Act::Defer, "no group yet");
1085 assert_eq!(s.spawned(Some(42)), Some((libc::SIGTERM, 42)));
1086 assert_eq!(s.on_signal(libc::SIGINT), Act::Die { pgid: 42 });
1087 assert_eq!(s.end(), None);
1088
1089 s.begin();
1090 assert_eq!(s.spawned(Some(7)), None, "nothing arrived");
1091 assert_eq!(s.end(), None);
1092
1093 s.begin();
1094 assert_eq!(s.on_signal(libc::SIGINT), Act::Defer);
1095 assert_eq!(
1096 s.spawned(None),
1097 Some((libc::SIGINT, 0)),
1098 "a failed spawn still stops tak"
1099 );
1100 assert_eq!(s.end(), None);
1101
1102 assert_eq!(
1103 s.on_signal(libc::SIGHUP),
1104 Act::Die { pgid: 0 },
1105 "after the step"
1106 );
1107 assert!(!s.wants_to_defer(), "and it never defers there");
1108 }
1109
1110 #[test]
1113 fn a_handler_preempted_past_the_step_still_acts() {
1114 let s = State::new();
1115
1116 s.begin();
1119 assert!(s.wants_to_defer());
1120 assert_eq!(s.spawned(Some(42)), None);
1121 assert_eq!(s.end(), None);
1122 assert_eq!(s.defer(libc::SIGTERM), Act::Die { pgid: 0 });
1123
1124 s.begin();
1127 assert!(s.wants_to_defer());
1128 assert_eq!(s.spawned(Some(42)), None);
1129 assert_eq!(s.defer(libc::SIGINT), Act::Die { pgid: 42 });
1130 assert_eq!(s.end(), Some(libc::SIGINT));
1131
1132 s.begin();
1135 assert_eq!(s.spawned(Some(42)), None);
1136 s.pending.store(libc::SIGHUP, SeqCst);
1137 assert_eq!(s.end(), Some(libc::SIGHUP), "acted on at teardown");
1138 }
1139 }
1140}
1141
1142fn stop_group(child: &mut std::process::Child) {
1152 #[cfg(unix)]
1153 {
1154 let pgid = child.id() as libc::pid_t;
1157 if unsafe { libc::killpg(pgid, libc::SIGKILL) } != 0 {
1158 let _ = child.kill();
1159 }
1160 }
1161 #[cfg(not(unix))]
1162 let _ = child.kill();
1163 let _ = child.wait();
1164}
1165
1166fn version_once(argv: &[String], site: &Site, timeout: Duration) -> Result<String> {
1167 let bin = argv
1168 .first()
1169 .map(String::as_str)
1170 .unwrap_or("(empty command)");
1171 let mut cmd = command(argv, site)?;
1172 cmd.stdin(Stdio::null())
1173 .stdout(Stdio::piped())
1174 .stderr(Stdio::piped());
1175 #[cfg(unix)]
1178 std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
1179 #[cfg(unix)]
1182 let _forward = forward_signals::Guard::install();
1183 let spawned = cmd.spawn();
1184 #[cfg(unix)]
1186 forward_signals::Guard::spawned(spawned.as_ref().ok().map(std::process::Child::id));
1187 let mut child = spawned.with_context(|| format!("failed to spawn `{bin}`"))?;
1188
1189 let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
1194 let spawn_reader = |r: Option<Box<dyn std::io::Read + Send>>| {
1195 let kept = Arc::new(Mutex::new(Vec::new()));
1196 if let Some(r) = r {
1197 let (kept, tx) = (Arc::clone(&kept), done_tx.clone());
1198 std::thread::spawn(move || {
1199 keep_prefix(r, VERSION_OUTPUT_CAP, &kept);
1200 let _ = tx.send(());
1201 });
1202 } else {
1203 let _ = done_tx.send(());
1204 }
1205 kept
1206 };
1207 let stdout = spawn_reader(child.stdout.take().map(|o| Box::new(o) as _));
1208 let stderr = spawn_reader(child.stderr.take().map(|e| Box::new(e) as _));
1209
1210 let deadline = Instant::now() + timeout;
1211 let status = loop {
1212 match child.try_wait() {
1213 Ok(Some(status)) => break status,
1214 Ok(None) if Instant::now() < deadline => {
1215 std::thread::sleep(Duration::from_millis(5));
1216 }
1217 Ok(None) => {
1218 stop_group(&mut child);
1219 bail!(
1220 "`{bin}` did not finish within {}, so it was stopped",
1221 crate::progress::fmt(timeout)
1222 );
1223 }
1224 Err(e) => {
1225 stop_group(&mut child);
1226 return Err(e).with_context(|| format!("failed to wait for `{bin}`"));
1227 }
1228 }
1229 };
1230 let grace = Instant::now() + VERSION_OUTPUT_GRACE;
1231 for _ in 0..2 {
1232 let left = grace.saturating_duration_since(Instant::now());
1233 if done_rx.recv_timeout(left).is_err() {
1234 break;
1235 }
1236 }
1237 let take = |kept: &Mutex<Vec<u8>>| kept.lock().map(|k| k.clone()).unwrap_or_default();
1238 let (stdout, stderr) = (take(&stdout), take(&stderr));
1239
1240 if !status.success() {
1243 let stderr = String::from_utf8_lossy(&stderr);
1244 bail!(
1245 "`{bin}` exited with {status}: {}",
1246 stderr
1247 .lines()
1248 .map(str::trim)
1249 .rfind(|l| !l.is_empty())
1250 .unwrap_or("(no output)")
1251 );
1252 }
1253 let first = |bytes: &[u8]| {
1254 String::from_utf8_lossy(bytes)
1255 .lines()
1256 .map(str::trim)
1257 .find(|l| !l.is_empty())
1258 .map(str::to_string)
1259 };
1260 first(&stdout)
1261 .or_else(|| first(&stderr))
1262 .with_context(|| format!("`{bin}` printed nothing"))
1263}
1264
1265fn count(
1268 cmd: &[String],
1269 prepare: Option<&[String]>,
1270 site: &Site,
1271 ok: &[i32],
1272) -> Result<Option<Counted>> {
1273 if !valgrind_available() {
1274 return Ok(None);
1275 }
1276
1277 let mut samples: Vec<u64> = Vec::with_capacity(COUNTER_RUNS as usize);
1278 for _ in 0..COUNTER_RUNS {
1279 if let Some(p) = prepare {
1280 prepare_once(p, site)?;
1281 }
1282 let mut argv: Vec<String> = [
1283 "valgrind",
1284 "--tool=cachegrind",
1285 "--cache-sim=no",
1286 "--branch-sim=no",
1287 "--cachegrind-out-file=/dev/null",
1288 ]
1289 .map(String::from)
1290 .to_vec();
1291 argv.extend_from_slice(cmd);
1292 let mut c = command(&argv, site)?;
1293 c.stdout(Stdio::null());
1294 let out = c.output().context("failed to run valgrind")?;
1295
1296 let stderr = String::from_utf8_lossy(&out.stderr);
1298 let bin = cmd.first().map(String::as_str).unwrap_or("(empty command)");
1299 accepted(bin, out.status, ok, " under valgrind")?;
1300 match parse_irefs(&stderr) {
1301 Some(n) => samples.push(n),
1302 None => bail!(
1306 "valgrind ran but emitted no `I refs` summary: {}",
1307 stderr.lines().last().unwrap_or("(no output)").trim()
1308 ),
1309 }
1310 }
1311
1312 Ok(Some(Counted {
1313 min: *samples.iter().min().expect("COUNTER_RUNS > 0"),
1314 max: *samples.iter().max().expect("COUNTER_RUNS > 0"),
1315 runs: COUNTER_RUNS,
1316 }))
1317}
1318
1319fn parse_irefs(stderr: &str) -> Option<u64> {
1321 let line = stderr.lines().find(|l| l.contains("I refs:"))?;
1322 let digits: String = line
1323 .rsplit(':')
1324 .next()?
1325 .chars()
1326 .filter(|c| c.is_ascii_digit())
1327 .collect();
1328 digits.parse().ok()
1329}
1330
1331#[cfg(test)]
1332mod tests {
1333 use super::*;
1334
1335 #[test]
1336 fn parses_cachegrind_summary() {
1337 let s = "==12== I refs: 48,349,132\n";
1338 assert_eq!(parse_irefs(s), Some(48_349_132));
1339 }
1340
1341 #[test]
1342 fn missing_summary_is_none_not_panic() {
1343 assert_eq!(parse_irefs("valgrind: command not found"), None);
1344 }
1345
1346 fn removals(settings: &Settings) -> Vec<String> {
1348 subject("true", settings)
1349 .get_envs()
1350 .filter(|(_, v)| v.is_none())
1351 .map(|(k, _)| k.to_string_lossy().into_owned())
1352 .collect()
1353 }
1354
1355 #[test]
1358 fn subject_commands_remove_the_default_denied_variables() {
1359 let removed = removals(&Settings::default());
1360 for key in Settings::default().scrubbed_env() {
1361 assert!(removed.contains(&key.to_string()), "{key} not removed");
1362 }
1363 }
1364
1365 #[test]
1368 fn the_removal_follows_the_settings() {
1369 let removed = removals(&Settings {
1370 env_deny: vec!["CUSTOM_SECRET".into()],
1371 env_allow: Vec::new(),
1372 ..Settings::default()
1373 });
1374 assert!(removed.contains(&"CUSTOM_SECRET".to_string()));
1375 assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
1376 }
1377
1378 #[test]
1381 fn an_allowed_variable_survives() {
1382 let removed = removals(&Settings {
1383 env_deny: vec!["GITHUB_TOKEN".into(), "GH_TOKEN".into()],
1384 env_allow: vec!["GITHUB_TOKEN".into()],
1385 ..Settings::default()
1386 });
1387 assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
1388 assert!(removed.contains(&"GH_TOKEN".to_string()));
1389 }
1390
1391 #[test]
1392 fn zero_runs_is_rejected_not_a_panic() {
1393 let plan = Plan {
1394 cmd: vec!["true".into()],
1395 warmup: 0,
1396 runs: 0,
1397 dir: None,
1398 settings: Settings::default(),
1399 };
1400 assert!(wall(&plan).is_err());
1401 }
1402
1403 #[test]
1404 fn a_failed_subject_is_not_recorded_as_a_fast_run() {
1405 #[cfg(unix)]
1406 let cmd = vec!["/bin/sh".into(), "-c".into(), "exit 42".into()];
1407 #[cfg(windows)]
1408 let cmd = vec!["cmd".into(), "/C".into(), "exit /B 42".into()];
1409
1410 let err = wall(&Plan {
1411 cmd,
1412 warmup: 0,
1413 runs: 1,
1414 dir: None,
1415 settings: Settings::default(),
1416 })
1417 .unwrap_err();
1418
1419 assert!(format!("{err:#}").contains("exited with"), "{err:#}");
1420 }
1421
1422 #[test]
1423 fn wall_reports_min_le_p50_le_max() {
1424 let plan = Plan {
1425 cmd: vec!["true".into()],
1426 warmup: 1,
1427 runs: 5,
1428 dir: None,
1429 settings: Settings::default(),
1430 };
1431 let m = wall(&plan).unwrap();
1432 assert!(m["wall_min_ms"] <= m["wall_p50_ms"]);
1433 assert!(m["wall_p50_ms"] <= m["wall_max_ms"]);
1434 assert_eq!(m["wall_n"], 5.0);
1435 }
1436
1437 #[test]
1439 fn the_schedule_gives_each_subject_its_counts() {
1440 let counts = [(2, 10), (1, 5), (0, 3)];
1441 let order = schedule(&counts, 7);
1442 for (i, &(warmup, runs)) in counts.iter().enumerate() {
1443 let of = |timed| {
1444 order
1445 .iter()
1446 .filter(|s| s.subject == i && s.timed == timed)
1447 .count()
1448 };
1449 assert_eq!(of(false), warmup as usize, "subject {i} warmups");
1450 assert_eq!(of(true), runs as usize, "subject {i} runs");
1451 }
1452 let first_timed = order.iter().position(|s| s.timed).unwrap();
1453 assert!(order[first_timed..].iter().all(|s| s.timed));
1454 }
1455
1456 #[test]
1457 fn the_same_seed_gives_the_same_order() {
1458 let counts = [(1, 8), (1, 8), (1, 8)];
1459 assert_eq!(schedule(&counts, 42), schedule(&counts, 42));
1460 assert_ne!(schedule(&counts, 42), schedule(&counts, 43));
1461 }
1462
1463 #[test]
1466 fn each_round_runs_every_subject_once_in_a_varying_order() {
1467 let order = schedule(&[(0, 20), (0, 20), (0, 20)], 1);
1468 let rounds: Vec<Vec<usize>> = order
1469 .chunks(3)
1470 .map(|r| r.iter().map(|s| s.subject).collect())
1471 .collect();
1472 assert_eq!(rounds.len(), 20);
1473 for r in &rounds {
1474 let mut sorted = r.clone();
1475 sorted.sort();
1476 assert_eq!(sorted, [0, 1, 2], "round {r:?}");
1477 }
1478 assert!(rounds.iter().any(|r| r != &rounds[0]), "never shuffled");
1479 }
1480
1481 #[test]
1484 fn a_subject_with_fewer_runs_is_spread_across_the_run() {
1485 let order = schedule(&[(0, 10), (0, 5)], 3);
1486 let fewer: Vec<usize> = order
1487 .iter()
1488 .enumerate()
1489 .filter(|(_, s)| s.subject == 1)
1490 .map(|(i, _)| i)
1491 .collect();
1492 assert_eq!(fewer.len(), 5);
1493 assert!(
1494 *fewer.last().unwrap() >= order.len() - 3,
1495 "last sample of the smaller subject is near the end: {fewer:?} of {}",
1496 order.len()
1497 );
1498 }
1499
1500 #[test]
1501 fn a_benchmark_seed_depends_on_its_name_and_the_run_seed() {
1502 assert_eq!(seed_for(1, "a"), seed_for(1, "a"));
1503 assert_ne!(seed_for(1, "a"), seed_for(1, "b"));
1504 assert_ne!(seed_for(1, "a"), seed_for(2, "a"));
1505 }
1506
1507 #[test]
1508 fn stats_report_the_sample_standard_deviation() {
1509 let m = stats(&[2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]);
1510 assert_eq!(m["wall_min_ms"], 2.0);
1511 assert_eq!(m["wall_max_ms"], 9.0);
1512 assert_eq!(m["wall_mean_ms"], 5.0);
1513 assert!((m["wall_stddev_ms"] - 2.138_089_935).abs() < 1e-6);
1515 assert_eq!(stats(&[3.0])["wall_stddev_ms"], 0.0);
1516 }
1517
1518 #[cfg(unix)]
1520 #[test]
1521 fn a_failing_subject_does_not_stop_the_others() {
1522 let mk = |name: &str, cmd: &[&str]| Subject {
1523 name: name.into(),
1524 cmd: cmd.iter().map(|s| s.to_string()).collect(),
1525 prepare: None,
1526 setup: None,
1527 setup_dir: None,
1528 check: None,
1529 dir: None,
1530 version_cmd: None,
1531 env: BTreeMap::new(),
1532 vars: BTreeMap::new(),
1533 when: None,
1534 runs: Runs::Fixed(4),
1535 auto: AutoRuns {
1536 budget: Duration::from_secs(30),
1537 min: 5,
1538 max: 50,
1539 },
1540 warmup: 1,
1541 counters: false,
1542 ok_exit_codes: vec![0],
1543 };
1544 let res = interleaved(
1545 &[mk("ok", &["true"]), mk("bad", &["false"])],
1546 5,
1547 &Settings::default(),
1548 &mut Quiet,
1549 );
1550 assert_eq!(res[0].as_ref().unwrap().times.len(), 4);
1551 assert!(format!("{:#}", res[1].as_ref().unwrap_err()).contains("exited with"));
1552 }
1553
1554 #[cfg(unix)]
1556 fn version_sh(script: &str, env: &[(&str, &str)], timeout: Duration) -> Result<String> {
1557 let settings = Settings::default();
1558 let env: BTreeMap<String, String> = env
1559 .iter()
1560 .map(|(k, v)| (k.to_string(), v.to_string()))
1561 .collect();
1562 let site = Site {
1563 dir: None,
1564 env: &env,
1565 settings: &settings,
1566 };
1567 version_once(&["sh".into(), "-c".into(), script.into()], &site, timeout)
1568 }
1569
1570 #[cfg(unix)]
1573 #[test]
1574 fn a_version_is_the_first_line_printed() {
1575 let sh = |script: &str| version_sh(script, &[("V", "9.9")], VERSION_TIMEOUT);
1576 assert_eq!(
1577 sh("printf '\\n tool %s \\nbuilt today\\n' \"$V\"").unwrap(),
1578 "tool 9.9",
1579 "first non-empty line, trimmed, in the subject's env"
1580 );
1581 assert_eq!(sh("echo 'java 21' >&2").unwrap(), "java 21");
1582 let err = format!("{:#}", sh("echo nope >&2; exit 2").unwrap_err());
1583 assert!(err.contains("`sh`") && err.contains("nope"), "{err}");
1584 assert!(sh("true").is_err(), "no output is no version");
1585 }
1586
1587 #[cfg(unix)]
1590 #[test]
1591 fn a_version_is_read_from_a_capped_prefix() {
1592 let sh = |script: &str| version_sh(script, &[], VERSION_TIMEOUT);
1593 assert_eq!(sh("yes 'tool 1.0' | head -c 10000000").unwrap(), "tool 1.0");
1594 assert_eq!(
1595 sh("yes 'java 21' | head -c 10000000 >&2").unwrap(),
1596 "java 21",
1597 "a flood on stderr"
1598 );
1599 let kept = Mutex::new(Vec::new());
1600 let mut src = std::io::Cursor::new(vec![7u8; 100]);
1601 keep_prefix(&mut src, 10, &kept);
1602 assert_eq!(kept.lock().unwrap().len(), 10, "only the cap is kept");
1603 assert_eq!(
1604 src.position(),
1605 100,
1606 "the rest is read, not left in the pipe"
1607 );
1608 }
1609
1610 #[cfg(unix)]
1613 #[test]
1614 fn a_failing_version_cmd_is_an_error_even_past_the_cap() {
1615 let err = version_sh(
1616 "yes 'usage: tool [flags]' | head -c 100000; echo 'unknown flag' >&2; exit 1",
1617 &[],
1618 VERSION_TIMEOUT,
1619 )
1620 .unwrap_err();
1621 let err = format!("{err:#}");
1622 assert!(
1623 err.contains("exited with") && err.contains("unknown flag"),
1624 "{err}"
1625 );
1626 }
1627
1628 #[cfg(unix)]
1631 #[test]
1632 fn a_version_cmd_that_never_finishes_is_stopped() {
1633 let t = Duration::from_millis(300);
1634 let began = Instant::now();
1635 for script in ["exec yes 'tool 2.0' >&2", "exec sleep 30"] {
1637 let err = format!("{:#}", version_sh(script, &[], t).unwrap_err());
1638 assert!(err.contains("did not finish"), "{script}: {err}");
1639 }
1640 assert!(
1641 began.elapsed() < Duration::from_secs(5),
1642 "{:?}",
1643 began.elapsed()
1644 );
1645 }
1646
1647 #[cfg(unix)]
1650 #[test]
1651 fn a_timeout_stops_the_whole_process_group() {
1652 let dir = tempfile::tempdir().unwrap();
1653 let pidfile = dir.path().join("pid");
1654 let script = format!("sleep 30 & echo $! > '{}'; wait", pidfile.display());
1655 let err = version_sh(&script, &[], Duration::from_millis(300)).unwrap_err();
1656 assert!(format!("{err:#}").contains("did not finish"), "{err:#}");
1657 let pid = std::fs::read_to_string(&pidfile).unwrap();
1658 let pid = pid.trim();
1659 let until = Instant::now() + Duration::from_secs(2);
1660 while running(pid) && Instant::now() < until {
1661 std::thread::sleep(Duration::from_millis(20));
1662 }
1663 assert!(
1664 !running(pid),
1665 "the background sleep {pid} outlived the timeout"
1666 );
1667 }
1668
1669 #[cfg(unix)]
1674 fn running(pid: &str) -> bool {
1675 #[cfg(target_os = "linux")]
1676 {
1677 let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) else {
1680 return false;
1681 };
1682 let state = stat
1683 .rfind(')')
1684 .and_then(|i| stat[i + 1..].trim_start().chars().next());
1685 !matches!(state, None | Some('Z' | 'X' | 'x'))
1686 }
1687 #[cfg(not(target_os = "linux"))]
1688 {
1689 let Ok(out) = Command::new("ps")
1690 .args(["-o", "stat=", "-p", pid])
1691 .stderr(Stdio::null())
1692 .output()
1693 else {
1694 return false;
1695 };
1696 let stat = String::from_utf8_lossy(&out.stdout);
1697 let stat = stat.trim();
1698 out.status.success() && !stat.is_empty() && !stat.starts_with('Z')
1699 }
1700 }
1701
1702 #[cfg(unix)]
1705 #[test]
1706 fn a_background_process_holding_the_pipe_does_not_hold_up_the_version() {
1707 let began = Instant::now();
1708 let v = version_sh("sleep 5 & echo 'tool 3.0'", &[], VERSION_TIMEOUT).unwrap();
1709 assert_eq!(v, "tool 3.0");
1710 assert!(
1711 began.elapsed() < Duration::from_secs(3),
1712 "{:?}",
1713 began.elapsed()
1714 );
1715 }
1716
1717 #[cfg(unix)]
1719 #[test]
1720 fn a_failing_prepare_is_reported_as_prepare() {
1721 let res = interleaved(
1722 &[Subject {
1723 name: "x".into(),
1724 cmd: vec!["true".into()],
1725 prepare: Some(vec![
1726 "/bin/sh".into(),
1727 "-c".into(),
1728 "echo nope >&2; exit 3".into(),
1729 ]),
1730 setup: None,
1731 setup_dir: None,
1732 check: None,
1733 dir: None,
1734 version_cmd: None,
1735 env: BTreeMap::new(),
1736 vars: BTreeMap::new(),
1737 when: None,
1738 runs: Runs::Fixed(1),
1739 auto: AutoRuns {
1740 budget: Duration::from_secs(30),
1741 min: 5,
1742 max: 50,
1743 },
1744 warmup: 0,
1745 counters: false,
1746 ok_exit_codes: vec![0],
1747 }],
1748 0,
1749 &Settings::default(),
1750 &mut Quiet,
1751 );
1752 let msg = format!("{:#}", res[0].as_ref().unwrap_err());
1753 assert!(msg.contains("prepare") && msg.contains("nope"), "{msg}");
1754 }
1755
1756 #[cfg(unix)]
1759 fn alternating(dir: &Path, warmup: u32, runs: u32) -> Subject {
1760 Subject {
1761 name: "alt".into(),
1762 cmd: vec![
1763 "/bin/sh".into(),
1764 "-c".into(),
1765 "echo x >> n".into(),
1766 ],
1767 prepare: None,
1768 setup: None,
1769 setup_dir: None,
1770 check: Some(vec![
1771 "/bin/sh".into(),
1772 "-c".into(),
1773 "echo check >> checked; runs=$(( $(wc -l < n) )); test $(( runs % 2 )) = 1 || { echo \"run $runs is even\" >&2; exit 1; }".into(),
1775 ]),
1776 version_cmd: None,
1777 dir: Some(dir.to_path_buf()),
1778 env: BTreeMap::new(),
1779 vars: BTreeMap::new(),
1780 when: None,
1781 runs: Runs::Fixed(runs),
1782 auto: AutoRuns {
1783 budget: Duration::from_secs(30),
1784 min: 5,
1785 max: 50,
1786 },
1787 warmup,
1788 counters: false,
1789 ok_exit_codes: vec![0],
1790 }
1791 }
1792
1793 #[cfg(unix)]
1796 #[test]
1797 fn a_failing_check_marks_the_sample_without_dropping_the_subject() {
1798 let dir = tempfile::tempdir().unwrap();
1799 let res = interleaved(
1800 &[alternating(dir.path(), 1, 6)],
1801 0,
1802 &Settings::default(),
1803 &mut Quiet,
1804 );
1805 let s = res[0].as_ref().unwrap();
1806 assert_eq!(s.times.len(), 6);
1807 assert_eq!(s.checks, [false, true, false, true, false, true]);
1809 assert_eq!(s.passed(), 3);
1810 assert!(
1811 s.first_failure
1812 .as_deref()
1813 .unwrap()
1814 .contains("run 2 is even"),
1815 "{s:?}"
1816 );
1817 let checked = std::fs::read_to_string(dir.path().join("checked")).unwrap();
1818 assert_eq!(checked.lines().count(), 6, "no check after the warmup");
1819 }
1820
1821 #[cfg(unix)]
1825 #[test]
1826 fn ok_exit_codes_do_not_pass_a_check_that_exits_1() {
1827 let dir = tempfile::tempdir().unwrap();
1828 let mut s = alternating(dir.path(), 0, 2);
1829 s.cmd = vec!["/bin/sh".into(), "-c".into(), "exit 1".into()];
1830 s.check = Some(vec!["/bin/sh".into(), "-c".into(), "exit 1".into()]);
1831 s.ok_exit_codes = vec![0, 1];
1832 let res = interleaved(&[s], 0, &Settings::default(), &mut Quiet);
1833 let s = res[0].as_ref().unwrap();
1834 assert_eq!(s.exit_codes, [1, 1]);
1835 assert_eq!(s.checks, [false, false]);
1836 assert_eq!(s.passed(), 0);
1837 }
1838
1839 #[cfg(unix)]
1842 #[test]
1843 fn a_check_that_cannot_start_drops_the_subject() {
1844 let dir = tempfile::tempdir().unwrap();
1845 let mut s = alternating(dir.path(), 0, 2);
1846 s.check = Some(vec!["/nonexistent/tak-check".into()]);
1847 let res = interleaved(&[s], 0, &Settings::default(), &mut Quiet);
1848 let msg = format!("{:#}", res[0].as_ref().unwrap_err());
1849 assert!(msg.contains("failed to spawn check"), "{msg}");
1850 }
1851
1852 #[cfg(unix)]
1857 #[test]
1858 fn a_process_left_by_a_passing_step_can_still_write_to_stderr() {
1859 let dir = tempfile::tempdir().unwrap();
1860 let env = BTreeMap::new();
1861 let settings = Settings::default();
1862 let site = Site {
1863 dir: Some(dir.path()),
1864 env: &env,
1865 settings: &settings,
1866 };
1867 const N: usize = 10;
1868 let start = Instant::now();
1869 for i in 0..N {
1870 let script = format!(
1871 "{{ sh -c 'sleep 1; echo late >&2'; echo $? > s{i}.tmp && mv s{i}.tmp s{i}; }} & exit 0"
1872 );
1873 let step = ["/bin/sh".to_string(), "-c".into(), script];
1874 assert_eq!(untimed("setup", &step, &site).unwrap(), None);
1875 }
1876 let took = start.elapsed();
1877 assert!(took < Duration::from_secs(2), "{N} passes took {took:?}");
1878
1879 let deadline = Instant::now() + Duration::from_secs(20);
1880 let statuses: Vec<String> = (0..N)
1881 .map(|i| {
1882 loop {
1883 if let Ok(s) = std::fs::read_to_string(dir.path().join(format!("s{i}"))) {
1884 break s.trim().to_string();
1885 }
1886 assert!(Instant::now() < deadline, "leftover {i} never finished");
1887 std::thread::sleep(Duration::from_millis(50));
1888 }
1889 })
1890 .collect();
1891 assert!(statuses.iter().all(|s| s == "0"), "{statuses:?}");
1892 }
1893
1894 #[derive(Default)]
1896 struct Log {
1897 plans: Vec<Vec<u64>>,
1898 finished: Vec<usize>,
1899 events: Vec<String>,
1901 }
1902 impl Observer for Log {
1903 fn planned(&mut self, remaining: &[u64]) {
1904 self.plans.push(remaining.to_vec());
1905 }
1906 fn setting_up(&mut self, subject: usize) {
1907 self.events.push(format!("setup:{subject}"));
1908 }
1909 fn started(&mut self, subject: usize) {
1910 self.events.push(format!("start:{subject}"));
1911 }
1912 fn dropped(&mut self, subject: usize) {
1913 self.events.push(format!("drop:{subject}"));
1914 }
1915 fn finished(&mut self, subject: usize, _: Duration) {
1916 self.finished.push(subject);
1917 }
1918 }
1919
1920 #[cfg(unix)]
1923 #[test]
1924 fn setups_run_once_first_and_a_failing_one_drops_its_subject() {
1925 let sh = |script: &str| Some(["/bin/sh", "-c", script].map(String::from).to_vec());
1926 let mk = |name: &str, setup: Option<Vec<String>>| Subject {
1927 name: name.into(),
1928 cmd: vec!["true".into()],
1929 prepare: None,
1930 setup,
1931 setup_dir: None,
1932 check: None,
1933 version_cmd: None,
1934 dir: None,
1935 env: BTreeMap::new(),
1936 vars: BTreeMap::new(),
1937 when: None,
1938 runs: Runs::Auto,
1939 auto: AutoRuns {
1940 budget: Duration::from_secs(30),
1941 min: 2,
1942 max: 2,
1943 },
1944 warmup: 1,
1945 counters: false,
1946 ok_exit_codes: vec![0],
1947 };
1948 let mut log = Log::default();
1949 let res = interleaved(
1950 &[
1951 mk("ok", sh("true")),
1952 mk("bad", sh("echo no fixture >&2; exit 2")),
1953 mk("none", None),
1954 ],
1955 3,
1956 &Settings::default(),
1957 &mut log,
1958 );
1959 assert_eq!(log.events[..3], ["setup:0", "setup:1", "drop:1"]);
1960 assert!(!log.events[3..].iter().any(|e| e.starts_with("setup:")));
1961 assert!(!log.events.contains(&"start:1".to_string()));
1962 assert_eq!(res[0].as_ref().unwrap().times.len(), 2);
1963 assert_eq!(res[2].as_ref().unwrap().times.len(), 2);
1964 let msg = format!("{:#}", res[1].as_ref().unwrap_err());
1965 assert!(msg.contains("setup") && msg.contains("no fixture"), "{msg}");
1966 assert_eq!(log.finished.len(), 2 * (1 + 2));
1968 }
1969
1970 #[cfg(unix)]
1974 #[test]
1975 fn auto_runs_give_a_slow_subject_the_floor_and_a_fast_one_more() {
1976 let mk = |name: &str, secs: &str, warmup: u32| Subject {
1977 name: name.into(),
1978 cmd: vec!["sleep".into(), secs.into()],
1979 prepare: None,
1980 setup: None,
1981 setup_dir: None,
1982 check: None,
1983 dir: None,
1984 version_cmd: None,
1985 env: BTreeMap::new(),
1986 vars: BTreeMap::new(),
1987 when: None,
1988 runs: Runs::Auto,
1989 auto: AutoRuns {
1990 budget: Duration::from_millis(400),
1991 min: 2,
1992 max: 6,
1993 },
1994 warmup,
1995 counters: false,
1996 ok_exit_codes: vec![0],
1997 };
1998 let mut log = Log::default();
1999 let res = interleaved(
2001 &[mk("fast", "0.02", 1), mk("slow", "0.3", 0)],
2002 9,
2003 &Settings::default(),
2004 &mut log,
2005 );
2006 let fast = res[0].as_ref().unwrap().times.len();
2007 let slow = res[1].as_ref().unwrap().times.len();
2008 assert_eq!(slow, 2, "0.4s budget / 0.3s sample is below the floor");
2009 assert!(fast > slow && fast <= 6, "fast got {fast}");
2010 assert_eq!(log.plans[0], [1 + 2, 2]);
2012 assert_eq!(log.plans.len(), 2);
2013 assert_eq!(log.finished.len(), 1 + fast + slow);
2014 }
2015
2016 #[test]
2017 fn steady_samples_raise_no_warning() {
2018 assert!(warnings(&[10.0, 10.2, 9.9, 10.1, 10.0, 10.3]).is_empty());
2019 assert!(warnings(&[10.0, 50.0]).is_empty(), "too few to judge");
2020 }
2021
2022 #[test]
2023 fn a_spike_is_an_outlier() {
2024 let w = warnings(&[10.0, 10.2, 9.9, 10.1, 40.0, 10.0, 10.1]);
2025 assert_eq!(w.len(), 1, "{w:?}");
2026 assert!(
2027 w[0].starts_with("1 of 7 samples are slow outliers"),
2028 "{w:?}"
2029 );
2030 }
2031
2032 #[test]
2033 fn a_slow_first_sample_is_called_out() {
2034 let w = warnings(&[35.0, 10.0, 10.2, 9.9, 10.1, 10.0]);
2035 assert!(
2036 w.iter().any(|m| m.contains("first sample took 3.5x")),
2037 "{w:?}"
2038 );
2039 }
2040
2041 #[test]
2044 fn a_spike_among_identical_samples_is_still_an_outlier() {
2045 let w = warnings(&[10.0, 10.0, 10.0, 100.0, 10.0]);
2046 assert!(w.iter().any(|m| m.contains("slow outliers")), "{w:?}");
2047 assert!(
2048 warnings(&[10.0; 6]).is_empty(),
2049 "identical samples are fine"
2050 );
2051 }
2052
2053 #[test]
2056 fn a_fast_outlier_is_flagged_as_possibly_the_minimum() {
2057 let w = warnings(&[100.0, 101.0, 99.0, 102.0, 10.0, 100.0]);
2058 assert!(
2059 w.iter()
2060 .any(|m| m.contains("fast outliers") && m.contains("minimum")),
2061 "{w:?}"
2062 );
2063 }
2064
2065 #[test]
2068 fn several_spikes_over_a_flat_majority_are_caught() {
2069 let w = warnings(&[10.0, 10.0, 10.0, 10.0, 40.0, 45.0]);
2070 assert!(
2071 w.iter()
2072 .any(|m| m.starts_with("2 of 6 samples are slow outliers")),
2073 "{w:?}"
2074 );
2075 assert!(
2076 warnings(&[10.0, 10.0, 10.0, 11.0, 10.0]).is_empty(),
2077 "10% is not a spike"
2078 );
2079 }
2080}