1use crate::config::{
22 AutoRuns, CountUntil, DEFAULT_OK_EXIT_CODES, MetricSource, Runs, SELF_TOOL, Subject,
23};
24use crate::settings::Settings;
25use anyhow::{Context, Result, bail};
26use std::collections::BTreeMap;
27use std::path::Path;
28use std::process::{Command, Stdio};
29use std::sync::{Arc, Mutex};
30use std::time::Duration;
31use std::time::Instant;
32
33#[derive(Debug, Clone)]
34pub struct Plan {
35 pub cmd: Vec<String>,
36 pub warmup: u32,
37 pub runs: u32,
38 pub dir: Option<std::path::PathBuf>,
42 pub settings: Settings,
46}
47
48fn subject(bin: &str, settings: &Settings) -> Command {
67 let mut c = Command::new(bin);
68 for key in settings.scrubbed_env() {
69 c.env_remove(key);
70 }
71 c
72}
73
74#[derive(Debug, Clone, Copy)]
76struct Site<'a> {
77 dir: Option<&'a Path>,
78 env: &'a BTreeMap<String, String>,
79 settings: &'a Settings,
80}
81
82fn command(argv: &[String], site: &Site) -> Result<Command> {
88 let (bin, args) = argv.split_first().context("empty command")?;
89 let mut c = subject(bin, site.settings);
90 c.args(args).envs(site.env);
91 if let Some(d) = site.dir {
92 c.current_dir(d);
93 }
94 #[cfg(unix)]
95 if tracked::OWN_GROUPS.load(std::sync::atomic::Ordering::SeqCst) {
96 std::os::unix::process::CommandExt::process_group(&mut c, 0);
97 }
98 Ok(c)
99}
100
101fn run_tracked(c: &mut Command) -> std::io::Result<std::process::ExitStatus> {
105 let mut child = c.spawn()?;
106 tracked::started(child.id());
107 let status = child.wait();
108 tracked::finished();
109 status
110}
111
112#[cfg(unix)]
127pub fn use_own_groups() {
128 tracked::OWN_GROUPS.store(true, std::sync::atomic::Ordering::SeqCst);
129}
130
131#[cfg(unix)]
136pub fn stop_running() {
137 use std::sync::atomic::Ordering::SeqCst;
138 tracked::STOPPED.store(true, SeqCst);
139 tracked::kill_all();
140}
141
142mod tracked {
145 use std::sync::Mutex;
146 use std::sync::atomic::{AtomicBool, Ordering::SeqCst};
147
148 pub(super) static OWN_GROUPS: AtomicBool = AtomicBool::new(false);
149 pub(super) static STOPPED: AtomicBool = AtomicBool::new(false);
150
151 static GROUPS: Mutex<Groups> = Mutex::new(Groups::new());
159
160 #[derive(Debug, Default, PartialEq)]
163 pub(super) struct Groups {
164 running: i32,
166 left: Vec<i32>,
172 }
173
174 impl Groups {
175 pub(super) const fn new() -> Groups {
176 Groups {
177 running: 0,
178 left: Vec::new(),
179 }
180 }
181
182 pub(super) fn start(&mut self, pgid: i32) {
183 self.running = pgid;
184 }
185
186 pub(super) fn finish(&mut self, alive: impl Fn(i32) -> bool) {
193 self.left.retain(|g| alive(*g));
194 if self.running > 0 && alive(self.running) {
195 self.left.push(self.running);
196 }
197 self.running = 0;
198 }
199
200 pub(super) fn targets(&self) -> Vec<i32> {
202 std::iter::once(self.running)
203 .filter(|g| *g > 0)
204 .chain(self.left.iter().copied())
205 .collect()
206 }
207 }
208
209 fn groups() -> std::sync::MutexGuard<'static, Groups> {
210 GROUPS.lock().unwrap_or_else(|e| e.into_inner())
213 }
214
215 pub(super) fn started(pid: u32) {
221 if !OWN_GROUPS.load(SeqCst) {
222 return;
223 }
224 groups().start(pid as i32);
225 if STOPPED.load(SeqCst) {
226 kill(pid as i32);
227 }
228 }
229
230 pub(super) fn finished() {
233 if OWN_GROUPS.load(SeqCst) {
234 groups().finish(alive);
235 }
236 }
237
238 pub(super) fn kill_all() {
241 for g in groups().targets() {
242 kill(g);
243 }
244 }
245
246 #[cfg(unix)]
247 fn alive(pgid: i32) -> bool {
248 unsafe { libc::killpg(pgid, 0) == 0 }
250 }
251
252 #[cfg(not(unix))]
253 fn alive(_pgid: i32) -> bool {
254 false
255 }
256
257 #[cfg(unix)]
258 pub(super) fn kill(pgid: i32) {
259 if pgid > 0 {
260 unsafe {
262 libc::killpg(pgid, libc::SIGKILL);
263 }
264 }
265 }
266
267 #[cfg(not(unix))]
268 pub(super) fn kill(_pgid: i32) {}
269
270 #[cfg(test)]
271 mod tests {
272 use super::Groups;
273
274 #[test]
278 fn a_group_is_never_untracked_while_it_has_members() {
279 let mut g = Groups::new();
280 assert!(g.targets().is_empty());
281 g.start(10);
282 assert_eq!(g.targets(), [10]);
283
284 g.finish(|p| p == 10);
286 assert_eq!(g.targets(), [10]);
287 g.start(20);
288 assert_eq!(g.targets(), [20, 10]);
289
290 g.finish(|p| p == 10);
292 assert_eq!(g.targets(), [10]);
293
294 g.start(30);
296 g.finish(|_| false);
297 assert!(g.targets().is_empty());
298 assert_eq!(g, Groups::new());
299 }
300 }
301}
302
303#[derive(Debug, Clone, Copy, PartialEq)]
305pub struct Sample {
306 pub ms: f64,
308 pub exit_code: i32,
311}
312
313fn accepted(bin: &str, status: std::process::ExitStatus, ok: &[i32], via: &str) -> Result<i32> {
320 match status.code() {
321 Some(code) if ok.contains(&code) => Ok(code),
322 _ if ok == DEFAULT_OK_EXIT_CODES => {
326 bail!("benchmark subject `{bin}` exited with {status}{via}")
327 }
328 _ => bail!(
329 "benchmark subject `{bin}` exited with {status}{via}, and ok_exit_codes is {}",
330 ok.iter().map(i32::to_string).collect::<Vec<_>>().join(", ")
331 ),
332 }
333}
334
335fn time_once(cmd: &[String], site: &Site, ok: &[i32]) -> Result<Sample> {
341 let mut c = command(cmd, site)?;
342 c.stdout(Stdio::null()).stderr(Stdio::null());
343 let bin = &cmd[0];
344 let start = Instant::now();
345 let mut child = c
346 .spawn()
347 .with_context(|| format!("failed to spawn `{bin}`"))?;
348 tracked::started(child.id());
350 let status = child.wait();
351 let ms = start.elapsed().as_secs_f64() * 1000.0;
352 tracked::finished();
353 let status = status.with_context(|| format!("failed to wait for `{bin}`"))?;
354 let exit_code = accepted(bin, status, ok, "")?;
355 Ok(Sample { ms, exit_code })
356}
357
358const UNTIMED_STDERR_TAIL: usize = 4096;
362
363fn prepare_once(cmd: &[String], site: &Site) -> Result<()> {
366 required("prepare", cmd, site)
367}
368
369fn required(what: &str, cmd: &[String], site: &Site) -> Result<()> {
371 match untimed(what, cmd, site)? {
372 None => Ok(()),
373 Some(failure) => bail!("{failure}"),
374 }
375}
376
377fn check_once(cmd: &[String], site: &Site) -> Result<Option<String>> {
382 untimed("check", cmd, site)
383}
384
385fn untimed(step: &str, cmd: &[String], site: &Site) -> Result<Option<String>> {
417 let mut c = command(cmd, site)?;
418 let bin = &cmd[0];
419 let err = tempfile::tempfile()
420 .with_context(|| format!("failed to create a file for {step} `{bin}`'s stderr"))?;
421 let reader = err
422 .try_clone()
423 .with_context(|| format!("failed to create a file for {step} `{bin}`'s stderr"))?;
424 c.stdin(Stdio::null())
425 .stdout(Stdio::null())
426 .stderr(Stdio::from(err));
427 let status = run_tracked(&mut c).with_context(|| format!("failed to spawn {step} `{bin}`"))?;
428 if status.success() {
429 return Ok(None);
430 }
431 let tail = stderr_tail(&reader).unwrap_or_default();
435 let stderr = String::from_utf8_lossy(&tail);
436 Ok(Some(match stderr.lines().rfind(|l| !l.trim().is_empty()) {
437 Some(last) => format!("{step} `{bin}` exited with {status}: {}", last.trim()),
438 None => format!("{step} `{bin}` exited with {status}"),
439 }))
440}
441
442const METRIC_OUTPUT_MAX: usize = 1024;
446
447pub fn custom_metric(source: &MetricSource, s: &Subject, settings: &Settings) -> Result<f64> {
466 match source {
467 MetricSource::File(path) => {
468 let meta = std::fs::metadata(path)
469 .with_context(|| format!("could not read the size of {}", path.display()))?;
470 if !meta.is_file() {
471 bail!("{} is not a regular file", path.display());
472 }
473 Ok(meta.len() as f64)
474 }
475 MetricSource::Cmd(argv) => {
476 let site = Site {
477 dir: s.dir.as_deref(),
478 env: &s.env,
479 settings,
480 };
481 metric_cmd_once(argv, &site)
482 }
483 }
484}
485
486fn metric_cmd_once(argv: &[String], site: &Site) -> Result<f64> {
487 let bin = &argv[0];
488 let out = capture(argv, site, None, METRIC_OUTPUT_MAX, true)?;
489 if out.overflowed || out.stdout_open {
496 stop_leftovers(out.pgid);
497 }
498 if out.overflowed {
501 bail!(
502 "`{bin}` and what it started printed more than {METRIC_OUTPUT_MAX} bytes, so they were \
503 stopped; a metric command prints one number and nothing else"
504 );
505 }
506 if out.stdout_open {
509 bail!(
510 "`{bin}` exited but left a process holding its stdout open, so that was stopped; \
511 a metric command must finish its output before it exits"
512 );
513 }
514 if !out.status.success() {
515 bail!(
516 "`{bin}` exited with {}: {}",
517 out.status,
518 last_line(&out.stderr_tail)
519 );
520 }
521 let text = std::str::from_utf8(&out.stdout)
522 .map_err(|_| anyhow::anyhow!("`{bin}` printed something that is not UTF-8"))?;
523 parse_metric_value(text).with_context(|| format!("`{bin}`"))
524}
525
526pub fn parse_metric_value(text: &str) -> Result<f64> {
539 let t = text.trim_matches(|c: char| c.is_ascii_whitespace());
540 if t.is_empty() {
541 bail!("printed nothing; a metric command prints one number");
542 }
543 let bytes = t.as_bytes();
544 let digits = |i: &mut usize| {
545 let start = *i;
546 while *i < bytes.len() && bytes[*i].is_ascii_digit() {
547 *i += 1;
548 }
549 *i > start
550 };
551 let mut i = 0;
552 let mut ok = digits(&mut i);
553 if ok && i < bytes.len() && bytes[i] == b'.' {
554 i += 1;
555 ok = digits(&mut i);
556 }
557 if ok && i < bytes.len() && (bytes[i] == b'e' || bytes[i] == b'E') {
558 i += 1;
559 if i < bytes.len() && (bytes[i] == b'+' || bytes[i] == b'-') {
560 i += 1;
561 }
562 ok = digits(&mut i);
563 }
564 if !ok || i != bytes.len() {
565 bail!(
566 "printed {t:?}, not one number; a metric command prints a single non-negative \
567 number such as `1234` or `12.5`, and nothing else"
568 );
569 }
570 let v: f64 = t
571 .parse()
572 .with_context(|| format!("printed {t:?}, which is not a number"))?;
573 if !v.is_finite() {
574 bail!("printed {t:?}, which is too large to record");
575 }
576 Ok(v)
577}
578
579fn stderr_tail(f: &std::fs::File) -> std::io::Result<Vec<u8>> {
587 let len = f.metadata()?.len();
588 let start = len.saturating_sub(UNTIMED_STDERR_TAIL as u64);
589 let mut buf = vec![0u8; (len - start) as usize];
590 let mut filled = 0;
591 while filled < buf.len() {
592 let n = read_at(f, &mut buf[filled..], start + filled as u64)?;
593 if n == 0 {
594 break;
595 }
596 filled += n;
597 }
598 buf.truncate(filled);
599 Ok(buf)
600}
601
602#[cfg(unix)]
603fn read_at(f: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result<usize> {
604 std::os::unix::fs::FileExt::read_at(f, buf, offset)
605}
606
607#[cfg(windows)]
608fn read_at(f: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result<usize> {
609 std::os::windows::fs::FileExt::seek_read(f, buf, offset)
610}
611
612#[derive(Debug, Clone, Copy, PartialEq, Eq)]
614pub struct Slot {
615 pub subject: usize,
617 pub timed: bool,
620}
621
622pub fn schedule(counts: &[(u32, u32)], seed: u64) -> Vec<Slot> {
640 let mut rng = fastrand::Rng::with_seed(seed);
641 let warmups: Vec<u64> = counts.iter().map(|&(w, _)| u64::from(w)).collect();
642 let runs: Vec<u64> = counts.iter().map(|&(_, r)| u64::from(r)).collect();
643 let mut out = rounds(&warmups, false, &mut rng);
644 out.extend(rounds(&runs, true, &mut rng));
645 out
646}
647
648fn rounds(count: &[u64], timed: bool, rng: &mut fastrand::Rng) -> Vec<Slot> {
650 let total = count.iter().copied().max().unwrap_or(0);
651 let mut out = Vec::new();
652 for round in 0..total {
653 let mut due: Vec<usize> = (0..count.len())
656 .filter(|&i| (round + 1) * count[i] / total > round * count[i] / total)
657 .collect();
658 rng.shuffle(&mut due);
659 out.extend(due.into_iter().map(|subject| Slot { subject, timed }));
660 }
661 out
662}
663
664pub fn seed_for(seed: u64, bench: &str) -> u64 {
667 bench.bytes().fold(seed ^ 0xcbf2_9ce4_8422_2325, |h, b| {
669 (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)
670 })
671}
672
673pub trait Observer {
675 fn planned(&mut self, _remaining: &[u64]) {}
678 fn setting_up(&mut self, _subject: usize) {}
681 fn set_up(&mut self, _subject: usize) -> Result<()> {
688 Ok(())
689 }
690 fn before_run(&mut self, _subject: usize) -> Result<()> {
697 Ok(())
698 }
699 fn started(&mut self, _subject: usize) {}
701 fn finished(&mut self, _subject: usize, _elapsed: Duration) {}
703 fn dropped(&mut self, _subject: usize) {}
705}
706
707pub struct Quiet;
709impl Observer for Quiet {}
710
711#[derive(Debug, Clone, Default, PartialEq)]
713pub struct Samples {
714 pub times: Vec<f64>,
716 pub checks: Vec<bool>,
719 pub exit_codes: Vec<i32>,
722 pub first_failure: Option<String>,
724}
725
726impl Samples {
727 pub fn passed(&self) -> usize {
729 self.checks.iter().filter(|&&ok| ok).count()
730 }
731}
732
733pub fn interleaved(
758 subjects: &[Subject],
759 seed: u64,
760 settings: &Settings,
761 observer: &mut dyn Observer,
762) -> Vec<Result<Samples>> {
763 interleaved_with_versions(subjects, seed, settings, observer).0
764}
765
766pub type Version = Option<Result<String>>;
769
770pub fn interleaved_with_versions(
778 subjects: &[Subject],
779 seed: u64,
780 settings: &Settings,
781 observer: &mut dyn Observer,
782) -> (Vec<Result<Samples>>, Vec<Version>) {
783 let mut rng = fastrand::Rng::with_seed(seed);
784 let mut results: Vec<Result<Samples>> = subjects
785 .iter()
786 .map(|s| {
787 if s.runs == Runs::Fixed(0) {
789 bail!("runs must be at least 1");
790 }
791 Ok(Samples::default())
792 })
793 .collect();
794 let mut fastest: Vec<Option<Duration>> = vec![None; subjects.len()];
798
799 let warmups: Vec<u64> = subjects.iter().map(|s| u64::from(s.warmup)).collect();
800 let pilots: Vec<u64> = subjects
801 .iter()
802 .map(|s| u64::from(s.runs == Runs::Auto && s.warmup == 0))
803 .collect();
804 let provisional: Vec<u64> = subjects
806 .iter()
807 .zip(&warmups)
808 .map(|(s, w)| {
809 w + u64::from(match s.runs {
810 Runs::Fixed(n) => n,
811 Runs::Auto => s.auto.min,
812 })
813 })
814 .collect();
815 observer.planned(&provisional);
816
817 for (i, s) in subjects.iter().enumerate() {
818 let (Some(setup), Ok(_)) = (&s.setup, &results[i]) else {
819 continue;
820 };
821 observer.setting_up(i);
822 let site = Site {
823 dir: s.setup_dir.as_deref(),
824 env: &s.env,
825 settings,
826 };
827 if let Err(e) = observer
830 .before_run(i)
831 .and_then(|()| required("setup", setup, &site))
832 {
833 results[i] = Err(e);
834 observer.dropped(i);
835 }
836 }
837 for (i, result) in results.iter_mut().enumerate() {
838 if result.is_ok()
839 && let Err(e) = observer.set_up(i)
840 {
841 *result = Err(e);
842 observer.dropped(i);
843 }
844 }
845
846 let versions: Vec<Version> = subjects
847 .iter()
848 .zip(&results)
849 .map(|(s, r)| r.as_ref().ok().and_then(|_| subject_version(s, settings)))
850 .collect();
851
852 let mut first = rounds(&warmups, false, &mut rng);
853 first.extend(rounds(&pilots, true, &mut rng));
854 run_slots(
855 &first,
856 subjects,
857 settings,
858 &mut results,
859 &mut fastest,
860 observer,
861 );
862
863 let remaining: Vec<u64> = subjects
864 .iter()
865 .enumerate()
866 .map(|(i, s)| match (&results[i], s.runs) {
867 (Err(_), _) => 0,
868 (Ok(_), Runs::Fixed(n)) => u64::from(n),
869 (Ok(taken), Runs::Auto) => {
870 let n = auto_runs(&s.auto, fastest[i]);
871 u64::from(n).saturating_sub(taken.times.len() as u64)
872 }
873 })
874 .collect();
875 observer.planned(&remaining);
876 let second = rounds(&remaining, true, &mut rng);
877 run_slots(
878 &second,
879 subjects,
880 settings,
881 &mut results,
882 &mut fastest,
883 observer,
884 );
885 (results, versions)
886}
887
888fn auto_runs(auto: &AutoRuns, fastest: Option<Duration>) -> u32 {
891 fastest.map_or(auto.min, |d| auto.runs_for(d))
892}
893
894fn run_slots(
901 slots: &[Slot],
902 subjects: &[Subject],
903 settings: &Settings,
904 results: &mut [Result<Samples>],
905 fastest: &mut [Option<Duration>],
906 observer: &mut dyn Observer,
907) {
908 for slot in slots {
909 let Ok(samples) = &mut results[slot.subject] else {
910 continue;
911 };
912 let s = &subjects[slot.subject];
913 let site = Site {
914 dir: s.dir.as_deref(),
915 env: &s.env,
916 settings,
917 };
918 observer.started(slot.subject);
919 let vetted = if s.prepare.is_some() {
923 observer.before_run(slot.subject)
924 } else {
925 Ok(())
926 };
927 let began = Instant::now();
928 let taken = vetted
929 .and_then(|()| {
930 s.prepare
931 .as_deref()
932 .map_or(Ok(()), |p| prepare_once(p, &site))
933 })
934 .and_then(|()| observer.before_run(slot.subject))
935 .and_then(|()| time_once(&s.cmd, &site, &s.ok_exit_codes));
936 let elapsed = began.elapsed();
937 let checked = match (&taken, &s.check) {
940 (Ok(_), Some(check)) if slot.timed => observer
943 .before_run(slot.subject)
944 .and_then(|()| check_once(check, &site))
945 .map(Some),
946 _ => Ok(None),
947 };
948 match taken.and_then(|sample| checked.map(|c| (sample, c))) {
949 Ok((sample, check)) => {
950 if slot.timed {
951 samples.times.push(sample.ms);
952 samples.exit_codes.push(sample.exit_code);
953 }
954 if let Some(failure) = check {
955 samples.checks.push(failure.is_none());
956 if samples.first_failure.is_none() {
957 samples.first_failure = failure;
958 }
959 }
960 let f = &mut fastest[slot.subject];
961 *f = Some(f.map_or(elapsed, |f| f.min(elapsed)));
962 observer.finished(slot.subject, began.elapsed());
963 }
964 Err(e) => {
965 results[slot.subject] = Err(e);
966 observer.dropped(slot.subject);
967 }
968 }
969 }
970}
971
972pub fn stats(samples: &[f64]) -> BTreeMap<String, f64> {
979 let mut sorted = samples.to_vec();
980 sorted.sort_by(f64::total_cmp);
981 let n = sorted.len();
982 let mean = sorted.iter().sum::<f64>() / n as f64;
983 let stddev = if n > 1 {
985 (sorted.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64).sqrt()
986 } else {
987 0.0
988 };
989 BTreeMap::from([
990 ("wall_min_ms".to_string(), sorted[0]),
991 ("wall_p50_ms".to_string(), sorted[n / 2]),
992 ("wall_mean_ms".to_string(), mean),
993 ("wall_max_ms".to_string(), sorted[n - 1]),
994 ("wall_stddev_ms".to_string(), stddev),
995 ("wall_n".to_string(), n as f64),
996 ])
997}
998
999pub fn warnings(samples: &[f64]) -> Vec<String> {
1014 let mut out = Vec::new();
1015 let n = samples.len();
1016 if n < 5 {
1017 return out;
1018 }
1019 let median = |v: &mut Vec<f64>| {
1020 v.sort_by(f64::total_cmp);
1021 let m = v.len();
1022 if m.is_multiple_of(2) {
1023 (v[m / 2 - 1] + v[m / 2]) / 2.0
1024 } else {
1025 v[m / 2]
1026 }
1027 };
1028 let med = median(&mut samples.to_vec());
1029 let mad = median(&mut samples.iter().map(|x| (x - med).abs()).collect());
1030 let outlier = |x: f64| {
1037 if mad > 0.0 {
1038 0.6745 * (x - med).abs() / mad > 3.5
1039 } else {
1040 med > 0.0 && (x - med).abs() > 0.25 * med
1041 }
1042 };
1043 {
1044 let (fast, slow) = samples
1045 .iter()
1046 .filter(|&&x| outlier(x))
1047 .fold(
1048 (0, 0),
1049 |(f, s), &x| if x < med { (f + 1, s) } else { (f, s + 1) },
1050 );
1051 if slow > 0 {
1052 out.push(format!(
1053 "{slow} of {n} samples are slow outliers; something else was running, or the \
1054 command's work varies. Consider a quieter machine or more runs."
1055 ));
1056 }
1057 if fast > 0 {
1060 out.push(format!(
1061 "{fast} of {n} samples are fast outliers, and the reported minimum may be one of \
1062 them; check the command did the same work every time."
1063 ));
1064 }
1065 }
1066 let rest = median(&mut samples[1..].to_vec());
1067 if rest > 0.0 && samples[0] > 2.0 * rest {
1068 out.push(format!(
1069 "the first sample took {:.1}x the median of the rest; the warmup did not fill some \
1070 cache. Consider more warmup runs.",
1071 samples[0] / rest
1072 ));
1073 }
1074 out
1075}
1076
1077pub fn wall(plan: &Plan) -> Result<BTreeMap<String, f64>> {
1079 let subject = Subject {
1080 name: SELF_TOOL.to_string(),
1081 cmd: plan.cmd.clone(),
1082 prepare: None,
1083 setup: None,
1084 setup_dir: None,
1085 check: None,
1086 dir: plan.dir.clone(),
1087 version_cmd: None,
1088 env: BTreeMap::new(),
1089 vars: BTreeMap::new(),
1090 when: None,
1091 runs: Runs::Fixed(plan.runs),
1092 auto: AutoRuns {
1093 budget: crate::config::DEFAULT_BUDGET,
1094 min: crate::config::DEFAULT_MIN_RUNS,
1095 max: crate::config::DEFAULT_MAX_RUNS,
1096 },
1097 warmup: plan.warmup,
1098 counters: false,
1099 allocations: false,
1100 count_until: Default::default(),
1101 ok_exit_codes: DEFAULT_OK_EXIT_CODES.to_vec(),
1102 metrics: BTreeMap::new(),
1103 };
1104 let samples = interleaved(
1106 std::slice::from_ref(&subject),
1107 0,
1108 &plan.settings,
1109 &mut Quiet,
1110 )
1111 .pop()
1112 .expect("one result per subject")?;
1113 Ok(stats(&samples.times))
1114}
1115
1116pub fn valgrind_available() -> bool {
1122 Command::new("valgrind")
1123 .arg("--version")
1124 .stdout(Stdio::null())
1125 .stderr(Stdio::null())
1126 .status()
1127 .map(|s| s.success())
1128 .unwrap_or(false)
1129}
1130
1131const COUNTER_RUNS: u32 = 3;
1134
1135const SPREAD_WARN_PCT: f64 = 0.5;
1140
1141#[derive(Debug, Clone, Copy)]
1143pub struct Counted {
1144 pub min: u64,
1145 pub max: u64,
1146 pub runs: u32,
1147}
1148
1149impl Counted {
1150 pub fn spread_pct(&self) -> f64 {
1152 if self.min == 0 {
1153 return 0.0;
1154 }
1155 (self.max - self.min) as f64 / self.min as f64 * 100.0
1156 }
1157
1158 pub fn is_suspect(&self) -> bool {
1165 self.spread_pct() > SPREAD_WARN_PCT
1166 }
1167}
1168
1169pub fn instructions(
1181 cmd: &[String],
1182 dir: Option<&std::path::Path>,
1183 settings: &Settings,
1184) -> Result<Option<Counted>> {
1185 count(
1186 cmd,
1187 None,
1188 &Site {
1189 dir,
1190 env: &BTreeMap::new(),
1191 settings,
1192 },
1193 &DEFAULT_OK_EXIT_CODES,
1194 CountUntil::Exit,
1195 false,
1196 &|| Ok(()),
1197 )
1198 .map(|c| c.map(|(c, _)| c))
1199}
1200
1201pub fn subject_instructions(s: &Subject, settings: &Settings) -> Result<Option<Counted>> {
1205 subject_count(s, settings, false, &|| Ok(())).map(|c| c.map(|(c, _)| c))
1206}
1207
1208pub fn subject_instructions_vetted(
1211 s: &Subject,
1212 settings: &Settings,
1213 vet: &dyn Fn() -> Result<()>,
1214) -> Result<Option<Counted>> {
1215 subject_count(s, settings, false, vet).map(|c| c.map(|(c, _)| c))
1216}
1217
1218pub fn subject_profile(s: &Subject, settings: &Settings) -> Result<Option<(Counted, Profiled)>> {
1226 subject_profile_vetted(s, settings, &|| Ok(()))
1227}
1228
1229pub fn subject_profile_vetted(
1231 s: &Subject,
1232 settings: &Settings,
1233 vet: &dyn Fn() -> Result<()>,
1234) -> Result<Option<(Counted, Profiled)>> {
1235 Ok(subject_count(s, settings, true, vet)?
1236 .map(|(c, p)| (c, p.expect("a profile was asked for"))))
1237}
1238
1239pub type Profiled = Result<Vec<u8>>;
1241
1242fn subject_count(
1243 s: &Subject,
1244 settings: &Settings,
1245 profile: bool,
1246 vet: &dyn Fn() -> Result<()>,
1247) -> Result<Option<(Counted, Option<Profiled>)>> {
1248 count(
1249 &s.cmd,
1250 s.prepare.as_deref(),
1251 &Site {
1252 dir: s.dir.as_deref(),
1253 env: &s.env,
1254 settings,
1255 },
1256 &s.ok_exit_codes,
1257 s.count_until,
1258 profile,
1259 vet,
1260 )
1261}
1262
1263pub fn subject_version(s: &Subject, settings: &Settings) -> Option<Result<String>> {
1274 let argv = s.version_cmd.as_ref()?;
1275 let site = Site {
1276 dir: s.dir.as_deref(),
1277 env: &s.env,
1278 settings,
1279 };
1280 Some(version_once(argv, &site, VERSION_TIMEOUT))
1281}
1282
1283const VERSION_OUTPUT_CAP: usize = 8192;
1287
1288const VERSION_TIMEOUT: Duration = Duration::from_secs(10);
1293
1294const VERSION_OUTPUT_GRACE: Duration = Duration::from_millis(500);
1299
1300fn keep_prefix(
1310 mut r: impl std::io::Read,
1311 cap: usize,
1312 kept: &Mutex<Vec<u8>>,
1313 overflow: &std::sync::atomic::AtomicBool,
1314 tail: Option<&Mutex<Vec<u8>>>,
1315) {
1316 let mut buf = [0u8; 8192];
1317 loop {
1318 match r.read(&mut buf) {
1319 Ok(0) => return,
1320 Ok(n) => {
1321 let Ok(mut k) = kept.lock() else { return };
1322 let room = cap.saturating_sub(k.len());
1323 if n > room {
1324 overflow.store(true, std::sync::atomic::Ordering::SeqCst);
1325 }
1326 k.extend_from_slice(&buf[..n.min(room)]);
1327 if let Some(Ok(mut t)) = tail.map(Mutex::lock) {
1328 t.extend_from_slice(&buf[..n]);
1329 let excess = t.len().saturating_sub(UNTIMED_STDERR_TAIL);
1330 t.drain(..excess);
1331 }
1332 }
1333 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
1334 Err(_) => return,
1335 }
1336 }
1337}
1338
1339#[cfg(unix)]
1351mod forward_signals {
1352 use std::sync::atomic::{AtomicBool, AtomicI32, Ordering::SeqCst};
1353
1354 const SIGNALS: [libc::c_int; 3] = [libc::SIGINT, libc::SIGTERM, libc::SIGHUP];
1355
1356 pub(super) struct State {
1379 spawning: AtomicBool,
1382 pgid: AtomicI32,
1384 pending: AtomicI32,
1387 done: AtomicBool,
1390 }
1391
1392 #[derive(Debug, PartialEq, Eq)]
1394 pub(super) enum Act {
1395 Defer,
1397 Die { pgid: i32 },
1399 }
1400
1401 impl State {
1402 pub(super) const fn new() -> State {
1403 State {
1404 spawning: AtomicBool::new(false),
1405 pgid: AtomicI32::new(0),
1406 pending: AtomicI32::new(0),
1407 done: AtomicBool::new(true),
1408 }
1409 }
1410
1411 pub(super) fn begin(&self) {
1412 self.pending.store(0, SeqCst);
1413 self.pgid.store(0, SeqCst);
1414 self.done.store(false, SeqCst);
1415 self.spawning.store(true, SeqCst);
1416 }
1417
1418 pub(super) fn on_signal(&self, sig: libc::c_int) -> Act {
1420 if self.wants_to_defer() {
1421 self.defer(sig)
1422 } else {
1423 Act::Die {
1424 pgid: self.pgid.load(SeqCst),
1425 }
1426 }
1427 }
1428
1429 fn wants_to_defer(&self) -> bool {
1432 let spawning = self.spawning.load(SeqCst);
1433 spawning && self.pgid.load(SeqCst) == 0
1434 }
1435
1436 fn defer(&self, sig: libc::c_int) -> Act {
1439 self.pending.store(sig, SeqCst);
1440 if self.done.load(SeqCst) {
1441 return Act::Die { pgid: 0 };
1442 }
1443 match self.pgid.load(SeqCst) {
1444 0 => Act::Defer,
1445 pgid => Act::Die { pgid },
1446 }
1447 }
1448
1449 pub(super) fn spawned(&self, pid: Option<u32>) -> Option<(libc::c_int, i32)> {
1453 let pgid = pid.map_or(0, |p| p as i32);
1454 self.pgid.store(pgid, SeqCst);
1455 self.spawning.store(false, SeqCst);
1456 let sig = self.pending.swap(0, SeqCst);
1457 (sig != 0).then_some((sig, pgid))
1458 }
1459
1460 pub(super) fn end(&self) -> Option<libc::c_int> {
1464 self.spawning.store(false, SeqCst);
1465 self.done.store(true, SeqCst);
1466 self.pgid.store(0, SeqCst);
1467 let sig = self.pending.swap(0, SeqCst);
1468 (sig != 0).then_some(sig)
1469 }
1470 }
1471
1472 static STATE: State = State::new();
1473
1474 fn die(sig: libc::c_int, pgid: i32) {
1478 unsafe {
1480 if pgid > 0 {
1481 libc::killpg(pgid, libc::SIGKILL);
1482 }
1483 libc::signal(sig, libc::SIG_DFL);
1484 libc::raise(sig);
1485 }
1486 }
1487
1488 extern "C" fn forward(sig: libc::c_int) {
1489 if let Act::Die { pgid } = STATE.on_signal(sig) {
1490 die(sig, pgid);
1491 }
1492 }
1493
1494 pub struct Guard {
1495 previous: Vec<(libc::c_int, libc::sigaction)>,
1496 }
1497
1498 impl Guard {
1499 pub fn install() -> Guard {
1502 STATE.begin();
1503 let mut previous = Vec::new();
1504 for sig in SIGNALS {
1505 unsafe {
1509 let mut new: libc::sigaction = std::mem::zeroed();
1510 new.sa_sigaction = forward as extern "C" fn(libc::c_int) as libc::sighandler_t;
1511 libc::sigemptyset(&mut new.sa_mask);
1512 let mut old: libc::sigaction = std::mem::zeroed();
1513 if libc::sigaction(sig, &new, &mut old) == 0 {
1514 previous.push((sig, old));
1515 }
1516 }
1517 }
1518 Guard { previous }
1519 }
1520
1521 pub fn spawned(pid: Option<u32>) {
1524 if let Some((sig, pgid)) = STATE.spawned(pid) {
1525 die(sig, pgid);
1526 }
1527 }
1528 }
1529
1530 impl Drop for Guard {
1531 fn drop(&mut self) {
1532 if let Some(sig) = STATE.end() {
1535 die(sig, 0);
1536 }
1537 for (sig, old) in &self.previous {
1538 unsafe {
1540 libc::sigaction(*sig, old, std::ptr::null_mut());
1541 }
1542 }
1543 }
1544 }
1545
1546 #[cfg(test)]
1550 mod tests {
1551 use super::{Act, SeqCst, State};
1552
1553 #[test]
1554 fn a_signal_during_the_spawn_is_held_until_the_group_is_known() {
1555 let s = State::new();
1556 s.begin();
1557 assert_eq!(s.on_signal(libc::SIGTERM), Act::Defer, "no group yet");
1558 assert_eq!(s.spawned(Some(42)), Some((libc::SIGTERM, 42)));
1559 assert_eq!(s.on_signal(libc::SIGINT), Act::Die { pgid: 42 });
1560 assert_eq!(s.end(), None);
1561
1562 s.begin();
1563 assert_eq!(s.spawned(Some(7)), None, "nothing arrived");
1564 assert_eq!(s.end(), None);
1565
1566 s.begin();
1567 assert_eq!(s.on_signal(libc::SIGINT), Act::Defer);
1568 assert_eq!(
1569 s.spawned(None),
1570 Some((libc::SIGINT, 0)),
1571 "a failed spawn still stops tak"
1572 );
1573 assert_eq!(s.end(), None);
1574
1575 assert_eq!(
1576 s.on_signal(libc::SIGHUP),
1577 Act::Die { pgid: 0 },
1578 "after the step"
1579 );
1580 assert!(!s.wants_to_defer(), "and it never defers there");
1581 }
1582
1583 #[test]
1586 fn a_handler_preempted_past_the_step_still_acts() {
1587 let s = State::new();
1588
1589 s.begin();
1592 assert!(s.wants_to_defer());
1593 assert_eq!(s.spawned(Some(42)), None);
1594 assert_eq!(s.end(), None);
1595 assert_eq!(s.defer(libc::SIGTERM), Act::Die { pgid: 0 });
1596
1597 s.begin();
1600 assert!(s.wants_to_defer());
1601 assert_eq!(s.spawned(Some(42)), None);
1602 assert_eq!(s.defer(libc::SIGINT), Act::Die { pgid: 42 });
1603 assert_eq!(s.end(), Some(libc::SIGINT));
1604
1605 s.begin();
1608 assert_eq!(s.spawned(Some(42)), None);
1609 s.pending.store(libc::SIGHUP, SeqCst);
1610 assert_eq!(s.end(), Some(libc::SIGHUP), "acted on at teardown");
1611 }
1612 }
1613}
1614
1615fn stop_group(child: &mut std::process::Child) {
1626 #[cfg(unix)]
1627 {
1628 let pgid = child.id() as libc::pid_t;
1631 if unsafe { libc::killpg(pgid, libc::SIGKILL) } != 0 {
1632 let _ = child.kill();
1633 }
1634 }
1635 #[cfg(not(unix))]
1636 let _ = child.kill();
1637 let _ = child.wait();
1638}
1639
1640fn version_once(argv: &[String], site: &Site, timeout: Duration) -> Result<String> {
1641 let bin = argv
1642 .first()
1643 .map(String::as_str)
1644 .unwrap_or("(empty command)");
1645 let Captured {
1646 status,
1647 stdout,
1648 stderr,
1649 stderr_tail,
1650 ..
1651 } = capture(argv, site, Some(timeout), VERSION_OUTPUT_CAP, false)?;
1652
1653 if !status.success() {
1656 bail!("`{bin}` exited with {status}: {}", last_line(&stderr_tail));
1657 }
1658 let first = |bytes: &[u8]| {
1659 String::from_utf8_lossy(bytes)
1660 .lines()
1661 .map(str::trim)
1662 .find(|l| !l.is_empty())
1663 .map(str::to_string)
1664 };
1665 first(&stdout)
1666 .or_else(|| first(&stderr))
1667 .with_context(|| format!("`{bin}` printed nothing"))
1668}
1669
1670fn last_line(bytes: &[u8]) -> String {
1672 String::from_utf8_lossy(bytes)
1673 .lines()
1674 .map(str::trim)
1675 .rfind(|l| !l.is_empty())
1676 .unwrap_or("(no output)")
1677 .to_string()
1678}
1679
1680struct Captured {
1682 status: std::process::ExitStatus,
1683 stdout: Vec<u8>,
1685 stderr: Vec<u8>,
1687 stderr_tail: Vec<u8>,
1689 overflowed: bool,
1692 stdout_open: bool,
1695 pgid: u32,
1698}
1699
1700fn stop_leftovers(pgid: u32) {
1709 #[cfg(unix)]
1710 unsafe {
1712 libc::killpg(pgid as libc::pid_t, libc::SIGKILL);
1713 }
1714 #[cfg(not(unix))]
1715 let _ = pgid;
1716}
1717
1718fn capture(
1732 argv: &[String],
1733 site: &Site,
1734 timeout: Option<Duration>,
1735 stdout_cap: usize,
1736 stop_past_cap: bool,
1737) -> Result<Captured> {
1738 use std::sync::atomic::{AtomicBool, Ordering::SeqCst};
1739 let bin = argv
1740 .first()
1741 .map(String::as_str)
1742 .unwrap_or("(empty command)");
1743 let mut cmd = command(argv, site)?;
1744 cmd.stdin(Stdio::null())
1745 .stdout(Stdio::piped())
1746 .stderr(Stdio::piped());
1747 #[cfg(unix)]
1750 std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
1751 #[cfg(unix)]
1754 let _forward = forward_signals::Guard::install();
1755 let spawned = cmd.spawn();
1756 #[cfg(unix)]
1758 forward_signals::Guard::spawned(spawned.as_ref().ok().map(std::process::Child::id));
1759 let mut child = spawned.with_context(|| format!("failed to spawn `{bin}`"))?;
1760 tracked::started(child.id());
1765 struct Finished;
1766 impl Drop for Finished {
1767 fn drop(&mut self) {
1768 tracked::finished();
1769 }
1770 }
1771 let _finished = Finished;
1772
1773 let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
1778 let overflow = Arc::new(AtomicBool::new(false));
1779 let ignored = Arc::new(AtomicBool::new(false));
1781 let stdout_done = Arc::new(AtomicBool::new(false));
1782 let unused = Arc::new(AtomicBool::new(false));
1783 let spawn_reader = |r: Option<Box<dyn std::io::Read + Send>>,
1784 cap: usize,
1785 flag: &Arc<AtomicBool>,
1786 done: &Arc<AtomicBool>,
1787 tail: Option<&Arc<Mutex<Vec<u8>>>>| {
1788 let kept = Arc::new(Mutex::new(Vec::new()));
1789 if let Some(r) = r {
1790 let (kept, tx, flag, done) = (
1791 Arc::clone(&kept),
1792 done_tx.clone(),
1793 Arc::clone(flag),
1794 Arc::clone(done),
1795 );
1796 let tail = tail.map(Arc::clone);
1797 std::thread::spawn(move || {
1798 keep_prefix(r, cap, &kept, &flag, tail.as_deref());
1799 done.store(true, SeqCst);
1800 let _ = tx.send(());
1801 });
1802 } else {
1803 done.store(true, SeqCst);
1804 let _ = done_tx.send(());
1805 }
1806 kept
1807 };
1808 let stdout = spawn_reader(
1809 child.stdout.take().map(|o| Box::new(o) as _),
1810 stdout_cap,
1811 &overflow,
1812 &stdout_done,
1813 None,
1814 );
1815 let stderr_tail = Arc::new(Mutex::new(Vec::new()));
1816 let stderr = spawn_reader(
1817 child.stderr.take().map(|e| Box::new(e) as _),
1818 VERSION_OUTPUT_CAP,
1819 &ignored,
1820 &unused,
1821 Some(&stderr_tail),
1822 );
1823
1824 let deadline = timeout.map(|t| Instant::now() + t);
1825 let status = loop {
1826 if stop_past_cap && overflow.load(SeqCst) {
1827 stop_group(&mut child);
1828 break child
1830 .wait()
1831 .with_context(|| format!("failed to wait for `{bin}`"))?;
1832 }
1833 match child.try_wait() {
1834 Ok(Some(status)) => break status,
1835 Ok(None) if deadline.is_none_or(|d| Instant::now() < d) => {
1836 std::thread::sleep(Duration::from_millis(5));
1837 }
1838 Ok(None) => {
1839 stop_group(&mut child);
1840 bail!(
1841 "`{bin}` did not finish within {}, so it was stopped",
1842 crate::progress::fmt(timeout.unwrap_or_default())
1843 );
1844 }
1845 Err(e) => {
1846 stop_group(&mut child);
1847 return Err(e).with_context(|| format!("failed to wait for `{bin}`"));
1848 }
1849 }
1850 };
1851 let grace = Instant::now() + VERSION_OUTPUT_GRACE;
1852 for _ in 0..2 {
1853 let left = grace.saturating_duration_since(Instant::now());
1854 if done_rx.recv_timeout(left).is_err() {
1855 break;
1856 }
1857 }
1858 let take = |kept: &Mutex<Vec<u8>>| kept.lock().map(|k| k.clone()).unwrap_or_default();
1859 Ok(Captured {
1860 status,
1861 stdout: take(&stdout),
1862 stderr: take(&stderr),
1863 stderr_tail: take(&stderr_tail),
1864 overflowed: overflow.load(SeqCst),
1865 stdout_open: !stdout_done.load(SeqCst),
1866 pgid: child.id(),
1867 })
1868}
1869
1870const VALGRIND_LOG_CAP: u64 = 1 << 20;
1874
1875#[cfg(unix)]
1908fn under_valgrind(
1909 tool: &[&str],
1910 cmd: &[String],
1911 site: &Site,
1912) -> Result<(std::process::ExitStatus, String, u32)> {
1913 use std::io::{Read, Seek};
1914 use std::os::fd::AsRawFd;
1915 use std::os::unix::process::CommandExt;
1916 let mut log = tempfile::tempfile().context("failed to create a file for valgrind's log")?;
1917 let fd = log.as_raw_fd();
1918 let mut argv: Vec<String> = std::iter::once("valgrind")
1919 .chain(tool.iter().copied())
1920 .map(String::from)
1921 .collect();
1922 argv.push(format!("--log-fd={fd}"));
1923 argv.extend_from_slice(cmd);
1924 let mut c = command(&argv, site)?;
1925 c.stdin(Stdio::null())
1926 .stdout(Stdio::null())
1927 .stderr(Stdio::null());
1928 unsafe {
1931 c.pre_exec(move || {
1932 if libc::fcntl(fd, libc::F_SETFD, 0) == -1 {
1933 return Err(std::io::Error::last_os_error());
1934 }
1935 Ok(())
1936 });
1937 }
1938 let mut child = c.spawn().context("failed to run valgrind")?;
1943 let pid = child.id();
1944 tracked::started(pid);
1945 let status = child.wait();
1946 tracked::finished();
1947 let status = status.context("failed to run valgrind")?;
1948 let mut raw = Vec::new();
1952 log.rewind().context("failed to read valgrind's log")?;
1953 log.take(VALGRIND_LOG_CAP)
1954 .read_to_end(&mut raw)
1955 .context("failed to read valgrind's log")?;
1956 let prefix = format!("=={pid}==");
1957 let own: String = String::from_utf8_lossy(&raw)
1958 .lines()
1959 .filter(|l| l.starts_with(&prefix))
1960 .flat_map(|l| [l, "\n"])
1961 .collect();
1962 Ok((status, own, pid))
1963}
1964
1965#[cfg(not(unix))]
1968fn under_valgrind(
1969 _tool: &[&str],
1970 _cmd: &[String],
1971 _site: &Site,
1972) -> Result<(std::process::ExitStatus, String, u32)> {
1973 bail!("valgrind runs only on Unix")
1974}
1975
1976fn last_log_line(log: &str) -> &str {
1980 log.lines()
1981 .map(|l| valgrind_line(l).unwrap_or(l).trim())
1982 .rfind(|l| !l.is_empty())
1983 .unwrap_or("(valgrind wrote no log; it may not have been able to start the command)")
1984}
1985
1986fn count(
2002 cmd: &[String],
2003 prepare: Option<&[String]>,
2004 site: &Site,
2005 ok: &[i32],
2006 until: CountUntil,
2007 profile: bool,
2008 vet: &dyn Fn() -> Result<()>,
2009) -> Result<Option<(Counted, Option<Profiled>)>> {
2010 if !valgrind_available() {
2011 return Ok(None);
2012 }
2013 let exec = until == CountUntil::Exec;
2014
2015 let (scratch, unkept) = match (profile || exec).then(tempfile::tempdir) {
2020 Some(Ok(d)) => (Some(d), None),
2021 Some(Err(e)) if exec => {
2022 return Err(anyhow::Error::new(e)
2023 .context("could not create a directory for callgrind's counts"));
2024 }
2025 Some(Err(e)) => (
2026 None,
2027 Some(
2028 anyhow::Error::new(e)
2029 .context("could not create a directory for cachegrind profiles"),
2030 ),
2031 ),
2032 None => (None, None),
2033 };
2034 let mut samples: Vec<u64> = Vec::with_capacity(COUNTER_RUNS as usize);
2035 for run in 0..COUNTER_RUNS {
2036 if let Some(p) = prepare {
2039 vet()?;
2040 prepare_once(p, site)?;
2041 }
2042 vet()?;
2043 let out_file = match &scratch {
2044 Some(d) => d
2048 .path()
2049 .join(format!("run-{run}"))
2050 .to_string_lossy()
2051 .replace('%', "%%"),
2052 None => "/dev/null".to_string(),
2053 };
2054 let bin = cmd.first().map(String::as_str).unwrap_or("(empty command)");
2055 if exec {
2056 let out_arg = format!("--callgrind-out-file={out_file}.%p");
2059 let (status, log, pid) = under_valgrind(
2060 &["--tool=callgrind", "--dump-before=*execve*", &out_arg],
2061 cmd,
2062 site,
2063 )?;
2064 accepted(bin, status, ok, " under valgrind")?;
2065 let dir = scratch
2066 .as_ref()
2067 .expect("an exec count has a scratch directory");
2068 samples.push(callgrind_total(
2069 dir.path(),
2070 &format!("run-{run}"),
2071 pid,
2072 &log,
2073 )?);
2074 continue;
2075 }
2076 let out_arg = format!("--cachegrind-out-file={out_file}");
2077 let (status, log, _) = under_valgrind(
2078 &[
2079 "--tool=cachegrind",
2080 "--cache-sim=no",
2081 "--branch-sim=no",
2082 &out_arg,
2083 ],
2084 cmd,
2085 site,
2086 )?;
2087
2088 accepted(bin, status, ok, " under valgrind")?;
2090 match parse_irefs(&log) {
2091 Some(0) => {
2099 let unwritable =
2100 valgrind_lines(&log).any(|l| l.contains("can't open output data file"));
2101 if unwritable {
2102 bail!(
2103 "cachegrind could not write its profile to {out_file}, and counts nothing when that happens"
2104 );
2105 }
2106 bail!("cachegrind counted no instructions");
2107 }
2108 Some(n) => samples.push(n),
2109 None => bail!(
2113 "valgrind ran but emitted no `I refs` summary: {}",
2114 last_log_line(&log)
2115 ),
2116 }
2117 }
2118
2119 let counted = Counted {
2120 min: *samples.iter().min().expect("COUNTER_RUNS > 0"),
2121 max: *samples.iter().max().expect("COUNTER_RUNS > 0"),
2122 runs: COUNTER_RUNS,
2123 };
2124 let best = samples
2128 .iter()
2129 .position(|n| *n == counted.min)
2130 .expect("the minimum is one of the samples");
2131 let kept = match (scratch, unkept) {
2132 _ if exec => profile.then(|| {
2133 Err(anyhow::anyhow!(
2134 "no profile is kept for count_until = \"exec\": the count comes from callgrind, whose profile tak profile does not read"
2135 ))
2136 }),
2137 (Some(d), _) => {
2138 let path = d.path().join(format!("run-{best}"));
2139 Some(
2140 std::fs::read(&path)
2141 .with_context(|| format!("cachegrind wrote no profile to {}", path.display()))
2142 .and_then(|raw| {
2143 if raw.is_empty() {
2144 bail!("cachegrind wrote an empty profile to {}", path.display());
2145 }
2146 Ok(raw)
2147 }),
2148 )
2149 }
2150 (None, Some(e)) => Some(Err(e)),
2151 (None, None) => None,
2152 };
2153 Ok(Some((counted, kept)))
2154}
2155
2156fn callgrind_total(dir: &Path, stem: &str, pid: u32, log: &str) -> Result<u64> {
2172 let base = format!("{stem}.{pid}");
2173 let mut total: u64 = 0;
2174 let entries = std::fs::read_dir(dir)
2175 .with_context(|| format!("could not read callgrind's counts in {}", dir.display()))?;
2176 for entry in entries {
2177 let entry = entry
2178 .with_context(|| format!("could not read callgrind's counts in {}", dir.display()))?;
2179 let name = entry.file_name();
2180 let name = name.to_string_lossy();
2181 let ours = name == base
2182 || name
2183 .strip_prefix(&base)
2184 .and_then(|r| r.strip_prefix('.'))
2185 .is_some_and(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()));
2186 if !ours {
2187 continue;
2188 }
2189 let path = entry.path();
2190 let text = std::fs::read_to_string(&path)
2191 .with_context(|| format!("could not read callgrind's counts in {}", path.display()))?;
2192 total += callgrind_part(&text)
2193 .with_context(|| format!("callgrind wrote no total to {}", path.display()))?;
2194 }
2195 if total == 0 {
2196 bail!(
2197 "callgrind counted no instructions before the process exited or exec'd; \
2198 count_until = \"exec\" needs the exec to go through a function named execve, \
2199 as the C library's does: {}",
2200 last_log_line(log)
2201 );
2202 }
2203 Ok(total)
2204}
2205
2206fn callgrind_part(text: &str) -> Option<u64> {
2209 if text.trim().is_empty() {
2210 return Some(0);
2211 }
2212 let number = |key: &str| {
2213 text.lines()
2214 .find_map(|l| l.strip_prefix(key))
2215 .and_then(|rest| rest.split_whitespace().next())
2216 .and_then(|n| n.parse::<u64>().ok())
2217 };
2218 number("totals:").or_else(|| number("summary:"))
2219}
2220
2221fn parse_irefs(log: &str) -> Option<u64> {
2228 let line = valgrind_lines(log)
2229 .filter(|l| l.contains("I refs:"))
2230 .last()?;
2231 let digits: String = line
2232 .rsplit(':')
2233 .next()?
2234 .chars()
2235 .filter(|c| c.is_ascii_digit())
2236 .collect();
2237 digits.parse().ok()
2238}
2239
2240#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2242pub struct Heap {
2243 pub blocks: u64,
2245 pub bytes: u64,
2247 pub peak_bytes: u64,
2249}
2250
2251impl Heap {
2252 pub fn metrics(&self) -> [(&'static str, u64); 3] {
2255 [
2256 ("alloc_blocks", self.blocks),
2257 ("alloc_bytes", self.bytes),
2258 ("alloc_peak_bytes", self.peak_bytes),
2259 ]
2260 }
2261}
2262
2263#[derive(Debug, Clone, Copy)]
2266pub struct Allocated {
2267 pub min: Heap,
2268 pub max: Heap,
2269 pub runs: u32,
2270}
2271
2272fn spread(lo: u64, hi: u64) -> f64 {
2277 match (lo, hi) {
2278 (0, 0) => 0.0,
2279 (0, _) => f64::INFINITY,
2280 (lo, hi) => (hi - lo) as f64 / lo as f64 * 100.0,
2281 }
2282}
2283
2284impl Allocated {
2285 pub fn totals_spread_pct(&self) -> f64 {
2287 spread(self.min.blocks, self.max.blocks).max(spread(self.min.bytes, self.max.bytes))
2288 }
2289
2290 pub fn peak_spread_pct(&self) -> f64 {
2292 spread(self.min.peak_bytes, self.max.peak_bytes)
2293 }
2294
2295 pub fn is_suspect(&self) -> bool {
2300 self.totals_spread_pct() > SPREAD_WARN_PCT
2301 }
2302
2303 pub fn peak_is_unsteady(&self) -> bool {
2308 self.peak_spread_pct() > SPREAD_WARN_PCT
2309 }
2310
2311 pub fn saw_nothing(&self) -> bool {
2316 self.max.blocks == 0
2317 }
2318}
2319
2320pub fn subject_allocations(s: &Subject, settings: &Settings) -> Result<Option<Allocated>> {
2334 subject_allocations_vetted(s, settings, &|| Ok(()))
2335}
2336
2337pub fn subject_allocations_vetted(
2341 s: &Subject,
2342 settings: &Settings,
2343 vet: &dyn Fn() -> Result<()>,
2344) -> Result<Option<Allocated>> {
2345 let site = Site {
2346 dir: s.dir.as_deref(),
2347 env: &s.env,
2348 settings,
2349 };
2350 allocations(&s.cmd, s.prepare.as_deref(), &site, &s.ok_exit_codes, vet)
2351}
2352
2353fn allocations(
2356 cmd: &[String],
2357 prepare: Option<&[String]>,
2358 site: &Site,
2359 ok: &[i32],
2360 vet: &dyn Fn() -> Result<()>,
2361) -> Result<Option<Allocated>> {
2362 if !valgrind_available() {
2363 return Ok(None);
2364 }
2365 let bin = cmd.first().map(String::as_str).unwrap_or("(empty command)");
2366 let mut runs: Vec<Heap> = Vec::with_capacity(COUNTER_RUNS as usize);
2367 for _ in 0..COUNTER_RUNS {
2368 if let Some(p) = prepare {
2372 vet()?;
2373 prepare_once(p, site)?;
2374 }
2375 vet()?;
2376 let (status, log, _) =
2380 under_valgrind(&["--tool=dhat", "--dhat-out-file=/dev/null"], cmd, site)?;
2381 accepted(bin, status, ok, " under valgrind")?;
2382 match parse_dhat(&log) {
2383 Some(h) => runs.push(h),
2384 None => bail!(
2385 "valgrind ran but emitted no DHAT summary: {}",
2386 last_log_line(&log)
2387 ),
2388 }
2389 }
2390 let fold = |f: fn(u64, u64) -> u64| {
2391 runs.iter()
2392 .copied()
2393 .reduce(|a, b| Heap {
2394 blocks: f(a.blocks, b.blocks),
2395 bytes: f(a.bytes, b.bytes),
2396 peak_bytes: f(a.peak_bytes, b.peak_bytes),
2397 })
2398 .expect("COUNTER_RUNS > 0")
2399 };
2400 Ok(Some(Allocated {
2401 min: fold(u64::min),
2402 max: fold(u64::max),
2403 runs: COUNTER_RUNS,
2404 }))
2405}
2406
2407fn parse_dhat(log: &str) -> Option<Heap> {
2421 let field = |name: &str| {
2422 let rest = valgrind_lines(log).find_map(|l| l.trim_start().strip_prefix(name))?;
2423 let (bytes, rest) = rest.trim().split_once(" bytes in ")?;
2424 let blocks = rest.split_whitespace().next()?;
2425 Some((dhat_number(bytes)?, dhat_number(blocks)?))
2426 };
2427 let (bytes, blocks) = field("Total:")?;
2428 let (peak_bytes, _) = field("At t-gmax:")?;
2429 Some(Heap {
2430 blocks,
2431 bytes,
2432 peak_bytes,
2433 })
2434}
2435
2436fn valgrind_line(line: &str) -> Option<&str> {
2438 let rest = line.strip_prefix("==")?;
2439 let (pid, rest) = rest.split_once("==")?;
2440 (!pid.is_empty() && pid.chars().all(|c| c.is_ascii_digit())).then_some(rest)
2441}
2442
2443fn dhat_number(s: &str) -> Option<u64> {
2445 let digits: String = s.trim().chars().filter(|&c| c != ',').collect();
2446 if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
2447 return None;
2448 }
2449 digits.parse().ok()
2450}
2451
2452fn valgrind_lines(log: &str) -> impl Iterator<Item = &str> {
2454 log.lines().filter_map(valgrind_line)
2455}
2456
2457#[cfg(test)]
2458mod tests {
2459 use super::*;
2460
2461 #[test]
2465 fn a_callgrind_total_sums_the_subjects_parts_alone() {
2466 let d = tempfile::tempdir().unwrap();
2467 let write = |name: &str, text: &str| std::fs::write(d.path().join(name), text).unwrap();
2468 write("run-0.41", "");
2469 write(
2470 "run-0.41.1",
2471 "version: 1\nevents: Ir\npart: 1\nsummary: 1000\ntotals: 1000\n",
2472 );
2473 write("run-0.41.2", "part: 2\ntotals: 20\n");
2474 write("run-0.410", "totals: 5\n");
2475 write("run-0.42.1", "totals: 300\n");
2476 write("run-1.41.1", "totals: 7\n");
2477 assert_eq!(callgrind_total(d.path(), "run-0", 41, "").unwrap(), 1020);
2478 assert_eq!(callgrind_total(d.path(), "run-0", 42, "").unwrap(), 300);
2479 assert_eq!(callgrind_part("summary: 9\n"), Some(9), "older callgrind");
2480 assert_eq!(callgrind_part("events: Ir\n"), None);
2481 }
2482
2483 #[test]
2486 fn a_callgrind_run_that_dumped_nothing_is_not_a_count() {
2487 let d = tempfile::tempdir().unwrap();
2488 std::fs::write(d.path().join("run-0.41"), "").unwrap();
2489 let err = callgrind_total(d.path(), "run-0", 41, "").unwrap_err();
2490 assert!(format!("{err:#}").contains("execve"), "{err:#}");
2491 }
2492
2493 const DHAT_3_22: &str = "\
2496==9== DHAT, a dynamic heap analysis tool
2497==9== Copyright (C) 2010-2018, and GNU GPL'd, by Mozilla Foundation
2498==9== Using Valgrind-3.22.0 and LibVEX; rerun with -h for copyright info
2499==9== Command: git --version
2500==9==
2501git version 2.43.0
2502==9==
2503==9== Total: 7,119 bytes in 31 blocks
2504==9== At t-gmax: 6,847 bytes in 25 blocks
2505==9== At t-end: 2,379 bytes in 15 blocks
2506==9== Reads: 1,067 bytes
2507==9== Writes: 1,546 bytes
2508==9==
2509==9== To view the resulting profile, open
2510==9== file:///usr/libexec/valgrind/dh_view.html
2511==9== in a web browser, click on \"Load...\", and then select the file
2512==9== /dev/null
2513==9== The text at the bottom explains the abbreviations used in the output.
2514";
2515
2516 #[test]
2517 fn parses_a_dhat_summary() {
2518 assert_eq!(
2519 parse_dhat(DHAT_3_22),
2520 Some(Heap {
2521 blocks: 31,
2522 bytes: 7_119,
2523 peak_bytes: 6_847,
2524 })
2525 );
2526 }
2527
2528 #[test]
2531 fn parses_counts_past_a_million() {
2532 let s = "==21== Total: 2,626,313 bytes in 2,833 blocks\n\
2533 ==21== At t-gmax: 1,185,686 bytes in 1,661 blocks\n";
2534 assert_eq!(
2535 parse_dhat(s),
2536 Some(Heap {
2537 blocks: 2_833,
2538 bytes: 2_626_313,
2539 peak_bytes: 1_185_686,
2540 })
2541 );
2542 }
2543
2544 #[test]
2547 fn only_valgrinds_own_lines_are_read() {
2548 let s = "Total: 5 bytes in 1 blocks\n\
2549 ==12== \n\
2550 ==12== Total: 8,748 bytes in 17 blocks\n\
2551 ==12== At t-gmax: 8,748 bytes in 17 blocks\n";
2552 assert_eq!(parse_dhat(s).unwrap().blocks, 17);
2553 assert_eq!(
2554 parse_dhat("Total: 5 bytes in 1 blocks\nAt t-gmax: 5 bytes in 1 blocks\n"),
2555 None
2556 );
2557 assert_eq!(valgrind_line("==x== Total:"), None);
2558 assert_eq!(valgrind_line("==== Total:"), None);
2559 }
2560
2561 #[test]
2562 fn a_missing_or_truncated_dhat_summary_is_none() {
2563 assert_eq!(parse_dhat(""), None);
2564 assert_eq!(parse_dhat("==3== Total: 1 bytes in 1 blocks\n"), None);
2566 assert_eq!(
2567 parse_dhat(
2568 "==3== Total: lots bytes in 1 blocks\n==3== At t-gmax: 1 bytes in 1 blocks\n"
2569 ),
2570 None
2571 );
2572 }
2573
2574 #[test]
2577 fn totals_and_peak_spread_are_judged_apart() {
2578 let h = |blocks, bytes, peak_bytes| Heap {
2579 blocks,
2580 bytes,
2581 peak_bytes,
2582 };
2583 let a = |min, max| Allocated { min, max, runs: 3 };
2584 let steady = a(h(10, 1000, 500), h(10, 1000, 500));
2585 assert_eq!(steady.totals_spread_pct(), 0.0);
2586 assert!(!steady.is_suspect() && !steady.peak_is_unsteady());
2587
2588 let threaded = a(h(10, 1000, 500), h(10, 1000, 510));
2589 assert!((threaded.peak_spread_pct() - 2.0).abs() < 1e-9);
2590 assert!(threaded.peak_is_unsteady() && !threaded.is_suspect());
2591
2592 let first_run = a(h(496, 2_077_237, 1_790_738), h(1140, 2_227_102, 1_888_914));
2594 assert!(first_run.is_suspect());
2595 assert!((first_run.totals_spread_pct() - 129.84).abs() < 0.01);
2596
2597 assert!(a(h(0, 0, 0), h(1, 8, 8)).totals_spread_pct().is_infinite());
2599 assert!(a(h(0, 0, 0), h(0, 0, 0)).saw_nothing());
2600 assert!(!steady.saw_nothing());
2601 }
2602
2603 #[test]
2606 fn a_count_printed_by_the_subject_is_not_the_count() {
2607 let s = "I refs: 5\n==7== error: can't open output data file\n==7== I refs: 1,234\nI refs: 9\n";
2608 assert_eq!(parse_irefs(s), Some(1_234));
2609 assert_eq!(parse_irefs("I refs: 5\n"), None);
2610 assert_eq!(
2611 valgrind_lines("==x== no\n== 1== no\n==12== yes\n").collect::<Vec<_>>(),
2612 [" yes"]
2613 );
2614 }
2615
2616 #[test]
2617 fn parses_cachegrind_summary() {
2618 let s = "==12== I refs: 48,349,132\n";
2619 assert_eq!(parse_irefs(s), Some(48_349_132));
2620 }
2621
2622 #[test]
2623 fn missing_summary_is_none_not_panic() {
2624 assert_eq!(parse_irefs("valgrind: command not found"), None);
2625 }
2626
2627 fn removals(settings: &Settings) -> Vec<String> {
2629 subject("true", settings)
2630 .get_envs()
2631 .filter(|(_, v)| v.is_none())
2632 .map(|(k, _)| k.to_string_lossy().into_owned())
2633 .collect()
2634 }
2635
2636 #[test]
2639 fn subject_commands_remove_the_default_denied_variables() {
2640 let removed = removals(&Settings::default());
2641 for key in Settings::default().scrubbed_env() {
2642 assert!(removed.contains(&key.to_string()), "{key} not removed");
2643 }
2644 }
2645
2646 #[test]
2649 fn the_removal_follows_the_settings() {
2650 let removed = removals(&Settings {
2651 env_deny: vec!["CUSTOM_SECRET".into()],
2652 env_allow: Vec::new(),
2653 ..Settings::default()
2654 });
2655 assert!(removed.contains(&"CUSTOM_SECRET".to_string()));
2656 assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
2657 }
2658
2659 #[test]
2662 fn an_allowed_variable_survives() {
2663 let removed = removals(&Settings {
2664 env_deny: vec!["GITHUB_TOKEN".into(), "GH_TOKEN".into()],
2665 env_allow: vec!["GITHUB_TOKEN".into()],
2666 ..Settings::default()
2667 });
2668 assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
2669 assert!(removed.contains(&"GH_TOKEN".to_string()));
2670 }
2671
2672 #[test]
2673 fn zero_runs_is_rejected_not_a_panic() {
2674 let plan = Plan {
2675 cmd: vec!["true".into()],
2676 warmup: 0,
2677 runs: 0,
2678 dir: None,
2679 settings: Settings::default(),
2680 };
2681 assert!(wall(&plan).is_err());
2682 }
2683
2684 #[test]
2685 fn a_failed_subject_is_not_recorded_as_a_fast_run() {
2686 #[cfg(unix)]
2687 let cmd = vec!["/bin/sh".into(), "-c".into(), "exit 42".into()];
2688 #[cfg(windows)]
2689 let cmd = vec!["cmd".into(), "/C".into(), "exit /B 42".into()];
2690
2691 let err = wall(&Plan {
2692 cmd,
2693 warmup: 0,
2694 runs: 1,
2695 dir: None,
2696 settings: Settings::default(),
2697 })
2698 .unwrap_err();
2699
2700 assert!(format!("{err:#}").contains("exited with"), "{err:#}");
2701 }
2702
2703 #[test]
2704 fn wall_reports_min_le_p50_le_max() {
2705 let plan = Plan {
2706 cmd: vec!["true".into()],
2707 warmup: 1,
2708 runs: 5,
2709 dir: None,
2710 settings: Settings::default(),
2711 };
2712 let m = wall(&plan).unwrap();
2713 assert!(m["wall_min_ms"] <= m["wall_p50_ms"]);
2714 assert!(m["wall_p50_ms"] <= m["wall_max_ms"]);
2715 assert_eq!(m["wall_n"], 5.0);
2716 }
2717
2718 #[test]
2720 fn the_schedule_gives_each_subject_its_counts() {
2721 let counts = [(2, 10), (1, 5), (0, 3)];
2722 let order = schedule(&counts, 7);
2723 for (i, &(warmup, runs)) in counts.iter().enumerate() {
2724 let of = |timed| {
2725 order
2726 .iter()
2727 .filter(|s| s.subject == i && s.timed == timed)
2728 .count()
2729 };
2730 assert_eq!(of(false), warmup as usize, "subject {i} warmups");
2731 assert_eq!(of(true), runs as usize, "subject {i} runs");
2732 }
2733 let first_timed = order.iter().position(|s| s.timed).unwrap();
2734 assert!(order[first_timed..].iter().all(|s| s.timed));
2735 }
2736
2737 #[test]
2738 fn the_same_seed_gives_the_same_order() {
2739 let counts = [(1, 8), (1, 8), (1, 8)];
2740 assert_eq!(schedule(&counts, 42), schedule(&counts, 42));
2741 assert_ne!(schedule(&counts, 42), schedule(&counts, 43));
2742 }
2743
2744 #[test]
2747 fn each_round_runs_every_subject_once_in_a_varying_order() {
2748 let order = schedule(&[(0, 20), (0, 20), (0, 20)], 1);
2749 let rounds: Vec<Vec<usize>> = order
2750 .chunks(3)
2751 .map(|r| r.iter().map(|s| s.subject).collect())
2752 .collect();
2753 assert_eq!(rounds.len(), 20);
2754 for r in &rounds {
2755 let mut sorted = r.clone();
2756 sorted.sort();
2757 assert_eq!(sorted, [0, 1, 2], "round {r:?}");
2758 }
2759 assert!(rounds.iter().any(|r| r != &rounds[0]), "never shuffled");
2760 }
2761
2762 #[test]
2765 fn a_subject_with_fewer_runs_is_spread_across_the_run() {
2766 let order = schedule(&[(0, 10), (0, 5)], 3);
2767 let fewer: Vec<usize> = order
2768 .iter()
2769 .enumerate()
2770 .filter(|(_, s)| s.subject == 1)
2771 .map(|(i, _)| i)
2772 .collect();
2773 assert_eq!(fewer.len(), 5);
2774 assert!(
2775 *fewer.last().unwrap() >= order.len() - 3,
2776 "last sample of the smaller subject is near the end: {fewer:?} of {}",
2777 order.len()
2778 );
2779 }
2780
2781 #[test]
2782 fn a_benchmark_seed_depends_on_its_name_and_the_run_seed() {
2783 assert_eq!(seed_for(1, "a"), seed_for(1, "a"));
2784 assert_ne!(seed_for(1, "a"), seed_for(1, "b"));
2785 assert_ne!(seed_for(1, "a"), seed_for(2, "a"));
2786 }
2787
2788 #[test]
2789 fn stats_report_the_sample_standard_deviation() {
2790 let m = stats(&[2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]);
2791 assert_eq!(m["wall_min_ms"], 2.0);
2792 assert_eq!(m["wall_max_ms"], 9.0);
2793 assert_eq!(m["wall_mean_ms"], 5.0);
2794 assert!((m["wall_stddev_ms"] - 2.138_089_935).abs() < 1e-6);
2796 assert_eq!(stats(&[3.0])["wall_stddev_ms"], 0.0);
2797 }
2798
2799 #[cfg(unix)]
2801 #[test]
2802 fn a_failing_subject_does_not_stop_the_others() {
2803 let mk = |name: &str, cmd: &[&str]| Subject {
2804 name: name.into(),
2805 cmd: cmd.iter().map(|s| s.to_string()).collect(),
2806 prepare: None,
2807 setup: None,
2808 setup_dir: None,
2809 check: None,
2810 dir: None,
2811 version_cmd: None,
2812 env: BTreeMap::new(),
2813 vars: BTreeMap::new(),
2814 when: None,
2815 runs: Runs::Fixed(4),
2816 auto: AutoRuns {
2817 budget: Duration::from_secs(30),
2818 min: 5,
2819 max: 50,
2820 },
2821 warmup: 1,
2822 counters: false,
2823 allocations: false,
2824 count_until: Default::default(),
2825 ok_exit_codes: vec![0],
2826 metrics: BTreeMap::new(),
2827 };
2828 let res = interleaved(
2829 &[mk("ok", &["true"]), mk("bad", &["false"])],
2830 5,
2831 &Settings::default(),
2832 &mut Quiet,
2833 );
2834 assert_eq!(res[0].as_ref().unwrap().times.len(), 4);
2835 assert!(format!("{:#}", res[1].as_ref().unwrap_err()).contains("exited with"));
2836 }
2837
2838 #[test]
2841 fn a_metric_value_is_exactly_one_non_negative_number() {
2842 for (text, want) in [
2843 ("1234", 1234.0),
2844 ("1234\n", 1234.0),
2845 (" \t12.5\r\n", 12.5),
2846 ("0", 0.0),
2847 ("1.5e3", 1500.0),
2848 ("2E-2", 0.02),
2849 ("007", 7.0),
2850 ] {
2851 assert_eq!(parse_metric_value(text).unwrap(), want, "{text:?}");
2852 }
2853 for bad in [
2854 "", "\n", "-1", "+1", ".5", "5.", "1e", "1e+", "nan", "inf", "0x10", "1,234", "12 kB",
2855 "1 2", "1\n2", "size: 3", "1e999",
2856 ] {
2857 assert!(parse_metric_value(bad).is_err(), "accepted {bad:?}");
2858 }
2859 }
2860
2861 fn with_metrics(dir: &Path, env: &[(&str, &str)]) -> Subject {
2862 Subject {
2863 name: "s".into(),
2864 cmd: vec!["true".into()],
2865 prepare: None,
2866 setup: None,
2867 setup_dir: None,
2868 check: None,
2869 dir: Some(dir.to_path_buf()),
2870 version_cmd: None,
2871 env: env
2872 .iter()
2873 .map(|(k, v)| (k.to_string(), v.to_string()))
2874 .collect(),
2875 vars: BTreeMap::new(),
2876 when: None,
2877 runs: Runs::Fixed(1),
2878 auto: AutoRuns {
2879 budget: Duration::from_secs(30),
2880 min: 5,
2881 max: 50,
2882 },
2883 warmup: 0,
2884 counters: false,
2885 allocations: false,
2886 count_until: Default::default(),
2887 ok_exit_codes: vec![0],
2888 metrics: BTreeMap::new(),
2889 }
2890 }
2891
2892 #[test]
2895 fn a_file_metric_is_its_size_in_bytes() {
2896 let dir = tempfile::tempdir().unwrap();
2897 let file = dir.path().join("bin");
2898 std::fs::write(&file, vec![0u8; 4321]).unwrap();
2899 let s = with_metrics(dir.path(), &[]);
2900 let settings = Settings::default();
2901 assert_eq!(
2902 custom_metric(&MetricSource::File(file), &s, &settings).unwrap(),
2903 4321.0
2904 );
2905 let err = custom_metric(&MetricSource::File(dir.path().into()), &s, &settings).unwrap_err();
2906 assert!(format!("{err:#}").contains("not a regular file"), "{err:#}");
2907 let missing = dir.path().join("missing");
2908 let err = custom_metric(&MetricSource::File(missing), &s, &settings).unwrap_err();
2909 assert!(format!("{err:#}").contains("missing"), "{err:#}");
2910 }
2911
2912 #[cfg(unix)]
2917 #[test]
2918 fn a_cmd_metric_runs_in_the_subjects_dir_and_env() {
2919 let dir = tempfile::tempdir().unwrap();
2920 std::fs::write(dir.path().join("here"), "").unwrap();
2921 let s = with_metrics(dir.path(), &[("N", "42")]);
2922 let settings = Settings::default();
2923 let sh = |script: &str| {
2924 custom_metric(
2925 &MetricSource::Cmd(vec!["sh".into(), "-c".into(), script.into()]),
2926 &s,
2927 &settings,
2928 )
2929 };
2930 assert_eq!(sh("test -e here && echo $N").unwrap(), 42.0);
2931 let err = format!("{:#}", sh("echo 5; echo broke >&2; exit 3").unwrap_err());
2932 assert!(
2933 err.contains("exit status: 3") && err.contains("broke"),
2934 "{err}"
2935 );
2936 let err = format!("{:#}", sh("echo 'bundle: 12 kB'").unwrap_err());
2937 assert!(err.contains("not one number"), "{err}");
2938 let err = format!("{:#}", sh("yes 1 | head -c 4096").unwrap_err());
2939 assert!(err.contains("more than 1024 bytes"), "{err}");
2940 let err = format!("{:#}", sh("yes 1 | head -c 1024").unwrap_err());
2942 assert!(err.contains("not one number"), "{err}");
2943 let start = Instant::now();
2946 let err = format!("{:#}", sh("exec yes 1").unwrap_err());
2947 assert!(err.contains("so they were stopped"), "{err}");
2948 assert!(start.elapsed() < Duration::from_secs(4));
2949 let err = format!(
2952 "{:#}",
2953 sh("yes 'noise line' | head -c 20000 >&2; echo 'the real error' >&2; exit 2")
2954 .unwrap_err()
2955 );
2956 assert!(err.ends_with("the real error"), "{err}");
2957 assert!(!err.contains("noise"), "{err}");
2958 }
2959
2960 #[cfg(unix)]
2965 #[test]
2966 fn a_metric_cmd_leaving_stdout_open_fails_and_is_stopped() {
2967 let err = leftover_metric("sleep 30 & echo $! > pid; echo 7");
2968 assert!(err.contains("stdout open"), "{err}");
2969 }
2970
2971 #[cfg(unix)]
2975 #[test]
2976 fn a_leftover_that_floods_stdout_after_exit_is_stopped() {
2977 let err = leftover_metric("(sleep 0.1; exec yes 1) & echo $! > pid; echo 7");
2978 assert!(
2979 err.contains("more than 1024 bytes") && err.contains("what it started"),
2980 "{err}"
2981 );
2982 }
2983
2984 #[cfg(unix)]
2988 fn leftover_metric(script: &str) -> String {
2989 let dir = tempfile::tempdir().unwrap();
2990 let s = with_metrics(dir.path(), &[]);
2991 let start = Instant::now();
2992 let err = custom_metric(
2993 &MetricSource::Cmd(vec!["sh".into(), "-c".into(), script.into()]),
2994 &s,
2995 &Settings::default(),
2996 )
2997 .unwrap_err();
2998 assert!(start.elapsed() < Duration::from_secs(4));
2999 let pid = std::fs::read_to_string(dir.path().join("pid")).unwrap();
3000 let pid = pid.trim();
3001 let until = Instant::now() + Duration::from_secs(2);
3004 while running(pid) && Instant::now() < until {
3005 std::thread::sleep(Duration::from_millis(20));
3006 }
3007 assert!(
3008 !running(pid),
3009 "the background process {pid} was left running"
3010 );
3011 format!("{err:#}")
3012 }
3013
3014 #[cfg(unix)]
3016 fn version_sh(script: &str, env: &[(&str, &str)], timeout: Duration) -> Result<String> {
3017 let settings = Settings::default();
3018 let env: BTreeMap<String, String> = env
3019 .iter()
3020 .map(|(k, v)| (k.to_string(), v.to_string()))
3021 .collect();
3022 let site = Site {
3023 dir: None,
3024 env: &env,
3025 settings: &settings,
3026 };
3027 version_once(&["sh".into(), "-c".into(), script.into()], &site, timeout)
3028 }
3029
3030 #[cfg(unix)]
3033 #[test]
3034 fn a_version_is_the_first_line_printed() {
3035 let sh = |script: &str| version_sh(script, &[("V", "9.9")], VERSION_TIMEOUT);
3036 assert_eq!(
3037 sh("printf '\\n tool %s \\nbuilt today\\n' \"$V\"").unwrap(),
3038 "tool 9.9",
3039 "first non-empty line, trimmed, in the subject's env"
3040 );
3041 assert_eq!(sh("echo 'java 21' >&2").unwrap(), "java 21");
3042 let err = format!("{:#}", sh("echo nope >&2; exit 2").unwrap_err());
3043 assert!(err.contains("`sh`") && err.contains("nope"), "{err}");
3044 assert!(sh("true").is_err(), "no output is no version");
3045 }
3046
3047 #[cfg(unix)]
3050 #[test]
3051 fn a_version_is_read_from_a_capped_prefix() {
3052 let sh = |script: &str| version_sh(script, &[], VERSION_TIMEOUT);
3053 assert_eq!(sh("yes 'tool 1.0' | head -c 10000000").unwrap(), "tool 1.0");
3054 assert_eq!(
3055 sh("yes 'java 21' | head -c 10000000 >&2").unwrap(),
3056 "java 21",
3057 "a flood on stderr"
3058 );
3059 let kept = Mutex::new(Vec::new());
3060 let mut src = std::io::Cursor::new(vec![7u8; 100]);
3061 let overflow = std::sync::atomic::AtomicBool::new(false);
3062 keep_prefix(&mut src, 10, &kept, &overflow, None);
3063 assert_eq!(kept.lock().unwrap().len(), 10, "only the cap is kept");
3064 assert_eq!(
3065 src.position(),
3066 100,
3067 "the rest is read, not left in the pipe"
3068 );
3069 assert!(overflow.into_inner(), "and going past the cap is noticed");
3070
3071 let (kept, overflow) = (
3072 Mutex::new(Vec::new()),
3073 std::sync::atomic::AtomicBool::new(false),
3074 );
3075 keep_prefix(
3076 std::io::Cursor::new(vec![7u8; 10]),
3077 10,
3078 &kept,
3079 &overflow,
3080 None,
3081 );
3082 assert!(!overflow.into_inner(), "exactly the cap is not past it");
3083 }
3084
3085 #[cfg(unix)]
3088 #[test]
3089 fn a_failing_version_cmd_is_an_error_even_past_the_cap() {
3090 let err = version_sh(
3091 "yes 'usage: tool [flags]' | head -c 100000; echo 'unknown flag' >&2; exit 1",
3092 &[],
3093 VERSION_TIMEOUT,
3094 )
3095 .unwrap_err();
3096 let err = format!("{err:#}");
3097 assert!(
3098 err.contains("exited with") && err.contains("unknown flag"),
3099 "{err}"
3100 );
3101 }
3102
3103 #[cfg(unix)]
3106 #[test]
3107 fn a_version_cmd_that_never_finishes_is_stopped() {
3108 let t = Duration::from_millis(300);
3109 let began = Instant::now();
3110 for script in ["exec yes 'tool 2.0' >&2", "exec sleep 30"] {
3112 let err = format!("{:#}", version_sh(script, &[], t).unwrap_err());
3113 assert!(err.contains("did not finish"), "{script}: {err}");
3114 }
3115 assert!(
3116 began.elapsed() < Duration::from_secs(5),
3117 "{:?}",
3118 began.elapsed()
3119 );
3120 }
3121
3122 #[cfg(unix)]
3125 #[test]
3126 fn a_timeout_stops_the_whole_process_group() {
3127 let dir = tempfile::tempdir().unwrap();
3128 let pidfile = dir.path().join("pid");
3129 let script = format!("sleep 30 & echo $! > '{}'; wait", pidfile.display());
3130 let err = version_sh(&script, &[], Duration::from_millis(300)).unwrap_err();
3131 assert!(format!("{err:#}").contains("did not finish"), "{err:#}");
3132 let pid = std::fs::read_to_string(&pidfile).unwrap();
3133 let pid = pid.trim();
3134 let until = Instant::now() + Duration::from_secs(2);
3135 while running(pid) && Instant::now() < until {
3136 std::thread::sleep(Duration::from_millis(20));
3137 }
3138 assert!(
3139 !running(pid),
3140 "the background sleep {pid} outlived the timeout"
3141 );
3142 }
3143
3144 #[cfg(unix)]
3149 fn running(pid: &str) -> bool {
3150 #[cfg(target_os = "linux")]
3151 {
3152 let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) else {
3155 return false;
3156 };
3157 let state = stat
3158 .rfind(')')
3159 .and_then(|i| stat[i + 1..].trim_start().chars().next());
3160 !matches!(state, None | Some('Z' | 'X' | 'x'))
3161 }
3162 #[cfg(not(target_os = "linux"))]
3163 {
3164 let Ok(out) = Command::new("ps")
3165 .args(["-o", "stat=", "-p", pid])
3166 .stderr(Stdio::null())
3167 .output()
3168 else {
3169 return false;
3170 };
3171 let stat = String::from_utf8_lossy(&out.stdout);
3172 let stat = stat.trim();
3173 out.status.success() && !stat.is_empty() && !stat.starts_with('Z')
3174 }
3175 }
3176
3177 #[cfg(unix)]
3180 #[test]
3181 fn a_background_process_holding_the_pipe_does_not_hold_up_the_version() {
3182 let began = Instant::now();
3183 let v = version_sh("sleep 5 & echo 'tool 3.0'", &[], VERSION_TIMEOUT).unwrap();
3184 assert_eq!(v, "tool 3.0");
3185 assert!(
3186 began.elapsed() < Duration::from_secs(3),
3187 "{:?}",
3188 began.elapsed()
3189 );
3190 }
3191
3192 #[cfg(unix)]
3194 #[test]
3195 fn a_failing_prepare_is_reported_as_prepare() {
3196 let res = interleaved(
3197 &[Subject {
3198 name: "x".into(),
3199 cmd: vec!["true".into()],
3200 prepare: Some(vec![
3201 "/bin/sh".into(),
3202 "-c".into(),
3203 "echo nope >&2; exit 3".into(),
3204 ]),
3205 setup: None,
3206 setup_dir: None,
3207 check: None,
3208 dir: None,
3209 version_cmd: None,
3210 env: BTreeMap::new(),
3211 vars: BTreeMap::new(),
3212 when: None,
3213 runs: Runs::Fixed(1),
3214 auto: AutoRuns {
3215 budget: Duration::from_secs(30),
3216 min: 5,
3217 max: 50,
3218 },
3219 warmup: 0,
3220 counters: false,
3221 allocations: false,
3222 count_until: Default::default(),
3223 ok_exit_codes: vec![0],
3224 metrics: BTreeMap::new(),
3225 }],
3226 0,
3227 &Settings::default(),
3228 &mut Quiet,
3229 );
3230 let msg = format!("{:#}", res[0].as_ref().unwrap_err());
3231 assert!(msg.contains("prepare") && msg.contains("nope"), "{msg}");
3232 }
3233
3234 #[cfg(unix)]
3237 fn alternating(dir: &Path, warmup: u32, runs: u32) -> Subject {
3238 Subject {
3239 name: "alt".into(),
3240 cmd: vec![
3241 "/bin/sh".into(),
3242 "-c".into(),
3243 "echo x >> n".into(),
3244 ],
3245 prepare: None,
3246 setup: None,
3247 setup_dir: None,
3248 check: Some(vec![
3249 "/bin/sh".into(),
3250 "-c".into(),
3251 "echo check >> checked; runs=$(( $(wc -l < n) )); test $(( runs % 2 )) = 1 || { echo \"run $runs is even\" >&2; exit 1; }".into(),
3253 ]),
3254 version_cmd: None,
3255 dir: Some(dir.to_path_buf()),
3256 env: BTreeMap::new(),
3257 vars: BTreeMap::new(),
3258 when: None,
3259 runs: Runs::Fixed(runs),
3260 auto: AutoRuns {
3261 budget: Duration::from_secs(30),
3262 min: 5,
3263 max: 50,
3264 },
3265 warmup,
3266 counters: false,
3267 allocations: false,
3268 count_until: Default::default(),
3269 ok_exit_codes: vec![0],
3270 metrics: BTreeMap::new(),
3271 }
3272 }
3273
3274 #[cfg(unix)]
3277 #[test]
3278 fn a_failing_check_marks_the_sample_without_dropping_the_subject() {
3279 let dir = tempfile::tempdir().unwrap();
3280 let res = interleaved(
3281 &[alternating(dir.path(), 1, 6)],
3282 0,
3283 &Settings::default(),
3284 &mut Quiet,
3285 );
3286 let s = res[0].as_ref().unwrap();
3287 assert_eq!(s.times.len(), 6);
3288 assert_eq!(s.checks, [false, true, false, true, false, true]);
3290 assert_eq!(s.passed(), 3);
3291 assert!(
3292 s.first_failure
3293 .as_deref()
3294 .unwrap()
3295 .contains("run 2 is even"),
3296 "{s:?}"
3297 );
3298 let checked = std::fs::read_to_string(dir.path().join("checked")).unwrap();
3299 assert_eq!(checked.lines().count(), 6, "no check after the warmup");
3300 }
3301
3302 #[cfg(unix)]
3306 #[test]
3307 fn ok_exit_codes_do_not_pass_a_check_that_exits_1() {
3308 let dir = tempfile::tempdir().unwrap();
3309 let mut s = alternating(dir.path(), 0, 2);
3310 s.cmd = vec!["/bin/sh".into(), "-c".into(), "exit 1".into()];
3311 s.check = Some(vec!["/bin/sh".into(), "-c".into(), "exit 1".into()]);
3312 s.ok_exit_codes = vec![0, 1];
3313 let res = interleaved(&[s], 0, &Settings::default(), &mut Quiet);
3314 let s = res[0].as_ref().unwrap();
3315 assert_eq!(s.exit_codes, [1, 1]);
3316 assert_eq!(s.checks, [false, false]);
3317 assert_eq!(s.passed(), 0);
3318 }
3319
3320 #[cfg(unix)]
3323 #[test]
3324 fn a_check_that_cannot_start_drops_the_subject() {
3325 let dir = tempfile::tempdir().unwrap();
3326 let mut s = alternating(dir.path(), 0, 2);
3327 s.check = Some(vec!["/nonexistent/tak-check".into()]);
3328 let res = interleaved(&[s], 0, &Settings::default(), &mut Quiet);
3329 let msg = format!("{:#}", res[0].as_ref().unwrap_err());
3330 assert!(msg.contains("failed to spawn check"), "{msg}");
3331 }
3332
3333 #[cfg(unix)]
3338 #[test]
3339 fn a_process_left_by_a_passing_step_can_still_write_to_stderr() {
3340 let dir = tempfile::tempdir().unwrap();
3341 let env = BTreeMap::new();
3342 let settings = Settings::default();
3343 let site = Site {
3344 dir: Some(dir.path()),
3345 env: &env,
3346 settings: &settings,
3347 };
3348 const N: usize = 10;
3349 let start = Instant::now();
3350 for i in 0..N {
3351 let script = format!(
3352 "{{ sh -c 'sleep 1; echo late >&2'; echo $? > s{i}.tmp && mv s{i}.tmp s{i}; }} & exit 0"
3353 );
3354 let step = ["/bin/sh".to_string(), "-c".into(), script];
3355 assert_eq!(untimed("setup", &step, &site).unwrap(), None);
3356 }
3357 let took = start.elapsed();
3358 assert!(took < Duration::from_secs(2), "{N} passes took {took:?}");
3359
3360 let deadline = Instant::now() + Duration::from_secs(20);
3361 let statuses: Vec<String> = (0..N)
3362 .map(|i| {
3363 loop {
3364 if let Ok(s) = std::fs::read_to_string(dir.path().join(format!("s{i}"))) {
3365 break s.trim().to_string();
3366 }
3367 assert!(Instant::now() < deadline, "leftover {i} never finished");
3368 std::thread::sleep(Duration::from_millis(50));
3369 }
3370 })
3371 .collect();
3372 assert!(statuses.iter().all(|s| s == "0"), "{statuses:?}");
3373 }
3374
3375 #[derive(Default)]
3377 struct Log {
3378 plans: Vec<Vec<u64>>,
3379 finished: Vec<usize>,
3380 events: Vec<String>,
3382 }
3383 impl Observer for Log {
3384 fn planned(&mut self, remaining: &[u64]) {
3385 self.plans.push(remaining.to_vec());
3386 }
3387 fn setting_up(&mut self, subject: usize) {
3388 self.events.push(format!("setup:{subject}"));
3389 }
3390 fn started(&mut self, subject: usize) {
3391 self.events.push(format!("start:{subject}"));
3392 }
3393 fn dropped(&mut self, subject: usize) {
3394 self.events.push(format!("drop:{subject}"));
3395 }
3396 fn finished(&mut self, subject: usize, _: Duration) {
3397 self.finished.push(subject);
3398 }
3399 }
3400
3401 #[cfg(unix)]
3404 #[test]
3405 fn setups_run_once_first_and_a_failing_one_drops_its_subject() {
3406 let sh = |script: &str| Some(["/bin/sh", "-c", script].map(String::from).to_vec());
3407 let mk = |name: &str, setup: Option<Vec<String>>| Subject {
3408 name: name.into(),
3409 cmd: vec!["true".into()],
3410 prepare: None,
3411 setup,
3412 setup_dir: None,
3413 check: None,
3414 version_cmd: None,
3415 dir: None,
3416 env: BTreeMap::new(),
3417 vars: BTreeMap::new(),
3418 when: None,
3419 runs: Runs::Auto,
3420 auto: AutoRuns {
3421 budget: Duration::from_secs(30),
3422 min: 2,
3423 max: 2,
3424 },
3425 warmup: 1,
3426 counters: false,
3427 allocations: false,
3428 count_until: Default::default(),
3429 ok_exit_codes: vec![0],
3430 metrics: BTreeMap::new(),
3431 };
3432 let mut log = Log::default();
3433 let res = interleaved(
3434 &[
3435 mk("ok", sh("true")),
3436 mk("bad", sh("echo no fixture >&2; exit 2")),
3437 mk("none", None),
3438 ],
3439 3,
3440 &Settings::default(),
3441 &mut log,
3442 );
3443 assert_eq!(log.events[..3], ["setup:0", "setup:1", "drop:1"]);
3444 assert!(!log.events[3..].iter().any(|e| e.starts_with("setup:")));
3445 assert!(!log.events.contains(&"start:1".to_string()));
3446 assert_eq!(res[0].as_ref().unwrap().times.len(), 2);
3447 assert_eq!(res[2].as_ref().unwrap().times.len(), 2);
3448 let msg = format!("{:#}", res[1].as_ref().unwrap_err());
3449 assert!(msg.contains("setup") && msg.contains("no fixture"), "{msg}");
3450 assert_eq!(log.finished.len(), 2 * (1 + 2));
3452 }
3453
3454 #[cfg(unix)]
3460 #[test]
3461 fn auto_runs_give_a_slow_subject_the_floor_and_a_fast_one_more() {
3462 let mk = |name: &str, secs: &str, warmup: u32| Subject {
3463 name: name.into(),
3464 cmd: vec!["sleep".into(), secs.into()],
3465 prepare: None,
3466 setup: None,
3467 setup_dir: None,
3468 check: None,
3469 dir: None,
3470 version_cmd: None,
3471 env: BTreeMap::new(),
3472 vars: BTreeMap::new(),
3473 when: None,
3474 runs: Runs::Auto,
3475 auto: AutoRuns {
3476 budget: Duration::from_millis(600),
3477 min: 2,
3478 max: 6,
3479 },
3480 warmup,
3481 counters: false,
3482 allocations: false,
3483 count_until: Default::default(),
3484 ok_exit_codes: vec![0],
3485 metrics: BTreeMap::new(),
3486 };
3487 let mut log = Log::default();
3488 let res = interleaved(
3490 &[mk("fast", "0.01", 1), mk("slow", "0.5", 0)],
3491 9,
3492 &Settings::default(),
3493 &mut log,
3494 );
3495 let fast = res[0].as_ref().unwrap().times.len();
3496 let slow = res[1].as_ref().unwrap().times.len();
3497 assert_eq!(slow, 2, "0.6s budget / 0.5s sample is below the floor");
3498 assert!(fast > slow && fast <= 6, "fast got {fast}");
3499 assert_eq!(log.plans[0], [1 + 2, 2]);
3501 assert_eq!(log.plans.len(), 2);
3502 assert_eq!(log.finished.len(), 1 + fast + slow);
3503 }
3504
3505 #[test]
3506 fn steady_samples_raise_no_warning() {
3507 assert!(warnings(&[10.0, 10.2, 9.9, 10.1, 10.0, 10.3]).is_empty());
3508 assert!(warnings(&[10.0, 50.0]).is_empty(), "too few to judge");
3509 }
3510
3511 #[test]
3512 fn a_spike_is_an_outlier() {
3513 let w = warnings(&[10.0, 10.2, 9.9, 10.1, 40.0, 10.0, 10.1]);
3514 assert_eq!(w.len(), 1, "{w:?}");
3515 assert!(
3516 w[0].starts_with("1 of 7 samples are slow outliers"),
3517 "{w:?}"
3518 );
3519 }
3520
3521 #[test]
3522 fn a_slow_first_sample_is_called_out() {
3523 let w = warnings(&[35.0, 10.0, 10.2, 9.9, 10.1, 10.0]);
3524 assert!(
3525 w.iter().any(|m| m.contains("first sample took 3.5x")),
3526 "{w:?}"
3527 );
3528 }
3529
3530 #[test]
3533 fn a_spike_among_identical_samples_is_still_an_outlier() {
3534 let w = warnings(&[10.0, 10.0, 10.0, 100.0, 10.0]);
3535 assert!(w.iter().any(|m| m.contains("slow outliers")), "{w:?}");
3536 assert!(
3537 warnings(&[10.0; 6]).is_empty(),
3538 "identical samples are fine"
3539 );
3540 }
3541
3542 #[test]
3545 fn a_fast_outlier_is_flagged_as_possibly_the_minimum() {
3546 let w = warnings(&[100.0, 101.0, 99.0, 102.0, 10.0, 100.0]);
3547 assert!(
3548 w.iter()
3549 .any(|m| m.contains("fast outliers") && m.contains("minimum")),
3550 "{w:?}"
3551 );
3552 }
3553
3554 #[test]
3557 fn several_spikes_over_a_flat_majority_are_caught() {
3558 let w = warnings(&[10.0, 10.0, 10.0, 10.0, 40.0, 45.0]);
3559 assert!(
3560 w.iter()
3561 .any(|m| m.starts_with("2 of 6 samples are slow outliers")),
3562 "{w:?}"
3563 );
3564 assert!(
3565 warnings(&[10.0, 10.0, 10.0, 11.0, 10.0]).is_empty(),
3566 "10% is not a spike"
3567 );
3568 }
3569}