Skip to main content

tak_cli/
config.rs

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