1use crate::config::{AutoRuns, DEFAULT_OK_EXIT_CODES, MetricSource, Runs, SELF_TOOL, Subject};
22use crate::settings::Settings;
23use anyhow::{Context, Result, bail};
24use std::collections::BTreeMap;
25use std::path::Path;
26use std::process::{Command, Stdio};
27use std::sync::{Arc, Mutex};
28use std::time::Duration;
29use std::time::Instant;
30
31#[derive(Debug, Clone)]
32pub struct Plan {
33 pub cmd: Vec<String>,
34 pub warmup: u32,
35 pub runs: u32,
36 pub dir: Option<std::path::PathBuf>,
40 pub settings: Settings,
44}
45
46fn subject(bin: &str, settings: &Settings) -> Command {
65 let mut c = Command::new(bin);
66 for key in settings.scrubbed_env() {
67 c.env_remove(key);
68 }
69 c
70}
71
72#[derive(Debug, Clone, Copy)]
74struct Site<'a> {
75 dir: Option<&'a Path>,
76 env: &'a BTreeMap<String, String>,
77 settings: &'a Settings,
78}
79
80fn command(argv: &[String], site: &Site) -> Result<Command> {
86 let (bin, args) = argv.split_first().context("empty command")?;
87 let mut c = subject(bin, site.settings);
88 c.args(args).envs(site.env);
89 if let Some(d) = site.dir {
90 c.current_dir(d);
91 }
92 #[cfg(unix)]
93 if tracked::OWN_GROUPS.load(std::sync::atomic::Ordering::SeqCst) {
94 std::os::unix::process::CommandExt::process_group(&mut c, 0);
95 }
96 Ok(c)
97}
98
99fn run_tracked(c: &mut Command) -> std::io::Result<std::process::ExitStatus> {
103 let mut child = c.spawn()?;
104 tracked::started(child.id());
105 let status = child.wait();
106 tracked::finished();
107 status
108}
109
110#[cfg(unix)]
125pub fn use_own_groups() {
126 tracked::OWN_GROUPS.store(true, std::sync::atomic::Ordering::SeqCst);
127}
128
129#[cfg(unix)]
134pub fn stop_running() {
135 use std::sync::atomic::Ordering::SeqCst;
136 tracked::STOPPED.store(true, SeqCst);
137 tracked::kill_all();
138}
139
140mod tracked {
143 use std::sync::Mutex;
144 use std::sync::atomic::{AtomicBool, Ordering::SeqCst};
145
146 pub(super) static OWN_GROUPS: AtomicBool = AtomicBool::new(false);
147 pub(super) static STOPPED: AtomicBool = AtomicBool::new(false);
148
149 static GROUPS: Mutex<Groups> = Mutex::new(Groups::new());
157
158 #[derive(Debug, Default, PartialEq)]
161 pub(super) struct Groups {
162 running: i32,
164 left: Vec<i32>,
170 }
171
172 impl Groups {
173 pub(super) const fn new() -> Groups {
174 Groups {
175 running: 0,
176 left: Vec::new(),
177 }
178 }
179
180 pub(super) fn start(&mut self, pgid: i32) {
181 self.running = pgid;
182 }
183
184 pub(super) fn finish(&mut self, alive: impl Fn(i32) -> bool) {
191 self.left.retain(|g| alive(*g));
192 if self.running > 0 && alive(self.running) {
193 self.left.push(self.running);
194 }
195 self.running = 0;
196 }
197
198 pub(super) fn targets(&self) -> Vec<i32> {
200 std::iter::once(self.running)
201 .filter(|g| *g > 0)
202 .chain(self.left.iter().copied())
203 .collect()
204 }
205 }
206
207 fn groups() -> std::sync::MutexGuard<'static, Groups> {
208 GROUPS.lock().unwrap_or_else(|e| e.into_inner())
211 }
212
213 pub(super) fn started(pid: u32) {
219 if !OWN_GROUPS.load(SeqCst) {
220 return;
221 }
222 groups().start(pid as i32);
223 if STOPPED.load(SeqCst) {
224 kill(pid as i32);
225 }
226 }
227
228 pub(super) fn finished() {
231 if OWN_GROUPS.load(SeqCst) {
232 groups().finish(alive);
233 }
234 }
235
236 pub(super) fn kill_all() {
239 for g in groups().targets() {
240 kill(g);
241 }
242 }
243
244 #[cfg(unix)]
245 fn alive(pgid: i32) -> bool {
246 unsafe { libc::killpg(pgid, 0) == 0 }
248 }
249
250 #[cfg(not(unix))]
251 fn alive(_pgid: i32) -> bool {
252 false
253 }
254
255 #[cfg(unix)]
256 pub(super) fn kill(pgid: i32) {
257 if pgid > 0 {
258 unsafe {
260 libc::killpg(pgid, libc::SIGKILL);
261 }
262 }
263 }
264
265 #[cfg(not(unix))]
266 pub(super) fn kill(_pgid: i32) {}
267
268 #[cfg(test)]
269 mod tests {
270 use super::Groups;
271
272 #[test]
276 fn a_group_is_never_untracked_while_it_has_members() {
277 let mut g = Groups::new();
278 assert!(g.targets().is_empty());
279 g.start(10);
280 assert_eq!(g.targets(), [10]);
281
282 g.finish(|p| p == 10);
284 assert_eq!(g.targets(), [10]);
285 g.start(20);
286 assert_eq!(g.targets(), [20, 10]);
287
288 g.finish(|p| p == 10);
290 assert_eq!(g.targets(), [10]);
291
292 g.start(30);
294 g.finish(|_| false);
295 assert!(g.targets().is_empty());
296 assert_eq!(g, Groups::new());
297 }
298 }
299}
300
301#[derive(Debug, Clone, Copy, PartialEq)]
303pub struct Sample {
304 pub ms: f64,
306 pub exit_code: i32,
309}
310
311fn accepted(bin: &str, status: std::process::ExitStatus, ok: &[i32], via: &str) -> Result<i32> {
318 match status.code() {
319 Some(code) if ok.contains(&code) => Ok(code),
320 _ if ok == DEFAULT_OK_EXIT_CODES => {
324 bail!("benchmark subject `{bin}` exited with {status}{via}")
325 }
326 _ => bail!(
327 "benchmark subject `{bin}` exited with {status}{via}, and ok_exit_codes is {}",
328 ok.iter().map(i32::to_string).collect::<Vec<_>>().join(", ")
329 ),
330 }
331}
332
333fn time_once(cmd: &[String], site: &Site, ok: &[i32]) -> Result<Sample> {
339 let mut c = command(cmd, site)?;
340 c.stdout(Stdio::null()).stderr(Stdio::null());
341 let bin = &cmd[0];
342 let start = Instant::now();
343 let mut child = c
344 .spawn()
345 .with_context(|| format!("failed to spawn `{bin}`"))?;
346 tracked::started(child.id());
348 let status = child.wait();
349 let ms = start.elapsed().as_secs_f64() * 1000.0;
350 tracked::finished();
351 let status = status.with_context(|| format!("failed to wait for `{bin}`"))?;
352 let exit_code = accepted(bin, status, ok, "")?;
353 Ok(Sample { ms, exit_code })
354}
355
356const UNTIMED_STDERR_TAIL: usize = 4096;
360
361fn prepare_once(cmd: &[String], site: &Site) -> Result<()> {
364 required("prepare", cmd, site)
365}
366
367fn required(what: &str, cmd: &[String], site: &Site) -> Result<()> {
369 match untimed(what, cmd, site)? {
370 None => Ok(()),
371 Some(failure) => bail!("{failure}"),
372 }
373}
374
375fn check_once(cmd: &[String], site: &Site) -> Result<Option<String>> {
380 untimed("check", cmd, site)
381}
382
383fn untimed(step: &str, cmd: &[String], site: &Site) -> Result<Option<String>> {
415 let mut c = command(cmd, site)?;
416 let bin = &cmd[0];
417 let err = tempfile::tempfile()
418 .with_context(|| format!("failed to create a file for {step} `{bin}`'s stderr"))?;
419 let reader = err
420 .try_clone()
421 .with_context(|| format!("failed to create a file for {step} `{bin}`'s stderr"))?;
422 c.stdin(Stdio::null())
423 .stdout(Stdio::null())
424 .stderr(Stdio::from(err));
425 let status = run_tracked(&mut c).with_context(|| format!("failed to spawn {step} `{bin}`"))?;
426 if status.success() {
427 return Ok(None);
428 }
429 let tail = stderr_tail(&reader).unwrap_or_default();
433 let stderr = String::from_utf8_lossy(&tail);
434 Ok(Some(match stderr.lines().rfind(|l| !l.trim().is_empty()) {
435 Some(last) => format!("{step} `{bin}` exited with {status}: {}", last.trim()),
436 None => format!("{step} `{bin}` exited with {status}"),
437 }))
438}
439
440const METRIC_OUTPUT_MAX: usize = 1024;
444
445pub fn custom_metric(source: &MetricSource, s: &Subject, settings: &Settings) -> Result<f64> {
464 match source {
465 MetricSource::File(path) => {
466 let meta = std::fs::metadata(path)
467 .with_context(|| format!("could not read the size of {}", path.display()))?;
468 if !meta.is_file() {
469 bail!("{} is not a regular file", path.display());
470 }
471 Ok(meta.len() as f64)
472 }
473 MetricSource::Cmd(argv) => {
474 let site = Site {
475 dir: s.dir.as_deref(),
476 env: &s.env,
477 settings,
478 };
479 metric_cmd_once(argv, &site)
480 }
481 }
482}
483
484fn metric_cmd_once(argv: &[String], site: &Site) -> Result<f64> {
485 let bin = &argv[0];
486 let out = capture(argv, site, None, METRIC_OUTPUT_MAX, true)?;
487 if out.overflowed || out.stdout_open {
494 stop_leftovers(out.pgid);
495 }
496 if out.overflowed {
499 bail!(
500 "`{bin}` and what it started printed more than {METRIC_OUTPUT_MAX} bytes, so they were \
501 stopped; a metric command prints one number and nothing else"
502 );
503 }
504 if out.stdout_open {
507 bail!(
508 "`{bin}` exited but left a process holding its stdout open, so that was stopped; \
509 a metric command must finish its output before it exits"
510 );
511 }
512 if !out.status.success() {
513 bail!(
514 "`{bin}` exited with {}: {}",
515 out.status,
516 last_line(&out.stderr_tail)
517 );
518 }
519 let text = std::str::from_utf8(&out.stdout)
520 .map_err(|_| anyhow::anyhow!("`{bin}` printed something that is not UTF-8"))?;
521 parse_metric_value(text).with_context(|| format!("`{bin}`"))
522}
523
524pub fn parse_metric_value(text: &str) -> Result<f64> {
537 let t = text.trim_matches(|c: char| c.is_ascii_whitespace());
538 if t.is_empty() {
539 bail!("printed nothing; a metric command prints one number");
540 }
541 let bytes = t.as_bytes();
542 let digits = |i: &mut usize| {
543 let start = *i;
544 while *i < bytes.len() && bytes[*i].is_ascii_digit() {
545 *i += 1;
546 }
547 *i > start
548 };
549 let mut i = 0;
550 let mut ok = digits(&mut i);
551 if ok && i < bytes.len() && bytes[i] == b'.' {
552 i += 1;
553 ok = digits(&mut i);
554 }
555 if ok && i < bytes.len() && (bytes[i] == b'e' || bytes[i] == b'E') {
556 i += 1;
557 if i < bytes.len() && (bytes[i] == b'+' || bytes[i] == b'-') {
558 i += 1;
559 }
560 ok = digits(&mut i);
561 }
562 if !ok || i != bytes.len() {
563 bail!(
564 "printed {t:?}, not one number; a metric command prints a single non-negative \
565 number such as `1234` or `12.5`, and nothing else"
566 );
567 }
568 let v: f64 = t
569 .parse()
570 .with_context(|| format!("printed {t:?}, which is not a number"))?;
571 if !v.is_finite() {
572 bail!("printed {t:?}, which is too large to record");
573 }
574 Ok(v)
575}
576
577fn stderr_tail(f: &std::fs::File) -> std::io::Result<Vec<u8>> {
585 let len = f.metadata()?.len();
586 let start = len.saturating_sub(UNTIMED_STDERR_TAIL as u64);
587 let mut buf = vec![0u8; (len - start) as usize];
588 let mut filled = 0;
589 while filled < buf.len() {
590 let n = read_at(f, &mut buf[filled..], start + filled as u64)?;
591 if n == 0 {
592 break;
593 }
594 filled += n;
595 }
596 buf.truncate(filled);
597 Ok(buf)
598}
599
600#[cfg(unix)]
601fn read_at(f: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result<usize> {
602 std::os::unix::fs::FileExt::read_at(f, buf, offset)
603}
604
605#[cfg(windows)]
606fn read_at(f: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result<usize> {
607 std::os::windows::fs::FileExt::seek_read(f, buf, offset)
608}
609
610#[derive(Debug, Clone, Copy, PartialEq, Eq)]
612pub struct Slot {
613 pub subject: usize,
615 pub timed: bool,
618}
619
620pub fn schedule(counts: &[(u32, u32)], seed: u64) -> Vec<Slot> {
638 let mut rng = fastrand::Rng::with_seed(seed);
639 let warmups: Vec<u64> = counts.iter().map(|&(w, _)| u64::from(w)).collect();
640 let runs: Vec<u64> = counts.iter().map(|&(_, r)| u64::from(r)).collect();
641 let mut out = rounds(&warmups, false, &mut rng);
642 out.extend(rounds(&runs, true, &mut rng));
643 out
644}
645
646fn rounds(count: &[u64], timed: bool, rng: &mut fastrand::Rng) -> Vec<Slot> {
648 let total = count.iter().copied().max().unwrap_or(0);
649 let mut out = Vec::new();
650 for round in 0..total {
651 let mut due: Vec<usize> = (0..count.len())
654 .filter(|&i| (round + 1) * count[i] / total > round * count[i] / total)
655 .collect();
656 rng.shuffle(&mut due);
657 out.extend(due.into_iter().map(|subject| Slot { subject, timed }));
658 }
659 out
660}
661
662pub fn seed_for(seed: u64, bench: &str) -> u64 {
665 bench.bytes().fold(seed ^ 0xcbf2_9ce4_8422_2325, |h, b| {
667 (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)
668 })
669}
670
671pub trait Observer {
673 fn planned(&mut self, _remaining: &[u64]) {}
676 fn setting_up(&mut self, _subject: usize) {}
679 fn set_up(&mut self, _subject: usize) -> Result<()> {
686 Ok(())
687 }
688 fn before_run(&mut self, _subject: usize) -> Result<()> {
695 Ok(())
696 }
697 fn started(&mut self, _subject: usize) {}
699 fn finished(&mut self, _subject: usize, _elapsed: Duration) {}
701 fn dropped(&mut self, _subject: usize) {}
703}
704
705pub struct Quiet;
707impl Observer for Quiet {}
708
709#[derive(Debug, Clone, Default, PartialEq)]
711pub struct Samples {
712 pub times: Vec<f64>,
714 pub checks: Vec<bool>,
717 pub exit_codes: Vec<i32>,
720 pub first_failure: Option<String>,
722}
723
724impl Samples {
725 pub fn passed(&self) -> usize {
727 self.checks.iter().filter(|&&ok| ok).count()
728 }
729}
730
731pub fn interleaved(
756 subjects: &[Subject],
757 seed: u64,
758 settings: &Settings,
759 observer: &mut dyn Observer,
760) -> Vec<Result<Samples>> {
761 interleaved_with_versions(subjects, seed, settings, observer).0
762}
763
764pub type Version = Option<Result<String>>;
767
768pub fn interleaved_with_versions(
776 subjects: &[Subject],
777 seed: u64,
778 settings: &Settings,
779 observer: &mut dyn Observer,
780) -> (Vec<Result<Samples>>, Vec<Version>) {
781 let mut rng = fastrand::Rng::with_seed(seed);
782 let mut results: Vec<Result<Samples>> = subjects
783 .iter()
784 .map(|s| {
785 if s.runs == Runs::Fixed(0) {
787 bail!("runs must be at least 1");
788 }
789 Ok(Samples::default())
790 })
791 .collect();
792 let mut fastest: Vec<Option<Duration>> = vec![None; subjects.len()];
796
797 let warmups: Vec<u64> = subjects.iter().map(|s| u64::from(s.warmup)).collect();
798 let pilots: Vec<u64> = subjects
799 .iter()
800 .map(|s| u64::from(s.runs == Runs::Auto && s.warmup == 0))
801 .collect();
802 let provisional: Vec<u64> = subjects
804 .iter()
805 .zip(&warmups)
806 .map(|(s, w)| {
807 w + u64::from(match s.runs {
808 Runs::Fixed(n) => n,
809 Runs::Auto => s.auto.min,
810 })
811 })
812 .collect();
813 observer.planned(&provisional);
814
815 for (i, s) in subjects.iter().enumerate() {
816 let (Some(setup), Ok(_)) = (&s.setup, &results[i]) else {
817 continue;
818 };
819 observer.setting_up(i);
820 let site = Site {
821 dir: s.setup_dir.as_deref(),
822 env: &s.env,
823 settings,
824 };
825 if let Err(e) = observer
828 .before_run(i)
829 .and_then(|()| required("setup", setup, &site))
830 {
831 results[i] = Err(e);
832 observer.dropped(i);
833 }
834 }
835 for (i, result) in results.iter_mut().enumerate() {
836 if result.is_ok()
837 && let Err(e) = observer.set_up(i)
838 {
839 *result = Err(e);
840 observer.dropped(i);
841 }
842 }
843
844 let versions: Vec<Version> = subjects
845 .iter()
846 .zip(&results)
847 .map(|(s, r)| r.as_ref().ok().and_then(|_| subject_version(s, settings)))
848 .collect();
849
850 let mut first = rounds(&warmups, false, &mut rng);
851 first.extend(rounds(&pilots, true, &mut rng));
852 run_slots(
853 &first,
854 subjects,
855 settings,
856 &mut results,
857 &mut fastest,
858 observer,
859 );
860
861 let remaining: Vec<u64> = subjects
862 .iter()
863 .enumerate()
864 .map(|(i, s)| match (&results[i], s.runs) {
865 (Err(_), _) => 0,
866 (Ok(_), Runs::Fixed(n)) => u64::from(n),
867 (Ok(taken), Runs::Auto) => {
868 let n = auto_runs(&s.auto, fastest[i]);
869 u64::from(n).saturating_sub(taken.times.len() as u64)
870 }
871 })
872 .collect();
873 observer.planned(&remaining);
874 let second = rounds(&remaining, true, &mut rng);
875 run_slots(
876 &second,
877 subjects,
878 settings,
879 &mut results,
880 &mut fastest,
881 observer,
882 );
883 (results, versions)
884}
885
886fn auto_runs(auto: &AutoRuns, fastest: Option<Duration>) -> u32 {
889 fastest.map_or(auto.min, |d| auto.runs_for(d))
890}
891
892fn run_slots(
899 slots: &[Slot],
900 subjects: &[Subject],
901 settings: &Settings,
902 results: &mut [Result<Samples>],
903 fastest: &mut [Option<Duration>],
904 observer: &mut dyn Observer,
905) {
906 for slot in slots {
907 let Ok(samples) = &mut results[slot.subject] else {
908 continue;
909 };
910 let s = &subjects[slot.subject];
911 let site = Site {
912 dir: s.dir.as_deref(),
913 env: &s.env,
914 settings,
915 };
916 observer.started(slot.subject);
917 let vetted = if s.prepare.is_some() {
921 observer.before_run(slot.subject)
922 } else {
923 Ok(())
924 };
925 let began = Instant::now();
926 let taken = vetted
927 .and_then(|()| {
928 s.prepare
929 .as_deref()
930 .map_or(Ok(()), |p| prepare_once(p, &site))
931 })
932 .and_then(|()| observer.before_run(slot.subject))
933 .and_then(|()| time_once(&s.cmd, &site, &s.ok_exit_codes));
934 let elapsed = began.elapsed();
935 let checked = match (&taken, &s.check) {
938 (Ok(_), Some(check)) if slot.timed => observer
941 .before_run(slot.subject)
942 .and_then(|()| check_once(check, &site))
943 .map(Some),
944 _ => Ok(None),
945 };
946 match taken.and_then(|sample| checked.map(|c| (sample, c))) {
947 Ok((sample, check)) => {
948 if slot.timed {
949 samples.times.push(sample.ms);
950 samples.exit_codes.push(sample.exit_code);
951 }
952 if let Some(failure) = check {
953 samples.checks.push(failure.is_none());
954 if samples.first_failure.is_none() {
955 samples.first_failure = failure;
956 }
957 }
958 let f = &mut fastest[slot.subject];
959 *f = Some(f.map_or(elapsed, |f| f.min(elapsed)));
960 observer.finished(slot.subject, began.elapsed());
961 }
962 Err(e) => {
963 results[slot.subject] = Err(e);
964 observer.dropped(slot.subject);
965 }
966 }
967 }
968}
969
970pub fn stats(samples: &[f64]) -> BTreeMap<String, f64> {
977 let mut sorted = samples.to_vec();
978 sorted.sort_by(f64::total_cmp);
979 let n = sorted.len();
980 let mean = sorted.iter().sum::<f64>() / n as f64;
981 let stddev = if n > 1 {
983 (sorted.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64).sqrt()
984 } else {
985 0.0
986 };
987 BTreeMap::from([
988 ("wall_min_ms".to_string(), sorted[0]),
989 ("wall_p50_ms".to_string(), sorted[n / 2]),
990 ("wall_mean_ms".to_string(), mean),
991 ("wall_max_ms".to_string(), sorted[n - 1]),
992 ("wall_stddev_ms".to_string(), stddev),
993 ("wall_n".to_string(), n as f64),
994 ])
995}
996
997pub fn warnings(samples: &[f64]) -> Vec<String> {
1012 let mut out = Vec::new();
1013 let n = samples.len();
1014 if n < 5 {
1015 return out;
1016 }
1017 let median = |v: &mut Vec<f64>| {
1018 v.sort_by(f64::total_cmp);
1019 let m = v.len();
1020 if m.is_multiple_of(2) {
1021 (v[m / 2 - 1] + v[m / 2]) / 2.0
1022 } else {
1023 v[m / 2]
1024 }
1025 };
1026 let med = median(&mut samples.to_vec());
1027 let mad = median(&mut samples.iter().map(|x| (x - med).abs()).collect());
1028 let outlier = |x: f64| {
1035 if mad > 0.0 {
1036 0.6745 * (x - med).abs() / mad > 3.5
1037 } else {
1038 med > 0.0 && (x - med).abs() > 0.25 * med
1039 }
1040 };
1041 {
1042 let (fast, slow) = samples
1043 .iter()
1044 .filter(|&&x| outlier(x))
1045 .fold(
1046 (0, 0),
1047 |(f, s), &x| if x < med { (f + 1, s) } else { (f, s + 1) },
1048 );
1049 if slow > 0 {
1050 out.push(format!(
1051 "{slow} of {n} samples are slow outliers; something else was running, or the \
1052 command's work varies. Consider a quieter machine or more runs."
1053 ));
1054 }
1055 if fast > 0 {
1058 out.push(format!(
1059 "{fast} of {n} samples are fast outliers, and the reported minimum may be one of \
1060 them; check the command did the same work every time."
1061 ));
1062 }
1063 }
1064 let rest = median(&mut samples[1..].to_vec());
1065 if rest > 0.0 && samples[0] > 2.0 * rest {
1066 out.push(format!(
1067 "the first sample took {:.1}x the median of the rest; the warmup did not fill some \
1068 cache. Consider more warmup runs.",
1069 samples[0] / rest
1070 ));
1071 }
1072 out
1073}
1074
1075pub fn wall(plan: &Plan) -> Result<BTreeMap<String, f64>> {
1077 let subject = Subject {
1078 name: SELF_TOOL.to_string(),
1079 cmd: plan.cmd.clone(),
1080 prepare: None,
1081 setup: None,
1082 setup_dir: None,
1083 check: None,
1084 dir: plan.dir.clone(),
1085 version_cmd: None,
1086 env: BTreeMap::new(),
1087 vars: BTreeMap::new(),
1088 when: None,
1089 runs: Runs::Fixed(plan.runs),
1090 auto: AutoRuns {
1091 budget: crate::config::DEFAULT_BUDGET,
1092 min: crate::config::DEFAULT_MIN_RUNS,
1093 max: crate::config::DEFAULT_MAX_RUNS,
1094 },
1095 warmup: plan.warmup,
1096 counters: false,
1097 allocations: false,
1098 ok_exit_codes: DEFAULT_OK_EXIT_CODES.to_vec(),
1099 metrics: BTreeMap::new(),
1100 };
1101 let samples = interleaved(
1103 std::slice::from_ref(&subject),
1104 0,
1105 &plan.settings,
1106 &mut Quiet,
1107 )
1108 .pop()
1109 .expect("one result per subject")?;
1110 Ok(stats(&samples.times))
1111}
1112
1113pub fn valgrind_available() -> bool {
1119 Command::new("valgrind")
1120 .arg("--version")
1121 .stdout(Stdio::null())
1122 .stderr(Stdio::null())
1123 .status()
1124 .map(|s| s.success())
1125 .unwrap_or(false)
1126}
1127
1128const COUNTER_RUNS: u32 = 3;
1131
1132const SPREAD_WARN_PCT: f64 = 0.5;
1137
1138#[derive(Debug, Clone, Copy)]
1140pub struct Counted {
1141 pub min: u64,
1142 pub max: u64,
1143 pub runs: u32,
1144}
1145
1146impl Counted {
1147 pub fn spread_pct(&self) -> f64 {
1149 if self.min == 0 {
1150 return 0.0;
1151 }
1152 (self.max - self.min) as f64 / self.min as f64 * 100.0
1153 }
1154
1155 pub fn is_suspect(&self) -> bool {
1162 self.spread_pct() > SPREAD_WARN_PCT
1163 }
1164}
1165
1166pub fn instructions(
1178 cmd: &[String],
1179 dir: Option<&std::path::Path>,
1180 settings: &Settings,
1181) -> Result<Option<Counted>> {
1182 count(
1183 cmd,
1184 None,
1185 &Site {
1186 dir,
1187 env: &BTreeMap::new(),
1188 settings,
1189 },
1190 &DEFAULT_OK_EXIT_CODES,
1191 false,
1192 &|| Ok(()),
1193 )
1194 .map(|c| c.map(|(c, _)| c))
1195}
1196
1197pub fn subject_instructions(s: &Subject, settings: &Settings) -> Result<Option<Counted>> {
1201 subject_count(s, settings, false, &|| Ok(())).map(|c| c.map(|(c, _)| c))
1202}
1203
1204pub fn subject_instructions_vetted(
1207 s: &Subject,
1208 settings: &Settings,
1209 vet: &dyn Fn() -> Result<()>,
1210) -> Result<Option<Counted>> {
1211 subject_count(s, settings, false, vet).map(|c| c.map(|(c, _)| c))
1212}
1213
1214pub fn subject_profile(s: &Subject, settings: &Settings) -> Result<Option<(Counted, Profiled)>> {
1222 subject_profile_vetted(s, settings, &|| Ok(()))
1223}
1224
1225pub fn subject_profile_vetted(
1227 s: &Subject,
1228 settings: &Settings,
1229 vet: &dyn Fn() -> Result<()>,
1230) -> Result<Option<(Counted, Profiled)>> {
1231 Ok(subject_count(s, settings, true, vet)?
1232 .map(|(c, p)| (c, p.expect("a profile was asked for"))))
1233}
1234
1235pub type Profiled = Result<Vec<u8>>;
1237
1238fn subject_count(
1239 s: &Subject,
1240 settings: &Settings,
1241 profile: bool,
1242 vet: &dyn Fn() -> Result<()>,
1243) -> Result<Option<(Counted, Option<Profiled>)>> {
1244 count(
1245 &s.cmd,
1246 s.prepare.as_deref(),
1247 &Site {
1248 dir: s.dir.as_deref(),
1249 env: &s.env,
1250 settings,
1251 },
1252 &s.ok_exit_codes,
1253 profile,
1254 vet,
1255 )
1256}
1257
1258pub fn subject_version(s: &Subject, settings: &Settings) -> Option<Result<String>> {
1269 let argv = s.version_cmd.as_ref()?;
1270 let site = Site {
1271 dir: s.dir.as_deref(),
1272 env: &s.env,
1273 settings,
1274 };
1275 Some(version_once(argv, &site, VERSION_TIMEOUT))
1276}
1277
1278const VERSION_OUTPUT_CAP: usize = 8192;
1282
1283const VERSION_TIMEOUT: Duration = Duration::from_secs(10);
1288
1289const VERSION_OUTPUT_GRACE: Duration = Duration::from_millis(500);
1294
1295fn keep_prefix(
1305 mut r: impl std::io::Read,
1306 cap: usize,
1307 kept: &Mutex<Vec<u8>>,
1308 overflow: &std::sync::atomic::AtomicBool,
1309 tail: Option<&Mutex<Vec<u8>>>,
1310) {
1311 let mut buf = [0u8; 8192];
1312 loop {
1313 match r.read(&mut buf) {
1314 Ok(0) => return,
1315 Ok(n) => {
1316 let Ok(mut k) = kept.lock() else { return };
1317 let room = cap.saturating_sub(k.len());
1318 if n > room {
1319 overflow.store(true, std::sync::atomic::Ordering::SeqCst);
1320 }
1321 k.extend_from_slice(&buf[..n.min(room)]);
1322 if let Some(Ok(mut t)) = tail.map(Mutex::lock) {
1323 t.extend_from_slice(&buf[..n]);
1324 let excess = t.len().saturating_sub(UNTIMED_STDERR_TAIL);
1325 t.drain(..excess);
1326 }
1327 }
1328 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
1329 Err(_) => return,
1330 }
1331 }
1332}
1333
1334#[cfg(unix)]
1346mod forward_signals {
1347 use std::sync::atomic::{AtomicBool, AtomicI32, Ordering::SeqCst};
1348
1349 const SIGNALS: [libc::c_int; 3] = [libc::SIGINT, libc::SIGTERM, libc::SIGHUP];
1350
1351 pub(super) struct State {
1374 spawning: AtomicBool,
1377 pgid: AtomicI32,
1379 pending: AtomicI32,
1382 done: AtomicBool,
1385 }
1386
1387 #[derive(Debug, PartialEq, Eq)]
1389 pub(super) enum Act {
1390 Defer,
1392 Die { pgid: i32 },
1394 }
1395
1396 impl State {
1397 pub(super) const fn new() -> State {
1398 State {
1399 spawning: AtomicBool::new(false),
1400 pgid: AtomicI32::new(0),
1401 pending: AtomicI32::new(0),
1402 done: AtomicBool::new(true),
1403 }
1404 }
1405
1406 pub(super) fn begin(&self) {
1407 self.pending.store(0, SeqCst);
1408 self.pgid.store(0, SeqCst);
1409 self.done.store(false, SeqCst);
1410 self.spawning.store(true, SeqCst);
1411 }
1412
1413 pub(super) fn on_signal(&self, sig: libc::c_int) -> Act {
1415 if self.wants_to_defer() {
1416 self.defer(sig)
1417 } else {
1418 Act::Die {
1419 pgid: self.pgid.load(SeqCst),
1420 }
1421 }
1422 }
1423
1424 fn wants_to_defer(&self) -> bool {
1427 let spawning = self.spawning.load(SeqCst);
1428 spawning && self.pgid.load(SeqCst) == 0
1429 }
1430
1431 fn defer(&self, sig: libc::c_int) -> Act {
1434 self.pending.store(sig, SeqCst);
1435 if self.done.load(SeqCst) {
1436 return Act::Die { pgid: 0 };
1437 }
1438 match self.pgid.load(SeqCst) {
1439 0 => Act::Defer,
1440 pgid => Act::Die { pgid },
1441 }
1442 }
1443
1444 pub(super) fn spawned(&self, pid: Option<u32>) -> Option<(libc::c_int, i32)> {
1448 let pgid = pid.map_or(0, |p| p as i32);
1449 self.pgid.store(pgid, SeqCst);
1450 self.spawning.store(false, SeqCst);
1451 let sig = self.pending.swap(0, SeqCst);
1452 (sig != 0).then_some((sig, pgid))
1453 }
1454
1455 pub(super) fn end(&self) -> Option<libc::c_int> {
1459 self.spawning.store(false, SeqCst);
1460 self.done.store(true, SeqCst);
1461 self.pgid.store(0, SeqCst);
1462 let sig = self.pending.swap(0, SeqCst);
1463 (sig != 0).then_some(sig)
1464 }
1465 }
1466
1467 static STATE: State = State::new();
1468
1469 fn die(sig: libc::c_int, pgid: i32) {
1473 unsafe {
1475 if pgid > 0 {
1476 libc::killpg(pgid, libc::SIGKILL);
1477 }
1478 libc::signal(sig, libc::SIG_DFL);
1479 libc::raise(sig);
1480 }
1481 }
1482
1483 extern "C" fn forward(sig: libc::c_int) {
1484 if let Act::Die { pgid } = STATE.on_signal(sig) {
1485 die(sig, pgid);
1486 }
1487 }
1488
1489 pub struct Guard {
1490 previous: Vec<(libc::c_int, libc::sigaction)>,
1491 }
1492
1493 impl Guard {
1494 pub fn install() -> Guard {
1497 STATE.begin();
1498 let mut previous = Vec::new();
1499 for sig in SIGNALS {
1500 unsafe {
1504 let mut new: libc::sigaction = std::mem::zeroed();
1505 new.sa_sigaction = forward as extern "C" fn(libc::c_int) as libc::sighandler_t;
1506 libc::sigemptyset(&mut new.sa_mask);
1507 let mut old: libc::sigaction = std::mem::zeroed();
1508 if libc::sigaction(sig, &new, &mut old) == 0 {
1509 previous.push((sig, old));
1510 }
1511 }
1512 }
1513 Guard { previous }
1514 }
1515
1516 pub fn spawned(pid: Option<u32>) {
1519 if let Some((sig, pgid)) = STATE.spawned(pid) {
1520 die(sig, pgid);
1521 }
1522 }
1523 }
1524
1525 impl Drop for Guard {
1526 fn drop(&mut self) {
1527 if let Some(sig) = STATE.end() {
1530 die(sig, 0);
1531 }
1532 for (sig, old) in &self.previous {
1533 unsafe {
1535 libc::sigaction(*sig, old, std::ptr::null_mut());
1536 }
1537 }
1538 }
1539 }
1540
1541 #[cfg(test)]
1545 mod tests {
1546 use super::{Act, SeqCst, State};
1547
1548 #[test]
1549 fn a_signal_during_the_spawn_is_held_until_the_group_is_known() {
1550 let s = State::new();
1551 s.begin();
1552 assert_eq!(s.on_signal(libc::SIGTERM), Act::Defer, "no group yet");
1553 assert_eq!(s.spawned(Some(42)), Some((libc::SIGTERM, 42)));
1554 assert_eq!(s.on_signal(libc::SIGINT), Act::Die { pgid: 42 });
1555 assert_eq!(s.end(), None);
1556
1557 s.begin();
1558 assert_eq!(s.spawned(Some(7)), None, "nothing arrived");
1559 assert_eq!(s.end(), None);
1560
1561 s.begin();
1562 assert_eq!(s.on_signal(libc::SIGINT), Act::Defer);
1563 assert_eq!(
1564 s.spawned(None),
1565 Some((libc::SIGINT, 0)),
1566 "a failed spawn still stops tak"
1567 );
1568 assert_eq!(s.end(), None);
1569
1570 assert_eq!(
1571 s.on_signal(libc::SIGHUP),
1572 Act::Die { pgid: 0 },
1573 "after the step"
1574 );
1575 assert!(!s.wants_to_defer(), "and it never defers there");
1576 }
1577
1578 #[test]
1581 fn a_handler_preempted_past_the_step_still_acts() {
1582 let s = State::new();
1583
1584 s.begin();
1587 assert!(s.wants_to_defer());
1588 assert_eq!(s.spawned(Some(42)), None);
1589 assert_eq!(s.end(), None);
1590 assert_eq!(s.defer(libc::SIGTERM), Act::Die { pgid: 0 });
1591
1592 s.begin();
1595 assert!(s.wants_to_defer());
1596 assert_eq!(s.spawned(Some(42)), None);
1597 assert_eq!(s.defer(libc::SIGINT), Act::Die { pgid: 42 });
1598 assert_eq!(s.end(), Some(libc::SIGINT));
1599
1600 s.begin();
1603 assert_eq!(s.spawned(Some(42)), None);
1604 s.pending.store(libc::SIGHUP, SeqCst);
1605 assert_eq!(s.end(), Some(libc::SIGHUP), "acted on at teardown");
1606 }
1607 }
1608}
1609
1610fn stop_group(child: &mut std::process::Child) {
1621 #[cfg(unix)]
1622 {
1623 let pgid = child.id() as libc::pid_t;
1626 if unsafe { libc::killpg(pgid, libc::SIGKILL) } != 0 {
1627 let _ = child.kill();
1628 }
1629 }
1630 #[cfg(not(unix))]
1631 let _ = child.kill();
1632 let _ = child.wait();
1633}
1634
1635fn version_once(argv: &[String], site: &Site, timeout: Duration) -> Result<String> {
1636 let bin = argv
1637 .first()
1638 .map(String::as_str)
1639 .unwrap_or("(empty command)");
1640 let Captured {
1641 status,
1642 stdout,
1643 stderr,
1644 stderr_tail,
1645 ..
1646 } = capture(argv, site, Some(timeout), VERSION_OUTPUT_CAP, false)?;
1647
1648 if !status.success() {
1651 bail!("`{bin}` exited with {status}: {}", last_line(&stderr_tail));
1652 }
1653 let first = |bytes: &[u8]| {
1654 String::from_utf8_lossy(bytes)
1655 .lines()
1656 .map(str::trim)
1657 .find(|l| !l.is_empty())
1658 .map(str::to_string)
1659 };
1660 first(&stdout)
1661 .or_else(|| first(&stderr))
1662 .with_context(|| format!("`{bin}` printed nothing"))
1663}
1664
1665fn last_line(bytes: &[u8]) -> String {
1667 String::from_utf8_lossy(bytes)
1668 .lines()
1669 .map(str::trim)
1670 .rfind(|l| !l.is_empty())
1671 .unwrap_or("(no output)")
1672 .to_string()
1673}
1674
1675struct Captured {
1677 status: std::process::ExitStatus,
1678 stdout: Vec<u8>,
1680 stderr: Vec<u8>,
1682 stderr_tail: Vec<u8>,
1684 overflowed: bool,
1687 stdout_open: bool,
1690 pgid: u32,
1693}
1694
1695fn stop_leftovers(pgid: u32) {
1704 #[cfg(unix)]
1705 unsafe {
1707 libc::killpg(pgid as libc::pid_t, libc::SIGKILL);
1708 }
1709 #[cfg(not(unix))]
1710 let _ = pgid;
1711}
1712
1713fn capture(
1727 argv: &[String],
1728 site: &Site,
1729 timeout: Option<Duration>,
1730 stdout_cap: usize,
1731 stop_past_cap: bool,
1732) -> Result<Captured> {
1733 use std::sync::atomic::{AtomicBool, Ordering::SeqCst};
1734 let bin = argv
1735 .first()
1736 .map(String::as_str)
1737 .unwrap_or("(empty command)");
1738 let mut cmd = command(argv, site)?;
1739 cmd.stdin(Stdio::null())
1740 .stdout(Stdio::piped())
1741 .stderr(Stdio::piped());
1742 #[cfg(unix)]
1745 std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
1746 #[cfg(unix)]
1749 let _forward = forward_signals::Guard::install();
1750 let spawned = cmd.spawn();
1751 #[cfg(unix)]
1753 forward_signals::Guard::spawned(spawned.as_ref().ok().map(std::process::Child::id));
1754 let mut child = spawned.with_context(|| format!("failed to spawn `{bin}`"))?;
1755 tracked::started(child.id());
1760 struct Finished;
1761 impl Drop for Finished {
1762 fn drop(&mut self) {
1763 tracked::finished();
1764 }
1765 }
1766 let _finished = Finished;
1767
1768 let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
1773 let overflow = Arc::new(AtomicBool::new(false));
1774 let ignored = Arc::new(AtomicBool::new(false));
1776 let stdout_done = Arc::new(AtomicBool::new(false));
1777 let unused = Arc::new(AtomicBool::new(false));
1778 let spawn_reader = |r: Option<Box<dyn std::io::Read + Send>>,
1779 cap: usize,
1780 flag: &Arc<AtomicBool>,
1781 done: &Arc<AtomicBool>,
1782 tail: Option<&Arc<Mutex<Vec<u8>>>>| {
1783 let kept = Arc::new(Mutex::new(Vec::new()));
1784 if let Some(r) = r {
1785 let (kept, tx, flag, done) = (
1786 Arc::clone(&kept),
1787 done_tx.clone(),
1788 Arc::clone(flag),
1789 Arc::clone(done),
1790 );
1791 let tail = tail.map(Arc::clone);
1792 std::thread::spawn(move || {
1793 keep_prefix(r, cap, &kept, &flag, tail.as_deref());
1794 done.store(true, SeqCst);
1795 let _ = tx.send(());
1796 });
1797 } else {
1798 done.store(true, SeqCst);
1799 let _ = done_tx.send(());
1800 }
1801 kept
1802 };
1803 let stdout = spawn_reader(
1804 child.stdout.take().map(|o| Box::new(o) as _),
1805 stdout_cap,
1806 &overflow,
1807 &stdout_done,
1808 None,
1809 );
1810 let stderr_tail = Arc::new(Mutex::new(Vec::new()));
1811 let stderr = spawn_reader(
1812 child.stderr.take().map(|e| Box::new(e) as _),
1813 VERSION_OUTPUT_CAP,
1814 &ignored,
1815 &unused,
1816 Some(&stderr_tail),
1817 );
1818
1819 let deadline = timeout.map(|t| Instant::now() + t);
1820 let status = loop {
1821 if stop_past_cap && overflow.load(SeqCst) {
1822 stop_group(&mut child);
1823 break child
1825 .wait()
1826 .with_context(|| format!("failed to wait for `{bin}`"))?;
1827 }
1828 match child.try_wait() {
1829 Ok(Some(status)) => break status,
1830 Ok(None) if deadline.is_none_or(|d| Instant::now() < d) => {
1831 std::thread::sleep(Duration::from_millis(5));
1832 }
1833 Ok(None) => {
1834 stop_group(&mut child);
1835 bail!(
1836 "`{bin}` did not finish within {}, so it was stopped",
1837 crate::progress::fmt(timeout.unwrap_or_default())
1838 );
1839 }
1840 Err(e) => {
1841 stop_group(&mut child);
1842 return Err(e).with_context(|| format!("failed to wait for `{bin}`"));
1843 }
1844 }
1845 };
1846 let grace = Instant::now() + VERSION_OUTPUT_GRACE;
1847 for _ in 0..2 {
1848 let left = grace.saturating_duration_since(Instant::now());
1849 if done_rx.recv_timeout(left).is_err() {
1850 break;
1851 }
1852 }
1853 let take = |kept: &Mutex<Vec<u8>>| kept.lock().map(|k| k.clone()).unwrap_or_default();
1854 Ok(Captured {
1855 status,
1856 stdout: take(&stdout),
1857 stderr: take(&stderr),
1858 stderr_tail: take(&stderr_tail),
1859 overflowed: overflow.load(SeqCst),
1860 stdout_open: !stdout_done.load(SeqCst),
1861 pgid: child.id(),
1862 })
1863}
1864
1865const VALGRIND_LOG_CAP: u64 = 1 << 20;
1869
1870#[cfg(unix)]
1900fn under_valgrind(
1901 tool: &[&str],
1902 cmd: &[String],
1903 site: &Site,
1904) -> Result<(std::process::ExitStatus, String)> {
1905 use std::io::{Read, Seek};
1906 use std::os::fd::AsRawFd;
1907 use std::os::unix::process::CommandExt;
1908 let mut log = tempfile::tempfile().context("failed to create a file for valgrind's log")?;
1909 let fd = log.as_raw_fd();
1910 let mut argv: Vec<String> = std::iter::once("valgrind")
1911 .chain(tool.iter().copied())
1912 .map(String::from)
1913 .collect();
1914 argv.push(format!("--log-fd={fd}"));
1915 argv.extend_from_slice(cmd);
1916 let mut c = command(&argv, site)?;
1917 c.stdin(Stdio::null())
1918 .stdout(Stdio::null())
1919 .stderr(Stdio::null());
1920 unsafe {
1923 c.pre_exec(move || {
1924 if libc::fcntl(fd, libc::F_SETFD, 0) == -1 {
1925 return Err(std::io::Error::last_os_error());
1926 }
1927 Ok(())
1928 });
1929 }
1930 let mut child = c.spawn().context("failed to run valgrind")?;
1935 let pid = child.id();
1936 tracked::started(pid);
1937 let status = child.wait();
1938 tracked::finished();
1939 let status = status.context("failed to run valgrind")?;
1940 let mut raw = Vec::new();
1944 log.rewind().context("failed to read valgrind's log")?;
1945 log.take(VALGRIND_LOG_CAP)
1946 .read_to_end(&mut raw)
1947 .context("failed to read valgrind's log")?;
1948 let prefix = format!("=={pid}==");
1949 let own: String = String::from_utf8_lossy(&raw)
1950 .lines()
1951 .filter(|l| l.starts_with(&prefix))
1952 .flat_map(|l| [l, "\n"])
1953 .collect();
1954 Ok((status, own))
1955}
1956
1957#[cfg(not(unix))]
1960fn under_valgrind(
1961 _tool: &[&str],
1962 _cmd: &[String],
1963 _site: &Site,
1964) -> Result<(std::process::ExitStatus, String)> {
1965 bail!("valgrind runs only on Unix")
1966}
1967
1968fn last_log_line(log: &str) -> &str {
1972 log.lines()
1973 .map(|l| valgrind_line(l).unwrap_or(l).trim())
1974 .rfind(|l| !l.is_empty())
1975 .unwrap_or("(valgrind wrote no log; it may not have been able to start the command)")
1976}
1977
1978fn count(
1990 cmd: &[String],
1991 prepare: Option<&[String]>,
1992 site: &Site,
1993 ok: &[i32],
1994 profile: bool,
1995 vet: &dyn Fn() -> Result<()>,
1996) -> Result<Option<(Counted, Option<Profiled>)>> {
1997 if !valgrind_available() {
1998 return Ok(None);
1999 }
2000
2001 let (scratch, unkept) = match profile.then(tempfile::tempdir) {
2005 Some(Ok(d)) => (Some(d), None),
2006 Some(Err(e)) => (
2007 None,
2008 Some(
2009 anyhow::Error::new(e)
2010 .context("could not create a directory for cachegrind profiles"),
2011 ),
2012 ),
2013 None => (None, None),
2014 };
2015 let mut samples: Vec<u64> = Vec::with_capacity(COUNTER_RUNS as usize);
2016 for run in 0..COUNTER_RUNS {
2017 if let Some(p) = prepare {
2020 vet()?;
2021 prepare_once(p, site)?;
2022 }
2023 vet()?;
2024 let out_file = match &scratch {
2025 Some(d) => d
2029 .path()
2030 .join(format!("run-{run}"))
2031 .to_string_lossy()
2032 .replace('%', "%%"),
2033 None => "/dev/null".to_string(),
2034 };
2035 let out_arg = format!("--cachegrind-out-file={out_file}");
2036 let (status, log) = under_valgrind(
2037 &[
2038 "--tool=cachegrind",
2039 "--cache-sim=no",
2040 "--branch-sim=no",
2041 &out_arg,
2042 ],
2043 cmd,
2044 site,
2045 )?;
2046
2047 let bin = cmd.first().map(String::as_str).unwrap_or("(empty command)");
2049 accepted(bin, status, ok, " under valgrind")?;
2050 match parse_irefs(&log) {
2051 Some(0) => {
2059 let unwritable =
2060 valgrind_lines(&log).any(|l| l.contains("can't open output data file"));
2061 if unwritable {
2062 bail!(
2063 "cachegrind could not write its profile to {out_file}, and counts nothing when that happens"
2064 );
2065 }
2066 bail!("cachegrind counted no instructions");
2067 }
2068 Some(n) => samples.push(n),
2069 None => bail!(
2073 "valgrind ran but emitted no `I refs` summary: {}",
2074 last_log_line(&log)
2075 ),
2076 }
2077 }
2078
2079 let counted = Counted {
2080 min: *samples.iter().min().expect("COUNTER_RUNS > 0"),
2081 max: *samples.iter().max().expect("COUNTER_RUNS > 0"),
2082 runs: COUNTER_RUNS,
2083 };
2084 let best = samples
2088 .iter()
2089 .position(|n| *n == counted.min)
2090 .expect("the minimum is one of the samples");
2091 let kept = match (scratch, unkept) {
2092 (Some(d), _) => {
2093 let path = d.path().join(format!("run-{best}"));
2094 Some(
2095 std::fs::read(&path)
2096 .with_context(|| format!("cachegrind wrote no profile to {}", path.display()))
2097 .and_then(|raw| {
2098 if raw.is_empty() {
2099 bail!("cachegrind wrote an empty profile to {}", path.display());
2100 }
2101 Ok(raw)
2102 }),
2103 )
2104 }
2105 (None, Some(e)) => Some(Err(e)),
2106 (None, None) => None,
2107 };
2108 Ok(Some((counted, kept)))
2109}
2110
2111fn parse_irefs(log: &str) -> Option<u64> {
2118 let line = valgrind_lines(log)
2119 .filter(|l| l.contains("I refs:"))
2120 .last()?;
2121 let digits: String = line
2122 .rsplit(':')
2123 .next()?
2124 .chars()
2125 .filter(|c| c.is_ascii_digit())
2126 .collect();
2127 digits.parse().ok()
2128}
2129
2130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2132pub struct Heap {
2133 pub blocks: u64,
2135 pub bytes: u64,
2137 pub peak_bytes: u64,
2139}
2140
2141impl Heap {
2142 pub fn metrics(&self) -> [(&'static str, u64); 3] {
2145 [
2146 ("alloc_blocks", self.blocks),
2147 ("alloc_bytes", self.bytes),
2148 ("alloc_peak_bytes", self.peak_bytes),
2149 ]
2150 }
2151}
2152
2153#[derive(Debug, Clone, Copy)]
2156pub struct Allocated {
2157 pub min: Heap,
2158 pub max: Heap,
2159 pub runs: u32,
2160}
2161
2162fn spread(lo: u64, hi: u64) -> f64 {
2167 match (lo, hi) {
2168 (0, 0) => 0.0,
2169 (0, _) => f64::INFINITY,
2170 (lo, hi) => (hi - lo) as f64 / lo as f64 * 100.0,
2171 }
2172}
2173
2174impl Allocated {
2175 pub fn totals_spread_pct(&self) -> f64 {
2177 spread(self.min.blocks, self.max.blocks).max(spread(self.min.bytes, self.max.bytes))
2178 }
2179
2180 pub fn peak_spread_pct(&self) -> f64 {
2182 spread(self.min.peak_bytes, self.max.peak_bytes)
2183 }
2184
2185 pub fn is_suspect(&self) -> bool {
2190 self.totals_spread_pct() > SPREAD_WARN_PCT
2191 }
2192
2193 pub fn peak_is_unsteady(&self) -> bool {
2198 self.peak_spread_pct() > SPREAD_WARN_PCT
2199 }
2200
2201 pub fn saw_nothing(&self) -> bool {
2206 self.max.blocks == 0
2207 }
2208}
2209
2210pub fn subject_allocations(s: &Subject, settings: &Settings) -> Result<Option<Allocated>> {
2224 subject_allocations_vetted(s, settings, &|| Ok(()))
2225}
2226
2227pub fn subject_allocations_vetted(
2231 s: &Subject,
2232 settings: &Settings,
2233 vet: &dyn Fn() -> Result<()>,
2234) -> Result<Option<Allocated>> {
2235 let site = Site {
2236 dir: s.dir.as_deref(),
2237 env: &s.env,
2238 settings,
2239 };
2240 allocations(&s.cmd, s.prepare.as_deref(), &site, &s.ok_exit_codes, vet)
2241}
2242
2243fn allocations(
2246 cmd: &[String],
2247 prepare: Option<&[String]>,
2248 site: &Site,
2249 ok: &[i32],
2250 vet: &dyn Fn() -> Result<()>,
2251) -> Result<Option<Allocated>> {
2252 if !valgrind_available() {
2253 return Ok(None);
2254 }
2255 let bin = cmd.first().map(String::as_str).unwrap_or("(empty command)");
2256 let mut runs: Vec<Heap> = Vec::with_capacity(COUNTER_RUNS as usize);
2257 for _ in 0..COUNTER_RUNS {
2258 if let Some(p) = prepare {
2262 vet()?;
2263 prepare_once(p, site)?;
2264 }
2265 vet()?;
2266 let (status, log) =
2270 under_valgrind(&["--tool=dhat", "--dhat-out-file=/dev/null"], cmd, site)?;
2271 accepted(bin, status, ok, " under valgrind")?;
2272 match parse_dhat(&log) {
2273 Some(h) => runs.push(h),
2274 None => bail!(
2275 "valgrind ran but emitted no DHAT summary: {}",
2276 last_log_line(&log)
2277 ),
2278 }
2279 }
2280 let fold = |f: fn(u64, u64) -> u64| {
2281 runs.iter()
2282 .copied()
2283 .reduce(|a, b| Heap {
2284 blocks: f(a.blocks, b.blocks),
2285 bytes: f(a.bytes, b.bytes),
2286 peak_bytes: f(a.peak_bytes, b.peak_bytes),
2287 })
2288 .expect("COUNTER_RUNS > 0")
2289 };
2290 Ok(Some(Allocated {
2291 min: fold(u64::min),
2292 max: fold(u64::max),
2293 runs: COUNTER_RUNS,
2294 }))
2295}
2296
2297fn parse_dhat(log: &str) -> Option<Heap> {
2311 let field = |name: &str| {
2312 let rest = valgrind_lines(log).find_map(|l| l.trim_start().strip_prefix(name))?;
2313 let (bytes, rest) = rest.trim().split_once(" bytes in ")?;
2314 let blocks = rest.split_whitespace().next()?;
2315 Some((dhat_number(bytes)?, dhat_number(blocks)?))
2316 };
2317 let (bytes, blocks) = field("Total:")?;
2318 let (peak_bytes, _) = field("At t-gmax:")?;
2319 Some(Heap {
2320 blocks,
2321 bytes,
2322 peak_bytes,
2323 })
2324}
2325
2326fn valgrind_line(line: &str) -> Option<&str> {
2328 let rest = line.strip_prefix("==")?;
2329 let (pid, rest) = rest.split_once("==")?;
2330 (!pid.is_empty() && pid.chars().all(|c| c.is_ascii_digit())).then_some(rest)
2331}
2332
2333fn dhat_number(s: &str) -> Option<u64> {
2335 let digits: String = s.trim().chars().filter(|&c| c != ',').collect();
2336 if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
2337 return None;
2338 }
2339 digits.parse().ok()
2340}
2341
2342fn valgrind_lines(log: &str) -> impl Iterator<Item = &str> {
2344 log.lines().filter_map(valgrind_line)
2345}
2346
2347#[cfg(test)]
2348mod tests {
2349 use super::*;
2350
2351 const DHAT_3_22: &str = "\
2354==9== DHAT, a dynamic heap analysis tool
2355==9== Copyright (C) 2010-2018, and GNU GPL'd, by Mozilla Foundation
2356==9== Using Valgrind-3.22.0 and LibVEX; rerun with -h for copyright info
2357==9== Command: git --version
2358==9==
2359git version 2.43.0
2360==9==
2361==9== Total: 7,119 bytes in 31 blocks
2362==9== At t-gmax: 6,847 bytes in 25 blocks
2363==9== At t-end: 2,379 bytes in 15 blocks
2364==9== Reads: 1,067 bytes
2365==9== Writes: 1,546 bytes
2366==9==
2367==9== To view the resulting profile, open
2368==9== file:///usr/libexec/valgrind/dh_view.html
2369==9== in a web browser, click on \"Load...\", and then select the file
2370==9== /dev/null
2371==9== The text at the bottom explains the abbreviations used in the output.
2372";
2373
2374 #[test]
2375 fn parses_a_dhat_summary() {
2376 assert_eq!(
2377 parse_dhat(DHAT_3_22),
2378 Some(Heap {
2379 blocks: 31,
2380 bytes: 7_119,
2381 peak_bytes: 6_847,
2382 })
2383 );
2384 }
2385
2386 #[test]
2389 fn parses_counts_past_a_million() {
2390 let s = "==21== Total: 2,626,313 bytes in 2,833 blocks\n\
2391 ==21== At t-gmax: 1,185,686 bytes in 1,661 blocks\n";
2392 assert_eq!(
2393 parse_dhat(s),
2394 Some(Heap {
2395 blocks: 2_833,
2396 bytes: 2_626_313,
2397 peak_bytes: 1_185_686,
2398 })
2399 );
2400 }
2401
2402 #[test]
2405 fn only_valgrinds_own_lines_are_read() {
2406 let s = "Total: 5 bytes in 1 blocks\n\
2407 ==12== \n\
2408 ==12== Total: 8,748 bytes in 17 blocks\n\
2409 ==12== At t-gmax: 8,748 bytes in 17 blocks\n";
2410 assert_eq!(parse_dhat(s).unwrap().blocks, 17);
2411 assert_eq!(
2412 parse_dhat("Total: 5 bytes in 1 blocks\nAt t-gmax: 5 bytes in 1 blocks\n"),
2413 None
2414 );
2415 assert_eq!(valgrind_line("==x== Total:"), None);
2416 assert_eq!(valgrind_line("==== Total:"), None);
2417 }
2418
2419 #[test]
2420 fn a_missing_or_truncated_dhat_summary_is_none() {
2421 assert_eq!(parse_dhat(""), None);
2422 assert_eq!(parse_dhat("==3== Total: 1 bytes in 1 blocks\n"), None);
2424 assert_eq!(
2425 parse_dhat(
2426 "==3== Total: lots bytes in 1 blocks\n==3== At t-gmax: 1 bytes in 1 blocks\n"
2427 ),
2428 None
2429 );
2430 }
2431
2432 #[test]
2435 fn totals_and_peak_spread_are_judged_apart() {
2436 let h = |blocks, bytes, peak_bytes| Heap {
2437 blocks,
2438 bytes,
2439 peak_bytes,
2440 };
2441 let a = |min, max| Allocated { min, max, runs: 3 };
2442 let steady = a(h(10, 1000, 500), h(10, 1000, 500));
2443 assert_eq!(steady.totals_spread_pct(), 0.0);
2444 assert!(!steady.is_suspect() && !steady.peak_is_unsteady());
2445
2446 let threaded = a(h(10, 1000, 500), h(10, 1000, 510));
2447 assert!((threaded.peak_spread_pct() - 2.0).abs() < 1e-9);
2448 assert!(threaded.peak_is_unsteady() && !threaded.is_suspect());
2449
2450 let first_run = a(h(496, 2_077_237, 1_790_738), h(1140, 2_227_102, 1_888_914));
2452 assert!(first_run.is_suspect());
2453 assert!((first_run.totals_spread_pct() - 129.84).abs() < 0.01);
2454
2455 assert!(a(h(0, 0, 0), h(1, 8, 8)).totals_spread_pct().is_infinite());
2457 assert!(a(h(0, 0, 0), h(0, 0, 0)).saw_nothing());
2458 assert!(!steady.saw_nothing());
2459 }
2460
2461 #[test]
2464 fn a_count_printed_by_the_subject_is_not_the_count() {
2465 let s = "I refs: 5\n==7== error: can't open output data file\n==7== I refs: 1,234\nI refs: 9\n";
2466 assert_eq!(parse_irefs(s), Some(1_234));
2467 assert_eq!(parse_irefs("I refs: 5\n"), None);
2468 assert_eq!(
2469 valgrind_lines("==x== no\n== 1== no\n==12== yes\n").collect::<Vec<_>>(),
2470 [" yes"]
2471 );
2472 }
2473
2474 #[test]
2475 fn parses_cachegrind_summary() {
2476 let s = "==12== I refs: 48,349,132\n";
2477 assert_eq!(parse_irefs(s), Some(48_349_132));
2478 }
2479
2480 #[test]
2481 fn missing_summary_is_none_not_panic() {
2482 assert_eq!(parse_irefs("valgrind: command not found"), None);
2483 }
2484
2485 fn removals(settings: &Settings) -> Vec<String> {
2487 subject("true", settings)
2488 .get_envs()
2489 .filter(|(_, v)| v.is_none())
2490 .map(|(k, _)| k.to_string_lossy().into_owned())
2491 .collect()
2492 }
2493
2494 #[test]
2497 fn subject_commands_remove_the_default_denied_variables() {
2498 let removed = removals(&Settings::default());
2499 for key in Settings::default().scrubbed_env() {
2500 assert!(removed.contains(&key.to_string()), "{key} not removed");
2501 }
2502 }
2503
2504 #[test]
2507 fn the_removal_follows_the_settings() {
2508 let removed = removals(&Settings {
2509 env_deny: vec!["CUSTOM_SECRET".into()],
2510 env_allow: Vec::new(),
2511 ..Settings::default()
2512 });
2513 assert!(removed.contains(&"CUSTOM_SECRET".to_string()));
2514 assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
2515 }
2516
2517 #[test]
2520 fn an_allowed_variable_survives() {
2521 let removed = removals(&Settings {
2522 env_deny: vec!["GITHUB_TOKEN".into(), "GH_TOKEN".into()],
2523 env_allow: vec!["GITHUB_TOKEN".into()],
2524 ..Settings::default()
2525 });
2526 assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
2527 assert!(removed.contains(&"GH_TOKEN".to_string()));
2528 }
2529
2530 #[test]
2531 fn zero_runs_is_rejected_not_a_panic() {
2532 let plan = Plan {
2533 cmd: vec!["true".into()],
2534 warmup: 0,
2535 runs: 0,
2536 dir: None,
2537 settings: Settings::default(),
2538 };
2539 assert!(wall(&plan).is_err());
2540 }
2541
2542 #[test]
2543 fn a_failed_subject_is_not_recorded_as_a_fast_run() {
2544 #[cfg(unix)]
2545 let cmd = vec!["/bin/sh".into(), "-c".into(), "exit 42".into()];
2546 #[cfg(windows)]
2547 let cmd = vec!["cmd".into(), "/C".into(), "exit /B 42".into()];
2548
2549 let err = wall(&Plan {
2550 cmd,
2551 warmup: 0,
2552 runs: 1,
2553 dir: None,
2554 settings: Settings::default(),
2555 })
2556 .unwrap_err();
2557
2558 assert!(format!("{err:#}").contains("exited with"), "{err:#}");
2559 }
2560
2561 #[test]
2562 fn wall_reports_min_le_p50_le_max() {
2563 let plan = Plan {
2564 cmd: vec!["true".into()],
2565 warmup: 1,
2566 runs: 5,
2567 dir: None,
2568 settings: Settings::default(),
2569 };
2570 let m = wall(&plan).unwrap();
2571 assert!(m["wall_min_ms"] <= m["wall_p50_ms"]);
2572 assert!(m["wall_p50_ms"] <= m["wall_max_ms"]);
2573 assert_eq!(m["wall_n"], 5.0);
2574 }
2575
2576 #[test]
2578 fn the_schedule_gives_each_subject_its_counts() {
2579 let counts = [(2, 10), (1, 5), (0, 3)];
2580 let order = schedule(&counts, 7);
2581 for (i, &(warmup, runs)) in counts.iter().enumerate() {
2582 let of = |timed| {
2583 order
2584 .iter()
2585 .filter(|s| s.subject == i && s.timed == timed)
2586 .count()
2587 };
2588 assert_eq!(of(false), warmup as usize, "subject {i} warmups");
2589 assert_eq!(of(true), runs as usize, "subject {i} runs");
2590 }
2591 let first_timed = order.iter().position(|s| s.timed).unwrap();
2592 assert!(order[first_timed..].iter().all(|s| s.timed));
2593 }
2594
2595 #[test]
2596 fn the_same_seed_gives_the_same_order() {
2597 let counts = [(1, 8), (1, 8), (1, 8)];
2598 assert_eq!(schedule(&counts, 42), schedule(&counts, 42));
2599 assert_ne!(schedule(&counts, 42), schedule(&counts, 43));
2600 }
2601
2602 #[test]
2605 fn each_round_runs_every_subject_once_in_a_varying_order() {
2606 let order = schedule(&[(0, 20), (0, 20), (0, 20)], 1);
2607 let rounds: Vec<Vec<usize>> = order
2608 .chunks(3)
2609 .map(|r| r.iter().map(|s| s.subject).collect())
2610 .collect();
2611 assert_eq!(rounds.len(), 20);
2612 for r in &rounds {
2613 let mut sorted = r.clone();
2614 sorted.sort();
2615 assert_eq!(sorted, [0, 1, 2], "round {r:?}");
2616 }
2617 assert!(rounds.iter().any(|r| r != &rounds[0]), "never shuffled");
2618 }
2619
2620 #[test]
2623 fn a_subject_with_fewer_runs_is_spread_across_the_run() {
2624 let order = schedule(&[(0, 10), (0, 5)], 3);
2625 let fewer: Vec<usize> = order
2626 .iter()
2627 .enumerate()
2628 .filter(|(_, s)| s.subject == 1)
2629 .map(|(i, _)| i)
2630 .collect();
2631 assert_eq!(fewer.len(), 5);
2632 assert!(
2633 *fewer.last().unwrap() >= order.len() - 3,
2634 "last sample of the smaller subject is near the end: {fewer:?} of {}",
2635 order.len()
2636 );
2637 }
2638
2639 #[test]
2640 fn a_benchmark_seed_depends_on_its_name_and_the_run_seed() {
2641 assert_eq!(seed_for(1, "a"), seed_for(1, "a"));
2642 assert_ne!(seed_for(1, "a"), seed_for(1, "b"));
2643 assert_ne!(seed_for(1, "a"), seed_for(2, "a"));
2644 }
2645
2646 #[test]
2647 fn stats_report_the_sample_standard_deviation() {
2648 let m = stats(&[2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]);
2649 assert_eq!(m["wall_min_ms"], 2.0);
2650 assert_eq!(m["wall_max_ms"], 9.0);
2651 assert_eq!(m["wall_mean_ms"], 5.0);
2652 assert!((m["wall_stddev_ms"] - 2.138_089_935).abs() < 1e-6);
2654 assert_eq!(stats(&[3.0])["wall_stddev_ms"], 0.0);
2655 }
2656
2657 #[cfg(unix)]
2659 #[test]
2660 fn a_failing_subject_does_not_stop_the_others() {
2661 let mk = |name: &str, cmd: &[&str]| Subject {
2662 name: name.into(),
2663 cmd: cmd.iter().map(|s| s.to_string()).collect(),
2664 prepare: None,
2665 setup: None,
2666 setup_dir: None,
2667 check: None,
2668 dir: None,
2669 version_cmd: None,
2670 env: BTreeMap::new(),
2671 vars: BTreeMap::new(),
2672 when: None,
2673 runs: Runs::Fixed(4),
2674 auto: AutoRuns {
2675 budget: Duration::from_secs(30),
2676 min: 5,
2677 max: 50,
2678 },
2679 warmup: 1,
2680 counters: false,
2681 allocations: false,
2682 ok_exit_codes: vec![0],
2683 metrics: BTreeMap::new(),
2684 };
2685 let res = interleaved(
2686 &[mk("ok", &["true"]), mk("bad", &["false"])],
2687 5,
2688 &Settings::default(),
2689 &mut Quiet,
2690 );
2691 assert_eq!(res[0].as_ref().unwrap().times.len(), 4);
2692 assert!(format!("{:#}", res[1].as_ref().unwrap_err()).contains("exited with"));
2693 }
2694
2695 #[test]
2698 fn a_metric_value_is_exactly_one_non_negative_number() {
2699 for (text, want) in [
2700 ("1234", 1234.0),
2701 ("1234\n", 1234.0),
2702 (" \t12.5\r\n", 12.5),
2703 ("0", 0.0),
2704 ("1.5e3", 1500.0),
2705 ("2E-2", 0.02),
2706 ("007", 7.0),
2707 ] {
2708 assert_eq!(parse_metric_value(text).unwrap(), want, "{text:?}");
2709 }
2710 for bad in [
2711 "", "\n", "-1", "+1", ".5", "5.", "1e", "1e+", "nan", "inf", "0x10", "1,234", "12 kB",
2712 "1 2", "1\n2", "size: 3", "1e999",
2713 ] {
2714 assert!(parse_metric_value(bad).is_err(), "accepted {bad:?}");
2715 }
2716 }
2717
2718 fn with_metrics(dir: &Path, env: &[(&str, &str)]) -> Subject {
2719 Subject {
2720 name: "s".into(),
2721 cmd: vec!["true".into()],
2722 prepare: None,
2723 setup: None,
2724 setup_dir: None,
2725 check: None,
2726 dir: Some(dir.to_path_buf()),
2727 version_cmd: None,
2728 env: env
2729 .iter()
2730 .map(|(k, v)| (k.to_string(), v.to_string()))
2731 .collect(),
2732 vars: BTreeMap::new(),
2733 when: None,
2734 runs: Runs::Fixed(1),
2735 auto: AutoRuns {
2736 budget: Duration::from_secs(30),
2737 min: 5,
2738 max: 50,
2739 },
2740 warmup: 0,
2741 counters: false,
2742 allocations: false,
2743 ok_exit_codes: vec![0],
2744 metrics: BTreeMap::new(),
2745 }
2746 }
2747
2748 #[test]
2751 fn a_file_metric_is_its_size_in_bytes() {
2752 let dir = tempfile::tempdir().unwrap();
2753 let file = dir.path().join("bin");
2754 std::fs::write(&file, vec![0u8; 4321]).unwrap();
2755 let s = with_metrics(dir.path(), &[]);
2756 let settings = Settings::default();
2757 assert_eq!(
2758 custom_metric(&MetricSource::File(file), &s, &settings).unwrap(),
2759 4321.0
2760 );
2761 let err = custom_metric(&MetricSource::File(dir.path().into()), &s, &settings).unwrap_err();
2762 assert!(format!("{err:#}").contains("not a regular file"), "{err:#}");
2763 let missing = dir.path().join("missing");
2764 let err = custom_metric(&MetricSource::File(missing), &s, &settings).unwrap_err();
2765 assert!(format!("{err:#}").contains("missing"), "{err:#}");
2766 }
2767
2768 #[cfg(unix)]
2773 #[test]
2774 fn a_cmd_metric_runs_in_the_subjects_dir_and_env() {
2775 let dir = tempfile::tempdir().unwrap();
2776 std::fs::write(dir.path().join("here"), "").unwrap();
2777 let s = with_metrics(dir.path(), &[("N", "42")]);
2778 let settings = Settings::default();
2779 let sh = |script: &str| {
2780 custom_metric(
2781 &MetricSource::Cmd(vec!["sh".into(), "-c".into(), script.into()]),
2782 &s,
2783 &settings,
2784 )
2785 };
2786 assert_eq!(sh("test -e here && echo $N").unwrap(), 42.0);
2787 let err = format!("{:#}", sh("echo 5; echo broke >&2; exit 3").unwrap_err());
2788 assert!(
2789 err.contains("exit status: 3") && err.contains("broke"),
2790 "{err}"
2791 );
2792 let err = format!("{:#}", sh("echo 'bundle: 12 kB'").unwrap_err());
2793 assert!(err.contains("not one number"), "{err}");
2794 let err = format!("{:#}", sh("yes 1 | head -c 4096").unwrap_err());
2795 assert!(err.contains("more than 1024 bytes"), "{err}");
2796 let err = format!("{:#}", sh("yes 1 | head -c 1024").unwrap_err());
2798 assert!(err.contains("not one number"), "{err}");
2799 let start = Instant::now();
2802 let err = format!("{:#}", sh("exec yes 1").unwrap_err());
2803 assert!(err.contains("so they were stopped"), "{err}");
2804 assert!(start.elapsed() < Duration::from_secs(4));
2805 let err = format!(
2808 "{:#}",
2809 sh("yes 'noise line' | head -c 20000 >&2; echo 'the real error' >&2; exit 2")
2810 .unwrap_err()
2811 );
2812 assert!(err.ends_with("the real error"), "{err}");
2813 assert!(!err.contains("noise"), "{err}");
2814 }
2815
2816 #[cfg(unix)]
2821 #[test]
2822 fn a_metric_cmd_leaving_stdout_open_fails_and_is_stopped() {
2823 let err = leftover_metric("sleep 30 & echo $! > pid; echo 7");
2824 assert!(err.contains("stdout open"), "{err}");
2825 }
2826
2827 #[cfg(unix)]
2831 #[test]
2832 fn a_leftover_that_floods_stdout_after_exit_is_stopped() {
2833 let err = leftover_metric("(sleep 0.1; exec yes 1) & echo $! > pid; echo 7");
2834 assert!(
2835 err.contains("more than 1024 bytes") && err.contains("what it started"),
2836 "{err}"
2837 );
2838 }
2839
2840 #[cfg(unix)]
2844 fn leftover_metric(script: &str) -> String {
2845 let dir = tempfile::tempdir().unwrap();
2846 let s = with_metrics(dir.path(), &[]);
2847 let start = Instant::now();
2848 let err = custom_metric(
2849 &MetricSource::Cmd(vec!["sh".into(), "-c".into(), script.into()]),
2850 &s,
2851 &Settings::default(),
2852 )
2853 .unwrap_err();
2854 assert!(start.elapsed() < Duration::from_secs(4));
2855 let pid = std::fs::read_to_string(dir.path().join("pid")).unwrap();
2856 let pid = pid.trim();
2857 let until = Instant::now() + Duration::from_secs(2);
2860 while running(pid) && Instant::now() < until {
2861 std::thread::sleep(Duration::from_millis(20));
2862 }
2863 assert!(
2864 !running(pid),
2865 "the background process {pid} was left running"
2866 );
2867 format!("{err:#}")
2868 }
2869
2870 #[cfg(unix)]
2872 fn version_sh(script: &str, env: &[(&str, &str)], timeout: Duration) -> Result<String> {
2873 let settings = Settings::default();
2874 let env: BTreeMap<String, String> = env
2875 .iter()
2876 .map(|(k, v)| (k.to_string(), v.to_string()))
2877 .collect();
2878 let site = Site {
2879 dir: None,
2880 env: &env,
2881 settings: &settings,
2882 };
2883 version_once(&["sh".into(), "-c".into(), script.into()], &site, timeout)
2884 }
2885
2886 #[cfg(unix)]
2889 #[test]
2890 fn a_version_is_the_first_line_printed() {
2891 let sh = |script: &str| version_sh(script, &[("V", "9.9")], VERSION_TIMEOUT);
2892 assert_eq!(
2893 sh("printf '\\n tool %s \\nbuilt today\\n' \"$V\"").unwrap(),
2894 "tool 9.9",
2895 "first non-empty line, trimmed, in the subject's env"
2896 );
2897 assert_eq!(sh("echo 'java 21' >&2").unwrap(), "java 21");
2898 let err = format!("{:#}", sh("echo nope >&2; exit 2").unwrap_err());
2899 assert!(err.contains("`sh`") && err.contains("nope"), "{err}");
2900 assert!(sh("true").is_err(), "no output is no version");
2901 }
2902
2903 #[cfg(unix)]
2906 #[test]
2907 fn a_version_is_read_from_a_capped_prefix() {
2908 let sh = |script: &str| version_sh(script, &[], VERSION_TIMEOUT);
2909 assert_eq!(sh("yes 'tool 1.0' | head -c 10000000").unwrap(), "tool 1.0");
2910 assert_eq!(
2911 sh("yes 'java 21' | head -c 10000000 >&2").unwrap(),
2912 "java 21",
2913 "a flood on stderr"
2914 );
2915 let kept = Mutex::new(Vec::new());
2916 let mut src = std::io::Cursor::new(vec![7u8; 100]);
2917 let overflow = std::sync::atomic::AtomicBool::new(false);
2918 keep_prefix(&mut src, 10, &kept, &overflow, None);
2919 assert_eq!(kept.lock().unwrap().len(), 10, "only the cap is kept");
2920 assert_eq!(
2921 src.position(),
2922 100,
2923 "the rest is read, not left in the pipe"
2924 );
2925 assert!(overflow.into_inner(), "and going past the cap is noticed");
2926
2927 let (kept, overflow) = (
2928 Mutex::new(Vec::new()),
2929 std::sync::atomic::AtomicBool::new(false),
2930 );
2931 keep_prefix(
2932 std::io::Cursor::new(vec![7u8; 10]),
2933 10,
2934 &kept,
2935 &overflow,
2936 None,
2937 );
2938 assert!(!overflow.into_inner(), "exactly the cap is not past it");
2939 }
2940
2941 #[cfg(unix)]
2944 #[test]
2945 fn a_failing_version_cmd_is_an_error_even_past_the_cap() {
2946 let err = version_sh(
2947 "yes 'usage: tool [flags]' | head -c 100000; echo 'unknown flag' >&2; exit 1",
2948 &[],
2949 VERSION_TIMEOUT,
2950 )
2951 .unwrap_err();
2952 let err = format!("{err:#}");
2953 assert!(
2954 err.contains("exited with") && err.contains("unknown flag"),
2955 "{err}"
2956 );
2957 }
2958
2959 #[cfg(unix)]
2962 #[test]
2963 fn a_version_cmd_that_never_finishes_is_stopped() {
2964 let t = Duration::from_millis(300);
2965 let began = Instant::now();
2966 for script in ["exec yes 'tool 2.0' >&2", "exec sleep 30"] {
2968 let err = format!("{:#}", version_sh(script, &[], t).unwrap_err());
2969 assert!(err.contains("did not finish"), "{script}: {err}");
2970 }
2971 assert!(
2972 began.elapsed() < Duration::from_secs(5),
2973 "{:?}",
2974 began.elapsed()
2975 );
2976 }
2977
2978 #[cfg(unix)]
2981 #[test]
2982 fn a_timeout_stops_the_whole_process_group() {
2983 let dir = tempfile::tempdir().unwrap();
2984 let pidfile = dir.path().join("pid");
2985 let script = format!("sleep 30 & echo $! > '{}'; wait", pidfile.display());
2986 let err = version_sh(&script, &[], Duration::from_millis(300)).unwrap_err();
2987 assert!(format!("{err:#}").contains("did not finish"), "{err:#}");
2988 let pid = std::fs::read_to_string(&pidfile).unwrap();
2989 let pid = pid.trim();
2990 let until = Instant::now() + Duration::from_secs(2);
2991 while running(pid) && Instant::now() < until {
2992 std::thread::sleep(Duration::from_millis(20));
2993 }
2994 assert!(
2995 !running(pid),
2996 "the background sleep {pid} outlived the timeout"
2997 );
2998 }
2999
3000 #[cfg(unix)]
3005 fn running(pid: &str) -> bool {
3006 #[cfg(target_os = "linux")]
3007 {
3008 let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) else {
3011 return false;
3012 };
3013 let state = stat
3014 .rfind(')')
3015 .and_then(|i| stat[i + 1..].trim_start().chars().next());
3016 !matches!(state, None | Some('Z' | 'X' | 'x'))
3017 }
3018 #[cfg(not(target_os = "linux"))]
3019 {
3020 let Ok(out) = Command::new("ps")
3021 .args(["-o", "stat=", "-p", pid])
3022 .stderr(Stdio::null())
3023 .output()
3024 else {
3025 return false;
3026 };
3027 let stat = String::from_utf8_lossy(&out.stdout);
3028 let stat = stat.trim();
3029 out.status.success() && !stat.is_empty() && !stat.starts_with('Z')
3030 }
3031 }
3032
3033 #[cfg(unix)]
3036 #[test]
3037 fn a_background_process_holding_the_pipe_does_not_hold_up_the_version() {
3038 let began = Instant::now();
3039 let v = version_sh("sleep 5 & echo 'tool 3.0'", &[], VERSION_TIMEOUT).unwrap();
3040 assert_eq!(v, "tool 3.0");
3041 assert!(
3042 began.elapsed() < Duration::from_secs(3),
3043 "{:?}",
3044 began.elapsed()
3045 );
3046 }
3047
3048 #[cfg(unix)]
3050 #[test]
3051 fn a_failing_prepare_is_reported_as_prepare() {
3052 let res = interleaved(
3053 &[Subject {
3054 name: "x".into(),
3055 cmd: vec!["true".into()],
3056 prepare: Some(vec![
3057 "/bin/sh".into(),
3058 "-c".into(),
3059 "echo nope >&2; exit 3".into(),
3060 ]),
3061 setup: None,
3062 setup_dir: None,
3063 check: None,
3064 dir: None,
3065 version_cmd: None,
3066 env: BTreeMap::new(),
3067 vars: BTreeMap::new(),
3068 when: None,
3069 runs: Runs::Fixed(1),
3070 auto: AutoRuns {
3071 budget: Duration::from_secs(30),
3072 min: 5,
3073 max: 50,
3074 },
3075 warmup: 0,
3076 counters: false,
3077 allocations: false,
3078 ok_exit_codes: vec![0],
3079 metrics: BTreeMap::new(),
3080 }],
3081 0,
3082 &Settings::default(),
3083 &mut Quiet,
3084 );
3085 let msg = format!("{:#}", res[0].as_ref().unwrap_err());
3086 assert!(msg.contains("prepare") && msg.contains("nope"), "{msg}");
3087 }
3088
3089 #[cfg(unix)]
3092 fn alternating(dir: &Path, warmup: u32, runs: u32) -> Subject {
3093 Subject {
3094 name: "alt".into(),
3095 cmd: vec![
3096 "/bin/sh".into(),
3097 "-c".into(),
3098 "echo x >> n".into(),
3099 ],
3100 prepare: None,
3101 setup: None,
3102 setup_dir: None,
3103 check: Some(vec![
3104 "/bin/sh".into(),
3105 "-c".into(),
3106 "echo check >> checked; runs=$(( $(wc -l < n) )); test $(( runs % 2 )) = 1 || { echo \"run $runs is even\" >&2; exit 1; }".into(),
3108 ]),
3109 version_cmd: None,
3110 dir: Some(dir.to_path_buf()),
3111 env: BTreeMap::new(),
3112 vars: BTreeMap::new(),
3113 when: None,
3114 runs: Runs::Fixed(runs),
3115 auto: AutoRuns {
3116 budget: Duration::from_secs(30),
3117 min: 5,
3118 max: 50,
3119 },
3120 warmup,
3121 counters: false,
3122 allocations: false,
3123 ok_exit_codes: vec![0],
3124 metrics: BTreeMap::new(),
3125 }
3126 }
3127
3128 #[cfg(unix)]
3131 #[test]
3132 fn a_failing_check_marks_the_sample_without_dropping_the_subject() {
3133 let dir = tempfile::tempdir().unwrap();
3134 let res = interleaved(
3135 &[alternating(dir.path(), 1, 6)],
3136 0,
3137 &Settings::default(),
3138 &mut Quiet,
3139 );
3140 let s = res[0].as_ref().unwrap();
3141 assert_eq!(s.times.len(), 6);
3142 assert_eq!(s.checks, [false, true, false, true, false, true]);
3144 assert_eq!(s.passed(), 3);
3145 assert!(
3146 s.first_failure
3147 .as_deref()
3148 .unwrap()
3149 .contains("run 2 is even"),
3150 "{s:?}"
3151 );
3152 let checked = std::fs::read_to_string(dir.path().join("checked")).unwrap();
3153 assert_eq!(checked.lines().count(), 6, "no check after the warmup");
3154 }
3155
3156 #[cfg(unix)]
3160 #[test]
3161 fn ok_exit_codes_do_not_pass_a_check_that_exits_1() {
3162 let dir = tempfile::tempdir().unwrap();
3163 let mut s = alternating(dir.path(), 0, 2);
3164 s.cmd = vec!["/bin/sh".into(), "-c".into(), "exit 1".into()];
3165 s.check = Some(vec!["/bin/sh".into(), "-c".into(), "exit 1".into()]);
3166 s.ok_exit_codes = vec![0, 1];
3167 let res = interleaved(&[s], 0, &Settings::default(), &mut Quiet);
3168 let s = res[0].as_ref().unwrap();
3169 assert_eq!(s.exit_codes, [1, 1]);
3170 assert_eq!(s.checks, [false, false]);
3171 assert_eq!(s.passed(), 0);
3172 }
3173
3174 #[cfg(unix)]
3177 #[test]
3178 fn a_check_that_cannot_start_drops_the_subject() {
3179 let dir = tempfile::tempdir().unwrap();
3180 let mut s = alternating(dir.path(), 0, 2);
3181 s.check = Some(vec!["/nonexistent/tak-check".into()]);
3182 let res = interleaved(&[s], 0, &Settings::default(), &mut Quiet);
3183 let msg = format!("{:#}", res[0].as_ref().unwrap_err());
3184 assert!(msg.contains("failed to spawn check"), "{msg}");
3185 }
3186
3187 #[cfg(unix)]
3192 #[test]
3193 fn a_process_left_by_a_passing_step_can_still_write_to_stderr() {
3194 let dir = tempfile::tempdir().unwrap();
3195 let env = BTreeMap::new();
3196 let settings = Settings::default();
3197 let site = Site {
3198 dir: Some(dir.path()),
3199 env: &env,
3200 settings: &settings,
3201 };
3202 const N: usize = 10;
3203 let start = Instant::now();
3204 for i in 0..N {
3205 let script = format!(
3206 "{{ sh -c 'sleep 1; echo late >&2'; echo $? > s{i}.tmp && mv s{i}.tmp s{i}; }} & exit 0"
3207 );
3208 let step = ["/bin/sh".to_string(), "-c".into(), script];
3209 assert_eq!(untimed("setup", &step, &site).unwrap(), None);
3210 }
3211 let took = start.elapsed();
3212 assert!(took < Duration::from_secs(2), "{N} passes took {took:?}");
3213
3214 let deadline = Instant::now() + Duration::from_secs(20);
3215 let statuses: Vec<String> = (0..N)
3216 .map(|i| {
3217 loop {
3218 if let Ok(s) = std::fs::read_to_string(dir.path().join(format!("s{i}"))) {
3219 break s.trim().to_string();
3220 }
3221 assert!(Instant::now() < deadline, "leftover {i} never finished");
3222 std::thread::sleep(Duration::from_millis(50));
3223 }
3224 })
3225 .collect();
3226 assert!(statuses.iter().all(|s| s == "0"), "{statuses:?}");
3227 }
3228
3229 #[derive(Default)]
3231 struct Log {
3232 plans: Vec<Vec<u64>>,
3233 finished: Vec<usize>,
3234 events: Vec<String>,
3236 }
3237 impl Observer for Log {
3238 fn planned(&mut self, remaining: &[u64]) {
3239 self.plans.push(remaining.to_vec());
3240 }
3241 fn setting_up(&mut self, subject: usize) {
3242 self.events.push(format!("setup:{subject}"));
3243 }
3244 fn started(&mut self, subject: usize) {
3245 self.events.push(format!("start:{subject}"));
3246 }
3247 fn dropped(&mut self, subject: usize) {
3248 self.events.push(format!("drop:{subject}"));
3249 }
3250 fn finished(&mut self, subject: usize, _: Duration) {
3251 self.finished.push(subject);
3252 }
3253 }
3254
3255 #[cfg(unix)]
3258 #[test]
3259 fn setups_run_once_first_and_a_failing_one_drops_its_subject() {
3260 let sh = |script: &str| Some(["/bin/sh", "-c", script].map(String::from).to_vec());
3261 let mk = |name: &str, setup: Option<Vec<String>>| Subject {
3262 name: name.into(),
3263 cmd: vec!["true".into()],
3264 prepare: None,
3265 setup,
3266 setup_dir: None,
3267 check: None,
3268 version_cmd: None,
3269 dir: None,
3270 env: BTreeMap::new(),
3271 vars: BTreeMap::new(),
3272 when: None,
3273 runs: Runs::Auto,
3274 auto: AutoRuns {
3275 budget: Duration::from_secs(30),
3276 min: 2,
3277 max: 2,
3278 },
3279 warmup: 1,
3280 counters: false,
3281 allocations: false,
3282 ok_exit_codes: vec![0],
3283 metrics: BTreeMap::new(),
3284 };
3285 let mut log = Log::default();
3286 let res = interleaved(
3287 &[
3288 mk("ok", sh("true")),
3289 mk("bad", sh("echo no fixture >&2; exit 2")),
3290 mk("none", None),
3291 ],
3292 3,
3293 &Settings::default(),
3294 &mut log,
3295 );
3296 assert_eq!(log.events[..3], ["setup:0", "setup:1", "drop:1"]);
3297 assert!(!log.events[3..].iter().any(|e| e.starts_with("setup:")));
3298 assert!(!log.events.contains(&"start:1".to_string()));
3299 assert_eq!(res[0].as_ref().unwrap().times.len(), 2);
3300 assert_eq!(res[2].as_ref().unwrap().times.len(), 2);
3301 let msg = format!("{:#}", res[1].as_ref().unwrap_err());
3302 assert!(msg.contains("setup") && msg.contains("no fixture"), "{msg}");
3303 assert_eq!(log.finished.len(), 2 * (1 + 2));
3305 }
3306
3307 #[cfg(unix)]
3311 #[test]
3312 fn auto_runs_give_a_slow_subject_the_floor_and_a_fast_one_more() {
3313 let mk = |name: &str, secs: &str, warmup: u32| Subject {
3314 name: name.into(),
3315 cmd: vec!["sleep".into(), secs.into()],
3316 prepare: None,
3317 setup: None,
3318 setup_dir: None,
3319 check: None,
3320 dir: None,
3321 version_cmd: None,
3322 env: BTreeMap::new(),
3323 vars: BTreeMap::new(),
3324 when: None,
3325 runs: Runs::Auto,
3326 auto: AutoRuns {
3327 budget: Duration::from_millis(400),
3328 min: 2,
3329 max: 6,
3330 },
3331 warmup,
3332 counters: false,
3333 allocations: false,
3334 ok_exit_codes: vec![0],
3335 metrics: BTreeMap::new(),
3336 };
3337 let mut log = Log::default();
3338 let res = interleaved(
3340 &[mk("fast", "0.02", 1), mk("slow", "0.3", 0)],
3341 9,
3342 &Settings::default(),
3343 &mut log,
3344 );
3345 let fast = res[0].as_ref().unwrap().times.len();
3346 let slow = res[1].as_ref().unwrap().times.len();
3347 assert_eq!(slow, 2, "0.4s budget / 0.3s sample is below the floor");
3348 assert!(fast > slow && fast <= 6, "fast got {fast}");
3349 assert_eq!(log.plans[0], [1 + 2, 2]);
3351 assert_eq!(log.plans.len(), 2);
3352 assert_eq!(log.finished.len(), 1 + fast + slow);
3353 }
3354
3355 #[test]
3356 fn steady_samples_raise_no_warning() {
3357 assert!(warnings(&[10.0, 10.2, 9.9, 10.1, 10.0, 10.3]).is_empty());
3358 assert!(warnings(&[10.0, 50.0]).is_empty(), "too few to judge");
3359 }
3360
3361 #[test]
3362 fn a_spike_is_an_outlier() {
3363 let w = warnings(&[10.0, 10.2, 9.9, 10.1, 40.0, 10.0, 10.1]);
3364 assert_eq!(w.len(), 1, "{w:?}");
3365 assert!(
3366 w[0].starts_with("1 of 7 samples are slow outliers"),
3367 "{w:?}"
3368 );
3369 }
3370
3371 #[test]
3372 fn a_slow_first_sample_is_called_out() {
3373 let w = warnings(&[35.0, 10.0, 10.2, 9.9, 10.1, 10.0]);
3374 assert!(
3375 w.iter().any(|m| m.contains("first sample took 3.5x")),
3376 "{w:?}"
3377 );
3378 }
3379
3380 #[test]
3383 fn a_spike_among_identical_samples_is_still_an_outlier() {
3384 let w = warnings(&[10.0, 10.0, 10.0, 100.0, 10.0]);
3385 assert!(w.iter().any(|m| m.contains("slow outliers")), "{w:?}");
3386 assert!(
3387 warnings(&[10.0; 6]).is_empty(),
3388 "identical samples are fine"
3389 );
3390 }
3391
3392 #[test]
3395 fn a_fast_outlier_is_flagged_as_possibly_the_minimum() {
3396 let w = warnings(&[100.0, 101.0, 99.0, 102.0, 10.0, 100.0]);
3397 assert!(
3398 w.iter()
3399 .any(|m| m.contains("fast outliers") && m.contains("minimum")),
3400 "{w:?}"
3401 );
3402 }
3403
3404 #[test]
3407 fn several_spikes_over_a_flat_majority_are_caught() {
3408 let w = warnings(&[10.0, 10.0, 10.0, 10.0, 40.0, 45.0]);
3409 assert!(
3410 w.iter()
3411 .any(|m| m.starts_with("2 of 6 samples are slow outliers")),
3412 "{w:?}"
3413 );
3414 assert!(
3415 warnings(&[10.0, 10.0, 10.0, 11.0, 10.0]).is_empty(),
3416 "10% is not a spike"
3417 );
3418 }
3419}