tak-cli 0.0.11

Pre-v1 command-line benchmarking and performance tracking
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! `tak.toml` — declared benchmarks.
//!
//! Named after the tool rather than after its current contents. It already
//! holds more than a command list in spirit, and gates, runner classes and
//! competitor definitions all belong here too; `bench.toml` would be misnamed
//! the moment the first of those lands.
//!
//! The point of declaring benchmarks is that CI and a laptop run the same
//! thing. A command line in a workflow file drifts from the one people use
//! locally, and the numbers stop being comparable without anyone noticing.

use anyhow::{Context, Result, bail};
use serde::Deserialize;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

pub const FILE_NAME: &str = "tak.toml";

/// Defaults chosen to match `tak run`'s, so moving a command into `tak.toml`
/// does not silently change what it measures.
pub const DEFAULT_RUNS: u32 = 20;
pub const DEFAULT_WARMUP: u32 = 3;

#[derive(Debug, Deserialize)]
pub struct Config {
    /// Benchmarks by name. A BTreeMap so runs are ordered and reproducible
    /// rather than following the file's incidental key order.
    ///
    /// Settings tables — `[env]`, `[gate]`, `[report]`, `[runner]` — live in
    /// the same file but are not deserialized here: the settings registry
    /// declares their dotted keys, and `settings::TakConfigLayer` reads exactly
    /// those, so this type never has to be kept in step with it.
    #[serde(default)]
    pub bench: BTreeMap<String, Bench>,
}

#[derive(Debug, Deserialize)]
pub struct Bench {
    /// The command, for a benchmark of one program. Mutually exclusive with
    /// `subject`, which declares several programs measured against each other.
    #[serde(default)]
    cmd: Option<Cmd>,
    pub runs: Option<u32>,
    pub warmup: Option<u32>,
    /// Untimed command run before every sample. On a multi-subject benchmark
    /// this is the default for subjects that do not declare their own.
    #[serde(default)]
    prepare: Option<Cmd>,
    /// Directory to run in, relative to `tak.toml`.
    #[serde(default)]
    dir: Option<PathBuf>,
    /// Variables set for the command. Subjects inherit these and may override
    /// individual keys.
    #[serde(default)]
    env: BTreeMap<String, String>,
    /// Programs measured against each other, by name. The name is what their
    /// measurements are recorded under (`Record::tool`). A BTreeMap for the
    /// same reason `Config::bench` is one.
    #[serde(default)]
    subject: BTreeMap<String, SubjectDecl>,
}

/// One program in a multi-subject benchmark, as written in `tak.toml`.
#[derive(Debug, Deserialize)]
pub struct SubjectDecl {
    cmd: Cmd,
    #[serde(default)]
    prepare: Option<Cmd>,
    #[serde(default)]
    dir: Option<PathBuf>,
    #[serde(default)]
    env: BTreeMap<String, String>,
    runs: Option<u32>,
    warmup: Option<u32>,
    /// Opt in to instruction counting. Off by default because a
    /// multi-subject benchmark usually compares against other people's
    /// programs, whose instruction counts are not this project's to gate on:
    /// a competitor's upgrade would fail the gate.
    #[serde(default)]
    counters: bool,
}

/// A command, written either as a list or as a plain string.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum Cmd {
    Argv(Vec<String>),
    Line(String),
}

impl Cmd {
    /// The command as argv.
    ///
    /// A string is split on whitespace and nothing else. There is deliberately
    /// no shell: spawning one adds its own startup cost and variance to every
    /// sample, which for commands in the 10ms range is a large fraction of the
    /// measurement. Anything needing a pipe or a glob should be a list whose
    /// first element is the interpreter.
    fn argv(&self) -> Result<Vec<String>> {
        let v = match self {
            Cmd::Argv(v) => v.clone(),
            Cmd::Line(s) => s.split_whitespace().map(str::to_string).collect(),
        };
        if v.is_empty() {
            bail!("empty command");
        }
        Ok(v)
    }
}

/// The name a single-command benchmark records under. `compare` renders this
/// tool as the bare benchmark name.
pub const SELF_TOOL: &str = "self";

/// A subject with every default applied, ready to measure.
#[derive(Debug, Clone, PartialEq)]
pub struct Subject {
    /// Recorded as `Record::tool`.
    pub name: String,
    pub cmd: Vec<String>,
    pub prepare: Option<Vec<String>>,
    /// Relative to `tak.toml`; the caller resolves it.
    pub dir: Option<PathBuf>,
    pub env: BTreeMap<String, String>,
    pub runs: u32,
    pub warmup: u32,
    pub counters: bool,
}

