Skip to main content

tak_cli/
config.rs

1//! `tak.toml` — declared benchmarks.
2//!
3//! Named after the tool rather than after its current contents. It already
4//! holds more than a command list in spirit, and gates, runner classes and
5//! competitor definitions all belong here too; `bench.toml` would be misnamed
6//! the moment the first of those lands.
7//!
8//! The point of declaring benchmarks is that CI and a laptop run the same
9//! thing. A command line in a workflow file drifts from the one people use
10//! locally, and the numbers stop being comparable without anyone noticing.
11
12use anyhow::{Context, Result, bail};
13use serde::Deserialize;
14use std::collections::BTreeMap;
15use std::path::{Path, PathBuf};
16
17pub const FILE_NAME: &str = "tak.toml";
18
19/// Defaults chosen to match `tak run`'s, so moving a command into `tak.toml`
20/// does not silently change what it measures.
21pub const DEFAULT_RUNS: u32 = 20;
22pub const DEFAULT_WARMUP: u32 = 3;
23
24#[derive(Debug, Deserialize)]
25pub struct Config {
26    /// Benchmarks by name. A BTreeMap so runs are ordered and reproducible
27    /// rather than following the file's incidental key order.
28    ///
29    /// Settings tables — `[env]`, `[gate]`, `[report]`, `[runner]` — live in
30    /// the same file but are not deserialized here: the settings registry
31    /// declares their dotted keys, and `settings::TakConfigLayer` reads exactly
32    /// those, so this type never has to be kept in step with it.
33    #[serde(default)]
34    pub bench: BTreeMap<String, Bench>,
35}
36
37#[derive(Debug, Deserialize)]
38pub struct Bench {
39    /// The command, for a benchmark of one program. Mutually exclusive with
40    /// `subject`, which declares several programs measured against each other.
41    #[serde(default)]
42    cmd: Option<Cmd>,
43    pub runs: Option<u32>,
44    pub warmup: Option<u32>,
45    /// Untimed command run before every sample. On a multi-subject benchmark
46    /// this is the default for subjects that do not declare their own.
47    #[serde(default)]
48    prepare: Option<Cmd>,
49    /// Directory to run in, relative to `tak.toml`.
50    #[serde(default)]
51    dir: Option<PathBuf>,
52    /// Variables set for the command. Subjects inherit these and may override
53    /// individual keys.
54    #[serde(default)]
55    env: BTreeMap<String, String>,
56    /// Programs measured against each other, by name. The name is what their
57    /// measurements are recorded under (`Record::tool`). A BTreeMap for the
58    /// same reason `Config::bench` is one.
59    #[serde(default)]
60    subject: BTreeMap<String, SubjectDecl>,
61}
62
63/// One program in a multi-subject benchmark, as written in `tak.toml`.
64#[derive(Debug, Deserialize)]
65pub struct SubjectDecl {
66    cmd: Cmd,
67    #[serde(default)]
68    prepare: Option<Cmd>,
69    #[serde(default)]
70    dir: Option<PathBuf>,
71    #[serde(default)]
72    env: BTreeMap<String, String>,
73    runs: Option<u32>,
74    warmup: Option<u32>,
75    /// Opt in to instruction counting. Off by default because a
76    /// multi-subject benchmark usually compares against other people's
77    /// programs, whose instruction counts are not this project's to gate on:
78    /// a competitor's upgrade would fail the gate.
79    #[serde(default)]
80    counters: bool,
81}
82
83/// A command, written either as a list or as a plain string.
84#[derive(Debug, Deserialize)]
85#[serde(untagged)]
86enum Cmd {
87    Argv(Vec<String>),
88    Line(String),
89}
90
91impl Cmd {
92    /// The command as argv.
93    ///
94    /// A string is split on whitespace and nothing else. There is deliberately
95    /// no shell: spawning one adds its own startup cost and variance to every
96    /// sample, which for commands in the 10ms range is a large fraction of the
97    /// measurement. Anything needing a pipe or a glob should be a list whose
98    /// first element is the interpreter.
99    fn argv(&self) -> Result<Vec<String>> {
100        let v = match self {
101            Cmd::Argv(v) => v.clone(),
102            Cmd::Line(s) => s.split_whitespace().map(str::to_string).collect(),
103        };
104        if v.is_empty() {
105            bail!("empty command");
106        }
107        Ok(v)
108    }
109}
110
111/// The name a single-command benchmark records under. `compare` renders this
112/// tool as the bare benchmark name.
113pub const SELF_TOOL: &str = "self";
114
115/// A subject with every default applied, ready to measure.
116#[derive(Debug, Clone, PartialEq)]
117pub struct Subject {
118    /// Recorded as `Record::tool`.
119    pub name: String,
120    pub cmd: Vec<String>,
121    pub prepare: Option<Vec<String>>,
122    /// Relative to `tak.toml`; the caller resolves it.
123    pub dir: Option<PathBuf>,
124    pub env: BTreeMap<String, String>,
125    pub runs: u32,
126    pub warmup: u32,
127    pub counters: bool,
128}
129
130impl Subject {
131    /// Resolve paths against `root`, the directory holding `tak.toml`.
132    ///
133    /// `dir` becomes the working directory, but a relative program path — one
134    /// containing a `/`, like `./target/release/mycli` — is resolved against
135    /// `root`, not `dir`. Otherwise giving a subject a fixture directory would
136    /// make the project's own binary unfindable. A bare name is left for PATH
137    /// lookup, and arguments are never touched.
138    pub fn anchor(&mut self, root: &Path) {
139        let program = |argv: &mut Vec<String>| {
140            if let Some(p) = argv.first_mut()
141                && p.contains('/')
142                && Path::new(p.as_str()).is_relative()
143            {
144                *p = root.join(p.as_str()).to_string_lossy().into_owned();
145            }
146        };
147        program(&mut self.cmd);
148        if let Some(prepare) = &mut self.prepare {
149            program(prepare);
150        }
151        self.dir = Some(match &self.dir {
152            Some(d) => root.join(d),
153            None => root.to_path_buf(),
154        });
155    }
156}
157
158impl Bench {
159    /// Whether this benchmark compares several programs rather than measuring
160    /// one.
161    pub fn is_multi(&self) -> bool {
162        !self.subject.is_empty()
163    }
164
165    /// Every subject with the benchmark's defaults applied.
166    ///
167    /// A single-command benchmark is one subject named [`SELF_TOOL`] with
168    /// counters on, which is exactly what it measured before subjects existed.
169    pub fn subjects(&self) -> Result<Vec<Subject>> {
170        match (&self.cmd, self.subject.is_empty()) {
171            (Some(_), false) => bail!("declares both `cmd` and `subject`; use one or the other"),
172            (None, true) => bail!("has no command"),
173            (Some(cmd), true) => Ok(vec![Subject {
174                name: SELF_TOOL.to_string(),
175                cmd: cmd.argv()?,
176                prepare: self.prepare.as_ref().map(Cmd::argv).transpose()?,
177                dir: self.dir.clone(),
178                env: self.env.clone(),
179                runs: self.runs(),
180                warmup: self.warmup(),
181                counters: true,
182            }]),
183            (None, false) => self
184                .subject
185                .iter()
186                .map(|(name, s)| {
187                    let resolve = || -> Result<Subject> {
188                        // A subject's own prepare replaces the benchmark's rather
189                        // than running after it: the two usually reset the same
190                        // state, and running both would double the untimed cost.
191                        let prepare = s.prepare.as_ref().or(self.prepare.as_ref());
192                        let mut env = self.env.clone();
193                        env.extend(s.env.clone());
194                        Ok(Subject {
195                            name: name.clone(),
196                            cmd: s.cmd.argv()?,
197                            prepare: prepare.map(Cmd::argv).transpose()?,
198                            dir: s.dir.clone().or_else(|| self.dir.clone()),
199                            env,
200                            runs: s.runs.unwrap_or_else(|| self.runs()),
201                            warmup: s.warmup.unwrap_or_else(|| self.warmup()),
202                            counters: s.counters,
203                        })
204                    };
205                    resolve().with_context(|| format!("subject `{name}`"))
206                })
207                .collect(),
208        }
209    }
210
211    pub fn runs(&self) -> u32 {
212        self.runs.unwrap_or(DEFAULT_RUNS)
213    }
214
215    pub fn warmup(&self) -> u32 {
216        self.warmup.unwrap_or(DEFAULT_WARMUP)
217    }
218}
219
220impl Config {
221    pub fn parse(text: &str) -> Result<Self> {
222        let cfg: Config = toml::from_str(text).context("could not parse tak.toml")?;
223        // Every declared benchmark is validated up front rather than failing
224        // partway through a run that has already spent minutes measuring.
225        for (name, b) in &cfg.bench {
226            let subjects = b
227                .subjects()
228                .with_context(|| format!("benchmark `{name}`"))?;
229            for s in &subjects {
230                // Zero runs leaves nothing to report; catching it here names
231                // the benchmark instead of failing after the others ran.
232                if s.runs == 0 {
233                    bail!("benchmark `{name}`: runs must be at least 1");
234                }
235                if s.name.trim().is_empty() {
236                    bail!("benchmark `{name}`: a subject needs a name");
237                }
238                // `self` is the series a single-command benchmark records
239                // under. A subject taking it would be recorded, printed and
240                // exported as that series instead of as itself.
241                if b.is_multi() && s.name == SELF_TOOL {
242                    bail!(
243                        "benchmark `{name}`: `{SELF_TOOL}` is reserved and cannot name a subject"
244                    );
245                }
246            }
247        }
248        Ok(cfg)
249    }
250
251    /// Find and load `tak.toml`, searching upward from `start`.
252    ///
253    /// Walking up means `tak run` behaves the same from a subdirectory as from
254    /// the repository root, which is where people actually are.
255    pub fn find(start: &Path) -> Result<Option<(PathBuf, Self)>> {
256        for dir in start.ancestors() {
257            let path = dir.join(FILE_NAME);
258            if path.is_file() {
259                let text = std::fs::read_to_string(&path)
260                    .with_context(|| format!("could not read {}", path.display()))?;
261                let cfg = Self::parse(&text).with_context(|| format!("in {}", path.display()))?;
262                return Ok(Some((path, cfg)));
263            }
264        }
265        Ok(None)
266    }
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272
273    /// The single subject of a one-command benchmark.
274    fn only(c: &Config, bench: &str) -> Subject {
275        let mut s = c.bench[bench].subjects().unwrap();
276        assert_eq!(s.len(), 1);
277        s.remove(0)
278    }
279
280    #[test]
281    fn a_command_may_be_a_list_or_a_string() {
282        let c = Config::parse(
283            r#"
284            [bench.a]
285            cmd = ["mycli", "--version"]
286            [bench.b]
287            cmd = "mycli --help"
288            "#,
289        )
290        .unwrap();
291        assert_eq!(only(&c, "a").cmd, ["mycli", "--version"]);
292        assert_eq!(only(&c, "b").cmd, ["mycli", "--help"]);
293    }
294
295    /// A string is split on whitespace and nothing else — no shell means no
296    /// quoting, and pretending otherwise would measure the wrong thing.
297    #[test]
298    fn a_string_command_gets_no_shell_semantics() {
299        let c = Config::parse(
300            r#"[bench.a]
301cmd = "mycli 'two words'""#,
302        )
303        .unwrap();
304        assert_eq!(only(&c, "a").cmd, ["mycli", "'two", "words'"]);
305    }
306
307    #[test]
308    fn defaults_match_the_cli() {
309        let c = Config::parse("[bench.a]\ncmd = \"x\"").unwrap();
310        assert_eq!(c.bench["a"].runs(), DEFAULT_RUNS);
311        assert_eq!(c.bench["a"].warmup(), DEFAULT_WARMUP);
312    }
313
314    #[test]
315    fn per_benchmark_overrides_win() {
316        let c = Config::parse("[bench.a]\ncmd = \"x\"\nruns = 5\nwarmup = 1").unwrap();
317        assert_eq!(c.bench["a"].runs(), 5);
318        assert_eq!(c.bench["a"].warmup(), 1);
319    }
320
321    /// Validation happens at load, not partway through a run that has already
322    /// spent minutes measuring.
323    #[test]
324    fn an_empty_command_is_rejected_at_parse_time() {
325        let err = Config::parse("[bench.a]\ncmd = []").unwrap_err();
326        assert!(format!("{err:#}").contains('a'), "{err:#}");
327    }
328
329    #[test]
330    fn benchmarks_run_in_a_stable_order() {
331        let c = Config::parse("[bench.zebra]\ncmd = \"z\"\n[bench.alpha]\ncmd = \"a\"").unwrap();
332        assert_eq!(c.bench.keys().collect::<Vec<_>>(), ["alpha", "zebra"]);
333    }
334
335    #[test]
336    fn an_empty_file_declares_nothing() {
337        assert!(Config::parse("").unwrap().bench.is_empty());
338    }
339
340    #[test]
341    fn find_walks_up_from_a_subdirectory() {
342        let root = std::env::temp_dir().join(format!("tak-cfg-{}", std::process::id()));
343        let nested = root.join("a").join("b");
344        std::fs::create_dir_all(&nested).unwrap();
345        std::fs::write(root.join(FILE_NAME), "[bench.x]\ncmd = \"true\"").unwrap();
346
347        let (path, cfg) = Config::find(&nested).unwrap().expect("should find it");
348        assert_eq!(path, root.join(FILE_NAME));
349        assert!(cfg.bench.contains_key("x"));
350
351        std::fs::remove_dir_all(&root).ok();
352    }
353
354    /// A single-command benchmark keeps measuring what it did before subjects
355    /// existed: one series under `self`, with instruction counts.
356    #[test]
357    fn a_single_command_is_one_self_subject_with_counters() {
358        let c = Config::parse("[bench.a]\ncmd = \"x\"").unwrap();
359        let s = only(&c, "a");
360        assert_eq!(s.name, SELF_TOOL);
361        assert!(s.counters);
362        assert!(!c.bench["a"].is_multi());
363    }
364
365    #[test]
366    fn subjects_inherit_the_benchmark_defaults_and_may_override_them() {
367        let c = Config::parse(
368            r#"
369            [bench.install]
370            runs = 6
371            warmup = 2
372            prepare = ["rm", "-rf", "node_modules"]
373            dir = "fixture"
374            env = { CI = "1", HOME = "/tmp/shared" }
375
376            [bench.install.subject.aube]
377            cmd = "aube install"
378            env = { HOME = "/tmp/aube" }
379
380            [bench.install.subject.pnpm]
381            cmd = ["pnpm", "install"]
382            prepare = "rm -rf node_modules pnpm-lock.yaml"
383            dir = "fixture-pnpm"
384            runs = 3
385            warmup = 0
386            counters = true
387            "#,
388        )
389        .unwrap();
390        let b = &c.bench["install"];
391        assert!(b.is_multi());
392        let s = b.subjects().unwrap();
393        // BTreeMap order, not file order.
394        assert_eq!(s[0].name, "aube");
395        assert_eq!(s[1].name, "pnpm");
396
397        assert_eq!(s[0].cmd, ["aube", "install"]);
398        assert_eq!(
399            s[0].prepare.as_deref().unwrap(),
400            ["rm", "-rf", "node_modules"]
401        );
402        assert_eq!(s[0].dir.as_deref(), Some(Path::new("fixture")));
403        assert_eq!(s[0].env["CI"], "1");
404        assert_eq!(s[0].env["HOME"], "/tmp/aube");
405        assert_eq!((s[0].runs, s[0].warmup), (6, 2));
406        assert!(!s[0].counters, "named subjects count only when asked to");
407
408        assert_eq!(
409            s[1].prepare.as_deref().unwrap(),
410            ["rm", "-rf", "node_modules", "pnpm-lock.yaml"]
411        );
412        assert_eq!(s[1].dir.as_deref(), Some(Path::new("fixture-pnpm")));
413        assert_eq!(s[1].env["HOME"], "/tmp/shared");
414        assert_eq!((s[1].runs, s[1].warmup), (3, 0));
415        assert!(s[1].counters);
416    }
417
418    /// Declaring both would leave it ambiguous which is measured.
419    #[test]
420    fn cmd_and_subjects_together_are_rejected() {
421        let err =
422            Config::parse("[bench.a]\ncmd = \"x\"\n[bench.a.subject.b]\ncmd = \"y\"").unwrap_err();
423        assert!(format!("{err:#}").contains("both"), "{err:#}");
424    }
425
426    #[test]
427    fn a_benchmark_with_neither_is_rejected() {
428        let err = Config::parse("[bench.a]\nruns = 3").unwrap_err();
429        assert!(format!("{err:#}").contains("no command"), "{err:#}");
430    }
431
432    /// The error names the subject, not just the benchmark, so a large
433    /// comparison does not have to be bisected by hand.
434    #[test]
435    fn an_empty_subject_command_is_rejected_by_name() {
436        let err =
437            Config::parse("[bench.a.subject.good]\ncmd = \"x\"\n[bench.a.subject.bad]\ncmd = []")
438                .unwrap_err();
439        let msg = format!("{err:#}");
440        assert!(msg.contains("`a`") && msg.contains("`bad`"), "{msg}");
441    }
442
443    #[test]
444    fn an_empty_prepare_is_rejected() {
445        assert!(Config::parse("[bench.a]\ncmd = \"x\"\nprepare = []").is_err());
446    }
447
448    #[test]
449    fn zero_runs_is_rejected_at_parse_time() {
450        assert!(Config::parse("[bench.a.subject.b]\ncmd = \"x\"\nruns = 0").is_err());
451    }
452
453    #[test]
454    fn self_is_reserved_for_single_command_benchmarks() {
455        let err = Config::parse("[bench.a.subject.self]\ncmd = \"x\"").unwrap_err();
456        assert!(format!("{err:#}").contains("reserved"), "{err:#}");
457    }
458
459    /// `dir` sets where a command runs, not where a relative program path is
460    /// found: `./target/release/x` still means the one next to `tak.toml`.
461    #[test]
462    fn a_relative_program_path_is_anchored_at_the_config() {
463        let root = Path::new("/repo");
464        let mut s = Config::parse(
465            "[bench.a]\ncmd = [\"./target/x\", \"./arg\"]\nprepare = \"bin/reset\"\ndir = \"fix\"",
466        )
467        .unwrap()
468        .bench["a"]
469            .subjects()
470            .unwrap()
471            .remove(0);
472        s.anchor(root);
473        assert_eq!(
474            s.cmd,
475            ["/repo/./target/x", "./arg"],
476            "arguments are left alone"
477        );
478        assert_eq!(s.prepare.unwrap(), ["/repo/bin/reset"]);
479        assert_eq!(s.dir.unwrap(), Path::new("/repo/fix"));
480
481        let mut bare = Config::parse("[bench.a]\ncmd = \"mycli --version\"")
482            .unwrap()
483            .bench["a"]
484            .subjects()
485            .unwrap()
486            .remove(0);
487        bare.anchor(root);
488        assert_eq!(
489            bare.cmd[0], "mycli",
490            "a bare name is still looked up on PATH"
491        );
492        assert_eq!(bare.dir.unwrap(), Path::new("/repo"));
493    }
494}