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