1use crate::config::{AutoRuns, Runs, SELF_TOOL, Subject};
17use crate::settings::Settings;
18use anyhow::{Context, Result, bail};
19use std::collections::BTreeMap;
20use std::path::Path;
21use std::process::{Command, Stdio};
22use std::time::Duration;
23use std::time::Instant;
24
25#[derive(Debug, Clone)]
26pub struct Plan {
27 pub cmd: Vec<String>,
28 pub warmup: u32,
29 pub runs: u32,
30 pub dir: Option<std::path::PathBuf>,
34 pub settings: Settings,
38}
39
40fn subject(bin: &str, settings: &Settings) -> Command {
59 let mut c = Command::new(bin);
60 for key in settings.scrubbed_env() {
61 c.env_remove(key);
62 }
63 c
64}
65
66#[derive(Debug, Clone, Copy)]
68struct Site<'a> {
69 dir: Option<&'a Path>,
70 env: &'a BTreeMap<String, String>,
71 settings: &'a Settings,
72}
73
74fn command(argv: &[String], site: &Site) -> Result<Command> {
80 let (bin, args) = argv.split_first().context("empty command")?;
81 let mut c = subject(bin, site.settings);
82 c.args(args).envs(site.env);
83 if let Some(d) = site.dir {
84 c.current_dir(d);
85 }
86 Ok(c)
87}
88
89fn time_once(cmd: &[String], site: &Site) -> Result<f64> {
95 let mut c = command(cmd, site)?;
96 c.stdout(Stdio::null()).stderr(Stdio::null());
97 let bin = &cmd[0];
98 let start = Instant::now();
99 let status = c
100 .status()
101 .with_context(|| format!("failed to spawn `{bin}`"))?;
102 let elapsed = start.elapsed().as_secs_f64() * 1000.0;
103 if !status.success() {
104 bail!("benchmark subject `{bin}` exited with {status}");
105 }
106 Ok(elapsed)
107}
108
109const PREPARE_STDERR_TAIL: usize = 4096;
113
114fn prepare_once(cmd: &[String], site: &Site) -> Result<()> {
117 use std::io::Read;
118
119 let mut c = command(cmd, site)?;
120 let bin = &cmd[0];
121 let mut child = c
122 .stdin(Stdio::null())
123 .stdout(Stdio::null())
124 .stderr(Stdio::piped())
125 .spawn()
126 .with_context(|| format!("failed to spawn prepare `{bin}`"))?;
127 let mut tail: Vec<u8> = Vec::new();
130 if let Some(mut err) = child.stderr.take() {
131 let mut buf = [0u8; 8192];
132 loop {
133 let n = err.read(&mut buf).unwrap_or(0);
134 if n == 0 {
135 break;
136 }
137 tail.extend_from_slice(&buf[..n]);
138 if tail.len() > PREPARE_STDERR_TAIL {
139 tail.drain(..tail.len() - PREPARE_STDERR_TAIL);
140 }
141 }
142 }
143 let status = child
144 .wait()
145 .with_context(|| format!("failed to wait for prepare `{bin}`"))?;
146 if !status.success() {
147 let stderr = String::from_utf8_lossy(&tail);
148 bail!(
149 "prepare `{bin}` exited with {status}: {}",
150 stderr.lines().last().unwrap_or("(no output)").trim()
151 );
152 }
153 Ok(())
154}
155
156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub struct Slot {
159 pub subject: usize,
161 pub timed: bool,
164}
165
166pub fn schedule(counts: &[(u32, u32)], seed: u64) -> Vec<Slot> {
184 let mut rng = fastrand::Rng::with_seed(seed);
185 let warmups: Vec<u64> = counts.iter().map(|&(w, _)| u64::from(w)).collect();
186 let runs: Vec<u64> = counts.iter().map(|&(_, r)| u64::from(r)).collect();
187 let mut out = rounds(&warmups, false, &mut rng);
188 out.extend(rounds(&runs, true, &mut rng));
189 out
190}
191
192fn rounds(count: &[u64], timed: bool, rng: &mut fastrand::Rng) -> Vec<Slot> {
194 let total = count.iter().copied().max().unwrap_or(0);
195 let mut out = Vec::new();
196 for round in 0..total {
197 let mut due: Vec<usize> = (0..count.len())
200 .filter(|&i| (round + 1) * count[i] / total > round * count[i] / total)
201 .collect();
202 rng.shuffle(&mut due);
203 out.extend(due.into_iter().map(|subject| Slot { subject, timed }));
204 }
205 out
206}
207
208pub fn seed_for(seed: u64, bench: &str) -> u64 {
211 bench.bytes().fold(seed ^ 0xcbf2_9ce4_8422_2325, |h, b| {
213 (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)
214 })
215}
216
217pub trait Observer {
219 fn planned(&mut self, _remaining: &[u64]) {}
222 fn started(&mut self, _subject: usize) {}
224 fn finished(&mut self, _subject: usize, _elapsed: Duration) {}
226 fn dropped(&mut self, _subject: usize) {}
228}
229
230pub struct Quiet;
232impl Observer for Quiet {}
233
234pub fn interleaved(
247 subjects: &[Subject],
248 seed: u64,
249 settings: &Settings,
250 observer: &mut dyn Observer,
251) -> Vec<Result<Vec<f64>>> {
252 let mut rng = fastrand::Rng::with_seed(seed);
253 let mut results: Vec<Result<Vec<f64>>> = subjects
254 .iter()
255 .map(|s| {
256 if s.runs == Runs::Fixed(0) {
258 bail!("runs must be at least 1");
259 }
260 Ok(Vec::new())
261 })
262 .collect();
263 let mut fastest: Vec<Option<Duration>> = vec![None; subjects.len()];
267
268 let warmups: Vec<u64> = subjects.iter().map(|s| u64::from(s.warmup)).collect();
269 let pilots: Vec<u64> = subjects
270 .iter()
271 .map(|s| u64::from(s.runs == Runs::Auto && s.warmup == 0))
272 .collect();
273 let provisional: Vec<u64> = subjects
275 .iter()
276 .zip(&warmups)
277 .map(|(s, w)| {
278 w + u64::from(match s.runs {
279 Runs::Fixed(n) => n,
280 Runs::Auto => s.auto.min,
281 })
282 })
283 .collect();
284 observer.planned(&provisional);
285
286 let mut first = rounds(&warmups, false, &mut rng);
287 first.extend(rounds(&pilots, true, &mut rng));
288 run_slots(
289 &first,
290 subjects,
291 settings,
292 &mut results,
293 &mut fastest,
294 observer,
295 );
296
297 let remaining: Vec<u64> = subjects
298 .iter()
299 .enumerate()
300 .map(|(i, s)| match (&results[i], s.runs) {
301 (Err(_), _) => 0,
302 (Ok(_), Runs::Fixed(n)) => u64::from(n),
303 (Ok(taken), Runs::Auto) => {
304 let n = auto_runs(&s.auto, fastest[i]);
305 u64::from(n).saturating_sub(taken.len() as u64)
306 }
307 })
308 .collect();
309 observer.planned(&remaining);
310 let second = rounds(&remaining, true, &mut rng);
311 run_slots(
312 &second,
313 subjects,
314 settings,
315 &mut results,
316 &mut fastest,
317 observer,
318 );
319 results
320}
321
322fn auto_runs(auto: &AutoRuns, fastest: Option<Duration>) -> u32 {
325 fastest.map_or(auto.min, |d| auto.runs_for(d))
326}
327
328fn run_slots(
330 slots: &[Slot],
331 subjects: &[Subject],
332 settings: &Settings,
333 results: &mut [Result<Vec<f64>>],
334 fastest: &mut [Option<Duration>],
335 observer: &mut dyn Observer,
336) {
337 for slot in slots {
338 let Ok(samples) = &mut results[slot.subject] else {
339 continue;
340 };
341 let s = &subjects[slot.subject];
342 let site = Site {
343 dir: s.dir.as_deref(),
344 env: &s.env,
345 settings,
346 };
347 observer.started(slot.subject);
348 let began = Instant::now();
349 let taken = s
350 .prepare
351 .as_deref()
352 .map_or(Ok(()), |p| prepare_once(p, &site))
353 .and_then(|()| time_once(&s.cmd, &site));
354 let elapsed = began.elapsed();
355 match taken {
356 Ok(ms) => {
357 if slot.timed {
358 samples.push(ms);
359 }
360 let f = &mut fastest[slot.subject];
361 *f = Some(f.map_or(elapsed, |f| f.min(elapsed)));
362 observer.finished(slot.subject, elapsed);
363 }
364 Err(e) => {
365 results[slot.subject] = Err(e);
366 observer.dropped(slot.subject);
367 }
368 }
369 }
370}
371
372pub fn stats(samples: &[f64]) -> BTreeMap<String, f64> {
379 let mut sorted = samples.to_vec();
380 sorted.sort_by(f64::total_cmp);
381 let n = sorted.len();
382 let mean = sorted.iter().sum::<f64>() / n as f64;
383 let stddev = if n > 1 {
385 (sorted.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64).sqrt()
386 } else {
387 0.0
388 };
389 BTreeMap::from([
390 ("wall_min_ms".to_string(), sorted[0]),
391 ("wall_p50_ms".to_string(), sorted[n / 2]),
392 ("wall_mean_ms".to_string(), mean),
393 ("wall_max_ms".to_string(), sorted[n - 1]),
394 ("wall_stddev_ms".to_string(), stddev),
395 ("wall_n".to_string(), n as f64),
396 ])
397}
398
399pub fn wall(plan: &Plan) -> Result<BTreeMap<String, f64>> {
401 let subject = Subject {
402 name: SELF_TOOL.to_string(),
403 cmd: plan.cmd.clone(),
404 prepare: None,
405 dir: plan.dir.clone(),
406 env: BTreeMap::new(),
407 runs: Runs::Fixed(plan.runs),
408 auto: AutoRuns {
409 budget: crate::config::DEFAULT_BUDGET,
410 min: crate::config::DEFAULT_MIN_RUNS,
411 max: crate::config::DEFAULT_MAX_RUNS,
412 },
413 warmup: plan.warmup,
414 counters: false,
415 };
416 let samples = interleaved(
418 std::slice::from_ref(&subject),
419 0,
420 &plan.settings,
421 &mut Quiet,
422 )
423 .pop()
424 .expect("one result per subject")?;
425 Ok(stats(&samples))
426}
427
428pub fn valgrind_available() -> bool {
434 Command::new("valgrind")
435 .arg("--version")
436 .stdout(Stdio::null())
437 .stderr(Stdio::null())
438 .status()
439 .map(|s| s.success())
440 .unwrap_or(false)
441}
442
443const COUNTER_RUNS: u32 = 3;
446
447const SPREAD_WARN_PCT: f64 = 0.5;
452
453#[derive(Debug, Clone, Copy)]
455pub struct Counted {
456 pub min: u64,
457 pub max: u64,
458 pub runs: u32,
459}
460
461impl Counted {
462 pub fn spread_pct(&self) -> f64 {
464 if self.min == 0 {
465 return 0.0;
466 }
467 (self.max - self.min) as f64 / self.min as f64 * 100.0
468 }
469
470 pub fn is_suspect(&self) -> bool {
477 self.spread_pct() > SPREAD_WARN_PCT
478 }
479}
480
481pub fn instructions(
493 cmd: &[String],
494 dir: Option<&std::path::Path>,
495 settings: &Settings,
496) -> Result<Option<Counted>> {
497 count(
498 cmd,
499 None,
500 &Site {
501 dir,
502 env: &BTreeMap::new(),
503 settings,
504 },
505 )
506}
507
508pub fn subject_instructions(s: &Subject, settings: &Settings) -> Result<Option<Counted>> {
512 count(
513 &s.cmd,
514 s.prepare.as_deref(),
515 &Site {
516 dir: s.dir.as_deref(),
517 env: &s.env,
518 settings,
519 },
520 )
521}
522
523fn count(cmd: &[String], prepare: Option<&[String]>, site: &Site) -> Result<Option<Counted>> {
524 if !valgrind_available() {
525 return Ok(None);
526 }
527
528 let mut samples: Vec<u64> = Vec::with_capacity(COUNTER_RUNS as usize);
529 for _ in 0..COUNTER_RUNS {
530 if let Some(p) = prepare {
531 prepare_once(p, site)?;
532 }
533 let mut argv: Vec<String> = [
534 "valgrind",
535 "--tool=cachegrind",
536 "--cache-sim=no",
537 "--branch-sim=no",
538 "--cachegrind-out-file=/dev/null",
539 ]
540 .map(String::from)
541 .to_vec();
542 argv.extend_from_slice(cmd);
543 let mut c = command(&argv, site)?;
544 c.stdout(Stdio::null());
545 let out = c.output().context("failed to run valgrind")?;
546
547 let stderr = String::from_utf8_lossy(&out.stderr);
549 if !out.status.success() {
550 let bin = cmd.first().map(String::as_str).unwrap_or("(empty command)");
551 bail!(
552 "benchmark subject `{bin}` exited with {} under valgrind",
553 out.status
554 );
555 }
556 match parse_irefs(&stderr) {
557 Some(n) => samples.push(n),
558 None => bail!(
562 "valgrind ran but emitted no `I refs` summary: {}",
563 stderr.lines().last().unwrap_or("(no output)").trim()
564 ),
565 }
566 }
567
568 Ok(Some(Counted {
569 min: *samples.iter().min().expect("COUNTER_RUNS > 0"),
570 max: *samples.iter().max().expect("COUNTER_RUNS > 0"),
571 runs: COUNTER_RUNS,
572 }))
573}
574
575fn parse_irefs(stderr: &str) -> Option<u64> {
577 let line = stderr.lines().find(|l| l.contains("I refs:"))?;
578 let digits: String = line
579 .rsplit(':')
580 .next()?
581 .chars()
582 .filter(|c| c.is_ascii_digit())
583 .collect();
584 digits.parse().ok()
585}
586
587#[cfg(test)]
588mod tests {
589 use super::*;
590
591 #[test]
592 fn parses_cachegrind_summary() {
593 let s = "==12== I refs: 48,349,132\n";
594 assert_eq!(parse_irefs(s), Some(48_349_132));
595 }
596
597 #[test]
598 fn missing_summary_is_none_not_panic() {
599 assert_eq!(parse_irefs("valgrind: command not found"), None);
600 }
601
602 fn removals(settings: &Settings) -> Vec<String> {
604 subject("true", settings)
605 .get_envs()
606 .filter(|(_, v)| v.is_none())
607 .map(|(k, _)| k.to_string_lossy().into_owned())
608 .collect()
609 }
610
611 #[test]
614 fn subject_commands_remove_the_default_denied_variables() {
615 let removed = removals(&Settings::default());
616 for key in Settings::default().scrubbed_env() {
617 assert!(removed.contains(&key.to_string()), "{key} not removed");
618 }
619 }
620
621 #[test]
624 fn the_removal_follows_the_settings() {
625 let removed = removals(&Settings {
626 env_deny: vec!["CUSTOM_SECRET".into()],
627 env_allow: Vec::new(),
628 ..Settings::default()
629 });
630 assert!(removed.contains(&"CUSTOM_SECRET".to_string()));
631 assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
632 }
633
634 #[test]
637 fn an_allowed_variable_survives() {
638 let removed = removals(&Settings {
639 env_deny: vec!["GITHUB_TOKEN".into(), "GH_TOKEN".into()],
640 env_allow: vec!["GITHUB_TOKEN".into()],
641 ..Settings::default()
642 });
643 assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
644 assert!(removed.contains(&"GH_TOKEN".to_string()));
645 }
646
647 #[test]
648 fn zero_runs_is_rejected_not_a_panic() {
649 let plan = Plan {
650 cmd: vec!["true".into()],
651 warmup: 0,
652 runs: 0,
653 dir: None,
654 settings: Settings::default(),
655 };
656 assert!(wall(&plan).is_err());
657 }
658
659 #[test]
660 fn a_failed_subject_is_not_recorded_as_a_fast_run() {
661 #[cfg(unix)]
662 let cmd = vec!["/bin/sh".into(), "-c".into(), "exit 42".into()];
663 #[cfg(windows)]
664 let cmd = vec!["cmd".into(), "/C".into(), "exit /B 42".into()];
665
666 let err = wall(&Plan {
667 cmd,
668 warmup: 0,
669 runs: 1,
670 dir: None,
671 settings: Settings::default(),
672 })
673 .unwrap_err();
674
675 assert!(format!("{err:#}").contains("exited with"), "{err:#}");
676 }
677
678 #[test]
679 fn wall_reports_min_le_p50_le_max() {
680 let plan = Plan {
681 cmd: vec!["true".into()],
682 warmup: 1,
683 runs: 5,
684 dir: None,
685 settings: Settings::default(),
686 };
687 let m = wall(&plan).unwrap();
688 assert!(m["wall_min_ms"] <= m["wall_p50_ms"]);
689 assert!(m["wall_p50_ms"] <= m["wall_max_ms"]);
690 assert_eq!(m["wall_n"], 5.0);
691 }
692
693 #[test]
695 fn the_schedule_gives_each_subject_its_counts() {
696 let counts = [(2, 10), (1, 5), (0, 3)];
697 let order = schedule(&counts, 7);
698 for (i, &(warmup, runs)) in counts.iter().enumerate() {
699 let of = |timed| {
700 order
701 .iter()
702 .filter(|s| s.subject == i && s.timed == timed)
703 .count()
704 };
705 assert_eq!(of(false), warmup as usize, "subject {i} warmups");
706 assert_eq!(of(true), runs as usize, "subject {i} runs");
707 }
708 let first_timed = order.iter().position(|s| s.timed).unwrap();
709 assert!(order[first_timed..].iter().all(|s| s.timed));
710 }
711
712 #[test]
713 fn the_same_seed_gives_the_same_order() {
714 let counts = [(1, 8), (1, 8), (1, 8)];
715 assert_eq!(schedule(&counts, 42), schedule(&counts, 42));
716 assert_ne!(schedule(&counts, 42), schedule(&counts, 43));
717 }
718
719 #[test]
722 fn each_round_runs_every_subject_once_in_a_varying_order() {
723 let order = schedule(&[(0, 20), (0, 20), (0, 20)], 1);
724 let rounds: Vec<Vec<usize>> = order
725 .chunks(3)
726 .map(|r| r.iter().map(|s| s.subject).collect())
727 .collect();
728 assert_eq!(rounds.len(), 20);
729 for r in &rounds {
730 let mut sorted = r.clone();
731 sorted.sort();
732 assert_eq!(sorted, [0, 1, 2], "round {r:?}");
733 }
734 assert!(rounds.iter().any(|r| r != &rounds[0]), "never shuffled");
735 }
736
737 #[test]
740 fn a_subject_with_fewer_runs_is_spread_across_the_run() {
741 let order = schedule(&[(0, 10), (0, 5)], 3);
742 let fewer: Vec<usize> = order
743 .iter()
744 .enumerate()
745 .filter(|(_, s)| s.subject == 1)
746 .map(|(i, _)| i)
747 .collect();
748 assert_eq!(fewer.len(), 5);
749 assert!(
750 *fewer.last().unwrap() >= order.len() - 3,
751 "last sample of the smaller subject is near the end: {fewer:?} of {}",
752 order.len()
753 );
754 }
755
756 #[test]
757 fn a_benchmark_seed_depends_on_its_name_and_the_run_seed() {
758 assert_eq!(seed_for(1, "a"), seed_for(1, "a"));
759 assert_ne!(seed_for(1, "a"), seed_for(1, "b"));
760 assert_ne!(seed_for(1, "a"), seed_for(2, "a"));
761 }
762
763 #[test]
764 fn stats_report_the_sample_standard_deviation() {
765 let m = stats(&[2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]);
766 assert_eq!(m["wall_min_ms"], 2.0);
767 assert_eq!(m["wall_max_ms"], 9.0);
768 assert_eq!(m["wall_mean_ms"], 5.0);
769 assert!((m["wall_stddev_ms"] - 2.138_089_935).abs() < 1e-6);
771 assert_eq!(stats(&[3.0])["wall_stddev_ms"], 0.0);
772 }
773
774 #[cfg(unix)]
776 #[test]
777 fn a_failing_subject_does_not_stop_the_others() {
778 let mk = |name: &str, cmd: &[&str]| Subject {
779 name: name.into(),
780 cmd: cmd.iter().map(|s| s.to_string()).collect(),
781 prepare: None,
782 dir: None,
783 env: BTreeMap::new(),
784 runs: Runs::Fixed(4),
785 auto: AutoRuns {
786 budget: Duration::from_secs(30),
787 min: 5,
788 max: 50,
789 },
790 warmup: 1,
791 counters: false,
792 };
793 let res = interleaved(
794 &[mk("ok", &["true"]), mk("bad", &["false"])],
795 5,
796 &Settings::default(),
797 &mut Quiet,
798 );
799 assert_eq!(res[0].as_ref().unwrap().len(), 4);
800 assert!(format!("{:#}", res[1].as_ref().unwrap_err()).contains("exited with"));
801 }
802
803 #[cfg(unix)]
805 #[test]
806 fn a_failing_prepare_is_reported_as_prepare() {
807 let res = interleaved(
808 &[Subject {
809 name: "x".into(),
810 cmd: vec!["true".into()],
811 prepare: Some(vec![
812 "/bin/sh".into(),
813 "-c".into(),
814 "echo nope >&2; exit 3".into(),
815 ]),
816 dir: None,
817 env: BTreeMap::new(),
818 runs: Runs::Fixed(1),
819 auto: AutoRuns {
820 budget: Duration::from_secs(30),
821 min: 5,
822 max: 50,
823 },
824 warmup: 0,
825 counters: false,
826 }],
827 0,
828 &Settings::default(),
829 &mut Quiet,
830 );
831 let msg = format!("{:#}", res[0].as_ref().unwrap_err());
832 assert!(msg.contains("prepare") && msg.contains("nope"), "{msg}");
833 }
834
835 #[derive(Default)]
837 struct Log {
838 plans: Vec<Vec<u64>>,
839 finished: Vec<usize>,
840 }
841 impl Observer for Log {
842 fn planned(&mut self, remaining: &[u64]) {
843 self.plans.push(remaining.to_vec());
844 }
845 fn finished(&mut self, subject: usize, _: Duration) {
846 self.finished.push(subject);
847 }
848 }
849
850 #[cfg(unix)]
854 #[test]
855 fn auto_runs_give_a_slow_subject_the_floor_and_a_fast_one_more() {
856 let mk = |name: &str, secs: &str, warmup: u32| Subject {
857 name: name.into(),
858 cmd: vec!["sleep".into(), secs.into()],
859 prepare: None,
860 dir: None,
861 env: BTreeMap::new(),
862 runs: Runs::Auto,
863 auto: AutoRuns {
864 budget: Duration::from_millis(400),
865 min: 2,
866 max: 6,
867 },
868 warmup,
869 counters: false,
870 };
871 let mut log = Log::default();
872 let res = interleaved(
874 &[mk("fast", "0.02", 1), mk("slow", "0.3", 0)],
875 9,
876 &Settings::default(),
877 &mut log,
878 );
879 let fast = res[0].as_ref().unwrap().len();
880 let slow = res[1].as_ref().unwrap().len();
881 assert_eq!(slow, 2, "0.4s budget / 0.3s sample is below the floor");
882 assert!(fast > slow && fast <= 6, "fast got {fast}");
883 assert_eq!(log.plans[0], [1 + 2, 2]);
885 assert_eq!(log.plans.len(), 2);
886 assert_eq!(log.finished.len(), 1 + fast + slow);
887 }
888}