impl Subject {
    /// Resolve paths against `root`, the directory holding `tak.toml`.
    ///
    /// `dir` becomes the working directory, but a relative program path — one
    /// containing a `/`, like `./target/release/mycli` — is resolved against
    /// `root`, not `dir`. Otherwise giving a subject a fixture directory would
    /// make the project's own binary unfindable. A bare name is left for PATH
    /// lookup, and arguments are never touched.
    pub fn anchor(&mut self, root: &Path) {
        let program = |argv: &mut Vec<String>| {
            if let Some(p) = argv.first_mut()
                && p.contains('/')
                && Path::new(p.as_str()).is_relative()
            {
                *p = root.join(p.as_str()).to_string_lossy().into_owned();
            }
        };
        program(&mut self.cmd);
        if let Some(prepare) = &mut self.prepare {
            program(prepare);
        }
        self.dir = Some(match &self.dir {
            Some(d) => root.join(d),
            None => root.to_path_buf(),
        });
    }
}

impl Bench {
    /// Whether this benchmark compares several programs rather than measuring
    /// one.
    pub fn is_multi(&self) -> bool {
        !self.subject.is_empty()
    }

    /// Every subject with the benchmark's defaults applied.
    ///
    /// A single-command benchmark is one subject named [`SELF_TOOL`] with
    /// counters on, which is exactly what it measured before subjects existed.
    pub fn subjects(&self) -> Result<Vec<Subject>> {
        match (&self.cmd, self.subject.is_empty()) {
            (Some(_), false) => bail!("declares both `cmd` and `subject`; use one or the other"),
            (None, true) => bail!("has no command"),
            (Some(cmd), true) => Ok(vec![Subject {
                name: SELF_TOOL.to_string(),
                cmd: cmd.argv()?,
                prepare: self.prepare.as_ref().map(Cmd::argv).transpose()?,
                dir: self.dir.clone(),
                env: self.env.clone(),
                runs: self.runs(),
                warmup: self.warmup(),
                counters: true,
            }]),
            (None, false) => self
                .subject
                .iter()
                .map(|(name, s)| {
                    let resolve = || -> Result<Subject> {
                        // A subject's own prepare replaces the benchmark's rather
                        // than running after it: the two usually reset the same
                        // state, and running both would double the untimed cost.
                        let prepare = s.prepare.as_ref().or(self.prepare.as_ref());
                        let mut env = self.env.clone();
                        env.extend(s.env.clone());
                        Ok(Subject {
                            name: name.clone(),
                            cmd: s.cmd.argv()?,
                            prepare: prepare.map(Cmd::argv).transpose()?,
                            dir: s.dir.clone().or_else(|| self.dir.clone()),
                            env,
                            runs: s.runs.unwrap_or_else(|| self.runs()),
                            warmup: s.warmup.unwrap_or_else(|| self.warmup()),
                            counters: s.counters,
                        })
                    };
                    resolve().with_context(|| format!("subject `{name}`"))
                })
                .collect(),
        }
    }

    pub fn runs(&self) -> u32 {
        self.runs.unwrap_or(DEFAULT_RUNS)
    }

    pub fn warmup(&self) -> u32 {
        self.warmup.unwrap_or(DEFAULT_WARMUP)
    }
}

impl Config {
    pub fn parse(text: &str) -> Result<Self> {
        let cfg: Config = toml::from_str(text).context("could not parse tak.toml")?;
        // Every declared benchmark is validated up front rather than failing
        // partway through a run that has already spent minutes measuring.
        for (name, b) in &cfg.bench {
            let subjects = b
                .subjects()
                .with_context(|| format!("benchmark `{name}`"))?;
            for s in &subjects {
                // Zero runs leaves nothing to report; catching it here names
                // the benchmark instead of failing after the others ran.
                if s.runs == 0 {
                    bail!("benchmark `{name}`: runs must be at least 1");
                }
                if s.name.trim().is_empty() {
                    bail!("benchmark `{name}`: a subject needs a name");
                }
                // `self` is the series a single-command benchmark records
                // under. A subject taking it would be recorded, printed and
                // exported as that series instead of as itself.
                if b.is_multi() && s.name == SELF_TOOL {
                    bail!(
                        "benchmark `{name}`: `{SELF_TOOL}` is reserved and cannot name a subject"
                    );
                }
            }
        }
        Ok(cfg)
    }

