1use anyhow::{Context, Result, bail};
13use serde::Deserialize;
14use std::collections::BTreeMap;
15use std::path::{Path, PathBuf};
16use std::time::Duration;
17
18pub const FILE_NAME: &str = "tak.toml";
19
20pub const DEFAULT_RUNS: u32 = 20;
23pub const DEFAULT_WARMUP: u32 = 3;
24
25pub const DEFAULT_BUDGET: Duration = Duration::from_secs(30);
31pub const DEFAULT_MIN_RUNS: u32 = 5;
32pub const DEFAULT_MAX_RUNS: u32 = 50;
33
34#[derive(Debug, Deserialize)]
35pub struct Config {
36 #[serde(default)]
44 pub bench: BTreeMap<String, Bench>,
45}
46
47#[derive(Debug, Deserialize)]
48pub struct Bench {
49 #[serde(default)]
52 cmd: Option<Cmd>,
53 pub runs: Option<RunsDecl>,
55 pub warmup: Option<u32>,
56 pub budget: Option<String>,
58 pub min_runs: Option<u32>,
60 pub max_runs: Option<u32>,
62 #[serde(default)]
65 prepare: Option<Cmd>,
66 #[serde(default)]
68 dir: Option<PathBuf>,
69 #[serde(default)]
72 env: BTreeMap<String, String>,
73 #[serde(default)]
77 subject: BTreeMap<String, SubjectDecl>,
78}
79
80#[derive(Debug, Deserialize)]
82pub struct SubjectDecl {
83 cmd: Cmd,
84 #[serde(default)]
85 prepare: Option<Cmd>,
86 #[serde(default)]
87 dir: Option<PathBuf>,
88 #[serde(default)]
89 env: BTreeMap<String, String>,
90 runs: Option<RunsDecl>,
91 warmup: Option<u32>,
92 budget: Option<String>,
93 min_runs: Option<u32>,
94 max_runs: Option<u32>,
95 #[serde(default)]
100 counters: bool,
101}
102
103#[derive(Debug, Deserialize)]
105#[serde(untagged)]
106enum Cmd {
107 Argv(Vec<String>),
108 Line(String),
109}
110
111impl Cmd {
112 fn argv(&self) -> Result<Vec<String>> {
120 let v = match self {
121 Cmd::Argv(v) => v.clone(),
122 Cmd::Line(s) => s.split_whitespace().map(str::to_string).collect(),
123 };
124 if v.is_empty() {
125 bail!("empty command");
126 }
127 Ok(v)
128 }
129}
130
131#[derive(Debug, Clone, Deserialize)]
134#[serde(untagged)]
135pub enum RunsDecl {
136 Count(u32),
137 Word(String),
138}
139
140impl RunsDecl {
141 fn resolve(&self) -> Result<Runs> {
142 match self {
143 RunsDecl::Count(n) => Ok(Runs::Fixed(*n)),
144 RunsDecl::Word(w) if w == "auto" => Ok(Runs::Auto),
145 RunsDecl::Word(w) => bail!("runs must be a number or \"auto\", not {w:?}"),
146 }
147 }
148}
149
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
152pub enum Runs {
153 Fixed(u32),
154 Auto,
157}
158
159impl std::str::FromStr for Runs {
160 type Err = anyhow::Error;
161 fn from_str(s: &str) -> Result<Self> {
162 if s == "auto" {
163 return Ok(Runs::Auto);
164 }
165 s.parse()
166 .map(Runs::Fixed)
167 .map_err(|_| anyhow::anyhow!("runs must be a number or \"auto\", not {s:?}"))
168 }
169}
170
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175pub struct AutoRuns {
176 pub budget: Duration,
177 pub min: u32,
178 pub max: u32,
179}
180
181impl AutoRuns {
182 pub fn runs_for(&self, slot: Duration) -> u32 {
185 let fit = if slot.is_zero() {
186 u64::from(self.max)
187 } else {
188 (self.budget.as_secs_f64() / slot.as_secs_f64()) as u64
189 };
190 fit.clamp(u64::from(self.min), u64::from(self.max)) as u32
191 }
192}
193
194pub fn parse_duration(text: &str) -> Result<Duration> {
196 let t = text.trim();
197 let split = t
198 .find(|c: char| !(c.is_ascii_digit() || c == '.'))
199 .unwrap_or(t.len());
200 let (num, unit) = t.split_at(split);
201 let n: f64 = num
202 .parse()
203 .map_err(|_| anyhow::anyhow!("not a duration: {text:?} (try `30s` or `2m`)"))?;
204 let secs = match unit.trim() {
205 "ms" => n / 1000.0,
206 "" | "s" => n,
207 "m" => n * 60.0,
208 "h" => n * 3600.0,
209 _ => bail!("not a duration: {text:?} (units are ms, s, m, h)"),
210 };
211 if !secs.is_finite() || secs <= 0.0 {
212 bail!("a duration must be positive: {text:?}");
213 }
214 Duration::try_from_secs_f64(secs).map_err(|_| anyhow::anyhow!("duration too large: {text:?}"))
217}
218
219pub const SELF_TOOL: &str = "self";
222
223#[derive(Debug, Clone, PartialEq)]
225pub struct Subject {
226 pub name: String,
228 pub cmd: Vec<String>,
229 pub prepare: Option<Vec<String>>,
230 pub dir: Option<PathBuf>,
232 pub env: BTreeMap<String, String>,
233 pub runs: Runs,
234 pub auto: AutoRuns,
236 pub warmup: u32,
237 pub counters: bool,
238}
239
240impl Subject {
241 pub fn anchor(&mut self, root: &Path) {
249 let program = |argv: &mut Vec<String>| {
250 if let Some(p) = argv.first_mut()
251 && p.contains('/')
252 && Path::new(p.as_str()).is_relative()
253 {
254 *p = root.join(p.as_str()).to_string_lossy().into_owned();
255 }
256 };
257 program(&mut self.cmd);
258 if let Some(prepare) = &mut self.prepare {
259 program(prepare);
260 }
261 self.dir = Some(match &self.dir {
262 Some(d) => root.join(d),
263 None => root.to_path_buf(),
264 });
265 }
266}
267
268impl Bench {
269 pub fn is_multi(&self) -> bool {
272 !self.subject.is_empty()
273 }
274
275 pub fn subjects(&self) -> Result<Vec<Subject>> {
280 match (&self.cmd, self.subject.is_empty()) {
281 (Some(_), false) => bail!("declares both `cmd` and `subject`; use one or the other"),
282 (None, true) => bail!("has no command"),
283 (Some(cmd), true) => Ok(vec![Subject {
284 name: SELF_TOOL.to_string(),
285 cmd: cmd.argv()?,
286 prepare: self.prepare.as_ref().map(Cmd::argv).transpose()?,
287 dir: self.dir.clone(),
288 env: self.env.clone(),
289 runs: self.runs()?,
290 auto: self.auto(None, None, None)?,
291 warmup: self.warmup(),
292 counters: true,
293 }]),
294 (None, false) => self
295 .subject
296 .iter()
297 .map(|(name, s)| {
298 let resolve = || -> Result<Subject> {
299 let prepare = s.prepare.as_ref().or(self.prepare.as_ref());
303 let mut env = self.env.clone();
304 env.extend(s.env.clone());
305 Ok(Subject {
306 name: name.clone(),
307 cmd: s.cmd.argv()?,
308 prepare: prepare.map(Cmd::argv).transpose()?,
309 dir: s.dir.clone().or_else(|| self.dir.clone()),
310 env,
311 runs: match &s.runs {
312 Some(r) => r.resolve()?,
313 None => self.runs()?,
314 },
315 auto: self.auto(s.budget.as_deref(), s.min_runs, s.max_runs)?,
316 warmup: s.warmup.unwrap_or_else(|| self.warmup()),
317 counters: s.counters,
318 })
319 };
320 resolve().with_context(|| format!("subject `{name}`"))
321 })
322 .collect(),
323 }
324 }
325
326 pub fn runs(&self) -> Result<Runs> {
327 self.runs
328 .as_ref()
329 .map_or(Ok(Runs::Fixed(DEFAULT_RUNS)), RunsDecl::resolve)
330 }
331
332 fn auto(&self, budget: Option<&str>, min: Option<u32>, max: Option<u32>) -> Result<AutoRuns> {
335 let budget = match budget.or(self.budget.as_deref()) {
336 Some(b) => parse_duration(b).context("budget")?,
337 None => DEFAULT_BUDGET,
338 };
339 let a = AutoRuns {
340 budget,
341 min: min.or(self.min_runs).unwrap_or(DEFAULT_MIN_RUNS),
342 max: max.or(self.max_runs).unwrap_or(DEFAULT_MAX_RUNS),
343 };
344 if a.min == 0 {
345 bail!("min_runs must be at least 1");
346 }
347 if a.min > a.max {
348 bail!("min_runs ({}) is more than max_runs ({})", a.min, a.max);
349 }
350 Ok(a)
351 }
352
353 pub fn warmup(&self) -> u32 {
354 self.warmup.unwrap_or(DEFAULT_WARMUP)
355 }
356}
357
358impl Config {
359 pub fn parse(text: &str) -> Result<Self> {
360 let cfg: Config = toml::from_str(text).context("could not parse tak.toml")?;
361 for (name, b) in &cfg.bench {
364 let subjects = b
365 .subjects()
366 .with_context(|| format!("benchmark `{name}`"))?;
367 for s in &subjects {
368 if s.runs == Runs::Fixed(0) {
371 bail!("benchmark `{name}`: runs must be at least 1");
372 }
373 if s.name.trim().is_empty() {
374 bail!("benchmark `{name}`: a subject needs a name");
375 }
376 if b.is_multi() && s.name == SELF_TOOL {
380 bail!(
381 "benchmark `{name}`: `{SELF_TOOL}` is reserved and cannot name a subject"
382 );
383 }
384 }
385 }
386 Ok(cfg)
387 }
388
389 pub fn find(start: &Path) -> Result<Option<(PathBuf, Self)>> {
394 for dir in start.ancestors() {
395 let path = dir.join(FILE_NAME);
396 if path.is_file() {
397 let text = std::fs::read_to_string(&path)
398 .with_context(|| format!("could not read {}", path.display()))?;
399 let cfg = Self::parse(&text).with_context(|| format!("in {}", path.display()))?;
400 return Ok(Some((path, cfg)));
401 }
402 }
403 Ok(None)
404 }
405}
406
407#[cfg(test)]
408mod tests {
409 use super::*;
410
411 fn only(c: &Config, bench: &str) -> Subject {
413 let mut s = c.bench[bench].subjects().unwrap();
414 assert_eq!(s.len(), 1);
415 s.remove(0)
416 }
417
418 #[test]
419 fn a_command_may_be_a_list_or_a_string() {
420 let c = Config::parse(
421 r#"
422 [bench.a]
423 cmd = ["mycli", "--version"]
424 [bench.b]
425 cmd = "mycli --help"
426 "#,
427 )
428 .unwrap();
429 assert_eq!(only(&c, "a").cmd, ["mycli", "--version"]);
430 assert_eq!(only(&c, "b").cmd, ["mycli", "--help"]);
431 }
432
433 #[test]
436 fn a_string_command_gets_no_shell_semantics() {
437 let c = Config::parse(
438 r#"[bench.a]
439cmd = "mycli 'two words'""#,
440 )
441 .unwrap();
442 assert_eq!(only(&c, "a").cmd, ["mycli", "'two", "words'"]);
443 }
444
445 #[test]
446 fn defaults_match_the_cli() {
447 let c = Config::parse("[bench.a]\ncmd = \"x\"").unwrap();
448 assert_eq!(c.bench["a"].runs().unwrap(), Runs::Fixed(DEFAULT_RUNS));
449 assert_eq!(c.bench["a"].warmup(), DEFAULT_WARMUP);
450 }
451
452 #[test]
453 fn per_benchmark_overrides_win() {
454 let c = Config::parse("[bench.a]\ncmd = \"x\"\nruns = 5\nwarmup = 1").unwrap();
455 assert_eq!(c.bench["a"].runs().unwrap(), Runs::Fixed(5));
456 assert_eq!(c.bench["a"].warmup(), 1);
457 }
458
459 #[test]
462 fn an_empty_command_is_rejected_at_parse_time() {
463 let err = Config::parse("[bench.a]\ncmd = []").unwrap_err();
464 assert!(format!("{err:#}").contains('a'), "{err:#}");
465 }
466
467 #[test]
468 fn benchmarks_run_in_a_stable_order() {
469 let c = Config::parse("[bench.zebra]\ncmd = \"z\"\n[bench.alpha]\ncmd = \"a\"").unwrap();
470 assert_eq!(c.bench.keys().collect::<Vec<_>>(), ["alpha", "zebra"]);
471 }
472
473 #[test]
474 fn an_empty_file_declares_nothing() {
475 assert!(Config::parse("").unwrap().bench.is_empty());
476 }
477
478 #[test]
479 fn find_walks_up_from_a_subdirectory() {
480 let root = std::env::temp_dir().join(format!("tak-cfg-{}", std::process::id()));
481 let nested = root.join("a").join("b");
482 std::fs::create_dir_all(&nested).unwrap();
483 std::fs::write(root.join(FILE_NAME), "[bench.x]\ncmd = \"true\"").unwrap();
484
485 let (path, cfg) = Config::find(&nested).unwrap().expect("should find it");
486 assert_eq!(path, root.join(FILE_NAME));
487 assert!(cfg.bench.contains_key("x"));
488
489 std::fs::remove_dir_all(&root).ok();
490 }
491
492 #[test]
495 fn a_single_command_is_one_self_subject_with_counters() {
496 let c = Config::parse("[bench.a]\ncmd = \"x\"").unwrap();
497 let s = only(&c, "a");
498 assert_eq!(s.name, SELF_TOOL);
499 assert!(s.counters);
500 assert!(!c.bench["a"].is_multi());
501 }
502
503 #[test]
504 fn subjects_inherit_the_benchmark_defaults_and_may_override_them() {
505 let c = Config::parse(
506 r#"
507 [bench.install]
508 runs = 6
509 warmup = 2
510 prepare = ["rm", "-rf", "node_modules"]
511 dir = "fixture"
512 env = { CI = "1", HOME = "/tmp/shared" }
513
514 [bench.install.subject.aube]
515 cmd = "aube install"
516 env = { HOME = "/tmp/aube" }
517
518 [bench.install.subject.pnpm]
519 cmd = ["pnpm", "install"]
520 prepare = "rm -rf node_modules pnpm-lock.yaml"
521 dir = "fixture-pnpm"
522 runs = 3
523 warmup = 0
524 counters = true
525 "#,
526 )
527 .unwrap();
528 let b = &c.bench["install"];
529 assert!(b.is_multi());
530 let s = b.subjects().unwrap();
531 assert_eq!(s[0].name, "aube");
533 assert_eq!(s[1].name, "pnpm");
534
535 assert_eq!(s[0].cmd, ["aube", "install"]);
536 assert_eq!(
537 s[0].prepare.as_deref().unwrap(),
538 ["rm", "-rf", "node_modules"]
539 );
540 assert_eq!(s[0].dir.as_deref(), Some(Path::new("fixture")));
541 assert_eq!(s[0].env["CI"], "1");
542 assert_eq!(s[0].env["HOME"], "/tmp/aube");
543 assert_eq!((s[0].runs, s[0].warmup), (Runs::Fixed(6), 2));
544 assert!(!s[0].counters, "named subjects count only when asked to");
545
546 assert_eq!(
547 s[1].prepare.as_deref().unwrap(),
548 ["rm", "-rf", "node_modules", "pnpm-lock.yaml"]
549 );
550 assert_eq!(s[1].dir.as_deref(), Some(Path::new("fixture-pnpm")));
551 assert_eq!(s[1].env["HOME"], "/tmp/shared");
552 assert_eq!((s[1].runs, s[1].warmup), (Runs::Fixed(3), 0));
553 assert!(s[1].counters);
554 }
555
556 #[test]
558 fn cmd_and_subjects_together_are_rejected() {
559 let err =
560 Config::parse("[bench.a]\ncmd = \"x\"\n[bench.a.subject.b]\ncmd = \"y\"").unwrap_err();
561 assert!(format!("{err:#}").contains("both"), "{err:#}");
562 }
563
564 #[test]
565 fn a_benchmark_with_neither_is_rejected() {
566 let err = Config::parse("[bench.a]\nruns = 3").unwrap_err();
567 assert!(format!("{err:#}").contains("no command"), "{err:#}");
568 }
569
570 #[test]
573 fn an_empty_subject_command_is_rejected_by_name() {
574 let err =
575 Config::parse("[bench.a.subject.good]\ncmd = \"x\"\n[bench.a.subject.bad]\ncmd = []")
576 .unwrap_err();
577 let msg = format!("{err:#}");
578 assert!(msg.contains("`a`") && msg.contains("`bad`"), "{msg}");
579 }
580
581 #[test]
582 fn an_empty_prepare_is_rejected() {
583 assert!(Config::parse("[bench.a]\ncmd = \"x\"\nprepare = []").is_err());
584 }
585
586 #[test]
587 fn zero_runs_is_rejected_at_parse_time() {
588 assert!(Config::parse("[bench.a.subject.b]\ncmd = \"x\"\nruns = 0").is_err());
589 }
590
591 #[test]
592 fn self_is_reserved_for_single_command_benchmarks() {
593 let err = Config::parse("[bench.a.subject.self]\ncmd = \"x\"").unwrap_err();
594 assert!(format!("{err:#}").contains("reserved"), "{err:#}");
595 }
596
597 #[test]
600 fn a_relative_program_path_is_anchored_at_the_config() {
601 let root = Path::new("/repo");
602 let mut s = Config::parse(
603 "[bench.a]\ncmd = [\"./target/x\", \"./arg\"]\nprepare = \"bin/reset\"\ndir = \"fix\"",
604 )
605 .unwrap()
606 .bench["a"]
607 .subjects()
608 .unwrap()
609 .remove(0);
610 s.anchor(root);
611 assert_eq!(
612 s.cmd,
613 ["/repo/./target/x", "./arg"],
614 "arguments are left alone"
615 );
616 assert_eq!(s.prepare.unwrap(), ["/repo/bin/reset"]);
617 assert_eq!(s.dir.unwrap(), Path::new("/repo/fix"));
618
619 let mut bare = Config::parse("[bench.a]\ncmd = \"mycli --version\"")
620 .unwrap()
621 .bench["a"]
622 .subjects()
623 .unwrap()
624 .remove(0);
625 bare.anchor(root);
626 assert_eq!(
627 bare.cmd[0], "mycli",
628 "a bare name is still looked up on PATH"
629 );
630 assert_eq!(bare.dir.unwrap(), Path::new("/repo"));
631 }
632
633 #[test]
634 fn runs_may_be_auto_with_limits_inherited_and_overridden() {
635 let c = Config::parse(
636 r#"
637 [bench.b]
638 runs = "auto"
639 budget = "2m"
640 min_runs = 3
641
642 [bench.b.subject.fast]
643 cmd = "x"
644
645 [bench.b.subject.slow]
646 cmd = "y"
647 max_runs = 10
648 budget = "500ms"
649
650 [bench.b.subject.pinned]
651 cmd = "z"
652 runs = 7
653 "#,
654 )
655 .unwrap();
656 let s = c.bench["b"].subjects().unwrap();
657 let by = |n: &str| s.iter().find(|x| x.name == n).unwrap();
658 assert_eq!(by("fast").runs, Runs::Auto);
659 assert_eq!(
660 by("fast").auto,
661 AutoRuns {
662 budget: Duration::from_secs(120),
663 min: 3,
664 max: DEFAULT_MAX_RUNS
665 }
666 );
667 assert_eq!(by("slow").auto.budget, Duration::from_millis(500));
668 assert_eq!((by("slow").auto.min, by("slow").auto.max), (3, 10));
669 assert_eq!(by("pinned").runs, Runs::Fixed(7));
670 }
671
672 #[test]
673 fn bad_auto_settings_are_rejected_at_parse_time() {
674 for bad in [
675 "runs = \"lots\"",
676 "runs = \"auto\"\nbudget = \"soon\"",
677 "runs = \"auto\"\nbudget = \"0s\"",
678 "runs = \"auto\"\nmin_runs = 0",
679 "runs = \"auto\"\nmin_runs = 9\nmax_runs = 3",
680 ] {
681 let toml = format!("[bench.a]\ncmd = \"x\"\n{bad}");
682 assert!(Config::parse(&toml).is_err(), "accepted: {bad}");
683 }
684 }
685
686 #[test]
687 fn durations_take_the_common_units() {
688 assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
689 assert_eq!(parse_duration("30s").unwrap(), Duration::from_secs(30));
690 assert_eq!(parse_duration("45").unwrap(), Duration::from_secs(45));
691 assert_eq!(parse_duration("2m").unwrap(), Duration::from_secs(120));
692 assert_eq!(parse_duration("1.5h").unwrap(), Duration::from_secs(5400));
693 assert!(
694 parse_duration("1e300h").is_err(),
695 "too large is an error, not a panic"
696 );
697 }
698
699 #[test]
702 fn auto_runs_fit_the_budget_within_the_limits() {
703 let a = AutoRuns {
704 budget: Duration::from_secs(30),
705 min: 5,
706 max: 50,
707 };
708 assert_eq!(a.runs_for(Duration::from_millis(1700)), 17);
709 assert_eq!(a.runs_for(Duration::from_secs(21)), 5);
710 assert_eq!(a.runs_for(Duration::from_millis(300)), 50);
711 assert_eq!(a.runs_for(Duration::ZERO), 50);
712 }
713}