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 crate::compare::{Gate, Gates};
13use anyhow::{Context, Result, bail};
14use serde::Deserialize;
15use std::collections::BTreeMap;
16use std::path::{Path, PathBuf};
17use std::time::Duration;
18
19pub const FILE_NAME: &str = "tak.toml";
20
21/// Defaults chosen to match `tak run`'s, so moving a command into `tak.toml`
22/// does not silently change what it measures.
23pub const DEFAULT_RUNS: u32 = 20;
24pub const DEFAULT_WARMUP: u32 = 3;
25
26/// `runs = "auto"` defaults: about this much wall time per subject, prepare
27/// included, and never fewer or more runs than these. The floor keeps a slow
28/// competitor's result from resting on one or two samples; the ceiling stops
29/// a millisecond-scale subject from spending the whole budget on runs that
30/// stopped adding information long before.
31pub const DEFAULT_BUDGET: Duration = Duration::from_secs(30);
32pub const DEFAULT_MIN_RUNS: u32 = 5;
33pub const DEFAULT_MAX_RUNS: u32 = 50;
34
35/// Exit codes a sample may end with and still count, unless `ok_exit_codes`
36/// says otherwise: success, and nothing else, as a shell would judge it.
37pub const DEFAULT_OK_EXIT_CODES: [i32; 1] = [0];
38
39#[derive(Debug, Deserialize)]
40pub struct Config {
41    /// Benchmarks by name. A BTreeMap so runs are ordered and reproducible
42    /// rather than following the file's incidental key order.
43    ///
44    /// Settings tables — `[env]`, `[gate]`, `[report]`, `[runner]` — live in
45    /// the same file but are not deserialized here: the settings registry
46    /// declares their dotted keys, and `settings::TakConfigLayer` reads exactly
47    /// those, so this type never has to be kept in step with it. That is also
48    /// why defaults for every benchmark live under `[defaults]`, not `[env]`.
49    #[serde(default)]
50    pub bench: BTreeMap<String, Bench>,
51    /// Settings every benchmark starts from.
52    #[serde(default)]
53    defaults: Layer,
54    /// Settings for the benchmarks that name the group in `group = "..."`,
55    /// stacked between `[defaults]` and the benchmark's own. For settings
56    /// some benchmarks share and others do not, such as the setup command
57    /// and environment of the ones that measure the same fixture.
58    #[serde(default)]
59    group: BTreeMap<String, Layer>,
60    /// Subjects declared once, for benchmarks to name in `subjects = [...]`.
61    #[serde(default)]
62    subject: BTreeMap<String, SubjectDecl>,
63    /// How to build the project from a clean checkout, for
64    /// `tak backfill --commits`. Nothing else runs it: `tak run` measures
65    /// whatever is already built, as it always has.
66    #[serde(default)]
67    build: Option<BuildDecl>,
68}
69
70/// `[build]` as written.
71///
72/// `deny_unknown_fields` because this table is new and small, and a misspelt
73/// `evn` silently building without the variables it names would be measured
74/// at every commit of a backfill before anyone noticed.
75#[derive(Debug, Deserialize)]
76#[serde(deny_unknown_fields)]
77struct BuildDecl {
78    cmd: Cmd,
79    /// Relative to `tak.toml`, inside the checkout being built.
80    dir: Option<PathBuf>,
81    #[serde(default)]
82    env: BTreeMap<String, String>,
83}
84
85/// The build command, resolved and checked.
86#[derive(Debug, Clone, PartialEq)]
87pub struct Build {
88    pub cmd: Vec<String>,
89    /// Relative to the directory holding `tak.toml`; see [`Build::anchor`].
90    pub dir: Option<PathBuf>,
91    pub env: BTreeMap<String, String>,
92}
93
94impl Build {
95    /// Resolve the program and directory against `root`, the directory that
96    /// holds `tak.toml` in the checkout being built. The same rule as
97    /// [`Subject::anchor`]: a program path containing `/` is relative to
98    /// `root`, a bare name is looked up on PATH.
99    pub fn anchor(&mut self, root: &Path) {
100        if let Some(p) = self.cmd.first_mut()
101            && p.contains('/')
102            && Path::new(p.as_str()).is_relative()
103        {
104            *p = root.join(p.as_str()).to_string_lossy().into_owned();
105        }
106        self.dir = Some(match &self.dir {
107            Some(d) => root.join(d),
108            None => root.to_path_buf(),
109        });
110    }
111}
112
113impl BuildDecl {
114    fn resolve(&self) -> Result<Build> {
115        let cmd = self.cmd.argv().context("cmd")?;
116        // Not rendered, so a template here would reach the build as literal
117        // braces. Refusing it keeps the door open to rendering later without
118        // changing what an existing file means.
119        let strings = cmd
120            .iter()
121            .chain(self.env.values())
122            .map(String::as_str)
123            .chain(self.dir.as_ref().and_then(|d| d.to_str()));
124        if let Some(t) = strings
125            .into_iter()
126            .find(|s| crate::template::is_template(s))
127        {
128            bail!("templates are not supported in [build]: {t:?}");
129        }
130        if let Some(d) = &self.dir {
131            // The build runs in a throwaway checkout of an old commit. A
132            // directory outside it would build the live tree instead, and
133            // every commit of the backfill would measure the same binary.
134            if d.is_absolute()
135                || d.components()
136                    .any(|c| matches!(c, std::path::Component::ParentDir))
137            {
138                bail!(
139                    "dir must stay inside the checkout being built, not {}",
140                    d.display()
141                );
142            }
143        }
144        Ok(Build {
145            cmd,
146            dir: self.dir.clone(),
147            env: self.env.clone(),
148        })
149    }
150}
151
152/// The settings that stack: `[defaults]`, a benchmark, a shared subject and a
153/// benchmark's own subject table all carry them, and each overrides the one
154/// before. `env` and `vars` merge key by key rather than replacing.
155#[derive(Debug, Default, Deserialize)]
156struct Layer {
157    /// A count, or `"auto"` to size each subject from its own speed.
158    runs: Option<RunsDecl>,
159    warmup: Option<u32>,
160    /// `runs = "auto"`: wall time to spend per subject, as `30s`, `2m`, `500ms`.
161    budget: Option<String>,
162    /// `runs = "auto"`: fewest runs any subject gets.
163    min_runs: Option<u32>,
164    /// `runs = "auto"`: most runs any subject gets.
165    max_runs: Option<u32>,
166    /// Exit codes that count as a successful sample. Replaces, not merges:
167    /// a subject listing `[0, 1]` means exactly those.
168    ok_exit_codes: Option<Vec<i64>>,
169    /// Untimed command run before every sample.
170    prepare: Option<Cmd>,
171    /// Untimed command run once per benchmark and subject, before its first
172    /// sample, in the directory holding `tak.toml`.
173    setup: Option<Cmd>,
174    /// Untimed command run after every timed sample; its exit status says
175    /// whether that sample did the right work.
176    check: Option<Cmd>,
177    /// Command whose output names the subject's version, run once after
178    /// `setup` and before sampling, and reported in `--export-json`.
179    version_cmd: Option<Cmd>,
180    /// Directory to run in, relative to `tak.toml`.
181    dir: Option<PathBuf>,
182    /// Variables set for the command.
183    #[serde(default)]
184    env: BTreeMap<String, String>,
185    /// Values for templates, as `{{ vars.name }}`. Not passed to the command.
186    #[serde(default)]
187    vars: BTreeMap<String, String>,
188    /// Opt in to heap-allocation counting under DHAT. A layer setting rather
189    /// than a subject one like `counters`: it never gates, so there is no
190    /// competitor's upgrade for it to fail, and a single-command benchmark
191    /// needs a way to turn it on.
192    allocations: Option<bool>,
193    /// Numbers recorded beside the timings, by name: a file's size, or what
194    /// a command prints. Merged by name across layers, like `env`, with a
195    /// more specific layer's metric replacing a same-named one outright.
196    #[serde(default)]
197    metric: BTreeMap<String, MetricDecl>,
198}
199
200/// A custom metric as written: exactly one of `file` or `cmd`.
201///
202/// Two fields on one table rather than a tagged enum, so the error for a
203/// table with both or neither can name the metric and say what is wrong,
204/// instead of serde's "data did not match any variant".
205///
206/// Unknown keys are refused, unlike in the tables around it: with only two
207/// keys to spell, a typo such as `fiel = "new.bin"` next to an old `file`
208/// would otherwise go on recording the old file's size without a word.
209#[derive(Debug, Clone, Deserialize)]
210#[serde(deny_unknown_fields)]
211struct MetricDecl {
212    /// A path, relative to `tak.toml`, whose size in bytes is the value.
213    file: Option<String>,
214    /// A command that prints the value on stdout.
215    cmd: Option<Cmd>,
216}
217
218impl MetricDecl {
219    fn resolve(&self) -> Result<MetricSource> {
220        match (&self.file, &self.cmd) {
221            (Some(_), Some(_)) => bail!("sets both `file` and `cmd`; use one or the other"),
222            (None, None) => bail!("needs `file` or `cmd`"),
223            (Some(f), None) if f.trim().is_empty() => bail!("`file` is empty"),
224            (Some(f), None) => Ok(MetricSource::File(PathBuf::from(f))),
225            (None, Some(c)) => Ok(MetricSource::Cmd(c.argv().context("cmd")?)),
226        }
227    }
228}
229
230/// Where a custom metric's value comes from, resolved.
231#[derive(Debug, Clone, PartialEq)]
232pub enum MetricSource {
233    /// The size of this file in bytes. Relative to `tak.toml` until
234    /// [`Subject::anchor`] makes it absolute; never relative to `dir`.
235    File(PathBuf),
236    /// Run once, untimed, after the subject's samples, in its `dir` and
237    /// `env`; see [`crate::measure::custom_metric`].
238    Cmd(Vec<String>),
239}
240
241/// The longest name a custom metric may have. Room for a descriptive name
242/// with its unit on the end, and short enough to fit a report's table.
243const METRIC_NAME_MAX: usize = 64;
244
245/// Check a custom metric's name.
246///
247/// Lowercase ASCII, digits and `_`, starting with a letter. Names are keys in
248/// every record and are matched byte for byte across commits, so `Bundle_KB`
249/// and `bundle_kb` would silently be two series; one spelling per name rules
250/// that out. The charset also keeps a name usable unquoted as a TOML key, a
251/// JSON key and a jq path. Built-in names are refused because a declared
252/// metric shares the record's one map with them: an `instructions` printed by
253/// a script would replace the counted one, and the gate would read it.
254fn metric_name(name: &str) -> Result<()> {
255    // The charset below already excludes control characters. This check runs
256    // first anyway, so a newline in a metric name gets the same explanation
257    // as one in a benchmark name.
258    crate::record::check_name("metric", name)?;
259    let mut chars = name.chars();
260    let well_formed = chars.next().is_some_and(|c| c.is_ascii_lowercase())
261        && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_');
262    if !well_formed {
263        bail!(
264            "metric name {name:?} must start with a lowercase letter and use only a-z, 0-9 and _, \
265             such as `binary_bytes`"
266        );
267    }
268    if name.len() > METRIC_NAME_MAX {
269        bail!("metric name `{name}` is longer than {METRIC_NAME_MAX} characters");
270    }
271    if crate::record::is_builtin_metric(name) {
272        bail!(
273            "metric name `{name}` is reserved for what tak measures itself \
274             (`instructions`, and anything starting `wall_` or `alloc_`)"
275        );
276    }
277    Ok(())
278}
279
280#[derive(Debug, Deserialize)]
281pub struct Bench {
282    /// The command, for a benchmark of one program. Mutually exclusive with
283    /// `subjects` and `subject`, which declare several programs measured
284    /// against each other.
285    #[serde(default)]
286    cmd: Option<Cmd>,
287    #[serde(flatten)]
288    layer: Layer,
289    /// Run this benchmark only when this expr condition holds.
290    when: Option<String>,
291    /// This benchmark's gate, where it differs from `[gate]`.
292    gate: Option<GateDecl>,
293    /// The `[group.NAME]` whose settings this benchmark starts from.
294    group: Option<String>,
295    /// Shared `[subject.NAME]` tables this benchmark measures.
296    #[serde(default)]
297    subjects: Vec<String>,
298    /// Subjects declared here, or overrides of shared ones for this benchmark
299    /// only. The name is what their measurements are recorded under
300    /// (`Record::tool`). A BTreeMap for the same reason `Config::bench` is one.
301    #[serde(default)]
302    subject: BTreeMap<String, SubjectDecl>,
303}
304
305/// One program in a multi-subject benchmark, as written in `tak.toml`: either
306/// a shared `[subject.NAME]` or a benchmark's `[bench.B.subject.NAME]`.
307#[derive(Debug, Deserialize)]
308pub struct SubjectDecl {
309    /// Optional here because a benchmark's table may only override settings of
310    /// a shared subject that already has one.
311    #[serde(default)]
312    cmd: Option<Cmd>,
313    #[serde(flatten)]
314    layer: Layer,
315    /// Measure this subject only when this expr condition holds. A
316    /// benchmark's own table replaces a shared subject's condition.
317    when: Option<String>,
318    /// Opt in to instruction counting. Off by default because a
319    /// multi-subject benchmark usually compares against other people's
320    /// programs, whose instruction counts are not this project's to gate on:
321    /// a competitor's upgrade would fail the gate.
322    counters: Option<bool>,
323    /// This subject's gate, stacked on the benchmark's.
324    gate: Option<GateDecl>,
325}
326
327/// A `gate = { ... }` table on a benchmark or subject: the `[gate]` settings,
328/// overridden for one series.
329///
330/// Not part of [`Layer`], and so not settable in `[defaults]`. A gate for
331/// every benchmark is what `[gate]` already is, and a second spelling of it
332/// would outrank `--gate-pct` for no reason anyone could see from the command
333/// line. On a benchmark and a subject rather than in the layer stack also keeps
334/// it out of `tak run`, which has no use for it.
335///
336/// `deny_unknown_fields`, unlike the tables around it. A mistyped key here —
337/// `pc = 5` — would otherwise leave the benchmark at the global gate while the
338/// file reads as though it had its own, which is a gate the user thought they
339/// set.
340#[derive(Debug, Default, Clone, Copy, Deserialize)]
341#[serde(deny_unknown_fields)]
342struct GateDecl {
343    /// Percentage of the base an instruction count may rise by.
344    pct: Option<f64>,
345    /// Instructions a count may rise by, whatever the percentage.
346    min_delta: Option<u64>,
347    /// False reports the series and never fails on it.
348    enabled: Option<bool>,
349}
350
351impl GateDecl {
352    /// `gate` with what this table sets replaced, key by key: a subject that
353    /// only says `enabled = false` keeps its benchmark's percentage.
354    fn over(&self, gate: Gate) -> Gate {
355        Gate {
356            pct: self.pct.unwrap_or(gate.pct),
357            min_delta: self.min_delta.unwrap_or(gate.min_delta),
358            enabled: self.enabled.unwrap_or(gate.enabled),
359        }
360    }
361}
362
363/// A command, written either as a list or as a plain string.
364#[derive(Debug, Clone, Deserialize)]
365#[serde(untagged)]
366enum Cmd {
367    Argv(Vec<String>),
368    Line(String),
369}
370
371impl Cmd {
372    /// The command as argv.
373    ///
374    /// A string is split on whitespace and nothing else. There is deliberately
375    /// no shell: spawning one adds its own startup cost and variance to every
376    /// sample, which for commands in the 10ms range is a large fraction of the
377    /// measurement. Anything needing a pipe or a glob should be a list whose
378    /// first element is the interpreter.
379    fn argv(&self) -> Result<Vec<String>> {
380        let v = match self {
381            Cmd::Argv(v) => v.clone(),
382            Cmd::Line(s) => split_line(s),
383        };
384        if v.is_empty() {
385            bail!("empty command");
386        }
387        Ok(v)
388    }
389}
390
391/// Split a string command on whitespace, keeping each template tag whole:
392/// `mycli {{ vars.lockfile }}` is two arguments, the second rendered later.
393/// Nothing else is special — no quotes, no escapes — as for any string
394/// command.
395fn split_line(line: &str) -> Vec<String> {
396    let mut out = Vec::new();
397    let mut cur = String::new();
398    let mut close: Option<&str> = None;
399    let mut rest = line;
400    while let Some(c) = rest.chars().next() {
401        if let Some(end) = close {
402            if rest.starts_with(end) {
403                cur.push_str(end);
404                rest = &rest[end.len()..];
405                close = None;
406                continue;
407            }
408        } else if let Some(end) = [("{{", "}}"), ("{%", "%}"), ("{#", "#}")]
409            .iter()
410            .find_map(|(open, end)| rest.starts_with(open).then_some(*end))
411        {
412            cur.push_str(&rest[..2]);
413            rest = &rest[2..];
414            close = Some(end);
415            continue;
416        } else if c.is_whitespace() {
417            if !cur.is_empty() {
418                out.push(std::mem::take(&mut cur));
419            }
420            rest = &rest[c.len_utf8()..];
421            continue;
422        }
423        cur.push(c);
424        rest = &rest[c.len_utf8()..];
425    }
426    if !cur.is_empty() {
427        out.push(cur);
428    }
429    out
430}
431
432/// `runs` as written: a count, or a word. Only `"auto"` is a valid word,
433/// checked when the subject is resolved so the error names it.
434#[derive(Debug, Clone, Deserialize)]
435#[serde(untagged)]
436pub enum RunsDecl {
437    Count(u32),
438    Word(String),
439}
440
441impl RunsDecl {
442    fn resolve(&self) -> Result<Runs> {
443        match self {
444            RunsDecl::Count(n) => Ok(Runs::Fixed(*n)),
445            RunsDecl::Word(w) if w == "auto" => Ok(Runs::Auto),
446            RunsDecl::Word(w) => bail!("runs must be a number or \"auto\", not {w:?}"),
447        }
448    }
449}
450
451/// How many timed runs a subject gets.
452#[derive(Debug, Clone, Copy, PartialEq, Eq)]
453pub enum Runs {
454    Fixed(u32),
455    /// Decided after the warmups, from how long one sample takes: see
456    /// [`AutoRuns`].
457    Auto,
458}
459
460impl std::str::FromStr for Runs {
461    type Err = anyhow::Error;
462    fn from_str(s: &str) -> Result<Self> {
463        if s == "auto" {
464            return Ok(Runs::Auto);
465        }
466        s.parse()
467            .map(Runs::Fixed)
468            .map_err(|_| anyhow::anyhow!("runs must be a number or \"auto\", not {s:?}"))
469    }
470}
471
472/// The limits `runs = "auto"` works within. Resolved for every subject, so
473/// `tak run --runs auto` can switch a fixed benchmark over without the file
474/// having to declare them.
475#[derive(Debug, Clone, Copy, PartialEq, Eq)]
476pub struct AutoRuns {
477    pub budget: Duration,
478    pub min: u32,
479    pub max: u32,
480}
481
482impl AutoRuns {
483    /// Runs for a subject whose samples take `slot` each, prepare included:
484    /// as many as fit in the budget, within `min..=max`.
485    pub fn runs_for(&self, slot: Duration) -> u32 {
486        let fit = if slot.is_zero() {
487            u64::from(self.max)
488        } else {
489            (self.budget.as_secs_f64() / slot.as_secs_f64()) as u64
490        };
491        fit.clamp(u64::from(self.min), u64::from(self.max)) as u32
492    }
493}
494
495/// Parse `500ms`, `30s`, `2m` or `1h`; a bare number is seconds.
496pub fn parse_duration(text: &str) -> Result<Duration> {
497    let t = text.trim();
498    let split = t
499        .find(|c: char| !(c.is_ascii_digit() || c == '.'))
500        .unwrap_or(t.len());
501    let (num, unit) = t.split_at(split);
502    let n: f64 = num
503        .parse()
504        .map_err(|_| anyhow::anyhow!("not a duration: {text:?} (try `30s` or `2m`)"))?;
505    let secs = match unit.trim() {
506        "ms" => n / 1000.0,
507        "" | "s" => n,
508        "m" => n * 60.0,
509        "h" => n * 3600.0,
510        _ => bail!("not a duration: {text:?} (units are ms, s, m, h)"),
511    };
512    if !secs.is_finite() || secs <= 0.0 {
513        bail!("a duration must be positive: {text:?}");
514    }
515    // Finite and positive can still be too large for a Duration; that is a
516    // configuration error, not a panic.
517    Duration::try_from_secs_f64(secs).map_err(|_| anyhow::anyhow!("duration too large: {text:?}"))
518}
519
520/// The name a single-command benchmark records under. `compare` renders this
521/// tool as the bare benchmark name.
522pub const SELF_TOOL: &str = "self";
523
524/// A subject with every default applied, ready to measure.
525#[derive(Debug, Clone, PartialEq)]
526pub struct Subject {
527    /// Recorded as `Record::tool`.
528    pub name: String,
529    pub cmd: Vec<String>,
530    pub prepare: Option<Vec<String>>,
531    /// Run once before the subject's first sample. Always from the directory
532    /// holding `tak.toml`, never from `dir`; see [`Subject::anchor`].
533    pub setup: Option<Vec<String>>,
534    /// Where `setup` runs: set by [`Subject::anchor`] to the directory holding
535    /// `tak.toml`. `None` runs it in tak's own working directory.
536    pub setup_dir: Option<PathBuf>,
537    /// Run after every timed sample, untimed. Exit 0 means the sample passed.
538    pub check: Option<Vec<String>>,
539    /// Run once, untimed, after `setup` and before the first warmup; its first
540    /// line of output is the version exported for this subject. See
541    /// [`crate::measure::interleaved_with_versions`].
542    pub version_cmd: Option<Vec<String>>,
543    /// Relative to `tak.toml`; the caller resolves it.
544    pub dir: Option<PathBuf>,
545    pub env: BTreeMap<String, String>,
546    /// Template values from `vars` tables, used by [`crate::template`].
547    pub vars: BTreeMap<String, String>,
548    /// Measured only when this holds; see [`crate::condition`].
549    pub when: Option<String>,
550    pub runs: Runs,
551    /// The limits `Runs::Auto` works within.
552    pub auto: AutoRuns,
553    pub warmup: u32,
554    pub counters: bool,
555    /// Count heap allocations under DHAT. Recorded and reported, never gated.
556    pub allocations: bool,
557    /// Exit codes a timed or warmup sample may end with and still count.
558    /// Never empty. A death by signal fails whatever this holds, and
559    /// `setup` and `prepare` are always held to exit 0.
560    pub ok_exit_codes: Vec<i32>,
561    /// Custom metrics by name, recorded beside the timings. Empty unless a
562    /// layer declares some.
563    pub metrics: BTreeMap<String, MetricSource>,
564}
565
566impl Subject {
567    /// Resolve paths against `root`, the directory holding `tak.toml`.
568    ///
569    /// `dir` becomes the working directory, but a relative program path — one
570    /// containing a `/`, like `./target/release/mycli` — is resolved against
571    /// `root`, not `dir`. Otherwise giving a subject a fixture directory would
572    /// make the project's own binary unfindable. A bare name is left for PATH
573    /// lookup, and arguments are never touched.
574    ///
575    /// `setup` is the exception to `dir`: it runs in `root` itself. Its usual
576    /// job is to create or recreate `dir` — a clone, a generated project — and
577    /// a command cannot sensibly start inside a directory that does not exist
578    /// yet or that it is about to delete. Running it where `dir` is written
579    /// relative to also means the same path works as one of its arguments.
580    /// Choosing between the two by whether `dir` exists would give a setup a
581    /// different working directory on its second run than on its first.
582    pub fn anchor(&mut self, root: &Path) {
583        let program = |argv: &mut Vec<String>| {
584            if let Some(p) = argv.first_mut()
585                && p.contains('/')
586                && Path::new(p.as_str()).is_relative()
587            {
588                *p = root.join(p.as_str()).to_string_lossy().into_owned();
589            }
590        };
591        program(&mut self.cmd);
592        if let Some(prepare) = &mut self.prepare {
593            program(prepare);
594        }
595        if let Some(setup) = &mut self.setup {
596            program(setup);
597        }
598        if let Some(check) = &mut self.check {
599            program(check);
600        }
601        if let Some(version) = &mut self.version_cmd {
602            program(version);
603        }
604        // A metric's file is found from `tak.toml` like a program path, not
605        // from `dir`: the binary a startup benchmark runs from a fixture
606        // directory is still the one under `target/`. Unlike a program, a
607        // bare name is a path too, since there is no PATH to look it up on.
608        for source in self.metrics.values_mut() {
609            match source {
610                MetricSource::File(p) if p.is_relative() => *p = root.join(&*p),
611                MetricSource::File(_) => {}
612                MetricSource::Cmd(argv) => program(argv),
613            }
614        }
615        self.dir = Some(match &self.dir {
616            Some(d) => root.join(d),
617            None => root.to_path_buf(),
618        });
619        self.setup_dir = Some(root.to_path_buf());
620    }
621}
622
623impl Bench {
624    /// This benchmark's own `when` condition.
625    pub fn when(&self) -> Option<&str> {
626        self.when.as_deref()
627    }
628
629    /// The `[group.NAME]` this benchmark names, if any.
630    pub fn group(&self) -> Option<&str> {
631        self.group.as_deref()
632    }
633
634    /// Whether this benchmark compares several programs rather than measuring
635    /// one.
636    pub fn is_multi(&self) -> bool {
637        !self.subject.is_empty() || !self.subjects.is_empty()
638    }
639}
640
641impl Config {
642    /// Whether tak.toml declares `[group.NAME]`.
643    pub fn has_group(&self, name: &str) -> bool {
644        self.group.contains_key(name)
645    }
646
647    /// The names of the declared `[group.NAME]` tables.
648    pub fn group_names(&self) -> impl Iterator<Item = &str> {
649        self.group.keys().map(String::as_str)
650    }
651
652    /// Every subject of benchmark `name`, with each layer applied: defaults,
653    /// the benchmark's group, the benchmark, the shared subject, then the
654    /// benchmark's own subject table. Templates are not rendered yet; see [`crate::template::render`].
655    ///
656    /// A single-command benchmark is one subject named [`SELF_TOOL`] with
657    /// counters on, which is exactly what it measured before subjects existed.
658    pub fn subjects(&self, name: &str) -> Result<Vec<Subject>> {
659        let b = self
660            .bench
661            .get(name)
662            .with_context(|| format!("no benchmark `{name}`"))?;
663        let group = match &b.group {
664            Some(g) => Some(
665                self.group
666                    .get(g)
667                    .with_context(|| format!("names group `{g}`, but there is no [group.{g}]"))?,
668            ),
669            None => None,
670        };
671        let base: Vec<&Layer> = [Some(&self.defaults), group, Some(&b.layer)]
672            .into_iter()
673            .flatten()
674            .collect();
675        if let Some(cmd) = &b.cmd {
676            if b.is_multi() {
677                bail!("declares both `cmd` and subjects; use one or the other");
678            }
679            return Ok(vec![resolve(SELF_TOOL, cmd, true, None, &base)?]);
680        }
681        // A benchmark's own table can add a subject or override a shared one;
682        // either way it is measured, listed or not.
683        let names: std::collections::BTreeSet<&String> =
684            b.subjects.iter().chain(b.subject.keys()).collect();
685        if names.is_empty() {
686            bail!("has no command");
687        }
688        names
689            .into_iter()
690            .map(|n| {
691                let shared = self.subject.get(n);
692                let local = b.subject.get(n);
693                if b.subjects.contains(n) && shared.is_none() && local.is_none() {
694                    bail!("lists subject `{n}`, but there is no [subject.{n}]");
695                }
696                let cmd = local
697                    .and_then(|d| d.cmd.as_ref())
698                    .or_else(|| shared.and_then(|d| d.cmd.as_ref()))
699                    .with_context(|| format!("subject `{n}` has no command"))?;
700                let when = local
701                    .and_then(|d| d.when.clone())
702                    .or_else(|| shared.and_then(|d| d.when.clone()));
703                let counters = local
704                    .and_then(|d| d.counters)
705                    .or_else(|| shared.and_then(|d| d.counters))
706                    .unwrap_or(false);
707                let mut layers = base.clone();
708                layers.extend(shared.map(|d| &d.layer));
709                layers.extend(local.map(|d| &d.layer));
710                resolve(n, cmd, counters, when, &layers).with_context(|| format!("subject `{n}`"))
711            })
712            .collect()
713    }
714}
715
716impl Config {
717    /// Every settings layer in the file, with where it is.
718    fn layers(&self) -> Vec<(String, &Layer)> {
719        let mut out = vec![("defaults".to_string(), &self.defaults)];
720        for (g, l) in &self.group {
721            out.push((format!("group.{g}"), l));
722        }
723        for (n, d) in &self.subject {
724            out.push((format!("subject.{n}"), &d.layer));
725        }
726        for (b, bench) in &self.bench {
727            out.push((format!("bench.{b}"), &bench.layer));
728            for (n, d) in &bench.subject {
729                out.push((format!("bench.{b}.subject.{n}"), &d.layer));
730            }
731        }
732        out
733    }
734
735    /// Every `when` in the file, with where it is.
736    fn conditions(&self) -> Vec<(String, &str)> {
737        let mut out = Vec::new();
738        for (n, d) in &self.subject {
739            out.extend(d.when.as_deref().map(|w| (format!("subject.{n}.when"), w)));
740        }
741        for (b, bench) in &self.bench {
742            out.extend(
743                bench
744                    .when
745                    .as_deref()
746                    .map(|w| (format!("bench.{b}.when"), w)),
747            );
748            for (n, d) in &bench.subject {
749                out.extend(
750                    d.when
751                        .as_deref()
752                        .map(|w| (format!("bench.{b}.subject.{n}.when"), w)),
753                );
754            }
755        }
756        out
757    }
758
759    /// Every `gate` table in the file, with where it is.
760    fn gate_decls(&self) -> Vec<(String, &GateDecl)> {
761        let mut out = Vec::new();
762        for (n, d) in &self.subject {
763            out.extend(d.gate.as_ref().map(|g| (format!("subject.{n}.gate"), g)));
764        }
765        for (b, bench) in &self.bench {
766            out.extend(bench.gate.as_ref().map(|g| (format!("bench.{b}.gate"), g)));
767            for (n, d) in &bench.subject {
768                out.extend(
769                    d.gate
770                        .as_ref()
771                        .map(|g| (format!("bench.{b}.subject.{n}.gate"), g)),
772                );
773            }
774        }
775        out
776    }
777
778    /// The gate for every series this file declares, starting from `global`.
779    ///
780    /// Stacked in the same order as every other setting — the benchmark, then
781    /// the shared `[subject.NAME]`, then the benchmark's own subject table —
782    /// key by key, so a subject that only sets `enabled = false` keeps the
783    /// benchmark's percentage.
784    ///
785    /// `when` is not consulted. It decides whether a series is measured, and a
786    /// series that was measured on either side is compared under the gate the
787    /// file gives it, whichever machine is reading the notes.
788    pub fn gates(&self, global: Gate) -> Gates {
789        let mut gates = Gates::uniform(global);
790        for (name, b) in &self.bench {
791            let bench = b.gate.map_or(global, |d| d.over(global));
792            gates.set_bench(name, bench);
793            if !b.is_multi() {
794                gates.set_series(name, SELF_TOOL, bench);
795                continue;
796            }
797            for n in b.subjects.iter().chain(b.subject.keys()) {
798                let mut gate = bench;
799                for d in [self.subject.get(n), b.subject.get(n)]
800                    .into_iter()
801                    .flatten()
802                {
803                    if let Some(decl) = &d.gate {
804                        gate = decl.over(gate);
805                    }
806                }
807                gates.set_series(name, n, gate);
808            }
809        }
810        gates
811    }
812
813    /// Every string that may hold a template, as written, with where it is.
814    fn template_strings(&self) -> Vec<(String, &str)> {
815        fn layer<'a>(out: &mut Vec<(String, &'a str)>, at: &str, l: &'a Layer) {
816            if let Some(p) = &l.prepare {
817                cmd(out, &format!("{at}.prepare"), p);
818            }
819            if let Some(p) = &l.setup {
820                cmd(out, &format!("{at}.setup"), p);
821            }
822            if let Some(c) = &l.check {
823                cmd(out, &format!("{at}.check"), c);
824            }
825            if let Some(v) = &l.version_cmd {
826                cmd(out, &format!("{at}.version_cmd"), v);
827            }
828            if let Some(d) = l.dir.as_ref().and_then(|d| d.to_str()) {
829                out.push((format!("{at}.dir"), d));
830            }
831            for (k, v) in &l.env {
832                out.push((format!("{at}.env.{k}"), v));
833            }
834            for (k, v) in &l.vars {
835                out.push((format!("{at}.vars.{k}"), v));
836            }
837            for (k, m) in &l.metric {
838                if let Some(f) = &m.file {
839                    out.push((format!("{at}.metric.{k}.file"), f));
840                }
841                if let Some(c) = &m.cmd {
842                    cmd(out, &format!("{at}.metric.{k}.cmd"), c);
843                }
844            }
845        }
846        fn cmd<'a>(out: &mut Vec<(String, &'a str)>, at: &str, c: &'a Cmd) {
847            match c {
848                Cmd::Argv(v) => out.extend(v.iter().map(|a| (at.to_string(), a.as_str()))),
849                Cmd::Line(l) => out.push((at.to_string(), l)),
850            }
851        }
852        fn subject<'a>(out: &mut Vec<(String, &'a str)>, at: &str, d: &'a SubjectDecl) {
853            if let Some(c) = &d.cmd {
854                cmd(out, &format!("{at}.cmd"), c);
855            }
856            layer(out, at, &d.layer);
857        }
858        let mut out = Vec::new();
859        layer(&mut out, "defaults", &self.defaults);
860        for (g, l) in &self.group {
861            layer(&mut out, &format!("group.{g}"), l);
862        }
863        for (n, d) in &self.subject {
864            subject(&mut out, &format!("subject.{n}"), d);
865        }
866        for (b, bench) in &self.bench {
867            if let Some(c) = &bench.cmd {
868                cmd(&mut out, &format!("bench.{b}.cmd"), c);
869            }
870            layer(&mut out, &format!("bench.{b}"), &bench.layer);
871            for (n, d) in &bench.subject {
872                subject(&mut out, &format!("bench.{b}.subject.{n}"), d);
873            }
874        }
875        out
876    }
877}
878
879/// Stack `layers`, least specific first, into one subject. A later layer's
880/// setting replaces an earlier one's — a subject's own prepare replaces the
881/// benchmark's rather than running after it, since the two usually reset the
882/// same state, and `setup` and `check` likewise — except `env` and `vars`,
883/// which merge key by key.
884fn resolve(
885    name: &str,
886    cmd: &Cmd,
887    counters: bool,
888    when: Option<String>,
889    layers: &[&Layer],
890) -> Result<Subject> {
891    fn last<'a, T>(layers: &[&'a Layer], f: impl Fn(&'a Layer) -> Option<&'a T>) -> Option<&'a T> {
892        layers.iter().rev().find_map(|l| f(l))
893    }
894    let merged = |f: fn(&Layer) -> &BTreeMap<String, String>| {
895        layers.iter().fold(BTreeMap::new(), |mut m, l| {
896            m.extend(f(l).clone());
897            m
898        })
899    };
900    let budget = match last(layers, |l| l.budget.as_ref()) {
901        Some(b) => parse_duration(b).context("budget")?,
902        None => DEFAULT_BUDGET,
903    };
904    let auto = AutoRuns {
905        budget,
906        min: last(layers, |l| l.min_runs.as_ref())
907            .copied()
908            .unwrap_or(DEFAULT_MIN_RUNS),
909        max: last(layers, |l| l.max_runs.as_ref())
910            .copied()
911            .unwrap_or(DEFAULT_MAX_RUNS),
912    };
913    if auto.min == 0 {
914        bail!("min_runs must be at least 1");
915    }
916    if auto.min > auto.max {
917        bail!(
918            "min_runs ({}) is more than max_runs ({})",
919            auto.min,
920            auto.max
921        );
922    }
923    Ok(Subject {
924        name: name.to_string(),
925        cmd: cmd.argv()?,
926        prepare: last(layers, |l| l.prepare.as_ref())
927            .map(Cmd::argv)
928            .transpose()?,
929        setup: last(layers, |l| l.setup.as_ref())
930            .map(Cmd::argv)
931            .transpose()
932            .context("setup")?,
933        setup_dir: None,
934        check: last(layers, |l| l.check.as_ref())
935            .map(Cmd::argv)
936            .transpose()
937            .context("check")?,
938        version_cmd: last(layers, |l| l.version_cmd.as_ref())
939            .map(Cmd::argv)
940            .transpose()
941            .context("version_cmd")?,
942        dir: last(layers, |l| l.dir.as_ref()).cloned(),
943        env: merged(|l| &l.env),
944        vars: merged(|l| &l.vars),
945        when,
946        runs: last(layers, |l| l.runs.as_ref())
947            .map_or(Ok(Runs::Fixed(DEFAULT_RUNS)), RunsDecl::resolve)?,
948        auto,
949        warmup: last(layers, |l| l.warmup.as_ref())
950            .copied()
951            .unwrap_or(DEFAULT_WARMUP),
952        counters,
953        allocations: last(layers, |l| l.allocations.as_ref())
954            .copied()
955            .unwrap_or(false),
956        ok_exit_codes: match last(layers, |l| l.ok_exit_codes.as_ref()) {
957            Some(codes) => ok_exit_codes(codes)?,
958            None => DEFAULT_OK_EXIT_CODES.to_vec(),
959        },
960        metrics: {
961            // By name, a later layer's table replacing an earlier one's
962            // whole: a subject switching `binary_bytes` from `file` to `cmd`
963            // must not end up with both.
964            let mut decls: BTreeMap<&String, &MetricDecl> = BTreeMap::new();
965            for l in layers {
966                decls.extend(&l.metric);
967            }
968            decls
969                .into_iter()
970                .map(|(name, decl)| {
971                    let source = decl.resolve().with_context(|| format!("metric `{name}`"))?;
972                    Ok((name.clone(), source))
973                })
974                .collect::<Result<_>>()?
975        },
976    })
977}
978
979/// The range of exit codes a platform can report, when narrower than `i32`:
980/// Unix keeps only the low 8 bits of a process's status. `None` where the
981/// whole `i32` range is possible, as on Windows.
982pub fn exit_code_range(unix: bool) -> Option<std::ops::RangeInclusive<i32>> {
983    unix.then_some(0..=255)
984}
985
986/// The codes in `codes` that a platform can never report, so can never match.
987///
988/// A `tak.toml` shared between platforms may list a Windows code next to
989/// Unix ones, such as `[0, 1, -1073741819]`, so some impossible codes are
990/// only worth a warning. A list with *no* possible code would drop the
991/// subject at its first sample, which is a mistake to catch before it runs.
992pub fn impossible_exit_codes(codes: &[i32], unix: bool) -> Vec<i32> {
993    match exit_code_range(unix) {
994        Some(range) => codes
995            .iter()
996            .copied()
997            .filter(|c| !range.contains(c))
998            .collect(),
999        None => Vec::new(),
1000    }
1001}
1002
1003/// Check a subject's resolved `ok_exit_codes` against a platform: fail when
1004/// none of them is possible there, otherwise return the ones that are not,
1005/// for a warning.
1006///
1007/// Not part of loading `tak.toml`. A shared file may hold a Windows-only
1008/// subject, switched off elsewhere by `when`, whose codes are all impossible
1009/// on Unix; checking it at load would stop every other benchmark from
1010/// running there. `tak run` calls this only for the subjects it will measure.
1011pub fn check_platform_exit_codes(codes: &[i32], unix: bool) -> Result<Vec<i32>> {
1012    let impossible = impossible_exit_codes(codes, unix);
1013    if !impossible.is_empty() && impossible.len() == codes.len() {
1014        let range = exit_code_range(unix).expect("only a narrowed range rules codes out");
1015        bail!(
1016            "ok_exit_codes {} can never match: exit codes on this platform are {} to {}",
1017            join_codes(&impossible),
1018            range.start(),
1019            range.end()
1020        );
1021    }
1022    Ok(impossible)
1023}
1024
1025/// Exit codes for a message: `0, 1`.
1026pub fn join_codes(codes: &[i32]) -> String {
1027    codes
1028        .iter()
1029        .map(i32::to_string)
1030        .collect::<Vec<_>>()
1031        .join(", ")
1032}
1033
1034/// Check `ok_exit_codes` as written, returning it sorted and deduplicated.
1035///
1036/// The range is whatever `ExitStatus::code()` can report, which is an `i32`.
1037/// Unix only ever reports 0–255, but Windows passes a program's 32-bit exit
1038/// code through, and an NTSTATUS such as 0xC0000005 arrives negative
1039/// (-1073741819); limiting the list to 0–255 would make those unlistable.
1040/// An empty list would fail every sample, so it is an error here rather than
1041/// a confusing run.
1042fn ok_exit_codes(codes: &[i64]) -> Result<Vec<i32>> {
1043    if codes.is_empty() {
1044        bail!("ok_exit_codes must list at least one exit code");
1045    }
1046    let mut out = codes
1047        .iter()
1048        .map(|&c| match i32::try_from(c) {
1049            Ok(c) => Ok(c),
1050            Err(_) => bail!(
1051                "ok_exit_codes: {c} is not an exit code ({} to {})",
1052                i32::MIN,
1053                i32::MAX
1054            ),
1055        })
1056        .collect::<Result<Vec<_>>>()?;
1057    out.sort_unstable();
1058    out.dedup();
1059    Ok(out)
1060}
1061
1062impl Config {
1063    /// The `[build]` table, if the file declares one.
1064    pub fn build(&self) -> Result<Option<Build>> {
1065        self.build
1066            .as_ref()
1067            .map(BuildDecl::resolve)
1068            .transpose()
1069            .context("in [build]")
1070    }
1071
1072    pub fn parse(text: &str) -> Result<Self> {
1073        let cfg: Config = toml::from_str(text).context("could not parse tak.toml")?;
1074        cfg.build()?;
1075        // Every template in the file, used or not: a typo in a shared subject
1076        // no benchmark lists yet, or in a value an override replaces, is
1077        // still a typo, and should not wait to be found until it is used.
1078        for (place, value) in cfg.template_strings() {
1079            crate::template::check_str(value).with_context(|| format!("in {place}"))?;
1080        }
1081        for (place, when) in cfg.conditions() {
1082            crate::condition::check(when).with_context(|| format!("in {place}"))?;
1083        }
1084        // Likewise every `ok_exit_codes`, including one in a layer that
1085        // nothing resolves through yet.
1086        for (place, l) in cfg.layers() {
1087            if let Some(codes) = &l.ok_exit_codes {
1088                ok_exit_codes(codes).with_context(|| format!("in {place}"))?;
1089            }
1090            // And every metric, for the same reason.
1091            for (name, decl) in &l.metric {
1092                metric_name(name)
1093                    .and_then(|()| decl.resolve().map(drop))
1094                    .with_context(|| format!("in {place}.metric.{name}"))?;
1095            }
1096        }
1097        // Every gate, including a shared subject's that no benchmark lists
1098        // yet: `tak compare` is where a bad one would bite, and by then it is
1099        // a pull request's check that fails rather than the file's author.
1100        for (place, g) in cfg.gate_decls() {
1101            if let Some(pct) = g.pct {
1102                crate::compare::check_pct(pct).with_context(|| format!("in {place}.pct"))?;
1103            }
1104        }
1105        // Every name that can be recorded, including a shared subject no
1106        // benchmark lists yet: a control character in one could forge a
1107        // verdict line in a report. See `record::check_name`.
1108        for name in cfg.subject.keys() {
1109            crate::record::check_name("subject", name)?;
1110        }
1111        for (name, b) in &cfg.bench {
1112            crate::record::check_name("benchmark", name)?;
1113            for n in b.subject.keys().chain(b.subjects.iter()) {
1114                crate::record::check_name("subject", n)
1115                    .with_context(|| format!("benchmark `{}`", name.escape_default()))?;
1116            }
1117        }
1118        // Every declared benchmark is validated up front rather than failing
1119        // partway through a run that has already spent minutes measuring.
1120        for (name, b) in &cfg.bench {
1121            let subjects = cfg
1122                .subjects(name)
1123                .with_context(|| format!("benchmark `{name}`"))?;
1124            for s in &subjects {
1125                // Zero runs leaves nothing to report; catching it here names
1126                // the benchmark instead of failing after the others ran.
1127                if s.runs == Runs::Fixed(0) {
1128                    bail!("benchmark `{name}`: runs must be at least 1");
1129                }
1130                if s.name.trim().is_empty() {
1131                    bail!("benchmark `{name}`: a subject needs a name");
1132                }
1133                // `self` is the series a single-command benchmark records
1134                // under. A subject taking it would be recorded, printed and
1135                // exported as that series instead of as itself.
1136                if b.is_multi() && s.name == SELF_TOOL {
1137                    bail!(
1138                        "benchmark `{name}`: `{SELF_TOOL}` is reserved and cannot name a subject"
1139                    );
1140                }
1141            }
1142        }
1143        Ok(cfg)
1144    }
1145
1146    /// Load a named config file, for `tak run --config`.
1147    pub fn load(path: &Path) -> Result<Self> {
1148        let text = std::fs::read_to_string(path)
1149            .with_context(|| format!("could not read {}", path.display()))?;
1150        Self::parse(&text).with_context(|| format!("in {}", path.display()))
1151    }
1152
1153    /// Find and load `tak.toml`, searching upward from `start`.
1154    ///
1155    /// Walking up means `tak run` behaves the same from a subdirectory as from
1156    /// the repository root, which is where people actually are.
1157    pub fn find(start: &Path) -> Result<Option<(PathBuf, Self)>> {
1158        for dir in start.ancestors() {
1159            let path = dir.join(FILE_NAME);
1160            if path.is_file() {
1161                let text = std::fs::read_to_string(&path)
1162                    .with_context(|| format!("could not read {}", path.display()))?;
1163                let cfg = Self::parse(&text).with_context(|| format!("in {}", path.display()))?;
1164                return Ok(Some((path, cfg)));
1165            }
1166        }
1167        Ok(None)
1168    }
1169}
1170
1171#[cfg(test)]
1172mod tests {
1173    use super::*;
1174
1175    /// The single subject of a one-command benchmark.
1176    fn only(c: &Config, bench: &str) -> Subject {
1177        let mut s = c.subjects(bench).unwrap();
1178        assert_eq!(s.len(), 1);
1179        s.remove(0)
1180    }
1181
1182    #[test]
1183    fn a_command_may_be_a_list_or_a_string() {
1184        let c = Config::parse(
1185            r#"
1186            [bench.a]
1187            cmd = ["mycli", "--version"]
1188            [bench.b]
1189            cmd = "mycli --help"
1190            "#,
1191        )
1192        .unwrap();
1193        assert_eq!(only(&c, "a").cmd, ["mycli", "--version"]);
1194        assert_eq!(only(&c, "b").cmd, ["mycli", "--help"]);
1195    }
1196
1197    /// A string is split on whitespace and nothing else — no shell means no
1198    /// quoting, and pretending otherwise would measure the wrong thing.
1199    #[test]
1200    fn a_string_command_gets_no_shell_semantics() {
1201        let c = Config::parse(
1202            r#"[bench.a]
1203cmd = "mycli 'two words'""#,
1204        )
1205        .unwrap();
1206        assert_eq!(only(&c, "a").cmd, ["mycli", "'two", "words'"]);
1207    }
1208
1209    #[test]
1210    fn defaults_match_the_cli() {
1211        let c = Config::parse("[bench.a]\ncmd = \"x\"").unwrap();
1212        assert_eq!(only(&c, "a").runs, Runs::Fixed(DEFAULT_RUNS));
1213        assert_eq!(only(&c, "a").warmup, DEFAULT_WARMUP);
1214    }
1215
1216    #[test]
1217    fn per_benchmark_overrides_win() {
1218        let c = Config::parse("[bench.a]\ncmd = \"x\"\nruns = 5\nwarmup = 1").unwrap();
1219        assert_eq!(only(&c, "a").runs, Runs::Fixed(5));
1220        assert_eq!(only(&c, "a").warmup, 1);
1221    }
1222
1223    /// Validation happens at load, not partway through a run that has already
1224    /// spent minutes measuring.
1225    #[test]
1226    fn an_empty_command_is_rejected_at_parse_time() {
1227        let err = Config::parse("[bench.a]\ncmd = []").unwrap_err();
1228        assert!(format!("{err:#}").contains('a'), "{err:#}");
1229    }
1230
1231    #[test]
1232    fn benchmarks_run_in_a_stable_order() {
1233        let c = Config::parse("[bench.zebra]\ncmd = \"z\"\n[bench.alpha]\ncmd = \"a\"").unwrap();
1234        assert_eq!(c.bench.keys().collect::<Vec<_>>(), ["alpha", "zebra"]);
1235    }
1236
1237    #[test]
1238    fn an_empty_file_declares_nothing() {
1239        assert!(Config::parse("").unwrap().bench.is_empty());
1240    }
1241
1242    #[test]
1243    fn find_walks_up_from_a_subdirectory() {
1244        let root = std::env::temp_dir().join(format!("tak-cfg-{}", std::process::id()));
1245        let nested = root.join("a").join("b");
1246        std::fs::create_dir_all(&nested).unwrap();
1247        std::fs::write(root.join(FILE_NAME), "[bench.x]\ncmd = \"true\"").unwrap();
1248
1249        let (path, cfg) = Config::find(&nested).unwrap().expect("should find it");
1250        assert_eq!(path, root.join(FILE_NAME));
1251        assert!(cfg.bench.contains_key("x"));
1252
1253        std::fs::remove_dir_all(&root).ok();
1254    }
1255
1256    /// A single-command benchmark keeps measuring what it did before subjects
1257    /// existed: one series under `self`, with instruction counts.
1258    #[test]
1259    fn a_single_command_is_one_self_subject_with_counters() {
1260        let c = Config::parse("[bench.a]\ncmd = \"x\"").unwrap();
1261        let s = only(&c, "a");
1262        assert_eq!(s.name, SELF_TOOL);
1263        assert!(s.counters);
1264        assert!(!c.bench["a"].is_multi());
1265    }
1266
1267    /// `allocations` stacks like any layer setting, so a single-command
1268    /// benchmark can turn it on and a subject can turn a default off. Off
1269    /// unless asked for: every DHAT run costs as much as a cachegrind one.
1270    #[test]
1271    fn allocations_are_off_unless_a_layer_turns_them_on() {
1272        let c = Config::parse(
1273            r#"
1274            [bench.plain]
1275            cmd = "x"
1276
1277            [bench.single]
1278            cmd = "x"
1279            allocations = true
1280
1281            [defaults]
1282            allocations = true
1283
1284            [bench.multi.subject.on]
1285            cmd = "x"
1286            [bench.multi.subject.off]
1287            cmd = "y"
1288            allocations = false
1289            "#,
1290        )
1291        .unwrap();
1292        assert!(only(&c, "single").allocations);
1293        assert!(only(&c, "plain").allocations, "from [defaults]");
1294        let multi = c.subjects("multi").unwrap();
1295        assert!(!multi[0].allocations, "a subject's own setting wins");
1296        assert!(multi[1].allocations);
1297        assert!(!only(&Config::parse("[bench.a]\ncmd = \"x\"").unwrap(), "a").allocations);
1298    }
1299
1300    #[test]
1301    fn subjects_inherit_the_benchmark_defaults_and_may_override_them() {
1302        let c = Config::parse(
1303            r#"
1304            [bench.install]
1305            runs = 6
1306            warmup = 2
1307            prepare = ["rm", "-rf", "node_modules"]
1308            dir = "fixture"
1309            env = { CI = "1", HOME = "/tmp/shared" }
1310
1311            [bench.install.subject.aube]
1312            cmd = "aube install"
1313            env = { HOME = "/tmp/aube" }
1314
1315            [bench.install.subject.pnpm]
1316            cmd = ["pnpm", "install"]
1317            prepare = "rm -rf node_modules pnpm-lock.yaml"
1318            dir = "fixture-pnpm"
1319            runs = 3
1320            warmup = 0
1321            counters = true
1322            "#,
1323        )
1324        .unwrap();
1325        let b = &c.bench["install"];
1326        assert!(b.is_multi());
1327        let s = c.subjects("install").unwrap();
1328        // BTreeMap order, not file order.
1329        assert_eq!(s[0].name, "aube");
1330        assert_eq!(s[1].name, "pnpm");
1331
1332        assert_eq!(s[0].cmd, ["aube", "install"]);
1333        assert_eq!(
1334            s[0].prepare.as_deref().unwrap(),
1335            ["rm", "-rf", "node_modules"]
1336        );
1337        assert_eq!(s[0].dir.as_deref(), Some(Path::new("fixture")));
1338        assert_eq!(s[0].env["CI"], "1");
1339        assert_eq!(s[0].env["HOME"], "/tmp/aube");
1340        assert_eq!((s[0].runs, s[0].warmup), (Runs::Fixed(6), 2));
1341        assert!(!s[0].counters, "named subjects count only when asked to");
1342
1343        assert_eq!(
1344            s[1].prepare.as_deref().unwrap(),
1345            ["rm", "-rf", "node_modules", "pnpm-lock.yaml"]
1346        );
1347        assert_eq!(s[1].dir.as_deref(), Some(Path::new("fixture-pnpm")));
1348        assert_eq!(s[1].env["HOME"], "/tmp/shared");
1349        assert_eq!((s[1].runs, s[1].warmup), (Runs::Fixed(3), 0));
1350        assert!(s[1].counters);
1351    }
1352
1353    /// Declaring both would leave it ambiguous which is measured.
1354    #[test]
1355    fn cmd_and_subjects_together_are_rejected() {
1356        let err =
1357            Config::parse("[bench.a]\ncmd = \"x\"\n[bench.a.subject.b]\ncmd = \"y\"").unwrap_err();
1358        assert!(format!("{err:#}").contains("both"), "{err:#}");
1359    }
1360
1361    #[test]
1362    fn a_benchmark_with_neither_is_rejected() {
1363        let err = Config::parse("[bench.a]\nruns = 3").unwrap_err();
1364        assert!(format!("{err:#}").contains("no command"), "{err:#}");
1365    }
1366
1367    /// The error names the subject, not just the benchmark, so a large
1368    /// comparison does not have to be bisected by hand.
1369    #[test]
1370    fn an_empty_subject_command_is_rejected_by_name() {
1371        let err =
1372            Config::parse("[bench.a.subject.good]\ncmd = \"x\"\n[bench.a.subject.bad]\ncmd = []")
1373                .unwrap_err();
1374        let msg = format!("{err:#}");
1375        assert!(msg.contains("`a`") && msg.contains("`bad`"), "{msg}");
1376    }
1377
1378    #[test]
1379    fn an_empty_prepare_is_rejected() {
1380        assert!(Config::parse("[bench.a]\ncmd = \"x\"\nprepare = []").is_err());
1381    }
1382
1383    #[test]
1384    fn an_empty_check_is_rejected() {
1385        let err = Config::parse("[bench.a]\ncmd = \"x\"\ncheck = []").unwrap_err();
1386        assert!(format!("{err:#}").contains("check"), "{err:#}");
1387    }
1388
1389    /// `check` stacks like `prepare`: the most specific layer that sets one
1390    /// wins, and one that says nothing inherits.
1391    #[test]
1392    fn check_stacks_like_prepare() {
1393        let c = Config::parse(
1394            r#"
1395            [defaults]
1396            check = "git diff --quiet"
1397
1398            [subject.a]
1399            cmd = ["a"]
1400
1401            [subject.b]
1402            cmd = ["b"]
1403            check = ["./verify", "b"]
1404
1405            [bench.plain]
1406            cmd = "x"
1407
1408            [bench.cmp]
1409            subjects = ["a", "b"]
1410            [bench.cmp.subject.c]
1411            cmd = ["c"]
1412            check = ["./verify", "{{ subject }}"]
1413
1414            [bench.own]
1415            subjects = ["a", "b"]
1416            check = ["./bench-check"]
1417            [bench.own.subject.b]
1418            check = "./local-check"
1419            "#,
1420        )
1421        .unwrap();
1422        assert_eq!(only(&c, "plain").check.unwrap(), ["git", "diff", "--quiet"]);
1423        let cmp = c.subjects("cmp").unwrap();
1424        assert_eq!(
1425            cmp[0].check.as_deref().unwrap(),
1426            ["git", "diff", "--quiet"],
1427            "inherited from defaults"
1428        );
1429        assert_eq!(cmp[1].check.as_deref().unwrap(), ["./verify", "b"]);
1430        assert_eq!(
1431            cmp[2].check.as_deref().unwrap(),
1432            ["./verify", "{{ subject }}"],
1433            "rendered later"
1434        );
1435        let own = c.subjects("own").unwrap();
1436        assert_eq!(
1437            own[0].check.as_deref().unwrap(),
1438            ["./bench-check"],
1439            "bench over defaults"
1440        );
1441        assert_eq!(
1442            own[1].check.as_deref().unwrap(),
1443            ["./local-check"],
1444            "bench's own subject table over the shared subject"
1445        );
1446        assert!(
1447            Config::parse("[bench.a]\ncmd = \"x\"")
1448                .unwrap()
1449                .subjects("a")
1450                .unwrap()[0]
1451                .check
1452                .is_none()
1453        );
1454    }
1455
1456    #[test]
1457    fn a_broken_check_template_is_rejected_at_parse_time() {
1458        let err = Config::parse("[bench.a]\ncmd = \"x\"\ncheck = [\"{{ env.X \"]").unwrap_err();
1459        assert!(format!("{err:#}").contains("check"), "{err:#}");
1460    }
1461
1462    #[test]
1463    fn zero_runs_is_rejected_at_parse_time() {
1464        assert!(Config::parse("[bench.a.subject.b]\ncmd = \"x\"\nruns = 0").is_err());
1465    }
1466
1467    /// A name holding a newline could forge a verdict line in a report, so
1468    /// every name that can be recorded is checked at load: benchmarks, shared
1469    /// subjects (listed or not), and a benchmark's own subjects.
1470    #[test]
1471    fn a_control_character_in_any_name_is_rejected() {
1472        for text in [
1473            "[bench.\"a\\nb\"]\ncmd = \"x\"",
1474            "[subject.\"s\\rt\"]\ncmd = \"x\"",
1475            "[bench.a.subject.\"s\\u001bt\"]\ncmd = \"x\"",
1476            "[subject.ok]\ncmd = \"x\"\n[bench.a]\nsubjects = [\"ok\", \"b\\tc\"]",
1477        ] {
1478            let err = Config::parse(text).unwrap_err();
1479            assert!(
1480                format!("{err:#}").contains("control character"),
1481                "{text}: {err:#}"
1482            );
1483        }
1484        // Everything else a name can hold is still fine.
1485        Config::parse("[bench.\" a,b `c` \"]\ncmd = \"x\"").unwrap();
1486    }
1487
1488    #[test]
1489    fn self_is_reserved_for_single_command_benchmarks() {
1490        let err = Config::parse("[bench.a.subject.self]\ncmd = \"x\"").unwrap_err();
1491        assert!(format!("{err:#}").contains("reserved"), "{err:#}");
1492    }
1493
1494    /// `dir` sets where a command runs, not where a relative program path is
1495    /// found: `./target/release/x` still means the one next to `tak.toml`.
1496    #[test]
1497    fn a_relative_program_path_is_anchored_at_the_config() {
1498        let root = Path::new("/repo");
1499        let mut s = Config::parse(
1500            "[bench.a]\ncmd = [\"./target/x\", \"./arg\"]\nprepare = \"bin/reset\"\ncheck = \"./bin/verify ./out\"\ndir = \"fix\"",
1501        )
1502        .unwrap()
1503        .subjects("a")
1504        .unwrap()
1505        .remove(0);
1506        s.anchor(root);
1507        assert_eq!(
1508            s.cmd,
1509            ["/repo/./target/x", "./arg"],
1510            "arguments are left alone"
1511        );
1512        assert_eq!(s.prepare.unwrap(), ["/repo/bin/reset"]);
1513        assert_eq!(s.check.unwrap(), ["/repo/./bin/verify", "./out"]);
1514        assert_eq!(s.dir.unwrap(), Path::new("/repo/fix"));
1515
1516        let mut bare = Config::parse("[bench.a]\ncmd = \"mycli --version\"")
1517            .unwrap()
1518            .subjects("a")
1519            .unwrap()
1520            .remove(0);
1521        bare.anchor(root);
1522        assert_eq!(
1523            bare.cmd[0], "mycli",
1524            "a bare name is still looked up on PATH"
1525        );
1526        assert_eq!(bare.dir.unwrap(), Path::new("/repo"));
1527    }
1528
1529    /// Setup layers like prepare — the most specific one replaces the rest —
1530    /// and a benchmark without one has none.
1531    #[test]
1532    fn setup_stacks_by_specificity_and_replaces() {
1533        let c = Config::parse(
1534            r#"
1535            [defaults]
1536            setup = "make fixture"
1537
1538            [subject.a]
1539            cmd = "a"
1540
1541            [subject.b]
1542            cmd = "b"
1543            setup = ["./clone", "b"]
1544
1545            [subject.c]
1546            cmd = "c"
1547
1548            [bench.x]
1549            subjects = ["a", "b", "c"]
1550            [bench.x.subject.c]
1551            setup = "./clone c --here"
1552
1553            [bench.y]
1554            subjects = ["a", "b"]
1555            setup = "./bench-setup"
1556            prepare = "reset"
1557            "#,
1558        )
1559        .unwrap();
1560        let setups = |bench: &str| -> Vec<Vec<String>> {
1561            c.subjects(bench)
1562                .unwrap()
1563                .into_iter()
1564                .map(|s| s.setup.unwrap())
1565                .collect()
1566        };
1567        assert_eq!(
1568            setups("x"),
1569            [
1570                vec!["make", "fixture"],
1571                vec!["./clone", "b"],
1572                vec!["./clone", "c", "--here"]
1573            ]
1574        );
1575        // The benchmark's replaces the defaults', and a shared subject's own
1576        // replaces the benchmark's. Prepare is untouched by any of it.
1577        assert_eq!(setups("y"), [vec!["./bench-setup"], vec!["./clone", "b"]]);
1578        assert_eq!(
1579            c.subjects("y").unwrap()[0].prepare.as_deref().unwrap(),
1580            ["reset"]
1581        );
1582
1583        let none = Config::parse("[bench.z]\ncmd = \"x\"").unwrap();
1584        assert_eq!(only(&none, "z").setup, None);
1585    }
1586
1587    /// Setup runs from the directory holding tak.toml whatever `dir` says,
1588    /// so it can create `dir`; its program is anchored there like any other.
1589    #[test]
1590    fn setup_runs_from_the_config_directory() {
1591        let mut s = Config::parse(
1592            "[bench.a]\ncmd = \"x\"\nsetup = [\"./bin/clone\", \"work\"]\ndir = \"work\"",
1593        )
1594        .unwrap()
1595        .subjects("a")
1596        .unwrap()
1597        .remove(0);
1598        s.anchor(Path::new("/repo"));
1599        assert_eq!(s.setup.unwrap(), ["/repo/./bin/clone", "work"]);
1600        assert_eq!(s.setup_dir.unwrap(), Path::new("/repo"));
1601        assert_eq!(s.dir.unwrap(), Path::new("/repo/work"));
1602    }
1603
1604    #[test]
1605    fn a_bad_setup_is_rejected_at_parse_time() {
1606        assert!(Config::parse("[bench.a]\ncmd = \"x\"\nsetup = []").is_err());
1607        let err = Config::parse("[defaults]\nsetup = [\"{{ env.X \"]\n[bench.a]\ncmd = \"x\"")
1608            .unwrap_err();
1609        assert!(format!("{err:#}").contains("defaults.setup"), "{err:#}");
1610    }
1611
1612    #[test]
1613    fn runs_may_be_auto_with_limits_inherited_and_overridden() {
1614        let c = Config::parse(
1615            r#"
1616            [bench.b]
1617            runs = "auto"
1618            budget = "2m"
1619            min_runs = 3
1620
1621            [bench.b.subject.fast]
1622            cmd = "x"
1623
1624            [bench.b.subject.slow]
1625            cmd = "y"
1626            max_runs = 10
1627            budget = "500ms"
1628
1629            [bench.b.subject.pinned]
1630            cmd = "z"
1631            runs = 7
1632            "#,
1633        )
1634        .unwrap();
1635        let s = c.subjects("b").unwrap();
1636        let by = |n: &str| s.iter().find(|x| x.name == n).unwrap();
1637        assert_eq!(by("fast").runs, Runs::Auto);
1638        assert_eq!(
1639            by("fast").auto,
1640            AutoRuns {
1641                budget: Duration::from_secs(120),
1642                min: 3,
1643                max: DEFAULT_MAX_RUNS
1644            }
1645        );
1646        assert_eq!(by("slow").auto.budget, Duration::from_millis(500));
1647        assert_eq!((by("slow").auto.min, by("slow").auto.max), (3, 10));
1648        assert_eq!(by("pinned").runs, Runs::Fixed(7));
1649    }
1650
1651    #[test]
1652    fn bad_auto_settings_are_rejected_at_parse_time() {
1653        for bad in [
1654            "runs = \"lots\"",
1655            "runs = \"auto\"\nbudget = \"soon\"",
1656            "runs = \"auto\"\nbudget = \"0s\"",
1657            "runs = \"auto\"\nmin_runs = 0",
1658            "runs = \"auto\"\nmin_runs = 9\nmax_runs = 3",
1659        ] {
1660            let toml = format!("[bench.a]\ncmd = \"x\"\n{bad}");
1661            assert!(Config::parse(&toml).is_err(), "accepted: {bad}");
1662        }
1663    }
1664
1665    #[test]
1666    fn durations_take_the_common_units() {
1667        assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
1668        assert_eq!(parse_duration("30s").unwrap(), Duration::from_secs(30));
1669        assert_eq!(parse_duration("45").unwrap(), Duration::from_secs(45));
1670        assert_eq!(parse_duration("2m").unwrap(), Duration::from_secs(120));
1671        assert_eq!(parse_duration("1.5h").unwrap(), Duration::from_secs(5400));
1672        assert!(
1673            parse_duration("1e300h").is_err(),
1674            "too large is an error, not a panic"
1675        );
1676    }
1677
1678    /// A slow subject is held at the floor, a fast one at the ceiling, and
1679    /// anything between gets what fits in the budget.
1680    #[test]
1681    fn auto_runs_fit_the_budget_within_the_limits() {
1682        let a = AutoRuns {
1683            budget: Duration::from_secs(30),
1684            min: 5,
1685            max: 50,
1686        };
1687        assert_eq!(a.runs_for(Duration::from_millis(1700)), 17);
1688        assert_eq!(a.runs_for(Duration::from_secs(21)), 5);
1689        assert_eq!(a.runs_for(Duration::from_millis(300)), 50);
1690        assert_eq!(a.runs_for(Duration::ZERO), 50);
1691    }
1692
1693    /// A subject declared once can be measured by several benchmarks, which
1694    /// can still override it for themselves; `[defaults]` is under all of it.
1695    #[test]
1696    fn shared_subjects_and_defaults_stack_by_specificity() {
1697        let c = Config::parse(
1698            r#"
1699            [defaults]
1700            runs = "auto"
1701            min_runs = 4
1702            prepare = "reset"
1703            env = { HOME = "/h", CI = "1" }
1704            vars = { kind = "default" }
1705
1706            [subject.aube]
1707            cmd = ["aube", "install"]
1708            env = { HOME = "/h-aube" }
1709            vars = { lockfile = "aube-lock.yaml" }
1710
1711            [subject.pnpm]
1712            cmd = ["pnpm", "install"]
1713            counters = true
1714
1715            [bench.warm]
1716            subjects = ["aube", "pnpm"]
1717
1718            [bench.cold]
1719            subjects = ["aube", "pnpm"]
1720            prepare = "reset --cold"
1721            warmup = 0
1722
1723            [bench.test]
1724            subjects = ["pnpm"]
1725            [bench.test.subject.aube]
1726            cmd = ["aube", "test"]
1727            [bench.test.subject.pnpm]
1728            cmd = ["pnpm", "install-test"]
1729            vars = { kind = "local" }
1730            "#,
1731        )
1732        .unwrap();
1733
1734        let warm = c.subjects("warm").unwrap();
1735        assert_eq!(
1736            warm.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
1737            ["aube", "pnpm"]
1738        );
1739        assert_eq!(warm[0].cmd, ["aube", "install"]);
1740        assert_eq!(warm[0].runs, Runs::Auto);
1741        assert_eq!(warm[0].auto.min, 4);
1742        assert_eq!(warm[0].prepare.as_deref().unwrap(), ["reset"]);
1743        assert_eq!(warm[0].env["HOME"], "/h-aube", "subject over defaults");
1744        assert_eq!(warm[0].env["CI"], "1", "merged, not replaced");
1745        assert_eq!(warm[0].vars["lockfile"], "aube-lock.yaml");
1746        assert_eq!(warm[0].vars["kind"], "default");
1747        assert!(!warm[0].counters && warm[1].counters);
1748
1749        let cold = c.subjects("cold").unwrap();
1750        assert_eq!(
1751            cold[0].prepare.as_deref().unwrap(),
1752            ["reset", "--cold"],
1753            "bench over defaults"
1754        );
1755        assert_eq!(cold[0].warmup, 0);
1756
1757        // A benchmark's own table adds a subject, or overrides a shared one.
1758        let test = c.subjects("test").unwrap();
1759        assert_eq!(test[0].cmd, ["aube", "test"]);
1760        assert_eq!(
1761            test[0].env["HOME"], "/h-aube",
1762            "inherits the shared subject"
1763        );
1764        assert_eq!(test[1].cmd, ["pnpm", "install-test"]);
1765        assert_eq!(test[1].vars["kind"], "local");
1766        assert!(test[1].counters, "an override keeps the shared setting");
1767    }
1768
1769    /// A group holds what some benchmarks share and others do not: it stacks
1770    /// over `[defaults]` and under the benchmark, in both benchmark forms.
1771    #[test]
1772    fn groups_stack_between_defaults_and_the_benchmark() {
1773        let c = Config::parse(
1774            r#"
1775            [defaults]
1776            warmup = 2
1777            env = { CI = "1", HOME = "/h" }
1778
1779            [group.fixture]
1780            setup = ["make", "fixture"]
1781            warmup = 1
1782            env = { HOME = "/fixture/home" }
1783
1784            [bench.single]
1785            group = "fixture"
1786            cmd = ["tool", "env"]
1787            warmup = 0
1788
1789            [bench.multi]
1790            group = "fixture"
1791            [bench.multi.subject.a]
1792            cmd = ["a"]
1793            env = { HOME = "/a" }
1794
1795            [bench.plain]
1796            cmd = ["tool", "--help"]
1797            "#,
1798        )
1799        .unwrap();
1800
1801        let single = &c.subjects("single").unwrap()[0];
1802        assert_eq!(single.setup.as_deref().unwrap(), ["make", "fixture"]);
1803        assert_eq!(single.warmup, 0, "bench over group");
1804        assert_eq!(single.env["HOME"], "/fixture/home", "group over defaults");
1805        assert_eq!(single.env["CI"], "1", "merged, not replaced");
1806
1807        let multi = &c.subjects("multi").unwrap()[0];
1808        assert_eq!(multi.setup.as_deref().unwrap(), ["make", "fixture"]);
1809        assert_eq!(multi.warmup, 1, "group over defaults");
1810        assert_eq!(multi.env["HOME"], "/a", "subject over group");
1811
1812        let plain = &c.subjects("plain").unwrap()[0];
1813        assert!(plain.setup.is_none(), "a group reaches only its benchmarks");
1814        assert_eq!(plain.warmup, 2);
1815    }
1816
1817    /// Naming a group that does not exist fails when the file is read, like
1818    /// listing a subject that does not, rather than measuring without it.
1819    #[test]
1820    fn an_unknown_group_is_an_error() {
1821        let err = Config::parse("[bench.a]\ncmd = \"x\"\ngroup = \"nope\"").unwrap_err();
1822        assert!(
1823            format!("{err:#}").contains("names group `nope`, but there is no [group.nope]"),
1824            "{err:#}"
1825        );
1826    }
1827
1828    /// A group no benchmark names yet still has its templates checked.
1829    #[test]
1830    fn an_unused_group_is_still_checked() {
1831        let err = Config::parse("[group.g]\nsetup = [\"{{ env.X \"]\n[bench.a]\ncmd = \"x\"")
1832            .unwrap_err();
1833        assert!(format!("{err:#}").contains("group.g.setup"), "{err:#}");
1834    }
1835
1836    /// `version_cmd` stacks like `prepare`, and its program is found the
1837    /// same way `cmd`'s is.
1838    #[test]
1839    fn version_cmd_stacks_and_is_anchored() {
1840        let c = Config::parse(
1841            r#"
1842            [defaults]
1843            version_cmd = ["{{ subject }}", "--version"]
1844
1845            [subject.lefthook]
1846            cmd = ["lefthook", "run", "pre-commit"]
1847            version_cmd = "lefthook version"
1848
1849            [subject.mine]
1850            cmd = ["./target/release/mine", "check"]
1851            version_cmd = ["./target/release/mine", "--version"]
1852
1853            [bench.hooks]
1854            subjects = ["lefthook", "mine", "pre-commit"]
1855            [bench.hooks.subject.pre-commit]
1856            cmd = ["pre-commit", "run"]
1857            "#,
1858        )
1859        .unwrap();
1860        let s = c.subjects("hooks").unwrap();
1861        let by = |n: &str| s.iter().find(|x| x.name == n).unwrap().clone();
1862        assert_eq!(
1863            by("lefthook").version_cmd.unwrap(),
1864            ["lefthook", "version"],
1865            "subject over defaults"
1866        );
1867        assert_eq!(
1868            by("pre-commit").version_cmd.unwrap(),
1869            ["{{ subject }}", "--version"],
1870            "inherited, rendered later"
1871        );
1872        let mut mine = by("mine");
1873        mine.anchor(Path::new("/repo"));
1874        assert_eq!(
1875            mine.version_cmd.unwrap(),
1876            ["/repo/./target/release/mine", "--version"]
1877        );
1878        assert!(
1879            Config::parse("[bench.a]\ncmd = \"x\"\nversion_cmd = []").is_err(),
1880            "an empty version_cmd is rejected like an empty prepare"
1881        );
1882    }
1883
1884    #[test]
1885    fn a_listed_subject_must_exist() {
1886        let err = Config::parse("[bench.a]\nsubjects = [\"ghost\"]").unwrap_err();
1887        assert!(format!("{err:#}").contains("[subject.ghost]"), "{err:#}");
1888    }
1889
1890    #[test]
1891    fn a_subject_needs_a_command_from_somewhere() {
1892        let err = Config::parse("[bench.a.subject.x]\nruns = 3").unwrap_err();
1893        assert!(format!("{err:#}").contains("no command"), "{err:#}");
1894    }
1895
1896    #[test]
1897    fn a_broken_template_is_rejected_at_parse_time() {
1898        let err = Config::parse("[bench.a]\ncmd = [\"x\", \"{{ env.X \"]").unwrap_err();
1899        assert!(format!("{err:#}").contains("template"), "{err:#}");
1900    }
1901
1902    /// A subject a benchmark both lists and declares itself is fine without a
1903    /// shared table: the local one provides everything.
1904    #[test]
1905    fn a_listed_subject_may_be_declared_locally() {
1906        let c = Config::parse("[bench.b]\nsubjects = [\"x\"]\n[bench.b.subject.x]\ncmd = [\"x\"]")
1907            .unwrap();
1908        assert_eq!(c.subjects("b").unwrap()[0].cmd, ["x"]);
1909    }
1910
1911    /// Only exit 0 counts unless a layer says otherwise, and the most specific
1912    /// layer's list replaces the others' rather than adding to them.
1913    #[test]
1914    fn ok_exit_codes_default_to_zero_and_stack_by_replacing() {
1915        let c = Config::parse(
1916            r#"
1917            [defaults]
1918            ok_exit_codes = [0, 1]
1919
1920            [subject.grep]
1921            cmd = ["grep", "x", "file"]
1922            ok_exit_codes = [1, 0, 1]
1923
1924            [subject.lint]
1925            cmd = ["lint"]
1926
1927            [bench.plain]
1928            cmd = "x"
1929
1930            [bench.cmp]
1931            subjects = ["grep", "lint"]
1932            ok_exit_codes = [0, 2]
1933
1934            [bench.strict]
1935            subjects = ["grep"]
1936            [bench.strict.subject.grep]
1937            ok_exit_codes = [0]
1938            "#,
1939        )
1940        .unwrap();
1941        assert_eq!(only(&c, "plain").ok_exit_codes, [0, 1], "from defaults");
1942        let cmp = c.subjects("cmp").unwrap();
1943        assert_eq!(
1944            cmp[0].ok_exit_codes,
1945            [0, 1],
1946            "shared subject, sorted and deduplicated"
1947        );
1948        assert_eq!(cmp[1].ok_exit_codes, [0, 2], "bench over defaults");
1949        assert_eq!(
1950            only(&c, "strict").ok_exit_codes,
1951            [0],
1952            "bench's own subject table"
1953        );
1954
1955        let bare = Config::parse("[bench.a]\ncmd = \"x\"").unwrap();
1956        assert_eq!(only(&bare, "a").ok_exit_codes, DEFAULT_OK_EXIT_CODES);
1957    }
1958
1959    /// Windows reports exit codes beyond 0–255, and an NTSTATUS such as
1960    /// 0xC0000005 as a negative `i32`, so the whole `i32` range is accepted.
1961    #[test]
1962    fn ok_exit_codes_take_any_i32() {
1963        let c = Config::parse(
1964            "[bench.a]\ncmd = \"x\"\nok_exit_codes = [0, 256, -1073741819, 2147483647]",
1965        )
1966        .unwrap();
1967        assert_eq!(
1968            only(&c, "a").ok_exit_codes,
1969            [-1073741819, 0, 256, 2147483647]
1970        );
1971    }
1972
1973    /// On Unix only 0–255 can be reported. A list with no such code is an
1974    /// error naming the subject; one with some is kept, and the rest are
1975    /// reported for a warning. Elsewhere the whole `i32` range is possible.
1976    #[test]
1977    fn ok_exit_codes_impossible_on_this_platform() {
1978        assert_eq!(
1979            impossible_exit_codes(&[0, 1, -1073741819, 256], true),
1980            [-1073741819, 256]
1981        );
1982        assert!(impossible_exit_codes(&[0, 1, -1073741819, 256], false).is_empty());
1983
1984        assert!(
1985            check_platform_exit_codes(&[0, 256], true).is_ok(),
1986            "some possible"
1987        );
1988        let err = check_platform_exit_codes(&[256, -1], true).unwrap_err();
1989        assert!(format!("{err:#}").contains("0 to 255"), "{err:#}");
1990        assert!(
1991            check_platform_exit_codes(&[256, -1], false).is_ok(),
1992            "fine on Windows"
1993        );
1994        assert!(check_platform_exit_codes(&[i32::MIN, i32::MAX], false).is_ok());
1995    }
1996
1997    /// Only the platform-independent checks run at load: a Windows-only
1998    /// subject whose codes are all impossible on Unix still loads, since
1999    /// `when` may keep it from ever running there.
2000    #[test]
2001    fn a_list_impossible_here_still_loads() {
2002        Config::parse("[bench.b.subject.win]\ncmd = \"x\"\nok_exit_codes = [-1073741819]").unwrap();
2003    }
2004
2005    /// A list that could never match a real exit status would fail every
2006    /// sample, so it is rejected before anything runs — even in a layer no
2007    /// benchmark uses yet.
2008    #[test]
2009    fn bad_ok_exit_codes_are_rejected_at_parse_time() {
2010        for bad in [
2011            "ok_exit_codes = []",
2012            "ok_exit_codes = [2147483648]",
2013            "ok_exit_codes = [-2147483649]",
2014            "ok_exit_codes = [0xC0000005]",
2015            "ok_exit_codes = [\"1\"]",
2016            "ok_exit_codes = 1",
2017        ] {
2018            let toml = format!("[bench.a]\ncmd = \"x\"\n{bad}");
2019            assert!(Config::parse(&toml).is_err(), "accepted: {bad}");
2020        }
2021        let unused =
2022            "[subject.spare]\ncmd = \"y\"\nok_exit_codes = [4294967296]\n[bench.a]\ncmd = \"x\"";
2023        let err = Config::parse(unused).unwrap_err();
2024        let msg = format!("{err:#}");
2025        assert!(
2026            msg.contains("subject.spare") && msg.contains("4294967296"),
2027            "{msg}"
2028        );
2029    }
2030
2031    /// Metrics merge by name across layers, like `env`: each layer can add
2032    /// one, and a more specific layer's table replaces a same-named one whole.
2033    #[test]
2034    fn metrics_merge_by_name_and_replace_whole() {
2035        let c = Config::parse(
2036            r#"
2037            [defaults.metric.binary_bytes]
2038            file = "target/release/{{ subject }}"
2039
2040            [subject.mine]
2041            cmd = ["./mine"]
2042            [subject.mine.metric.bundle_kb]
2043            cmd = "node size.js"
2044
2045            [subject.other]
2046            cmd = ["other"]
2047            [subject.other.metric.binary_bytes]
2048            cmd = ["./size-of", "other"]
2049
2050            [bench.plain]
2051            cmd = "x"
2052
2053            [bench.cmp]
2054            subjects = ["mine", "other"]
2055            [bench.cmp.metric.lines_count]
2056            cmd = ["wc-ish"]
2057            "#,
2058        )
2059        .unwrap();
2060        assert_eq!(
2061            only(&c, "plain").metrics,
2062            BTreeMap::from([(
2063                "binary_bytes".to_string(),
2064                MetricSource::File("target/release/{{ subject }}".into())
2065            )])
2066        );
2067        let cmp = c.subjects("cmp").unwrap();
2068        assert_eq!(
2069            cmp[0].metrics.keys().collect::<Vec<_>>(),
2070            ["binary_bytes", "bundle_kb", "lines_count"],
2071            "defaults, bench and subject all add"
2072        );
2073        assert_eq!(
2074            cmp[0].metrics["bundle_kb"],
2075            MetricSource::Cmd(vec!["node".into(), "size.js".into()])
2076        );
2077        assert_eq!(
2078            cmp[1].metrics["binary_bytes"],
2079            MetricSource::Cmd(vec!["./size-of".into(), "other".into()]),
2080            "replaced whole: a cmd, and no file left over"
2081        );
2082        assert!(
2083            Config::parse("[bench.a]\ncmd = \"x\"")
2084                .unwrap()
2085                .subjects("a")
2086                .unwrap()[0]
2087                .metrics
2088                .is_empty()
2089        );
2090    }
2091
2092    /// A metric's file is found from tak.toml whatever `dir` says, and its
2093    /// command like any other program.
2094    #[test]
2095    fn metric_paths_are_anchored_at_the_config() {
2096        let mut s = Config::parse(
2097            r#"
2098            [bench.a]
2099            cmd = "x"
2100            dir = "fixture"
2101            metric.rel_bytes.file = "target/mine"
2102            metric.abs_bytes.file = "/usr/bin/env"
2103            metric.script_count.cmd = ["./count.sh", "./arg"]
2104            metric.bare_count.cmd = "jq length out.json"
2105            "#,
2106        )
2107        .unwrap()
2108        .subjects("a")
2109        .unwrap()
2110        .remove(0);
2111        s.anchor(Path::new("/repo"));
2112        assert_eq!(
2113            s.metrics["rel_bytes"],
2114            MetricSource::File("/repo/target/mine".into())
2115        );
2116        assert_eq!(
2117            s.metrics["abs_bytes"],
2118            MetricSource::File("/usr/bin/env".into())
2119        );
2120        assert_eq!(
2121            s.metrics["script_count"],
2122            MetricSource::Cmd(vec!["/repo/./count.sh".into(), "./arg".into()])
2123        );
2124        assert_eq!(
2125            s.metrics["bare_count"],
2126            MetricSource::Cmd(vec!["jq".into(), "length".into(), "out.json".into()])
2127        );
2128    }
2129
2130    #[test]
2131    fn metric_names_are_checked_at_parse_time() {
2132        for good in ["binary_bytes", "a", "p99_ms", "x2"] {
2133            metric_name(good).unwrap_or_else(|e| panic!("{good}: {e:#}"));
2134        }
2135        for bad in [
2136            "",
2137            "Binary_bytes",
2138            "binary-bytes",
2139            "binary.bytes",
2140            "2x",
2141            "_x",
2142            "größe",
2143            "instructions",
2144            "wall_min_ms",
2145            "wall_custom",
2146        ] {
2147            assert!(metric_name(bad).is_err(), "accepted {bad:?}");
2148        }
2149        assert!(metric_name(&"a".repeat(METRIC_NAME_MAX)).is_ok());
2150        assert!(metric_name(&"a".repeat(METRIC_NAME_MAX + 1)).is_err());
2151        // A control character gets the explanation every recorded name gets.
2152        let err = format!("{:#}", metric_name("size\nbytes").unwrap_err());
2153        assert!(err.contains("control character"), "{err}");
2154        let err = Config::parse(
2155            "[bench.a]\ncmd = \"x\"\n[bench.a.metric.\"size\\nbytes\"]\nfile = \"a\"",
2156        )
2157        .unwrap_err();
2158        assert!(format!("{err:#}").contains("control character"), "{err:#}");
2159
2160        let err = Config::parse(
2161            "[bench.a]\ncmd = \"x\"\n[bench.a.metric.instructions]\ncmd = \"echo 1\"",
2162        )
2163        .unwrap_err();
2164        let msg = format!("{err:#}");
2165        assert!(
2166            msg.contains("bench.a.metric.instructions") && msg.contains("reserved"),
2167            "{msg}"
2168        );
2169
2170        // DHAT's counts share the record's map too: a script printing
2171        // `alloc_bytes` would overwrite the counted one.
2172        let err = format!("{:#}", metric_name("alloc_bytes").unwrap_err());
2173        assert!(err.contains("reserved") && err.contains("alloc_"), "{err}");
2174    }
2175
2176    /// Both, neither, or an empty one is a mistake, caught before anything
2177    /// runs — including in a layer nothing uses yet.
2178    #[test]
2179    fn a_metric_needs_exactly_one_source() {
2180        for (bad, why) in [
2181            ("file = \"a\"\ncmd = \"b\"", "both"),
2182            ("", "needs `file` or `cmd`"),
2183            ("file = \"\"", "empty"),
2184            ("cmd = []", "empty command"),
2185            ("cmd = [\"{{ env.X \"]", "template"),
2186        ] {
2187            let toml = format!("[bench.a]\ncmd = \"x\"\n[bench.a.metric.size_bytes]\n{bad}");
2188            let err = Config::parse(&toml).unwrap_err();
2189            let msg = format!("{err:#}");
2190            assert!(
2191                msg.contains(why) && msg.contains("size_bytes"),
2192                "{bad}: {msg}"
2193            );
2194        }
2195        // A misspelt key is an error, not ignored beside the one it meant.
2196        let err = Config::parse(
2197            "[bench.a]\ncmd = \"x\"\n[bench.a.metric.size_bytes]\nfile = \"old.bin\"\nfiel = \"new.bin\"",
2198        )
2199        .unwrap_err();
2200        assert!(format!("{err:#}").contains("fiel"), "{err:#}");
2201
2202        let unused = "[subject.spare]\ncmd = \"y\"\n[subject.spare.metric.Bad]\nfile = \"a\"\n[bench.a]\ncmd = \"x\"";
2203        let err = Config::parse(unused).unwrap_err();
2204        assert!(format!("{err:#}").contains("subject.spare"), "{err:#}");
2205    }
2206
2207    #[test]
2208    fn a_build_is_optional_and_anchored_like_a_subject() {
2209        assert_eq!(Config::parse("").unwrap().build().unwrap(), None);
2210        let mut b = Config::parse(
2211            "[build]\ncmd = \"./scripts/build --release\"\ndir = \"app\"\nenv = { PROFILE = \"release\" }",
2212        )
2213        .unwrap()
2214        .build()
2215        .unwrap()
2216        .unwrap();
2217        assert_eq!(b.cmd, ["./scripts/build", "--release"]);
2218        assert_eq!(b.env["PROFILE"], "release");
2219        b.anchor(Path::new("/wt"));
2220        assert_eq!(b.cmd[0], "/wt/./scripts/build");
2221        assert_eq!(b.dir.unwrap(), Path::new("/wt/app"));
2222
2223        let mut bare = Config::parse("[build]\ncmd = [\"cargo\", \"build\"]")
2224            .unwrap()
2225            .build()
2226            .unwrap()
2227            .unwrap();
2228        bare.anchor(Path::new("/wt"));
2229        assert_eq!(bare.cmd[0], "cargo", "a bare name is looked up on PATH");
2230        assert_eq!(bare.dir.unwrap(), Path::new("/wt"));
2231    }
2232
2233    /// A build outside the checkout would build the live tree at every
2234    /// commit, and a typo'd key would build without what it names.
2235    #[test]
2236    fn a_bad_build_is_rejected_at_parse_time() {
2237        for bad in [
2238            "cmd = []",
2239            "dir = \"x\"",
2240            "cmd = \"make\"\ndir = \"/abs\"",
2241            "cmd = \"make\"\ndir = \"../elsewhere\"",
2242            "cmd = \"make\"\nevn = { A = \"1\" }",
2243            "cmd = [\"make\", \"{{ env.HOME }}\"]",
2244            "cmd = \"make\"\nenv = { A = \"{{ env.X }}\" }",
2245        ] {
2246            Config::parse(&format!("[build]\n{bad}")).expect_err(bad);
2247        }
2248    }
2249
2250    /// The syntax check covers the whole file, not only what some benchmark
2251    /// ends up using.
2252    #[test]
2253    fn an_unused_broken_template_is_still_rejected() {
2254        let unused = "[subject.spare]\ncmd = [\"{{ env.X \"]\n[bench.b]\ncmd = [\"x\"]";
2255        assert!(Config::parse(unused).is_err(), "unlisted shared subject");
2256        let overridden = "[subject.a]\ncmd = [\"{% if %}\"]\n[bench.b]\nsubjects = [\"a\"]\n[bench.b.subject.a]\ncmd = [\"x\"]";
2257        assert!(
2258            Config::parse(overridden).is_err(),
2259            "shared value an override replaces"
2260        );
2261    }
2262
2263    fn global() -> Gate {
2264        Gate::new(1.0, 0).unwrap()
2265    }
2266
2267    fn gate(pct: f64, min_delta: u64, enabled: bool) -> Gate {
2268        Gate {
2269            pct,
2270            min_delta,
2271            enabled,
2272        }
2273    }
2274
2275    #[test]
2276    fn a_benchmark_without_a_gate_gets_the_global_one() {
2277        let c = Config::parse("[bench.a]\ncmd = \"x\"").unwrap();
2278        assert_eq!(c.gates(global()).get("a", SELF_TOOL), global());
2279    }
2280
2281    #[test]
2282    fn a_benchmark_gate_overrides_the_global_one_key_by_key() {
2283        let c = Config::parse(
2284            r#"
2285            [bench.startup]
2286            cmd = "x --version"
2287            gate = { pct = 5.0 }
2288
2289            [bench.quiet]
2290            cmd = "x --help"
2291            gate = { enabled = false, min_delta = 20000 }
2292            "#,
2293        )
2294        .unwrap();
2295        let gates = c.gates(Gate::new(1.0, 100).unwrap());
2296        assert_eq!(gates.get("startup", SELF_TOOL), gate(5.0, 100, true));
2297        assert_eq!(gates.get("quiet", SELF_TOOL), gate(1.0, 20_000, false));
2298    }
2299
2300    /// The same order every other setting stacks in: benchmark, shared
2301    /// subject, then the benchmark's own subject table — and each only
2302    /// replaces the keys it sets.
2303    #[test]
2304    fn subject_gates_stack_by_specificity() {
2305        let c = Config::parse(
2306            r#"
2307            [subject.mine]
2308            cmd = "mine install"
2309            counters = true
2310
2311            [subject.theirs]
2312            cmd = "theirs install"
2313            counters = true
2314            gate = { enabled = false }
2315
2316            [bench.install]
2317            subjects = ["mine", "theirs"]
2318            gate = { pct = 3.0 }
2319
2320            [bench.install.subject.theirs]
2321            gate = { min_delta = 5000 }
2322
2323            [bench.install.subject.local]
2324            cmd = "local install"
2325            counters = true
2326            gate = { pct = 0.5 }
2327            "#,
2328        )
2329        .unwrap();
2330        let gates = c.gates(global());
2331        assert_eq!(gates.get("install", "mine"), gate(3.0, 0, true));
2332        assert_eq!(gates.get("install", "theirs"), gate(3.0, 5_000, false));
2333        assert_eq!(gates.get("install", "local"), gate(0.5, 0, true));
2334        assert_eq!(
2335            gates.get("install", "removed"),
2336            gate(3.0, 0, true),
2337            "a subject no longer declared falls back to its benchmark"
2338        );
2339        assert_eq!(
2340            gates.get("gone", SELF_TOOL),
2341            global(),
2342            "a benchmark no longer declared falls back to the global gate"
2343        );
2344    }
2345
2346    /// A subject can turn a report-only benchmark's gate back on for itself.
2347    #[test]
2348    fn a_subject_may_re_enable_its_benchmarks_gate() {
2349        let c = Config::parse(
2350            r#"
2351            [bench.b]
2352            gate = { enabled = false }
2353            [bench.b.subject.ours]
2354            cmd = "x"
2355            counters = true
2356            gate = { enabled = true }
2357            [bench.b.subject.other]
2358            cmd = "y"
2359            "#,
2360        )
2361        .unwrap();
2362        let gates = c.gates(global());
2363        assert!(gates.get("b", "ours").enabled);
2364        assert!(!gates.get("b", "other").enabled);
2365    }
2366
2367    /// Checked at load, and everywhere in the file, not when `tak compare`
2368    /// finally reads the gate on a pull request.
2369    #[test]
2370    fn bad_gates_are_rejected_at_parse_time() {
2371        for (bad, needle) in [
2372            ("gate = { pct = -1.0 }", "bench.a.gate.pct"),
2373            ("gate = { pct = nan }", "bench.a.gate.pct"),
2374            ("gate = { pct = inf }", "bench.a.gate.pct"),
2375            ("gate = { min_delta = -1 }", "min_delta"),
2376            ("gate = { min_delta = 1.5 }", "min_delta"),
2377            ("gate = { enabled = \"no\" }", "enabled"),
2378            // A typo must not leave the benchmark at the global gate while
2379            // the file reads as though it had its own.
2380            ("gate = { pc = 5.0 }", "pc"),
2381            ("gate = false", "gate"),
2382        ] {
2383            let toml = format!("[bench.a]\ncmd = \"x\"\n{bad}");
2384            let err = Config::parse(&toml).expect_err(bad);
2385            let msg = format!("{err:#}");
2386            assert!(msg.contains(needle), "{bad}: {msg}");
2387        }
2388        let unused = "[subject.spare]\ncmd = \"y\"\ngate = { pct = -2.0 }\n[bench.a]\ncmd = \"x\"";
2389        let msg = format!("{:#}", Config::parse(unused).unwrap_err());
2390        assert!(msg.contains("subject.spare.gate.pct"), "{msg}");
2391        let local = "[bench.b.subject.s]\ncmd = \"y\"\ngate = { pct = -2.0 }";
2392        let msg = format!("{:#}", Config::parse(local).unwrap_err());
2393        assert!(msg.contains("bench.b.subject.s.gate.pct"), "{msg}");
2394    }
2395
2396    #[test]
2397    fn an_integer_percentage_is_a_percentage() {
2398        let c = Config::parse("[bench.a]\ncmd = \"x\"\ngate = { pct = 5 }").unwrap();
2399        assert_eq!(c.gates(global()).get("a", SELF_TOOL).pct, 5.0);
2400    }
2401}