    /// Find and load `tak.toml`, searching upward from `start`.
    ///
    /// Walking up means `tak run` behaves the same from a subdirectory as from
    /// the repository root, which is where people actually are.
    pub fn find(start: &Path) -> Result<Option<(PathBuf, Self)>> {
        for dir in start.ancestors() {
            let path = dir.join(FILE_NAME);
            if path.is_file() {
                let text = std::fs::read_to_string(&path)
                    .with_context(|| format!("could not read {}", path.display()))?;
                let cfg = Self::parse(&text).with_context(|| format!("in {}", path.display()))?;
                return Ok(Some((path, cfg)));
            }
        }
        Ok(None)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The single subject of a one-command benchmark.
    fn only(c: &Config, bench: &str) -> Subject {
        let mut s = c.bench[bench].subjects().unwrap();
        assert_eq!(s.len(), 1);
        s.remove(0)
    }

    #[test]
    fn a_command_may_be_a_list_or_a_string() {
        let c = Config::parse(
            r#"
            [bench.a]
            cmd = ["mycli", "--version"]
            [bench.b]
            cmd = "mycli --help"
            "#,
        )
        .unwrap();
        assert_eq!(only(&c, "a").cmd, ["mycli", "--version"]);
        assert_eq!(only(&c, "b").cmd, ["mycli", "--help"]);
    }

    /// A string is split on whitespace and nothing else — no shell means no
    /// quoting, and pretending otherwise would measure the wrong thing.
    #[test]
    fn a_string_command_gets_no_shell_semantics() {
        let c = Config::parse(
            r#"[bench.a]
cmd = "mycli 'two words'""#,
        )
        .unwrap();
        assert_eq!(only(&c, "a").cmd, ["mycli", "'two", "words'"]);
    }

    #[test]
    fn defaults_match_the_cli() {
        let c = Config::parse("[bench.a]\ncmd = \"x\"").unwrap();
        assert_eq!(c.bench["a"].runs(), DEFAULT_RUNS);
        assert_eq!(c.bench["a"].warmup(), DEFAULT_WARMUP);
    }

    #[test]
    fn per_benchmark_overrides_win() {
        let c = Config::parse("[bench.a]\ncmd = \"x\"\nruns = 5\nwarmup = 1").unwrap();
        assert_eq!(c.bench["a"].runs(), 5);
        assert_eq!(c.bench["a"].warmup(), 1);
    }

    /// Validation happens at load, not partway through a run that has already
    /// spent minutes measuring.
    #[test]
    fn an_empty_command_is_rejected_at_parse_time() {
        let err = Config::parse("[bench.a]\ncmd = []").unwrap_err();
        assert!(format!("{err:#}").contains('a'), "{err:#}");
    }

    #[test]
    fn benchmarks_run_in_a_stable_order() {
        let c = Config::parse("[bench.zebra]\ncmd = \"z\"\n[bench.alpha]\ncmd = \"a\"").unwrap();
        assert_eq!(c.bench.keys().collect::<Vec<_>>(), ["alpha", "zebra"]);
    }

    #[test]
    fn an_empty_file_declares_nothing() {
        assert!(Config::parse("").unwrap().bench.is_empty());
    }

    #[test]
    fn find_walks_up_from_a_subdirectory() {
        let root = std::env::temp_dir().join(format!("tak-cfg-{}", std::process::id()));
        let nested = root.join("a").join("b");
        std::fs::create_dir_all(&nested).unwrap();
        std::fs::write(root.join(FILE_NAME), "[bench.x]\ncmd = \"true\"").unwrap();

        let (path, cfg) = Config::find(&nested).unwrap().expect("should find it");
        assert_eq!(path, root.join(FILE_NAME));
        assert!(cfg.bench.contains_key("x"));

        std::fs::remove_dir_all(&root).ok();
    }

    /// A single-command benchmark keeps measuring what it did before subjects
    /// existed: one series under `self`, with instruction counts.
    #[test]
    fn a_single_command_is_one_self_subject_with_counters() {
        let c = Config::parse("[bench.a]\ncmd = \"x\"").unwrap();
        let s = only(&c, "a");
        assert_eq!(s.name, SELF_TOOL);
        assert!(s.counters);
        assert!(!c.bench["a"].is_multi());
    }

    #[test]
    fn subjects_inherit_the_benchmark_defaults_and_may_override_them() {
        let c = Config::parse(
            r#"
            [bench.install]
            runs = 6
            warmup = 2
            prepare = ["rm", "-rf", "node_modules"]
            dir = "fixture"
            env = { CI = "1", HOME = "/tmp/shared" }

            [bench.install.subject.aube]
            cmd = "aube install"
            env = { HOME = "/tmp/aube" }

            [bench.install.subject.pnpm]
            cmd = ["pnpm", "install"]
            prepare = "rm -rf node_modules pnpm-lock.yaml"
            dir = "fixture-pnpm"
            runs = 3
            warmup = 0
            counters = true
            "#,
        )
        .unwrap();
        let b = &c.bench["install"];
        assert!(b.is_multi());
        let s = b.subjects().unwrap();
        // BTreeMap order, not file order.
        assert_eq!(s[0].name, "aube");
        assert_eq!(s[1].name, "pnpm");

        assert_eq!(s[0].cmd, ["aube", "install"]);
        assert_eq!(
            s[0].prepare.as_deref().unwrap(),
            ["rm", "-rf", "node_modules"]
        );
        assert_eq!(s[0].dir.as_deref(), Some(Path::new("fixture")));
        assert_eq!(s[0].env["CI"], "1");
        assert_eq!(s[0].env["HOME"], "/tmp/aube");
        assert_eq!((s[0].runs, s[0].warmup), (6, 2));
        assert!(!s[0].counters, "named subjects count only when asked to");

        assert_eq!(
            s[1].prepare.as_deref().unwrap(),
            ["rm", "-rf", "node_modules", "pnpm-lock.yaml"]
        );
        assert_eq!(s[1].dir.as_deref(), Some(Path::new("fixture-pnpm")));
        assert_eq!(s[1].env["HOME"], "/tmp/shared");
        assert_eq!((s[1].runs, s[1].warmup), (3, 0));
        assert!(s[1].counters);
    }

    /// Declaring both would leave it ambiguous which is measured.
    #[test]
    fn cmd_and_subjects_together_are_rejected() {
        let err =
            Config::parse("[bench.a]\ncmd = \"x\"\n[bench.a.subject.b]\ncmd = \"y\"").unwrap_err();
        assert!(format!("{err:#}").contains("both"), "{err:#}");
    }

    #[test]
    fn a_benchmark_with_neither_is_rejected() {
        let err = Config::parse("[bench.a]\nruns = 3").unwrap_err();
        assert!(format!("{err:#}").contains("no command"), "{err:#}");
    }

    /// The error names the subject, not just the benchmark, so a large
    /// comparison does not have to be bisected by hand.
    #[test]
    fn an_empty_subject_command_is_rejected_by_name() {
        let err =
            Config::parse("[bench.a.subject.good]\ncmd = \"x\"\n[bench.a.subject.bad]\ncmd = []")
                .unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("`a`") && msg.contains("`bad`"), "{msg}");
    }

