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};
16use std::time::Duration;
17
18pub const FILE_NAME: &str = "tak.toml";
19
20/// Defaults chosen to match `tak run`'s, so moving a command into `tak.toml`
21/// does not silently change what it measures.
22pub const DEFAULT_RUNS: u32 = 20;
23pub const DEFAULT_WARMUP: u32 = 3;
24
25/// `runs = "auto"` defaults: about this much wall time per subject, prepare
26/// included, and never fewer or more runs than these. The floor keeps a slow
27/// competitor's result from resting on one or two samples; the ceiling stops
28/// a millisecond-scale subject from spending the whole budget on runs that
29/// stopped adding information long before.
30pub const DEFAULT_BUDGET: Duration = Duration::from_secs(30);
31pub const DEFAULT_MIN_RUNS: u32 = 5;
32pub const DEFAULT_MAX_RUNS: u32 = 50;
33
34/// Exit codes a sample may end with and still count, unless `ok_exit_codes`
35/// says otherwise: success, and nothing else, as a shell would judge it.
36pub const DEFAULT_OK_EXIT_CODES: [i32; 1] = [0];
37
38#[derive(Debug, Deserialize)]
39pub struct Config {
40    /// Benchmarks by name. A BTreeMap so runs are ordered and reproducible
41    /// rather than following the file's incidental key order.
42    ///
43    /// Settings tables — `[env]`, `[gate]`, `[report]`, `[runner]` — live in
44    /// the same file but are not deserialized here: the settings registry
45    /// declares their dotted keys, and `settings::TakConfigLayer` reads exactly
46    /// those, so this type never has to be kept in step with it. That is also
47    /// why defaults for every benchmark live under `[defaults]`, not `[env]`.
48    #[serde(default)]
49    pub bench: BTreeMap<String, Bench>,
50    /// Settings every benchmark starts from.
51    #[serde(default)]
52    defaults: Layer,
53    /// Subjects declared once, for benchmarks to name in `subjects = [...]`.
54    #[serde(default)]
55    subject: BTreeMap<String, SubjectDecl>,
56}
57
58/// The settings that stack: `[defaults]`, a benchmark, a shared subject and a
59/// benchmark's own subject table all carry them, and each overrides the one
60/// before. `env` and `vars` merge key by key rather than replacing.
61#[derive(Debug, Default, Deserialize)]
62struct Layer {
63    /// A count, or `"auto"` to size each subject from its own speed.
64    runs: Option<RunsDecl>,
65    warmup: Option<u32>,
66    /// `runs = "auto"`: wall time to spend per subject, as `30s`, `2m`, `500ms`.
67    budget: Option<String>,
68    /// `runs = "auto"`: fewest runs any subject gets.
69    min_runs: Option<u32>,
70    /// `runs = "auto"`: most runs any subject gets.
71    max_runs: Option<u32>,
72    /// Exit codes that count as a successful sample. Replaces, not merges:
73    /// a subject listing `[0, 1]` means exactly those.
74    ok_exit_codes: Option<Vec<i64>>,
75    /// Untimed command run before every sample.
76    prepare: Option<Cmd>,
77    /// Untimed command run once per benchmark and subject, before its first
78    /// sample, in the directory holding `tak.toml`.
79    setup: Option<Cmd>,
80    /// Untimed command run after every timed sample; its exit status says
81    /// whether that sample did the right work.
82    check: Option<Cmd>,
83    /// Command whose output names the subject's version, run once after
84    /// `setup` and before sampling, and reported in `--export-json`.
85    version_cmd: Option<Cmd>,
86    /// Directory to run in, relative to `tak.toml`.
87    dir: Option<PathBuf>,
88    /// Variables set for the command.
89    #[serde(default)]
90    env: BTreeMap<String, String>,
91    /// Values for templates, as `{{ vars.name }}`. Not passed to the command.
92    #[serde(default)]
93    vars: BTreeMap<String, String>,
94}
95
96#[derive(Debug, Deserialize)]
97pub struct Bench {
98    /// The command, for a benchmark of one program. Mutually exclusive with
99    /// `subjects` and `subject`, which declare several programs measured
100    /// against each other.
101    #[serde(default)]
102    cmd: Option<Cmd>,
103    #[serde(flatten)]
104    layer: Layer,
105    /// Run this benchmark only when this expr condition holds.
106    when: Option<String>,
107    /// Shared `[subject.NAME]` tables this benchmark measures.
108    #[serde(default)]
109    subjects: Vec<String>,
110    /// Subjects declared here, or overrides of shared ones for this benchmark
111    /// only. The name is what their measurements are recorded under
112    /// (`Record::tool`). A BTreeMap for the same reason `Config::bench` is one.
113    #[serde(default)]
114    subject: BTreeMap<String, SubjectDecl>,
115}
116
117/// One program in a multi-subject benchmark, as written in `tak.toml`: either
118/// a shared `[subject.NAME]` or a benchmark's `[bench.B.subject.NAME]`.
119#[derive(Debug, Deserialize)]
120pub struct SubjectDecl {
121    /// Optional here because a benchmark's table may only override settings of
122    /// a shared subject that already has one.
123    #[serde(default)]
124    cmd: Option<Cmd>,
125    #[serde(flatten)]
126    layer: Layer,
127    /// Measure this subject only when this expr condition holds. A
128    /// benchmark's own table replaces a shared subject's condition.
129    when: Option<String>,
130    /// Opt in to instruction counting. Off by default because a
131    /// multi-subject benchmark usually compares against other people's
132    /// programs, whose instruction counts are not this project's to gate on:
133    /// a competitor's upgrade would fail the gate.
134    counters: Option<bool>,
135}
136
137/// A command, written either as a list or as a plain string.
138#[derive(Debug, Clone, Deserialize)]
139#[serde(untagged)]
140enum Cmd {
141    Argv(Vec<String>),
142    Line(String),
143}
144
145impl Cmd {
146    /// The command as argv.
147    ///
148    /// A string is split on whitespace and nothing else. There is deliberately
149    /// no shell: spawning one adds its own startup cost and variance to every
150    /// sample, which for commands in the 10ms range is a large fraction of the
151    /// measurement. Anything needing a pipe or a glob should be a list whose
152    /// first element is the interpreter.
153    fn argv(&self) -> Result<Vec<String>> {
154        let v = match self {
155            Cmd::Argv(v) => v.clone(),
156            Cmd::Line(s) => split_line(s),
157        };
158        if v.is_empty() {
159            bail!("empty command");
160        }
161        Ok(v)
162    }
163}
164
165/// Split a string command on whitespace, keeping each template tag whole:
166/// `mycli {{ vars.lockfile }}` is two arguments, the second rendered later.
167/// Nothing else is special — no quotes, no escapes — as for any string
168/// command.
169fn split_line(line: &str) -> Vec<String> {
170    let mut out = Vec::new();
171    let mut cur = String::new();
172    let mut close: Option<&str> = None;
173    let mut rest = line;
174    while let Some(c) = rest.chars().next() {
175        if let Some(end) = close {
176            if rest.starts_with(end) {
177                cur.push_str(end);
178                rest = &rest[end.len()..];
179                close = None;
180                continue;
181            }
182        } else if let Some(end) = [("{{", "}}"), ("{%", "%}"), ("{#", "#}")]
183            .iter()
184            .find_map(|(open, end)| rest.starts_with(open).then_some(*end))
185        {
186            cur.push_str(&rest[..2]);
187            rest = &rest[2..];
188            close = Some(end);
189            continue;
190        } else if c.is_whitespace() {
191            if !cur.is_empty() {
192                out.push(std::mem::take(&mut cur));
193            }
194            rest = &rest[c.len_utf8()..];
195            continue;
196        }
197        cur.push(c);
198        rest = &rest[c.len_utf8()..];
199    }
200    if !cur.is_empty() {
201        out.push(cur);
202    }
203    out
204}
205
206/// `runs` as written: a count, or a word. Only `"auto"` is a valid word,
207/// checked when the subject is resolved so the error names it.
208#[derive(Debug, Clone, Deserialize)]
209#[serde(untagged)]
210pub enum RunsDecl {
211    Count(u32),
212    Word(String),
213}
214
215impl RunsDecl {
216    fn resolve(&self) -> Result<Runs> {
217        match self {
218            RunsDecl::Count(n) => Ok(Runs::Fixed(*n)),
219            RunsDecl::Word(w) if w == "auto" => Ok(Runs::Auto),
220            RunsDecl::Word(w) => bail!("runs must be a number or \"auto\", not {w:?}"),
221        }
222    }
223}
224
225/// How many timed runs a subject gets.
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub enum Runs {
228    Fixed(u32),
229    /// Decided after the warmups, from how long one sample takes: see
230    /// [`AutoRuns`].
231    Auto,
232}
233
234impl std::str::FromStr for Runs {
235    type Err = anyhow::Error;
236    fn from_str(s: &str) -> Result<Self> {
237        if s == "auto" {
238            return Ok(Runs::Auto);
239        }
240        s.parse()
241            .map(Runs::Fixed)
242            .map_err(|_| anyhow::anyhow!("runs must be a number or \"auto\", not {s:?}"))
243    }
244}
245
246/// The limits `runs = "auto"` works within. Resolved for every subject, so
247/// `tak run --runs auto` can switch a fixed benchmark over without the file
248/// having to declare them.
249#[derive(Debug, Clone, Copy, PartialEq, Eq)]
250pub struct AutoRuns {
251    pub budget: Duration,
252    pub min: u32,
253    pub max: u32,
254}
255
256impl AutoRuns {
257    /// Runs for a subject whose samples take `slot` each, prepare included:
258    /// as many as fit in the budget, within `min..=max`.
259    pub fn runs_for(&self, slot: Duration) -> u32 {
260        let fit = if slot.is_zero() {
261            u64::from(self.max)
262        } else {
263            (self.budget.as_secs_f64() / slot.as_secs_f64()) as u64
264        };
265        fit.clamp(u64::from(self.min), u64::from(self.max)) as u32
266    }
267}
268
269/// Parse `500ms`, `30s`, `2m` or `1h`; a bare number is seconds.
270pub fn parse_duration(text: &str) -> Result<Duration> {
271    let t = text.trim();
272    let split = t
273        .find(|c: char| !(c.is_ascii_digit() || c == '.'))
274        .unwrap_or(t.len());
275    let (num, unit) = t.split_at(split);
276    let n: f64 = num
277        .parse()
278        .map_err(|_| anyhow::anyhow!("not a duration: {text:?} (try `30s` or `2m`)"))?;
279    let secs = match unit.trim() {
280        "ms" => n / 1000.0,
281        "" | "s" => n,
282        "m" => n * 60.0,
283        "h" => n * 3600.0,
284        _ => bail!("not a duration: {text:?} (units are ms, s, m, h)"),
285    };
286    if !secs.is_finite() || secs <= 0.0 {
287        bail!("a duration must be positive: {text:?}");
288    }
289    // Finite and positive can still be too large for a Duration; that is a
290    // configuration error, not a panic.
291    Duration::try_from_secs_f64(secs).map_err(|_| anyhow::anyhow!("duration too large: {text:?}"))
292}
293
294/// The name a single-command benchmark records under. `compare` renders this
295/// tool as the bare benchmark name.
296pub const SELF_TOOL: &str = "self";
297
298/// A subject with every default applied, ready to measure.
299#[derive(Debug, Clone, PartialEq)]
300pub struct Subject {
301    /// Recorded as `Record::tool`.
302    pub name: String,
303    pub cmd: Vec<String>,
304    pub prepare: Option<Vec<String>>,
305    /// Run once before the subject's first sample. Always from the directory
306    /// holding `tak.toml`, never from `dir`; see [`Subject::anchor`].
307    pub setup: Option<Vec<String>>,
308    /// Where `setup` runs: set by [`Subject::anchor`] to the directory holding
309    /// `tak.toml`. `None` runs it in tak's own working directory.
310    pub setup_dir: Option<PathBuf>,
311    /// Run after every timed sample, untimed. Exit 0 means the sample passed.
312    pub check: Option<Vec<String>>,
313    /// Run once, untimed, after `setup` and before the first warmup; its first
314    /// line of output is the version exported for this subject. See
315    /// [`crate::measure::interleaved_with_versions`].
316    pub version_cmd: Option<Vec<String>>,
317    /// Relative to `tak.toml`; the caller resolves it.
318    pub dir: Option<PathBuf>,
319    pub env: BTreeMap<String, String>,
320    /// Template values from `vars` tables, used by [`crate::template`].
321    pub vars: BTreeMap<String, String>,
322    /// Measured only when this holds; see [`crate::condition`].
323    pub when: Option<String>,
324    pub runs: Runs,
325    /// The limits `Runs::Auto` works within.
326    pub auto: AutoRuns,
327    pub warmup: u32,
328    pub counters: bool,
329    /// Exit codes a timed or warmup sample may end with and still count.
330    /// Never empty. A death by signal fails whatever this holds, and
331    /// `setup` and `prepare` are always held to exit 0.
332    pub ok_exit_codes: Vec<i32>,
333}
334
335impl Subject {
336    /// Resolve paths against `root`, the directory holding `tak.toml`.
337    ///
338    /// `dir` becomes the working directory, but a relative program path — one
339    /// containing a `/`, like `./target/release/mycli` — is resolved against
340    /// `root`, not `dir`. Otherwise giving a subject a fixture directory would
341    /// make the project's own binary unfindable. A bare name is left for PATH
342    /// lookup, and arguments are never touched.
343    ///
344    /// `setup` is the exception to `dir`: it runs in `root` itself. Its usual
345    /// job is to create or recreate `dir` — a clone, a generated project — and
346    /// a command cannot sensibly start inside a directory that does not exist
347    /// yet or that it is about to delete. Running it where `dir` is written
348    /// relative to also means the same path works as one of its arguments.
349    /// Choosing between the two by whether `dir` exists would give a setup a
350    /// different working directory on its second run than on its first.
351    pub fn anchor(&mut self, root: &Path) {
352        let program = |argv: &mut Vec<String>| {
353            if let Some(p) = argv.first_mut()
354                && p.contains('/')
355                && Path::new(p.as_str()).is_relative()
356            {
357                *p = root.join(p.as_str()).to_string_lossy().into_owned();
358            }
359        };
360        program(&mut self.cmd);
361        if let Some(prepare) = &mut self.prepare {
362            program(prepare);
363        }
364        if let Some(setup) = &mut self.setup {
365            program(setup);
366        }
367        if let Some(check) = &mut self.check {
368            program(check);
369        }
370        if let Some(version) = &mut self.version_cmd {
371            program(version);
372        }
373        self.dir = Some(match &self.dir {
374            Some(d) => root.join(d),
375            None => root.to_path_buf(),
376        });
377        self.setup_dir = Some(root.to_path_buf());
378    }
379}
380
381impl Bench {
382    /// This benchmark's own `when` condition.
383    pub fn when(&self) -> Option<&str> {
384        self.when.as_deref()
385    }
386
387    /// Whether this benchmark compares several programs rather than measuring
388    /// one.
389    pub fn is_multi(&self) -> bool {
390        !self.subject.is_empty() || !self.subjects.is_empty()
391    }
392}
393
394impl Config {
395    /// Every subject of benchmark `name`, with each layer applied: defaults,
396    /// the benchmark, the shared subject, then the benchmark's own subject
397    /// table. Templates are not rendered yet; see [`crate::template::render`].
398    ///
399    /// A single-command benchmark is one subject named [`SELF_TOOL`] with
400    /// counters on, which is exactly what it measured before subjects existed.
401    pub fn subjects(&self, name: &str) -> Result<Vec<Subject>> {
402        let b = self
403            .bench
404            .get(name)
405            .with_context(|| format!("no benchmark `{name}`"))?;
406        if let Some(cmd) = &b.cmd {
407            if b.is_multi() {
408                bail!("declares both `cmd` and subjects; use one or the other");
409            }
410            return Ok(vec![resolve(
411                SELF_TOOL,
412                cmd,
413                true,
414                None,
415                &[&self.defaults, &b.layer],
416            )?]);
417        }
418        // A benchmark's own table can add a subject or override a shared one;
419        // either way it is measured, listed or not.
420        let names: std::collections::BTreeSet<&String> =
421            b.subjects.iter().chain(b.subject.keys()).collect();
422        if names.is_empty() {
423            bail!("has no command");
424        }
425        names
426            .into_iter()
427            .map(|n| {
428                let shared = self.subject.get(n);
429                let local = b.subject.get(n);
430                if b.subjects.contains(n) && shared.is_none() && local.is_none() {
431                    bail!("lists subject `{n}`, but there is no [subject.{n}]");
432                }
433                let cmd = local
434                    .and_then(|d| d.cmd.as_ref())
435                    .or_else(|| shared.and_then(|d| d.cmd.as_ref()))
436                    .with_context(|| format!("subject `{n}` has no command"))?;
437                let when = local
438                    .and_then(|d| d.when.clone())
439                    .or_else(|| shared.and_then(|d| d.when.clone()));
440                let counters = local
441                    .and_then(|d| d.counters)
442                    .or_else(|| shared.and_then(|d| d.counters))
443                    .unwrap_or(false);
444                let mut layers = vec![&self.defaults, &b.layer];
445                layers.extend(shared.map(|d| &d.layer));
446                layers.extend(local.map(|d| &d.layer));
447                resolve(n, cmd, counters, when, &layers).with_context(|| format!("subject `{n}`"))
448            })
449            .collect()
450    }
451}
452
453impl Config {
454    /// Every settings layer in the file, with where it is.
455    fn layers(&self) -> Vec<(String, &Layer)> {
456        let mut out = vec![("defaults".to_string(), &self.defaults)];
457        for (n, d) in &self.subject {
458            out.push((format!("subject.{n}"), &d.layer));
459        }
460        for (b, bench) in &self.bench {
461            out.push((format!("bench.{b}"), &bench.layer));
462            for (n, d) in &bench.subject {
463                out.push((format!("bench.{b}.subject.{n}"), &d.layer));
464            }
465        }
466        out
467    }
468
469    /// Every `when` in the file, with where it is.
470    fn conditions(&self) -> Vec<(String, &str)> {
471        let mut out = Vec::new();
472        for (n, d) in &self.subject {
473            out.extend(d.when.as_deref().map(|w| (format!("subject.{n}.when"), w)));
474        }
475        for (b, bench) in &self.bench {
476            out.extend(
477                bench
478                    .when
479                    .as_deref()
480                    .map(|w| (format!("bench.{b}.when"), w)),
481            );
482            for (n, d) in &bench.subject {
483                out.extend(
484                    d.when
485                        .as_deref()
486                        .map(|w| (format!("bench.{b}.subject.{n}.when"), w)),
487                );
488            }
489        }
490        out
491    }
492
493    /// Every string that may hold a template, as written, with where it is.
494    fn template_strings(&self) -> Vec<(String, &str)> {
495        fn layer<'a>(out: &mut Vec<(String, &'a str)>, at: &str, l: &'a Layer) {
496            if let Some(p) = &l.prepare {
497                cmd(out, &format!("{at}.prepare"), p);
498            }
499            if let Some(p) = &l.setup {
500                cmd(out, &format!("{at}.setup"), p);
501            }
502            if let Some(c) = &l.check {
503                cmd(out, &format!("{at}.check"), c);
504            }
505            if let Some(v) = &l.version_cmd {
506                cmd(out, &format!("{at}.version_cmd"), v);
507            }
508            if let Some(d) = l.dir.as_ref().and_then(|d| d.to_str()) {
509                out.push((format!("{at}.dir"), d));
510            }
511            for (k, v) in &l.env {
512                out.push((format!("{at}.env.{k}"), v));
513            }
514            for (k, v) in &l.vars {
515                out.push((format!("{at}.vars.{k}"), v));
516            }
517        }
518        fn cmd<'a>(out: &mut Vec<(String, &'a str)>, at: &str, c: &'a Cmd) {
519            match c {
520                Cmd::Argv(v) => out.extend(v.iter().map(|a| (at.to_string(), a.as_str()))),
521                Cmd::Line(l) => out.push((at.to_string(), l)),
522            }
523        }
524        fn subject<'a>(out: &mut Vec<(String, &'a str)>, at: &str, d: &'a SubjectDecl) {
525            if let Some(c) = &d.cmd {
526                cmd(out, &format!("{at}.cmd"), c);
527            }
528            layer(out, at, &d.layer);
529        }
530        let mut out = Vec::new();
531        layer(&mut out, "defaults", &self.defaults);
532        for (n, d) in &self.subject {
533            subject(&mut out, &format!("subject.{n}"), d);
534        }
535        for (b, bench) in &self.bench {
536            if let Some(c) = &bench.cmd {
537                cmd(&mut out, &format!("bench.{b}.cmd"), c);
538            }
539            layer(&mut out, &format!("bench.{b}"), &bench.layer);
540            for (n, d) in &bench.subject {
541                subject(&mut out, &format!("bench.{b}.subject.{n}"), d);
542            }
543        }
544        out
545    }
546}
547
548/// Stack `layers`, least specific first, into one subject. A later layer's
549/// setting replaces an earlier one's — a subject's own prepare replaces the
550/// benchmark's rather than running after it, since the two usually reset the
551/// same state, and `setup` and `check` likewise — except `env` and `vars`,
552/// which merge key by key.
553fn resolve(
554    name: &str,
555    cmd: &Cmd,
556    counters: bool,
557    when: Option<String>,
558    layers: &[&Layer],
559) -> Result<Subject> {
560    fn last<'a, T>(layers: &[&'a Layer], f: impl Fn(&'a Layer) -> Option<&'a T>) -> Option<&'a T> {
561        layers.iter().rev().find_map(|l| f(l))
562    }
563    let merged = |f: fn(&Layer) -> &BTreeMap<String, String>| {
564        layers.iter().fold(BTreeMap::new(), |mut m, l| {
565            m.extend(f(l).clone());
566            m
567        })
568    };
569    let budget = match last(layers, |l| l.budget.as_ref()) {
570        Some(b) => parse_duration(b).context("budget")?,
571        None => DEFAULT_BUDGET,
572    };
573    let auto = AutoRuns {
574        budget,
575        min: last(layers, |l| l.min_runs.as_ref())
576            .copied()
577            .unwrap_or(DEFAULT_MIN_RUNS),
578        max: last(layers, |l| l.max_runs.as_ref())
579            .copied()
580            .unwrap_or(DEFAULT_MAX_RUNS),
581    };
582    if auto.min == 0 {
583        bail!("min_runs must be at least 1");
584    }
585    if auto.min > auto.max {
586        bail!(
587            "min_runs ({}) is more than max_runs ({})",
588            auto.min,
589            auto.max
590        );
591    }
592    Ok(Subject {
593        name: name.to_string(),
594        cmd: cmd.argv()?,
595        prepare: last(layers, |l| l.prepare.as_ref())
596            .map(Cmd::argv)
597            .transpose()?,
598        setup: last(layers, |l| l.setup.as_ref())
599            .map(Cmd::argv)
600            .transpose()
601            .context("setup")?,
602        setup_dir: None,
603        check: last(layers, |l| l.check.as_ref())
604            .map(Cmd::argv)
605            .transpose()
606            .context("check")?,
607        version_cmd: last(layers, |l| l.version_cmd.as_ref())
608            .map(Cmd::argv)
609            .transpose()
610            .context("version_cmd")?,
611        dir: last(layers, |l| l.dir.as_ref()).cloned(),
612        env: merged(|l| &l.env),
613        vars: merged(|l| &l.vars),
614        when,
615        runs: last(layers, |l| l.runs.as_ref())
616            .map_or(Ok(Runs::Fixed(DEFAULT_RUNS)), RunsDecl::resolve)?,
617        auto,
618        warmup: last(layers, |l| l.warmup.as_ref())
619            .copied()
620            .unwrap_or(DEFAULT_WARMUP),
621        counters,
622        ok_exit_codes: match last(layers, |l| l.ok_exit_codes.as_ref()) {
623            Some(codes) => ok_exit_codes(codes)?,
624            None => DEFAULT_OK_EXIT_CODES.to_vec(),
625        },
626    })
627}
628
629/// The range of exit codes a platform can report, when narrower than `i32`:
630/// Unix keeps only the low 8 bits of a process's status. `None` where the
631/// whole `i32` range is possible, as on Windows.
632pub fn exit_code_range(unix: bool) -> Option<std::ops::RangeInclusive<i32>> {
633    unix.then_some(0..=255)
634}
635
636/// The codes in `codes` that a platform can never report, so can never match.
637///
638/// A `tak.toml` shared between platforms may list a Windows code next to
639/// Unix ones, such as `[0, 1, -1073741819]`, so some impossible codes are
640/// only worth a warning. A list with *no* possible code would drop the
641/// subject at its first sample, which is a mistake to catch before it runs.
642pub fn impossible_exit_codes(codes: &[i32], unix: bool) -> Vec<i32> {
643    match exit_code_range(unix) {
644        Some(range) => codes
645            .iter()
646            .copied()
647            .filter(|c| !range.contains(c))
648            .collect(),
649        None => Vec::new(),
650    }
651}
652
653/// Check a subject's resolved `ok_exit_codes` against a platform: fail when
654/// none of them is possible there, otherwise return the ones that are not,
655/// for a warning.
656///
657/// Not part of loading `tak.toml`. A shared file may hold a Windows-only
658/// subject, switched off elsewhere by `when`, whose codes are all impossible
659/// on Unix; checking it at load would stop every other benchmark from
660/// running there. `tak run` calls this only for the subjects it will measure.
661pub fn check_platform_exit_codes(codes: &[i32], unix: bool) -> Result<Vec<i32>> {
662    let impossible = impossible_exit_codes(codes, unix);
663    if !impossible.is_empty() && impossible.len() == codes.len() {
664        let range = exit_code_range(unix).expect("only a narrowed range rules codes out");
665        bail!(
666            "ok_exit_codes {} can never match: exit codes on this platform are {} to {}",
667            join_codes(&impossible),
668            range.start(),
669            range.end()
670        );
671    }
672    Ok(impossible)
673}
674
675/// Exit codes for a message: `0, 1`.
676pub fn join_codes(codes: &[i32]) -> String {
677    codes
678        .iter()
679        .map(i32::to_string)
680        .collect::<Vec<_>>()
681        .join(", ")
682}
683
684/// Check `ok_exit_codes` as written, returning it sorted and deduplicated.
685///
686/// The range is whatever `ExitStatus::code()` can report, which is an `i32`.
687/// Unix only ever reports 0–255, but Windows passes a program's 32-bit exit
688/// code through, and an NTSTATUS such as 0xC0000005 arrives negative
689/// (-1073741819); limiting the list to 0–255 would make those unlistable.
690/// An empty list would fail every sample, so it is an error here rather than
691/// a confusing run.
692fn ok_exit_codes(codes: &[i64]) -> Result<Vec<i32>> {
693    if codes.is_empty() {
694        bail!("ok_exit_codes must list at least one exit code");
695    }
696    let mut out = codes
697        .iter()
698        .map(|&c| match i32::try_from(c) {
699            Ok(c) => Ok(c),
700            Err(_) => bail!(
701                "ok_exit_codes: {c} is not an exit code ({} to {})",
702                i32::MIN,
703                i32::MAX
704            ),
705        })
706        .collect::<Result<Vec<_>>>()?;
707    out.sort_unstable();
708    out.dedup();
709    Ok(out)
710}
711
712impl Config {
713    pub fn parse(text: &str) -> Result<Self> {
714        let cfg: Config = toml::from_str(text).context("could not parse tak.toml")?;
715        // Every template in the file, used or not: a typo in a shared subject
716        // no benchmark lists yet, or in a value an override replaces, is
717        // still a typo, and should not wait to be found until it is used.
718        for (place, value) in cfg.template_strings() {
719            crate::template::check_str(value).with_context(|| format!("in {place}"))?;
720        }
721        for (place, when) in cfg.conditions() {
722            crate::condition::check(when).with_context(|| format!("in {place}"))?;
723        }
724        // Likewise every `ok_exit_codes`, including one in a layer that
725        // nothing resolves through yet.
726        for (place, l) in cfg.layers() {
727            if let Some(codes) = &l.ok_exit_codes {
728                ok_exit_codes(codes).with_context(|| format!("in {place}"))?;
729            }
730        }
731        // Every declared benchmark is validated up front rather than failing
732        // partway through a run that has already spent minutes measuring.
733        for (name, b) in &cfg.bench {
734            let subjects = cfg
735                .subjects(name)
736                .with_context(|| format!("benchmark `{name}`"))?;
737            for s in &subjects {
738                // Zero runs leaves nothing to report; catching it here names
739                // the benchmark instead of failing after the others ran.
740                if s.runs == Runs::Fixed(0) {
741                    bail!("benchmark `{name}`: runs must be at least 1");
742                }
743                if s.name.trim().is_empty() {
744                    bail!("benchmark `{name}`: a subject needs a name");
745                }
746                // `self` is the series a single-command benchmark records
747                // under. A subject taking it would be recorded, printed and
748                // exported as that series instead of as itself.
749                if b.is_multi() && s.name == SELF_TOOL {
750                    bail!(
751                        "benchmark `{name}`: `{SELF_TOOL}` is reserved and cannot name a subject"
752                    );
753                }
754            }
755        }
756        Ok(cfg)
757    }
758
759    /// Load a named config file, for `tak run --config`.
760    pub fn load(path: &Path) -> Result<Self> {
761        let text = std::fs::read_to_string(path)
762            .with_context(|| format!("could not read {}", path.display()))?;
763        Self::parse(&text).with_context(|| format!("in {}", path.display()))
764    }
765
766    /// Find and load `tak.toml`, searching upward from `start`.
767    ///
768    /// Walking up means `tak run` behaves the same from a subdirectory as from
769    /// the repository root, which is where people actually are.
770    pub fn find(start: &Path) -> Result<Option<(PathBuf, Self)>> {
771        for dir in start.ancestors() {
772            let path = dir.join(FILE_NAME);
773            if path.is_file() {
774                let text = std::fs::read_to_string(&path)
775                    .with_context(|| format!("could not read {}", path.display()))?;
776                let cfg = Self::parse(&text).with_context(|| format!("in {}", path.display()))?;
777                return Ok(Some((path, cfg)));
778            }
779        }
780        Ok(None)
781    }
782}
783
784#[cfg(test)]
785mod tests {
786    use super::*;
787
788    /// The single subject of a one-command benchmark.
789    fn only(c: &Config, bench: &str) -> Subject {
790        let mut s = c.subjects(bench).unwrap();
791        assert_eq!(s.len(), 1);
792        s.remove(0)
793    }
794
795    #[test]
796    fn a_command_may_be_a_list_or_a_string() {
797        let c = Config::parse(
798            r#"
799            [bench.a]
800            cmd = ["mycli", "--version"]
801            [bench.b]
802            cmd = "mycli --help"
803            "#,
804        )
805        .unwrap();
806        assert_eq!(only(&c, "a").cmd, ["mycli", "--version"]);
807        assert_eq!(only(&c, "b").cmd, ["mycli", "--help"]);
808    }
809
810    /// A string is split on whitespace and nothing else — no shell means no
811    /// quoting, and pretending otherwise would measure the wrong thing.
812    #[test]
813    fn a_string_command_gets_no_shell_semantics() {
814        let c = Config::parse(
815            r#"[bench.a]
816cmd = "mycli 'two words'""#,
817        )
818        .unwrap();
819        assert_eq!(only(&c, "a").cmd, ["mycli", "'two", "words'"]);
820    }
821
822    #[test]
823    fn defaults_match_the_cli() {
824        let c = Config::parse("[bench.a]\ncmd = \"x\"").unwrap();
825        assert_eq!(only(&c, "a").runs, Runs::Fixed(DEFAULT_RUNS));
826        assert_eq!(only(&c, "a").warmup, DEFAULT_WARMUP);
827    }
828
829    #[test]
830    fn per_benchmark_overrides_win() {
831        let c = Config::parse("[bench.a]\ncmd = \"x\"\nruns = 5\nwarmup = 1").unwrap();
832        assert_eq!(only(&c, "a").runs, Runs::Fixed(5));
833        assert_eq!(only(&c, "a").warmup, 1);
834    }
835
836    /// Validation happens at load, not partway through a run that has already
837    /// spent minutes measuring.
838    #[test]
839    fn an_empty_command_is_rejected_at_parse_time() {
840        let err = Config::parse("[bench.a]\ncmd = []").unwrap_err();
841        assert!(format!("{err:#}").contains('a'), "{err:#}");
842    }
843
844    #[test]
845    fn benchmarks_run_in_a_stable_order() {
846        let c = Config::parse("[bench.zebra]\ncmd = \"z\"\n[bench.alpha]\ncmd = \"a\"").unwrap();
847        assert_eq!(c.bench.keys().collect::<Vec<_>>(), ["alpha", "zebra"]);
848    }
849
850    #[test]
851    fn an_empty_file_declares_nothing() {
852        assert!(Config::parse("").unwrap().bench.is_empty());
853    }
854
855    #[test]
856    fn find_walks_up_from_a_subdirectory() {
857        let root = std::env::temp_dir().join(format!("tak-cfg-{}", std::process::id()));
858        let nested = root.join("a").join("b");
859        std::fs::create_dir_all(&nested).unwrap();
860        std::fs::write(root.join(FILE_NAME), "[bench.x]\ncmd = \"true\"").unwrap();
861
862        let (path, cfg) = Config::find(&nested).unwrap().expect("should find it");
863        assert_eq!(path, root.join(FILE_NAME));
864        assert!(cfg.bench.contains_key("x"));
865
866        std::fs::remove_dir_all(&root).ok();
867    }
868
869    /// A single-command benchmark keeps measuring what it did before subjects
870    /// existed: one series under `self`, with instruction counts.
871    #[test]
872    fn a_single_command_is_one_self_subject_with_counters() {
873        let c = Config::parse("[bench.a]\ncmd = \"x\"").unwrap();
874        let s = only(&c, "a");
875        assert_eq!(s.name, SELF_TOOL);
876        assert!(s.counters);
877        assert!(!c.bench["a"].is_multi());
878    }
879
880    #[test]
881    fn subjects_inherit_the_benchmark_defaults_and_may_override_them() {
882        let c = Config::parse(
883            r#"
884            [bench.install]
885            runs = 6
886            warmup = 2
887            prepare = ["rm", "-rf", "node_modules"]
888            dir = "fixture"
889            env = { CI = "1", HOME = "/tmp/shared" }
890
891            [bench.install.subject.aube]
892            cmd = "aube install"
893            env = { HOME = "/tmp/aube" }
894
895            [bench.install.subject.pnpm]
896            cmd = ["pnpm", "install"]
897            prepare = "rm -rf node_modules pnpm-lock.yaml"
898            dir = "fixture-pnpm"
899            runs = 3
900            warmup = 0
901            counters = true
902            "#,
903        )
904        .unwrap();
905        let b = &c.bench["install"];
906        assert!(b.is_multi());
907        let s = c.subjects("install").unwrap();
908        // BTreeMap order, not file order.
909        assert_eq!(s[0].name, "aube");
910        assert_eq!(s[1].name, "pnpm");
911
912        assert_eq!(s[0].cmd, ["aube", "install"]);
913        assert_eq!(
914            s[0].prepare.as_deref().unwrap(),
915            ["rm", "-rf", "node_modules"]
916        );
917        assert_eq!(s[0].dir.as_deref(), Some(Path::new("fixture")));
918        assert_eq!(s[0].env["CI"], "1");
919        assert_eq!(s[0].env["HOME"], "/tmp/aube");
920        assert_eq!((s[0].runs, s[0].warmup), (Runs::Fixed(6), 2));
921        assert!(!s[0].counters, "named subjects count only when asked to");
922
923        assert_eq!(
924            s[1].prepare.as_deref().unwrap(),
925            ["rm", "-rf", "node_modules", "pnpm-lock.yaml"]
926        );
927        assert_eq!(s[1].dir.as_deref(), Some(Path::new("fixture-pnpm")));
928        assert_eq!(s[1].env["HOME"], "/tmp/shared");
929        assert_eq!((s[1].runs, s[1].warmup), (Runs::Fixed(3), 0));
930        assert!(s[1].counters);
931    }
932
933    /// Declaring both would leave it ambiguous which is measured.
934    #[test]
935    fn cmd_and_subjects_together_are_rejected() {
936        let err =
937            Config::parse("[bench.a]\ncmd = \"x\"\n[bench.a.subject.b]\ncmd = \"y\"").unwrap_err();
938        assert!(format!("{err:#}").contains("both"), "{err:#}");
939    }
940
941    #[test]
942    fn a_benchmark_with_neither_is_rejected() {
943        let err = Config::parse("[bench.a]\nruns = 3").unwrap_err();
944        assert!(format!("{err:#}").contains("no command"), "{err:#}");
945    }
946
947    /// The error names the subject, not just the benchmark, so a large
948    /// comparison does not have to be bisected by hand.
949    #[test]
950    fn an_empty_subject_command_is_rejected_by_name() {
951        let err =
952            Config::parse("[bench.a.subject.good]\ncmd = \"x\"\n[bench.a.subject.bad]\ncmd = []")
953                .unwrap_err();
954        let msg = format!("{err:#}");
955        assert!(msg.contains("`a`") && msg.contains("`bad`"), "{msg}");
956    }
957
958    #[test]
959    fn an_empty_prepare_is_rejected() {
960        assert!(Config::parse("[bench.a]\ncmd = \"x\"\nprepare = []").is_err());
961    }
962
963    #[test]
964    fn an_empty_check_is_rejected() {
965        let err = Config::parse("[bench.a]\ncmd = \"x\"\ncheck = []").unwrap_err();
966        assert!(format!("{err:#}").contains("check"), "{err:#}");
967    }
968
969    /// `check` stacks like `prepare`: the most specific layer that sets one
970    /// wins, and one that says nothing inherits.
971    #[test]
972    fn check_stacks_like_prepare() {
973        let c = Config::parse(
974            r#"
975            [defaults]
976            check = "git diff --quiet"
977
978            [subject.a]
979            cmd = ["a"]
980
981            [subject.b]
982            cmd = ["b"]
983            check = ["./verify", "b"]
984
985            [bench.plain]
986            cmd = "x"
987
988            [bench.cmp]
989            subjects = ["a", "b"]
990            [bench.cmp.subject.c]
991            cmd = ["c"]
992            check = ["./verify", "{{ subject }}"]
993
994            [bench.own]
995            subjects = ["a", "b"]
996            check = ["./bench-check"]
997            [bench.own.subject.b]
998            check = "./local-check"
999            "#,
1000        )
1001        .unwrap();
1002        assert_eq!(only(&c, "plain").check.unwrap(), ["git", "diff", "--quiet"]);
1003        let cmp = c.subjects("cmp").unwrap();
1004        assert_eq!(
1005            cmp[0].check.as_deref().unwrap(),
1006            ["git", "diff", "--quiet"],
1007            "inherited from defaults"
1008        );
1009        assert_eq!(cmp[1].check.as_deref().unwrap(), ["./verify", "b"]);
1010        assert_eq!(
1011            cmp[2].check.as_deref().unwrap(),
1012            ["./verify", "{{ subject }}"],
1013            "rendered later"
1014        );
1015        let own = c.subjects("own").unwrap();
1016        assert_eq!(
1017            own[0].check.as_deref().unwrap(),
1018            ["./bench-check"],
1019            "bench over defaults"
1020        );
1021        assert_eq!(
1022            own[1].check.as_deref().unwrap(),
1023            ["./local-check"],
1024            "bench's own subject table over the shared subject"
1025        );
1026        assert!(
1027            Config::parse("[bench.a]\ncmd = \"x\"")
1028                .unwrap()
1029                .subjects("a")
1030                .unwrap()[0]
1031                .check
1032                .is_none()
1033        );
1034    }
1035
1036    #[test]
1037    fn a_broken_check_template_is_rejected_at_parse_time() {
1038        let err = Config::parse("[bench.a]\ncmd = \"x\"\ncheck = [\"{{ env.X \"]").unwrap_err();
1039        assert!(format!("{err:#}").contains("check"), "{err:#}");
1040    }
1041
1042    #[test]
1043    fn zero_runs_is_rejected_at_parse_time() {
1044        assert!(Config::parse("[bench.a.subject.b]\ncmd = \"x\"\nruns = 0").is_err());
1045    }
1046
1047    #[test]
1048    fn self_is_reserved_for_single_command_benchmarks() {
1049        let err = Config::parse("[bench.a.subject.self]\ncmd = \"x\"").unwrap_err();
1050        assert!(format!("{err:#}").contains("reserved"), "{err:#}");
1051    }
1052
1053    /// `dir` sets where a command runs, not where a relative program path is
1054    /// found: `./target/release/x` still means the one next to `tak.toml`.
1055    #[test]
1056    fn a_relative_program_path_is_anchored_at_the_config() {
1057        let root = Path::new("/repo");
1058        let mut s = Config::parse(
1059            "[bench.a]\ncmd = [\"./target/x\", \"./arg\"]\nprepare = \"bin/reset\"\ncheck = \"./bin/verify ./out\"\ndir = \"fix\"",
1060        )
1061        .unwrap()
1062        .subjects("a")
1063        .unwrap()
1064        .remove(0);
1065        s.anchor(root);
1066        assert_eq!(
1067            s.cmd,
1068            ["/repo/./target/x", "./arg"],
1069            "arguments are left alone"
1070        );
1071        assert_eq!(s.prepare.unwrap(), ["/repo/bin/reset"]);
1072        assert_eq!(s.check.unwrap(), ["/repo/./bin/verify", "./out"]);
1073        assert_eq!(s.dir.unwrap(), Path::new("/repo/fix"));
1074
1075        let mut bare = Config::parse("[bench.a]\ncmd = \"mycli --version\"")
1076            .unwrap()
1077            .subjects("a")
1078            .unwrap()
1079            .remove(0);
1080        bare.anchor(root);
1081        assert_eq!(
1082            bare.cmd[0], "mycli",
1083            "a bare name is still looked up on PATH"
1084        );
1085        assert_eq!(bare.dir.unwrap(), Path::new("/repo"));
1086    }
1087
1088    /// Setup layers like prepare — the most specific one replaces the rest —
1089    /// and a benchmark without one has none.
1090    #[test]
1091    fn setup_stacks_by_specificity_and_replaces() {
1092        let c = Config::parse(
1093            r#"
1094            [defaults]
1095            setup = "make fixture"
1096
1097            [subject.a]
1098            cmd = "a"
1099
1100            [subject.b]
1101            cmd = "b"
1102            setup = ["./clone", "b"]
1103
1104            [subject.c]
1105            cmd = "c"
1106
1107            [bench.x]
1108            subjects = ["a", "b", "c"]
1109            [bench.x.subject.c]
1110            setup = "./clone c --here"
1111
1112            [bench.y]
1113            subjects = ["a", "b"]
1114            setup = "./bench-setup"
1115            prepare = "reset"
1116            "#,
1117        )
1118        .unwrap();
1119        let setups = |bench: &str| -> Vec<Vec<String>> {
1120            c.subjects(bench)
1121                .unwrap()
1122                .into_iter()
1123                .map(|s| s.setup.unwrap())
1124                .collect()
1125        };
1126        assert_eq!(
1127            setups("x"),
1128            [
1129                vec!["make", "fixture"],
1130                vec!["./clone", "b"],
1131                vec!["./clone", "c", "--here"]
1132            ]
1133        );
1134        // The benchmark's replaces the defaults', and a shared subject's own
1135        // replaces the benchmark's. Prepare is untouched by any of it.
1136        assert_eq!(setups("y"), [vec!["./bench-setup"], vec!["./clone", "b"]]);
1137        assert_eq!(
1138            c.subjects("y").unwrap()[0].prepare.as_deref().unwrap(),
1139            ["reset"]
1140        );
1141
1142        let none = Config::parse("[bench.z]\ncmd = \"x\"").unwrap();
1143        assert_eq!(only(&none, "z").setup, None);
1144    }
1145
1146    /// Setup runs from the directory holding tak.toml whatever `dir` says,
1147    /// so it can create `dir`; its program is anchored there like any other.
1148    #[test]
1149    fn setup_runs_from_the_config_directory() {
1150        let mut s = Config::parse(
1151            "[bench.a]\ncmd = \"x\"\nsetup = [\"./bin/clone\", \"work\"]\ndir = \"work\"",
1152        )
1153        .unwrap()
1154        .subjects("a")
1155        .unwrap()
1156        .remove(0);
1157        s.anchor(Path::new("/repo"));
1158        assert_eq!(s.setup.unwrap(), ["/repo/./bin/clone", "work"]);
1159        assert_eq!(s.setup_dir.unwrap(), Path::new("/repo"));
1160        assert_eq!(s.dir.unwrap(), Path::new("/repo/work"));
1161    }
1162
1163    #[test]
1164    fn a_bad_setup_is_rejected_at_parse_time() {
1165        assert!(Config::parse("[bench.a]\ncmd = \"x\"\nsetup = []").is_err());
1166        let err = Config::parse("[defaults]\nsetup = [\"{{ env.X \"]\n[bench.a]\ncmd = \"x\"")
1167            .unwrap_err();
1168        assert!(format!("{err:#}").contains("defaults.setup"), "{err:#}");
1169    }
1170
1171    #[test]
1172    fn runs_may_be_auto_with_limits_inherited_and_overridden() {
1173        let c = Config::parse(
1174            r#"
1175            [bench.b]
1176            runs = "auto"
1177            budget = "2m"
1178            min_runs = 3
1179
1180            [bench.b.subject.fast]
1181            cmd = "x"
1182
1183            [bench.b.subject.slow]
1184            cmd = "y"
1185            max_runs = 10
1186            budget = "500ms"
1187
1188            [bench.b.subject.pinned]
1189            cmd = "z"
1190            runs = 7
1191            "#,
1192        )
1193        .unwrap();
1194        let s = c.subjects("b").unwrap();
1195        let by = |n: &str| s.iter().find(|x| x.name == n).unwrap();
1196        assert_eq!(by("fast").runs, Runs::Auto);
1197        assert_eq!(
1198            by("fast").auto,
1199            AutoRuns {
1200                budget: Duration::from_secs(120),
1201                min: 3,
1202                max: DEFAULT_MAX_RUNS
1203            }
1204        );
1205        assert_eq!(by("slow").auto.budget, Duration::from_millis(500));
1206        assert_eq!((by("slow").auto.min, by("slow").auto.max), (3, 10));
1207        assert_eq!(by("pinned").runs, Runs::Fixed(7));
1208    }
1209
1210    #[test]
1211    fn bad_auto_settings_are_rejected_at_parse_time() {
1212        for bad in [
1213            "runs = \"lots\"",
1214            "runs = \"auto\"\nbudget = \"soon\"",
1215            "runs = \"auto\"\nbudget = \"0s\"",
1216            "runs = \"auto\"\nmin_runs = 0",
1217            "runs = \"auto\"\nmin_runs = 9\nmax_runs = 3",
1218        ] {
1219            let toml = format!("[bench.a]\ncmd = \"x\"\n{bad}");
1220            assert!(Config::parse(&toml).is_err(), "accepted: {bad}");
1221        }
1222    }
1223
1224    #[test]
1225    fn durations_take_the_common_units() {
1226        assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
1227        assert_eq!(parse_duration("30s").unwrap(), Duration::from_secs(30));
1228        assert_eq!(parse_duration("45").unwrap(), Duration::from_secs(45));
1229        assert_eq!(parse_duration("2m").unwrap(), Duration::from_secs(120));
1230        assert_eq!(parse_duration("1.5h").unwrap(), Duration::from_secs(5400));
1231        assert!(
1232            parse_duration("1e300h").is_err(),
1233            "too large is an error, not a panic"
1234        );
1235    }
1236
1237    /// A slow subject is held at the floor, a fast one at the ceiling, and
1238    /// anything between gets what fits in the budget.
1239    #[test]
1240    fn auto_runs_fit_the_budget_within_the_limits() {
1241        let a = AutoRuns {
1242            budget: Duration::from_secs(30),
1243            min: 5,
1244            max: 50,
1245        };
1246        assert_eq!(a.runs_for(Duration::from_millis(1700)), 17);
1247        assert_eq!(a.runs_for(Duration::from_secs(21)), 5);
1248        assert_eq!(a.runs_for(Duration::from_millis(300)), 50);
1249        assert_eq!(a.runs_for(Duration::ZERO), 50);
1250    }
1251
1252    /// A subject declared once can be measured by several benchmarks, which
1253    /// can still override it for themselves; `[defaults]` is under all of it.
1254    #[test]
1255    fn shared_subjects_and_defaults_stack_by_specificity() {
1256        let c = Config::parse(
1257            r#"
1258            [defaults]
1259            runs = "auto"
1260            min_runs = 4
1261            prepare = "reset"
1262            env = { HOME = "/h", CI = "1" }
1263            vars = { kind = "default" }
1264
1265            [subject.aube]
1266            cmd = ["aube", "install"]
1267            env = { HOME = "/h-aube" }
1268            vars = { lockfile = "aube-lock.yaml" }
1269
1270            [subject.pnpm]
1271            cmd = ["pnpm", "install"]
1272            counters = true
1273
1274            [bench.warm]
1275            subjects = ["aube", "pnpm"]
1276
1277            [bench.cold]
1278            subjects = ["aube", "pnpm"]
1279            prepare = "reset --cold"
1280            warmup = 0
1281
1282            [bench.test]
1283            subjects = ["pnpm"]
1284            [bench.test.subject.aube]
1285            cmd = ["aube", "test"]
1286            [bench.test.subject.pnpm]
1287            cmd = ["pnpm", "install-test"]
1288            vars = { kind = "local" }
1289            "#,
1290        )
1291        .unwrap();
1292
1293        let warm = c.subjects("warm").unwrap();
1294        assert_eq!(
1295            warm.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
1296            ["aube", "pnpm"]
1297        );
1298        assert_eq!(warm[0].cmd, ["aube", "install"]);
1299        assert_eq!(warm[0].runs, Runs::Auto);
1300        assert_eq!(warm[0].auto.min, 4);
1301        assert_eq!(warm[0].prepare.as_deref().unwrap(), ["reset"]);
1302        assert_eq!(warm[0].env["HOME"], "/h-aube", "subject over defaults");
1303        assert_eq!(warm[0].env["CI"], "1", "merged, not replaced");
1304        assert_eq!(warm[0].vars["lockfile"], "aube-lock.yaml");
1305        assert_eq!(warm[0].vars["kind"], "default");
1306        assert!(!warm[0].counters && warm[1].counters);
1307
1308        let cold = c.subjects("cold").unwrap();
1309        assert_eq!(
1310            cold[0].prepare.as_deref().unwrap(),
1311            ["reset", "--cold"],
1312            "bench over defaults"
1313        );
1314        assert_eq!(cold[0].warmup, 0);
1315
1316        // A benchmark's own table adds a subject, or overrides a shared one.
1317        let test = c.subjects("test").unwrap();
1318        assert_eq!(test[0].cmd, ["aube", "test"]);
1319        assert_eq!(
1320            test[0].env["HOME"], "/h-aube",
1321            "inherits the shared subject"
1322        );
1323        assert_eq!(test[1].cmd, ["pnpm", "install-test"]);
1324        assert_eq!(test[1].vars["kind"], "local");
1325        assert!(test[1].counters, "an override keeps the shared setting");
1326    }
1327
1328    /// `version_cmd` stacks like `prepare`, and its program is found the
1329    /// same way `cmd`'s is.
1330    #[test]
1331    fn version_cmd_stacks_and_is_anchored() {
1332        let c = Config::parse(
1333            r#"
1334            [defaults]
1335            version_cmd = ["{{ subject }}", "--version"]
1336
1337            [subject.lefthook]
1338            cmd = ["lefthook", "run", "pre-commit"]
1339            version_cmd = "lefthook version"
1340
1341            [subject.mine]
1342            cmd = ["./target/release/mine", "check"]
1343            version_cmd = ["./target/release/mine", "--version"]
1344
1345            [bench.hooks]
1346            subjects = ["lefthook", "mine", "pre-commit"]
1347            [bench.hooks.subject.pre-commit]
1348            cmd = ["pre-commit", "run"]
1349            "#,
1350        )
1351        .unwrap();
1352        let s = c.subjects("hooks").unwrap();
1353        let by = |n: &str| s.iter().find(|x| x.name == n).unwrap().clone();
1354        assert_eq!(
1355            by("lefthook").version_cmd.unwrap(),
1356            ["lefthook", "version"],
1357            "subject over defaults"
1358        );
1359        assert_eq!(
1360            by("pre-commit").version_cmd.unwrap(),
1361            ["{{ subject }}", "--version"],
1362            "inherited, rendered later"
1363        );
1364        let mut mine = by("mine");
1365        mine.anchor(Path::new("/repo"));
1366        assert_eq!(
1367            mine.version_cmd.unwrap(),
1368            ["/repo/./target/release/mine", "--version"]
1369        );
1370        assert!(
1371            Config::parse("[bench.a]\ncmd = \"x\"\nversion_cmd = []").is_err(),
1372            "an empty version_cmd is rejected like an empty prepare"
1373        );
1374    }
1375
1376    #[test]
1377    fn a_listed_subject_must_exist() {
1378        let err = Config::parse("[bench.a]\nsubjects = [\"ghost\"]").unwrap_err();
1379        assert!(format!("{err:#}").contains("[subject.ghost]"), "{err:#}");
1380    }
1381
1382    #[test]
1383    fn a_subject_needs_a_command_from_somewhere() {
1384        let err = Config::parse("[bench.a.subject.x]\nruns = 3").unwrap_err();
1385        assert!(format!("{err:#}").contains("no command"), "{err:#}");
1386    }
1387
1388    #[test]
1389    fn a_broken_template_is_rejected_at_parse_time() {
1390        let err = Config::parse("[bench.a]\ncmd = [\"x\", \"{{ env.X \"]").unwrap_err();
1391        assert!(format!("{err:#}").contains("template"), "{err:#}");
1392    }
1393
1394    /// A subject a benchmark both lists and declares itself is fine without a
1395    /// shared table: the local one provides everything.
1396    #[test]
1397    fn a_listed_subject_may_be_declared_locally() {
1398        let c = Config::parse("[bench.b]\nsubjects = [\"x\"]\n[bench.b.subject.x]\ncmd = [\"x\"]")
1399            .unwrap();
1400        assert_eq!(c.subjects("b").unwrap()[0].cmd, ["x"]);
1401    }
1402
1403    /// Only exit 0 counts unless a layer says otherwise, and the most specific
1404    /// layer's list replaces the others' rather than adding to them.
1405    #[test]
1406    fn ok_exit_codes_default_to_zero_and_stack_by_replacing() {
1407        let c = Config::parse(
1408            r#"
1409            [defaults]
1410            ok_exit_codes = [0, 1]
1411
1412            [subject.grep]
1413            cmd = ["grep", "x", "file"]
1414            ok_exit_codes = [1, 0, 1]
1415
1416            [subject.lint]
1417            cmd = ["lint"]
1418
1419            [bench.plain]
1420            cmd = "x"
1421
1422            [bench.cmp]
1423            subjects = ["grep", "lint"]
1424            ok_exit_codes = [0, 2]
1425
1426            [bench.strict]
1427            subjects = ["grep"]
1428            [bench.strict.subject.grep]
1429            ok_exit_codes = [0]
1430            "#,
1431        )
1432        .unwrap();
1433        assert_eq!(only(&c, "plain").ok_exit_codes, [0, 1], "from defaults");
1434        let cmp = c.subjects("cmp").unwrap();
1435        assert_eq!(
1436            cmp[0].ok_exit_codes,
1437            [0, 1],
1438            "shared subject, sorted and deduplicated"
1439        );
1440        assert_eq!(cmp[1].ok_exit_codes, [0, 2], "bench over defaults");
1441        assert_eq!(
1442            only(&c, "strict").ok_exit_codes,
1443            [0],
1444            "bench's own subject table"
1445        );
1446
1447        let bare = Config::parse("[bench.a]\ncmd = \"x\"").unwrap();
1448        assert_eq!(only(&bare, "a").ok_exit_codes, DEFAULT_OK_EXIT_CODES);
1449    }
1450
1451    /// Windows reports exit codes beyond 0–255, and an NTSTATUS such as
1452    /// 0xC0000005 as a negative `i32`, so the whole `i32` range is accepted.
1453    #[test]
1454    fn ok_exit_codes_take_any_i32() {
1455        let c = Config::parse(
1456            "[bench.a]\ncmd = \"x\"\nok_exit_codes = [0, 256, -1073741819, 2147483647]",
1457        )
1458        .unwrap();
1459        assert_eq!(
1460            only(&c, "a").ok_exit_codes,
1461            [-1073741819, 0, 256, 2147483647]
1462        );
1463    }
1464
1465    /// On Unix only 0–255 can be reported. A list with no such code is an
1466    /// error naming the subject; one with some is kept, and the rest are
1467    /// reported for a warning. Elsewhere the whole `i32` range is possible.
1468    #[test]
1469    fn ok_exit_codes_impossible_on_this_platform() {
1470        assert_eq!(
1471            impossible_exit_codes(&[0, 1, -1073741819, 256], true),
1472            [-1073741819, 256]
1473        );
1474        assert!(impossible_exit_codes(&[0, 1, -1073741819, 256], false).is_empty());
1475
1476        assert!(
1477            check_platform_exit_codes(&[0, 256], true).is_ok(),
1478            "some possible"
1479        );
1480        let err = check_platform_exit_codes(&[256, -1], true).unwrap_err();
1481        assert!(format!("{err:#}").contains("0 to 255"), "{err:#}");
1482        assert!(
1483            check_platform_exit_codes(&[256, -1], false).is_ok(),
1484            "fine on Windows"
1485        );
1486        assert!(check_platform_exit_codes(&[i32::MIN, i32::MAX], false).is_ok());
1487    }
1488
1489    /// Only the platform-independent checks run at load: a Windows-only
1490    /// subject whose codes are all impossible on Unix still loads, since
1491    /// `when` may keep it from ever running there.
1492    #[test]
1493    fn a_list_impossible_here_still_loads() {
1494        Config::parse("[bench.b.subject.win]\ncmd = \"x\"\nok_exit_codes = [-1073741819]").unwrap();
1495    }
1496
1497    /// A list that could never match a real exit status would fail every
1498    /// sample, so it is rejected before anything runs — even in a layer no
1499    /// benchmark uses yet.
1500    #[test]
1501    fn bad_ok_exit_codes_are_rejected_at_parse_time() {
1502        for bad in [
1503            "ok_exit_codes = []",
1504            "ok_exit_codes = [2147483648]",
1505            "ok_exit_codes = [-2147483649]",
1506            "ok_exit_codes = [0xC0000005]",
1507            "ok_exit_codes = [\"1\"]",
1508            "ok_exit_codes = 1",
1509        ] {
1510            let toml = format!("[bench.a]\ncmd = \"x\"\n{bad}");
1511            assert!(Config::parse(&toml).is_err(), "accepted: {bad}");
1512        }
1513        let unused =
1514            "[subject.spare]\ncmd = \"y\"\nok_exit_codes = [4294967296]\n[bench.a]\ncmd = \"x\"";
1515        let err = Config::parse(unused).unwrap_err();
1516        let msg = format!("{err:#}");
1517        assert!(
1518            msg.contains("subject.spare") && msg.contains("4294967296"),
1519            "{msg}"
1520        );
1521    }
1522
1523    /// The syntax check covers the whole file, not only what some benchmark
1524    /// ends up using.
1525    #[test]
1526    fn an_unused_broken_template_is_still_rejected() {
1527        let unused = "[subject.spare]\ncmd = [\"{{ env.X \"]\n[bench.b]\ncmd = [\"x\"]";
1528        assert!(Config::parse(unused).is_err(), "unlisted shared subject");
1529        let overridden = "[subject.a]\ncmd = [\"{% if %}\"]\n[bench.b]\nsubjects = [\"a\"]\n[bench.b.subject.a]\ncmd = [\"x\"]";
1530        assert!(
1531            Config::parse(overridden).is_err(),
1532            "shared value an override replaces"
1533        );
1534    }
1535}