    #[test]
    fn an_empty_prepare_is_rejected() {
        assert!(Config::parse("[bench.a]\ncmd = \"x\"\nprepare = []").is_err());
    }

    #[test]
    fn zero_runs_is_rejected_at_parse_time() {
        assert!(Config::parse("[bench.a.subject.b]\ncmd = \"x\"\nruns = 0").is_err());
    }

    #[test]
    fn self_is_reserved_for_single_command_benchmarks() {
        let err = Config::parse("[bench.a.subject.self]\ncmd = \"x\"").unwrap_err();
        assert!(format!("{err:#}").contains("reserved"), "{err:#}");
    }

    /// `dir` sets where a command runs, not where a relative program path is
    /// found: `./target/release/x` still means the one next to `tak.toml`.
    #[test]
    fn a_relative_program_path_is_anchored_at_the_config() {
        let root = Path::new("/repo");
        let mut s = Config::parse(
            "[bench.a]\ncmd = [\"./target/x\", \"./arg\"]\nprepare = \"bin/reset\"\ndir = \"fix\"",
        )
        .unwrap()
        .bench["a"]
            .subjects()
            .unwrap()
            .remove(0);
        s.anchor(root);
        assert_eq!(
            s.cmd,
            ["/repo/./target/x", "./arg"],
            "arguments are left alone"
        );
        assert_eq!(s.prepare.unwrap(), ["/repo/bin/reset"]);
        assert_eq!(s.dir.unwrap(), Path::new("/repo/fix"));

        let mut bare = Config::parse("[bench.a]\ncmd = \"mycli --version\"")
            .unwrap()
            .bench["a"]
            .subjects()
            .unwrap()
            .remove(0);
        bare.anchor(root);
        assert_eq!(
            bare.cmd[0], "mycli",
            "a bare name is still looked up on PATH"
        );
        assert_eq!(bare.dir.unwrap(), Path::new("/repo"));
    }
}