Skip to main content

tak_cli/
compare.rs

1//! Compare one commit's measurements against another's.
2//!
3//! This is the part that can block a pull request, so it is deliberately narrow
4//! about what it will fail on. Only instruction counts gate. Wall clock is
5//! reported beside them and never gated: on identical hardware it moves 4-20%
6//! run to run, so a threshold tight enough to catch a real regression fires
7//! constantly, and one loose enough to stay quiet catches nothing.
8//!
9//! Rendering lives in [`markdown`], separate from the comparison itself, so a
10//! chart or a different report format is a new function rather than a rewrite.
11
12use crate::accept::Acceptances;
13use crate::config::SELF_TOOL;
14use crate::record::{Record, is_builtin_metric};
15use std::collections::{BTreeMap, BTreeSet};
16
17/// The only metric a gate may fire on.
18pub const GATED_METRIC: &str = "instructions";
19
20/// The timing metric shown alongside it, for context only.
21pub(crate) const WALL_METRIC: &str = "wall_min_ms";
22
23/// Heap-allocation metrics, in the order their columns appear. Recorded only
24/// by subjects that opt in, so they get a table of their own rather than
25/// columns every report would carry empty.
26const ALLOC_METRICS: [(&str, &str); 3] = [
27    ("alloc_blocks", "allocations"),
28    ("alloc_bytes", "bytes allocated"),
29    ("alloc_peak_bytes", "peak heap"),
30];
31
32/// What identifies a comparable series.
33///
34/// Runner is part of the key because it has to be: absolute counts shift
35/// between machine types by more than a real regression does, so comparing a
36/// measurement taken on one runner against another's is not a comparison at
37/// all. Two commits measured on different runners simply do not line up here,
38/// which is the correct outcome rather than a missing feature.
39pub type Key = (String, String, String);
40
41/// One metric, on one series, on both sides.
42#[derive(Debug, Clone, PartialEq)]
43pub struct Change {
44    pub bench: String,
45    pub tool: String,
46    pub runner: String,
47    pub metric: String,
48    pub base: f64,
49    pub head: f64,
50}
51
52impl Change {
53    /// Change as a percentage of the base, or `None` when the base is zero.
54    ///
55    /// `None` rather than `0.0`. Returning zero was worse than imprecise: the
56    /// gate compares this against the threshold, so a rise from a zero baseline
57    /// read as no change at all and passed silently, however large the head.
58    /// A percentage of nothing is undefined, and the type should say so.
59    pub fn pct(&self) -> Option<f64> {
60        if self.base == 0.0 {
61            return None;
62        }
63        Some((self.head - self.base) / self.base * 100.0)
64    }
65
66    /// Has this risen beyond `gate`'s threshold?
67    ///
68    /// Both limits have to be crossed: the percentage and the absolute floor.
69    /// The floor is for the benchmarks a percentage serves worst. On a
70    /// 450k-instruction startup check, 1% is 4,500 instructions — a new
71    /// dependency's relocations in the dynamic loader rather than anything the
72    /// program did — while the same 1% of a 100M-instruction install is a
73    /// million instructions of real work.
74    ///
75    /// From a zero base, any increase past the floor counts. There is no
76    /// percentage that means anything against zero, and passing would be the
77    /// one outcome that is certainly wrong.
78    ///
79    /// Whether the gate is enabled is not this function's question: a
80    /// report-only series is still held to its threshold, so the report can say
81    /// that it crossed one.
82    pub fn exceeds(&self, gate: &Gate) -> bool {
83        if self.metric != GATED_METRIC {
84            return false;
85        }
86        // `as f64` rounds a floor above 2^53, far past any worth writing down.
87        if self.head - self.base <= gate.min_delta as f64 {
88            return false;
89        }
90        match self.pct() {
91            Some(p) => p > gate.pct,
92            None => self.head > 0.0,
93        }
94    }
95}
96
97/// When an instruction count has risen far enough to fail `tak compare`.
98///
99/// Policy, not measurement, so it is never recorded: it comes from the settings
100/// and `tak.toml` of whoever runs the comparison. Stored with the records, a
101/// threshold change would read as a change in what was measured, and two
102/// writers with different gates would emit byte-different lines for the same
103/// measurement, which `cat_sort_uniq` cannot collapse.
104#[derive(Debug, Clone, Copy, PartialEq)]
105pub struct Gate {
106    /// Percentage of the base a count may rise by.
107    pub pct: f64,
108    /// Instructions a count may rise by, whatever the percentage says.
109    pub min_delta: u64,
110    /// False for a report-only series: still held to its threshold and flagged
111    /// when it crosses it, but never a reason to fail.
112    pub enabled: bool,
113}
114
115impl Gate {
116    /// An enabled gate, checked.
117    pub fn new(pct: f64, min_delta: u64) -> anyhow::Result<Self> {
118        check_pct(pct)?;
119        Ok(Self {
120            pct,
121            min_delta,
122            enabled: true,
123        })
124    }
125
126    /// The threshold, short enough for a table cell: `5%`, `5%, floor 20,000`.
127    pub(crate) fn threshold(&self) -> String {
128        if self.min_delta == 0 {
129            format!("{}%", self.pct)
130        } else {
131            format!("{}%, floor {}", self.pct, thousands(self.min_delta as f64))
132        }
133    }
134
135    /// The threshold, and whether crossing it fails.
136    pub(crate) fn describe(&self) -> String {
137        if self.enabled {
138            self.threshold()
139        } else {
140            format!("report only ({})", self.threshold())
141        }
142    }
143}
144
145/// Reject a gate percentage that cannot mean what it says.
146///
147/// NaN is the dangerous one: every comparison against it is false, so a gate of
148/// NaN passes everything while looking set. A negative percentage fails a
149/// benchmark that did not move, and infinity is `enabled = false` spelled in a
150/// way the report cannot show.
151pub fn check_pct(pct: f64) -> anyhow::Result<()> {
152    if !pct.is_finite() || pct < 0.0 {
153        anyhow::bail!("a gate percentage must be a finite number, 0 or more, not {pct}");
154    }
155    Ok(())
156}
157
158/// The gate for every series, as `tak.toml` declares it.
159///
160/// Looked up by benchmark and tool, never by runner. A gate is a statement
161/// about a benchmark — how much of its count is the program's own work — and
162/// that does not change with the machine it is measured on.
163#[derive(Debug, Clone, PartialEq)]
164pub struct Gates {
165    /// The `[gate]` settings: what a series without its own gate is held to.
166    pub global: Gate,
167    /// Each declared benchmark's own gate, for a series whose tool the
168    /// benchmark does not declare as a subject (any more).
169    benches: BTreeMap<String, Gate>,
170    /// Each declared (benchmark, subject), with every layer applied.
171    series: BTreeMap<(String, String), Gate>,
172}
173
174impl Gates {
175    /// The same gate for everything, as when there is no `tak.toml`.
176    pub fn uniform(global: Gate) -> Self {
177        Self {
178            global,
179            benches: BTreeMap::new(),
180            series: BTreeMap::new(),
181        }
182    }
183
184    pub fn set_bench(&mut self, bench: &str, gate: Gate) {
185        self.benches.insert(bench.to_string(), gate);
186    }
187
188    pub fn set_series(&mut self, bench: &str, tool: &str, gate: Gate) {
189        self.series
190            .insert((bench.to_string(), tool.to_string()), gate);
191    }
192
193    /// The gate for one series: its own, else its benchmark's, else the global
194    /// one.
195    ///
196    /// A benchmark in the notes but no longer in `tak.toml` gets the global
197    /// gate rather than none. It is usually on the base side only, where
198    /// nothing gates it anyway; when it is on both, the project has not said
199    /// it is special, and the gate everything else gets is the honest default.
200    pub fn get(&self, bench: &str, tool: &str) -> Gate {
201        self.series
202            .get(&(bench.to_string(), tool.to_string()))
203            .or_else(|| self.benches.get(bench))
204            .copied()
205            .unwrap_or(self.global)
206    }
207
208    fn of(&self, c: &Change) -> Gate {
209        self.get(&c.bench, &c.tool)
210    }
211
212    /// What these gates hold differently from `base`, by effective value: the
213    /// global gate as `[gate]`, then each series either side declares or
214    /// `measured` names whose resolved gate differs.
215    ///
216    /// Effective rather than structural. Declaring a benchmark with no `gate`
217    /// adds it to the maps at the global gate, which is what an undeclared
218    /// series gets anyway; reporting that as a change would tell a pull
219    /// request that only added a benchmark its gate takes effect later. A
220    /// series that merely follows `[gate]` on both sides is covered by
221    /// `[gate]` and not named again.
222    ///
223    /// Each entry is a code span, escaped by [`code`] like every other name in
224    /// the report: a benchmark name comes from the change under review, and one
225    /// holding a newline must not start a line of its own.
226    pub fn changes_from(&self, base: &Gates, measured: &BTreeSet<(String, String)>) -> Vec<String> {
227        let mut out = Vec::new();
228        if self.global != base.global {
229            out.push(code("[gate]"));
230        }
231        let follows = |g: &Gates, gate: Gate| gate == g.global;
232        let mut named = BTreeSet::new();
233        // A benchmark's own gate is what its undeclared subjects fall back to.
234        for bench in self.benches.keys().chain(base.benches.keys()) {
235            let of = |g: &Gates| g.benches.get(bench).copied().unwrap_or(g.global);
236            let (mine, theirs) = (of(self), of(base));
237            if mine != theirs && !(follows(self, mine) && follows(base, theirs)) {
238                named.insert(bench.clone());
239            }
240        }
241        let series = self
242            .series
243            .keys()
244            .chain(base.series.keys())
245            .chain(measured.iter());
246        for (bench, tool) in series {
247            let (mine, theirs) = (self.get(bench, tool), base.get(bench, tool));
248            if mine != theirs && !(follows(self, mine) && follows(base, theirs)) {
249                named.insert(name(bench, tool));
250            }
251        }
252        out.extend(named.iter().map(|n| code(n)));
253        out
254    }
255}
256
257#[derive(Debug, Default, PartialEq)]
258pub struct Comparison {
259    /// Every metric present on both sides, in a stable order.
260    pub changes: Vec<Change>,
261    /// Series measured on the head commit and not the base — a new benchmark,
262    /// or the first run on a new runner class. Reported, never gated: there is
263    /// nothing to compare against.
264    pub added: Vec<Key>,
265    /// Series on the base and not the head. Usually a benchmark that was
266    /// removed, occasionally a run that failed to record — worth surfacing
267    /// either way, because a silently vanishing benchmark stops gating.
268    pub removed: Vec<Key>,
269    /// Benchmarks the change declared it regresses on purpose. Their
270    /// regressions are still reported, and still counted by [`regressions`],
271    /// but not by [`failures`] — the set the gate actually fails on.
272    ///
273    /// [`regressions`]: Comparison::regressions
274    /// [`failures`]: Comparison::failures
275    pub accepted: Acceptances,
276    /// `Tak-Accept` trailers found in the range and deliberately not honoured,
277    /// because `accept_trailers` is off. Kept only to say so in the report.
278    pub ignored_trailers: Acceptances,
279    /// One Markdown line on where the gate came from, when that is worth
280    /// saying: the base had no `tak.toml`, or the head's would gate
281    /// differently. Rendered below the verdict rather than above it, because
282    /// scripts read the report's first line as its outcome.
283    pub gate_source: Option<String>,
284    /// Set when nothing was compared and `allow_empty` passed it rather than
285    /// failing it. Carried here, as `detect` carries its own, so the report
286    /// and the exit status cannot disagree.
287    pub allowed_empty: bool,
288}
289
290impl Comparison {
291    /// Changes beyond an enabled gate, accepted or not.
292    pub fn regressions(&self, gates: &Gates) -> Vec<&Change> {
293        self.changes
294            .iter()
295            .filter(|c| {
296                let gate = gates.of(c);
297                gate.enabled && c.exceeds(&gate)
298            })
299            .collect()
300    }
301
302    /// What `tak compare` fails on: regressions no acceptance covers.
303    ///
304    /// Layered on [`regressions`](Comparison::regressions), so each series is
305    /// still judged against its own effective gate, and an acceptance can only
306    /// waive a change that would otherwise have failed. A report-only series
307    /// never reaches this, so it never needs accepting.
308    pub fn failures(&self, gates: &Gates) -> Vec<&Change> {
309        self.regressions(gates)
310            .into_iter()
311            .filter(|c| !self.accepted.covers(&c.bench))
312            .collect()
313    }
314
315    /// The regressions an acceptance waived.
316    pub fn accepted_regressions(&self, gates: &Gates) -> Vec<&Change> {
317        self.regressions(gates)
318            .into_iter()
319            .filter(|c| self.accepted.covers(&c.bench))
320            .collect()
321    }
322
323    /// Attach what the change declared. Separate from [`compare`] because the
324    /// numbers and the declaration come from different places — notes and
325    /// commit messages — and a comparison is meaningful without either.
326    pub fn with_accepted(mut self, accepted: Acceptances) -> Self {
327        self.accepted = accepted;
328        self
329    }
330
331    /// Record trailers that were present but not honoured. They never affect
332    /// the gate; they exist so the report can explain why a trailer did nothing.
333    pub fn with_ignored_trailers(mut self, ignored: Acceptances) -> Self {
334        self.ignored_trailers = ignored;
335        self
336    }
337
338    /// Changes beyond a report-only gate: flagged, never failed on.
339    pub fn reported(&self, gates: &Gates) -> Vec<&Change> {
340        self.changes
341            .iter()
342            .filter(|c| {
343                let gate = gates.of(c);
344                !gate.enabled && c.exceeds(&gate)
345            })
346            .collect()
347    }
348
349    /// Whether every instruction count here is held to the global gate.
350    ///
351    /// When it is, the report and the error read exactly as they did before
352    /// per-benchmark gates existed. Scripts grep them — tak's own perf-pr
353    /// workflow among them — and a project that never wrote a per-benchmark
354    /// gate should not have its output change under it.
355    pub fn gated_uniformly(&self, gates: &Gates) -> bool {
356        self.changes
357            .iter()
358            .filter(|c| c.metric == GATED_METRIC)
359            .all(|c| gates.of(c) == gates.global)
360    }
361
362    /// True when there is nothing to compare — no overlapping series at all.
363    pub fn is_empty(&self) -> bool {
364        self.changes.is_empty()
365    }
366}
367
368/// Fold records into one value per (series, metric), taking the minimum.
369///
370/// A commit can carry several records for the same series: CI re-run, a retry,
371/// a local run pushed alongside. The minimum is the right reducer for the same
372/// reason tak reports the minimum within a run — the extra work a machine
373/// sometimes does is one-sided. Averaging would let one noisy sample move a
374/// number that is supposed to be deterministic.
375pub(crate) fn index(records: &[Record]) -> BTreeMap<(Key, String), f64> {
376    let mut out: BTreeMap<(Key, String), f64> = BTreeMap::new();
377    for r in records {
378        let key: Key = (r.bench.clone(), r.tool.clone(), r.runner.clone());
379        for (metric, value) in &r.metrics {
380            out.entry((key.clone(), metric.clone()))
381                .and_modify(|existing| {
382                    if value < existing {
383                        *existing = *value;
384                    }
385                })
386                .or_insert(*value);
387        }
388    }
389    out
390}
391
392/// Compare two sets of records.
393pub fn compare(base: &[Record], head: &[Record]) -> Comparison {
394    let (b, h) = (index(base), index(head));
395
396    let mut changes = Vec::new();
397    for ((key, metric), head_value) in &h {
398        if let Some(base_value) = b.get(&(key.clone(), metric.clone())) {
399            changes.push(Change {
400                bench: key.0.clone(),
401                tool: key.1.clone(),
402                runner: key.2.clone(),
403                metric: metric.clone(),
404                base: *base_value,
405                head: *head_value,
406            });
407        }
408    }
409
410    let base_keys: BTreeSet<Key> = b.keys().map(|(k, _)| k.clone()).collect();
411    let head_keys: BTreeSet<Key> = h.keys().map(|(k, _)| k.clone()).collect();
412
413    Comparison {
414        changes,
415        added: head_keys.difference(&base_keys).cloned().collect(),
416        removed: base_keys.difference(&head_keys).cloned().collect(),
417        accepted: Acceptances::default(),
418        ignored_trailers: Acceptances::default(),
419        gate_source: None,
420        allowed_empty: false,
421    }
422}
423
424/// Recent values for each series, oldest first.
425pub type Trend = BTreeMap<Key, Vec<f64>>;
426
427/// Assemble a trend from trunk history plus the revision under comparison.
428///
429/// `walked` is oldest-first, each entry a commit and the records attached to it.
430///
431/// The head's point is appended only when the walk did not already contain it.
432/// Appending unconditionally put it last even when it belongs in the middle —
433/// `tak compare v1.33.0 --rev v1.30.0` compares against an *ancestor*, and the
434/// line then ended on a value from earlier in the history while reading as
435/// though time ran left to right.
436pub fn build_trend(
437    walked: &[(String, Vec<Record>)],
438    head_sha: &str,
439    head_records: &[Record],
440) -> Trend {
441    let mut trend = Trend::new();
442    let mut head_in_history = false;
443    for (sha, records) in walked {
444        if sha == head_sha {
445            head_in_history = true;
446            // Its own measurements, in its own place in the timeline.
447            add_point(&mut trend, head_records);
448        } else {
449            add_point(&mut trend, records);
450        }
451    }
452    if !head_in_history {
453        add_point(&mut trend, head_records);
454    }
455    trend
456}
457
458/// Append one point per series, taking the minimum across a commit's records.
459///
460/// The minimum, matching how `compare` folds duplicates. A commit can carry
461/// several records for one series — a CI re-run, a retry — and taking each as
462/// its own point let a noisy re-run put a spike in the trend that the table,
463/// which reduces to the minimum, does not show.
464fn add_point(trend: &mut Trend, records: &[Record]) {
465    let mut lowest: BTreeMap<Key, f64> = BTreeMap::new();
466    for r in records {
467        if let Some(v) = r.metrics.get(GATED_METRIC) {
468            lowest
469                .entry((r.bench.clone(), r.tool.clone(), r.runner.clone()))
470                .and_modify(|e| {
471                    if v < e {
472                        *e = *v;
473                    }
474                })
475                .or_insert(*v);
476        }
477    }
478    for (key, value) in lowest {
479        trend.entry(key).or_default().push(value);
480    }
481}
482
483/// Eight levels of block, low to high.
484const BARS: [char; 8] = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
485
486/// A sparkline, scaled to the series' own range.
487///
488/// Per-series scaling is the only useful choice: an install benchmark at 100M
489/// instructions and a startup one at 7M share no axis, and a shared one would
490/// flatten every series but the largest into a straight line.
491///
492/// A flat series renders mid-height rather than at the floor. All-`▁` reads as
493/// "bottomed out" when it actually means "did not move", which for a
494/// deterministic metric is the best possible outcome and should not look like
495/// the worst.
496pub fn sparkline(values: &[f64]) -> String {
497    if values.len() < 2 {
498        return String::new();
499    }
500    let min = values.iter().copied().fold(f64::INFINITY, f64::min);
501    let max = values.iter().copied().fold(f64::NEG_INFINITY, f64::max);
502    if max <= min {
503        return BARS[BARS.len() / 2].to_string().repeat(values.len());
504    }
505    values
506        .iter()
507        .map(|v| {
508            let t = (v - min) / (max - min);
509            let i = (t * (BARS.len() - 1) as f64).round() as usize;
510            BARS[i.min(BARS.len() - 1)]
511        })
512        .collect()
513}
514
515/// `12345678` -> `12,345,678`
516pub(crate) fn thousands(v: f64) -> String {
517    let n = format!("{:.0}", v.abs());
518    let mut out = String::new();
519    for (i, c) in n.chars().enumerate() {
520        if i > 0 && (n.len() - i) % 3 == 0 {
521            out.push(',');
522        }
523        out.push(c);
524    }
525    if v < 0.0 { format!("-{out}") } else { out }
526}
527
528/// A percentage for display, or `new` when there is no base to compare to.
529pub(crate) fn signed_pct(p: Option<f64>) -> String {
530    match p {
531        Some(p) => format!("{}{:.2}%", if p >= 0.0 { "+" } else { "" }, p),
532        None => "new".to_string(),
533    }
534}
535
536/// Render a comparison as markdown, suitable for a PR comment or a terminal.
537///
538/// One format rather than two. A markdown table is readable unrendered, so a
539/// second plain-text renderer would be a second thing to keep correct for no
540/// gain.
541/// The line naming tak, appended unless the `credit` setting is off.
542///
543/// A report that turns up in someone's pull request should say what put it
544/// there: a reader who has never seen tak needs a way to find out, and a
545/// maintainer deciding whether to keep the comment needs to know what to turn
546/// off. Small, last, and one line — advertising that gets in the way of the
547/// numbers would be its own argument for removing it.
548pub(crate) const CREDIT: &str = "\n<sub>Measured by [tak](https://github.com/jdx/tak) — instruction-counted \
549     CLI benchmarks, stored in this repository's git notes.</sub>\n";
550
551/// The line saying an empty comparison passed only because `allow_empty` let
552/// it, shared by every report that can say it so they word it alike.
553///
554/// Names the setting, not the flag: `--allow-empty`, `TAK_ALLOW_EMPTY` and
555/// `[gate] allow_empty` are three spellings of it. Names the cost too, because
556/// the reader most likely to see this is the one whose notes were never
557/// fetched, and "passed" is the wrong thing to leave them with.
558pub const ALLOWED_EMPTY: &str = "This passes with a warning instead of failing, because \
559     `allow_empty` is on. That is expected on a new runner class, for a new benchmark, or on \
560     a first recording. It is also what history that was never recorded or never fetched \
561     looks like, so check which this is.";
562
563pub fn markdown(c: &Comparison, trend: &Trend, gates: &Gates, credit: bool) -> String {
564    let mut out = String::new();
565
566    if c.is_empty() {
567        // No early return. `added` and `removed` are often *most* interesting
568        // here — a runner migration produces exactly this state, and the useful
569        // half of the report is which benchmarks stopped being comparable.
570        out.push_str(
571            "**Nothing was compared, and so nothing was gated.** No series \
572             appears on both sides: either the base has no measurements \
573             recorded, or the two were measured on different runner classes, \
574             which are deliberately not comparable — counts shift between \
575             machine types by more than a real regression does.\n",
576        );
577        // A line of its own, below the first, never folded into it. That line
578        // is byte for byte what it was before this setting existed, because
579        // scripts match it as a whole — jdx/tak-action compares the full bold
580        // sentence, period included — and an exit status of 0 is exactly the
581        // case where the first line is all a script has left to go on.
582        if c.allowed_empty {
583            out.push_str(&format!("\n{ALLOWED_EMPTY}\n"));
584        }
585    } else {
586        out.push_str(&table(c, trend, gates));
587        out.push_str(&allocations(c));
588        out.push_str(&custom_table(c));
589    }
590
591    if let Some(line) = &c.gate_source {
592        out.push_str(&format!("\n{line}\n"));
593    }
594    out.push_str(&unused_acceptances(c, gates));
595    out.push_str(&ignored_trailers(c));
596    out.push_str(&outliers(c));
597    out.push_str(
598        "\n<sub>Only instruction counts gate. Wall clock is shown for context — \
599         on identical hardware it moves 4-20% run to run.</sub>\n",
600    );
601    if credit {
602        out.push_str(CREDIT);
603    }
604    out
605}
606
607/// A series' table cell: [`name`], plus the runner when `keys` holds the
608/// same bench and tool on another runner. Without it the two rows read
609/// identically, and nothing says which change was measured where.
610///
611/// Escaped like every other report site: control characters by [`name`]
612/// and [`escape_control`], then the whole cell by [`cell`], since bench,
613/// tool and runner names are free text — a runner class comes from the
614/// environment — and a bare `|` in any of them would split the row.
615fn row_name<'a>(key: &Key, keys: impl IntoIterator<Item = &'a Key>) -> String {
616    let (bench, tool, runner) = key;
617    let shared = keys
618        .into_iter()
619        .any(|(b, t, r)| b == bench && t == tool && r != runner);
620    let text = if shared {
621        format!("{} on {}", name(bench, tool), escape_control(runner))
622    } else {
623        name(bench, tool)
624    };
625    cell(&text)
626}
627
628/// How a series is named in a table row or a verdict: the bench, plus the tool
629/// when it is not the project itself.
630///
631/// Control characters are escaped. `tak.toml` rejects them at load, but a
632/// note written by an older tak can still hold one, and a newline in a table
633/// cell or a verdict would start a report line of its own.
634fn name(bench: &str, tool: &str) -> String {
635    let bench = escape_control(bench);
636    if tool == SELF_TOOL {
637        bench.into_owned()
638    } else {
639        format!("{bench} ({})", escape_control(tool))
640    }
641}
642
643/// The comparison table and its verdict.
644fn table(c: &Comparison, trend: &Trend, gates: &Gates) -> String {
645    let mut out = String::new();
646    // One row per series, both metrics side by side: reading them together is
647    // what tells you whether a wall-clock move is real.
648    let mut series: BTreeMap<Key, (Option<&Change>, Option<&Change>)> = BTreeMap::new();
649    for change in &c.changes {
650        let key = (
651            change.bench.clone(),
652            change.tool.clone(),
653            change.runner.clone(),
654        );
655        let slot = series.entry(key).or_insert((None, None));
656        match change.metric.as_str() {
657            GATED_METRIC => slot.0 = Some(change),
658            WALL_METRIC => slot.1 = Some(change),
659            _ => {}
660        }
661    }
662
663    let any_trend = series
664        .keys()
665        .any(|k| trend.get(k).is_some_and(|v| v.len() > 1));
666    // Only when some row is held to something other than the global gate. A
667    // column that says `1%` on every row is noise, and it would change the
668    // report of every project that never wrote a per-benchmark gate.
669    let uniform = c.gated_uniformly(gates);
670
671    let mut header = vec![("benchmark", "---")];
672    if any_trend {
673        header.push(("trend", "---"));
674    }
675    header.extend([("instructions", "---:"), ("Δ", "---:")]);
676    if !uniform {
677        header.push(("gate", "---"));
678    }
679    header.extend([("wall (min)", "---:"), ("Δ", "---:")]);
680    let row = |cells: &[String]| format!("| {} |\n", cells.join(" | "));
681    out.push_str(&row(&header
682        .iter()
683        .map(|(h, _)| h.to_string())
684        .collect::<Vec<_>>()));
685    out.push_str(&format!(
686        "|{}|\n",
687        header.iter().map(|(_, a)| *a).collect::<Vec<_>>().join("|")
688    ));
689
690    for (key, (ins, wall)) in &series {
691        let (bench, tool, _runner) = key;
692        let gate = gates.get(bench, tool);
693        let mut cells = vec![row_name(key, series.keys())];
694        if any_trend {
695            cells.push(
696                trend
697                    .get(key)
698                    .map(|v| sparkline(v))
699                    .filter(|s| !s.is_empty())
700                    .map(|s| format!("`{s}`"))
701                    .unwrap_or_else(|| "—".into()),
702            );
703        }
704        match ins {
705            Some(ch) => {
706                // A report-only row that crossed its threshold says so in
707                // words: the warning sign means "this fails", and a row that
708                // cannot fail should not wear it. An accepted row is marked
709                // too, so it cannot be read as a passing one by someone who
710                // only scans the table.
711                let flag = match (ch.exceeds(&gate), gate.enabled) {
712                    (true, true) if c.accepted.covers(bench) => " (accepted)",
713                    (true, true) => " ⚠️",
714                    (true, false) => " (not gated)",
715                    (false, _) => "",
716                };
717                cells.push(format!("{} → {}", thousands(ch.base), thousands(ch.head)));
718                cells.push(format!("**{}**{flag}", signed_pct(ch.pct())));
719            }
720            None => cells.extend(["—".into(), "—".into()]),
721        }
722        if !uniform {
723            // A row with no instruction count has nothing a gate applies to.
724            cells.push(if ins.is_some() {
725                gate.describe()
726            } else {
727                "—".into()
728            });
729        }
730        match wall {
731            Some(ch) => {
732                cells.push(format!("{:.2} → {:.2}ms", ch.base, ch.head));
733                cells.push(signed_pct(ch.pct()));
734            }
735            None => cells.extend(["—".into(), "—".into()]),
736        }
737        out.push_str(&row(&cells));
738    }
739
740    out.push('\n');
741    out.push_str(&verdict(c, gates, uniform));
742    out
743}
744
745/// The lines under the table that say what failed and what only rose.
746///
747/// With every row at the global gate, the wording is exactly what it was
748/// before per-benchmark gates existed, because scripts grep it: tak's own
749/// perf-pr workflow reads `benchmark(s) above the N% gate` to decide whether
750/// counts rose.
751fn verdict(c: &Comparison, gates: &Gates, uniform: bool) -> String {
752    let mut out = String::new();
753    let global = gates.global;
754    let listed = |changes: &[&Change], annotate: bool| {
755        changes
756            .iter()
757            .map(|ch| {
758                let mut s = format!("`{}` {}", name(&ch.bench, &ch.tool), signed_pct(ch.pct()));
759                if annotate {
760                    s.push_str(&format!(" (gate {})", gates.of(ch).threshold()));
761                }
762                s
763            })
764            .collect::<Vec<_>>()
765            .join(", ")
766    };
767
768    let regressions = c.regressions(gates);
769    let failures = c.failures(gates);
770    let accepted = c.accepted_regressions(gates);
771    if uniform {
772        // Named on both verdicts. Without it, a failing report can show one 2%
773        // rise failing beside another passing and give no reason; the floor is
774        // the reason. After the `N% gate` wording, which scripts match on.
775        let floor = if global.min_delta == 0 {
776            String::new()
777        } else {
778            format!(
779                " (rises of {} instructions or fewer are not counted)",
780                thousands(global.min_delta as f64)
781            )
782        };
783        if regressions.is_empty() {
784            out.push_str(&format!(
785                "No instruction-count regression above {}%{floor}.\n",
786                global.pct,
787            ));
788        } else if !failures.is_empty() {
789            out.push_str(&format!(
790                "**{} benchmark(s) above the {}% gate{floor}:** {}\n",
791                failures.len(),
792                global.pct,
793                listed(&failures, false)
794            ));
795        }
796        out.push_str(&accepted_line(
797            c,
798            &accepted,
799            &format!("the {}% gate", global.pct),
800            !failures.is_empty(),
801            |_| String::new(),
802        ));
803        return out;
804    }
805
806    let any_gated = c
807        .changes
808        .iter()
809        .any(|ch| ch.metric == GATED_METRIC && gates.of(ch).enabled);
810    if !any_gated {
811        // "No gated benchmark rose" is true of a table with none, and reads
812        // as a pass. Saying there was nothing to fail is the honest verdict.
813        out.push_str("Every benchmark here is report-only, so none can fail the gate.\n");
814    } else if regressions.is_empty() {
815        out.push_str("No gated benchmark rose beyond its gate.\n");
816    } else if !failures.is_empty() {
817        out.push_str(&format!(
818            "**{} benchmark(s) above their gate:** {}\n",
819            failures.len(),
820            listed(&failures, true)
821        ));
822    }
823    out.push_str(&accepted_line(
824        c,
825        &accepted,
826        "their gate",
827        !failures.is_empty(),
828        |ch| format!(" (gate {})", gates.of(ch).threshold()),
829    ));
830    let reported = c.reported(gates);
831    if !reported.is_empty() {
832        out.push_str(&format!(
833            "\n**{} report-only benchmark(s) above their gate, not failing:** {}\n",
834            reported.len(),
835            listed(&reported, true)
836        ));
837    }
838    out
839}
840
841/// The heap-allocation table, or nothing when no series has allocation
842/// metrics on both sides — so a project that never opted in sees the report
843/// it always did.
844///
845/// Never flagged, whatever the change: allocations are reported beside the
846/// gate, not part of it, until they have been shown to be as reproducible as
847/// instruction counts across the programs people measure.
848fn allocations(c: &Comparison) -> String {
849    let mut series: BTreeMap<Key, BTreeMap<&str, &Change>> = BTreeMap::new();
850    for change in &c.changes {
851        if ALLOC_METRICS.iter().any(|(m, _)| *m == change.metric) {
852            series
853                .entry((
854                    change.bench.clone(),
855                    change.tool.clone(),
856                    change.runner.clone(),
857                ))
858                .or_default()
859                .insert(change.metric.as_str(), change);
860        }
861    }
862    if series.is_empty() {
863        return String::new();
864    }
865    let mut out = String::from("\nHeap allocations, counted by DHAT; reported, not gated:\n\n");
866    out.push_str("| benchmark |");
867    for (_, title) in ALLOC_METRICS {
868        out.push_str(&format!(" {title} | Δ |"));
869    }
870    out.push_str("\n|---|");
871    out.push_str(&"---:|---:|".repeat(ALLOC_METRICS.len()));
872    out.push('\n');
873    for (key, metrics) in &series {
874        out.push_str(&format!("| {} |", row_name(key, series.keys())));
875        for (metric, _) in ALLOC_METRICS {
876            match metrics.get(metric) {
877                Some(ch) => out.push_str(&format!(
878                    " {} → {} | {} |",
879                    thousands(ch.base),
880                    thousands(ch.head),
881                    count_delta(ch)
882                )),
883                None => out.push_str(" — | — |"),
884            }
885        }
886        out.push('\n');
887    }
888    out
889}
890
891/// Custom metrics — anything a project declared in `tak.toml` rather than
892/// something tak measured itself — as a table of their own, or nothing when
893/// there are none.
894///
895/// Separate from the main table rather than more columns on it: the set of
896/// custom metrics differs from project to project and from benchmark to
897/// benchmark, so columns would be mostly empty, and a project without any
898/// keeps exactly the table it had. One row per series and metric, in the
899/// order `compare` produced them, which groups a series' metrics together.
900///
901/// Never flagged: nothing here gates, whatever it did. A declared metric is a
902/// number from a file or a script tak knows nothing about, and nothing has
903/// shown it to be as repeatable as an instruction count.
904fn custom_table(c: &Comparison) -> String {
905    let rows: Vec<&Change> = c
906        .changes
907        .iter()
908        .filter(|ch| !is_builtin_metric(&ch.metric))
909        .collect();
910    if rows.is_empty() {
911        return String::new();
912    }
913    let mut out = String::from("\n| benchmark | metric | value | Δ |\n|---|---|---:|---:|\n");
914    // Escaped like the main table's names. `tak.toml` only lets a metric be
915    // named in `[a-z0-9_]`, but these come from notes, which any writer may
916    // have produced: a `|` would shift the columns and a newline would start
917    // a report line of its own.
918    for ch in rows {
919        out.push_str(&format!(
920            "| {} | {} | {} → {} | {} |\n",
921            cell(&name(&ch.bench, &ch.tool)),
922            cell(&escape_control(&ch.metric)),
923            plain(ch.base),
924            plain(ch.head),
925            signed_pct(ch.pct())
926        ));
927    }
928    out.push_str(
929        "\n<sub>Metrics declared in tak.toml are reported, never gated. As for every \
930         metric, lower is taken as better.</sub>\n",
931    );
932    out
933}
934
935/// A custom metric's value: separated like a count when it is whole, which
936/// sizes and counts are, and as written otherwise. `abs`, unlike when tak
937/// prints its own measurement: a note may hold a line from any writer.
938fn plain(v: f64) -> String {
939    if v.fract() == 0.0 && v.abs() < 1e15 {
940        thousands(v)
941    } else {
942        v.to_string()
943    }
944}
945
946/// The accepted regressions, on their own line in bold, each with its runner,
947/// its gate when `gate_of` names one, and where the acceptance came from.
948///
949/// Its own line because an acceptance is an override of the gate, and the
950/// point of scoping it is that it stays as visible as the regression would
951/// have been. `above {which}` keeps the wording the failure line uses, so a
952/// script matching `(s) above the N% gate` or `above their gate` sees an
953/// accepted rise as a rise. The runner is named because one benchmark
954/// accepted on two runner classes is two entries that would otherwise read
955/// identically.
956fn accepted_line(
957    c: &Comparison,
958    accepted: &[&Change],
959    which: &str,
960    after_failures: bool,
961    gate_of: impl Fn(&Change) -> String,
962) -> String {
963    if accepted.is_empty() {
964        return String::new();
965    }
966    format!(
967        "{}**{} accepted regression(s) above {which}, not failing it:** {}\n",
968        if after_failures { "\n" } else { "" },
969        accepted.len(),
970        accepted
971            .iter()
972            .map(|ch| format!(
973                "{} on {} {}{} ({})",
974                code(&name(&ch.bench, &ch.tool)),
975                code(&ch.runner),
976                signed_pct(ch.pct()),
977                gate_of(ch),
978                c.accepted.describe(&ch.bench)
979            ))
980            .collect::<Vec<_>>()
981            .join(", ")
982    )
983}
984
985/// `text` as a Markdown code span, whatever it contains.
986///
987/// Acceptance names come from commit messages and flags, not from a validated
988/// config, so a backtick in one is plausible; a single-backtick span would close
989/// early and garble the rest of the line. CommonMark allows a fence of any
990/// length that does not occur inside.
991///
992/// Padded with one space each side whenever the text holds a backtick or starts
993/// or ends with a space. CommonMark strips one leading and one trailing space
994/// from a span that has both, so unpadded, `" startup "` renders exactly like
995/// `startup` — two benchmark names the flag deliberately keeps apart would
996/// read as one in the report. The padding is what gets stripped, leaving the
997/// name as written. A span of only spaces is never stripped, so it is left
998/// unpadded.
999///
1000/// Control characters are written as escapes (`\n`, `\u{1b}`). The report is
1001/// read line by line — tak's own perf-pr workflow decides a check's outcome by
1002/// what a line starts with — and a newline in an `--accept` value would let a
1003/// name begin a line of its own that reads as a verdict.
1004pub(crate) fn code(text: &str) -> String {
1005    let text = escape_control(text);
1006    let text = text.as_ref();
1007    let mut longest = 0;
1008    let mut run = 0;
1009    for ch in text.chars() {
1010        run = if ch == '`' { run + 1 } else { 0 };
1011        longest = longest.max(run);
1012    }
1013    let fence = "`".repeat(longest + 1);
1014    let edge_space = text.starts_with(' ') || text.ends_with(' ');
1015    let only_spaces = text.chars().all(|c| c == ' ');
1016    if (longest > 0 || edge_space) && !only_spaces {
1017        format!("{fence} {text} {fence}")
1018    } else {
1019        format!("{fence}{text}{fence}")
1020    }
1021}
1022
1023/// Plain `text` made safe for one Markdown table cell: an unescaped `|` in a
1024/// name from `tak.toml` or a note ends the cell early and shifts every column
1025/// after it.
1026///
1027/// Every `\|` is an escaped pipe to the table, whatever precedes it, and the
1028/// table strips that backslash before the inline parse — which then reads the
1029/// cell's own backslashes as escapes. So backslashes are doubled first, or a
1030/// subject's `\|` would render as a bare `|`, and `a\*b` as `a*b`. For a cell
1031/// whose text sits inside a code span, use [`code_cell`] instead.
1032pub(crate) fn cell(text: &str) -> String {
1033    text.replace('\\', "\\\\").replace('|', "\\|")
1034}
1035
1036/// [`cell`] for text inside a code span, as [`describe`] writes names:
1037/// pipes only.
1038///
1039/// The table strips a pipe's escaping backslash before the code span is
1040/// parsed, so `\|` still works there, but a code span shows every other
1041/// backslash as written. Doubling them, as [`cell`] does, put `win\\arm` in
1042/// the report for a runner named `win\arm`. One case cannot be written
1043/// exactly: a backslash directly before a pipe (`a\|b`) is left alone by the
1044/// table, so it renders as `a\\|b`. The row stays intact either way, checked
1045/// against comrak's GFM tables.
1046pub(crate) fn code_cell(text: &str) -> String {
1047    text.replace('|', "\\|")
1048}
1049
1050/// The [`Comparison::gate_source`] line: where the gate came from, when the
1051/// base had no `tak.toml` or the head's would gate differently; `None` when
1052/// there is nothing to say.
1053///
1054/// `path` is the base's `tak.toml` from the repository root, `at` the base
1055/// commit's short SHA, and `changed` what [`Gates::changes_from`] and the
1056/// caller named, each already a code span. Every interpolation goes through
1057/// [`code`]: the path is a directory name, which can hold a backtick that a
1058/// hand-written span would end early on, or a control character.
1059pub fn gate_source(path: Option<&str>, at: &str, changed: &[String]) -> Option<String> {
1060    let later = (!changed.is_empty()).then(|| {
1061        format!(
1062            " This revision changes the gate policy ({}), and the change takes effect \
1063             once it is merged.",
1064            changed.join(", ")
1065        )
1066    });
1067    match (path, later) {
1068        (None, later) => Some(format!(
1069            "No {} at the base, {}, so the gate is tak's defaults plus any flags and \
1070             environment variables.{}",
1071            code(crate::config::FILE_NAME),
1072            code(at),
1073            later.unwrap_or_default()
1074        )),
1075        (Some(path), Some(later)) => Some(format!(
1076            "The gate comes from {} at the base, {}.{later}",
1077            code(path),
1078            code(at)
1079        )),
1080        (Some(_), None) => None,
1081    }
1082}
1083
1084/// One line naming trailers that were ignored, so an author whose trailer did
1085/// nothing can see why rather than assume tak failed to read it.
1086fn ignored_trailers(c: &Comparison) -> String {
1087    if c.ignored_trailers.is_empty() {
1088        return String::new();
1089    }
1090    format!(
1091        "\n`{}` trailers were found but not honoured, because `gate.accept_trailers` is \
1092         off: {}\n",
1093        crate::accept::TRAILER,
1094        c.ignored_trailers
1095            .iter()
1096            .map(|(bench, _)| format!("{} ({})", code(bench), c.ignored_trailers.describe(bench)))
1097            .collect::<Vec<_>>()
1098            .join(", ")
1099    )
1100}
1101
1102/// Acceptances that did not accept anything, each with the reason.
1103///
1104/// Reported rather than dropped. A stale acceptance is harmless today and a
1105/// surprise the day that benchmark does regress; a misspelt one means the
1106/// regression it was written for still fails, and the author needs to see why.
1107/// A report-only benchmark is its own case: it can never fail, so accepting it
1108/// does nothing, and saying "did not rise" would be wrong when it did. None of
1109/// these fail the gate by themselves.
1110fn unused_acceptances(c: &Comparison, gates: &Gates) -> String {
1111    let mut quiet = Vec::new();
1112    let mut report_only = Vec::new();
1113    let mut unknown = Vec::new();
1114    for (bench, _) in c.accepted.iter() {
1115        let entry = format!("{} ({})", code(bench), c.accepted.describe(bench));
1116        let counted: Vec<&Change> = c
1117            .changes
1118            .iter()
1119            .filter(|ch| ch.bench == bench && ch.metric == GATED_METRIC)
1120            .collect();
1121        if !c.changes.iter().any(|ch| ch.bench == bench) {
1122            unknown.push(entry);
1123        } else if counted.iter().any(|ch| {
1124            let gate = gates.of(ch);
1125            gate.enabled && ch.exceeds(&gate)
1126        }) {
1127            // Accepted something.
1128        } else if !counted.is_empty() && counted.iter().all(|ch| !gates.of(ch).enabled) {
1129            report_only.push(entry);
1130        } else {
1131            quiet.push(entry);
1132        }
1133    }
1134    let mut out = String::new();
1135    if !quiet.is_empty() {
1136        out.push_str(&format!(
1137            "\nAccepted, but not above its gate, so nothing was accepted: {}\n",
1138            quiet.join(", ")
1139        ));
1140    }
1141    if !report_only.is_empty() {
1142        out.push_str(&format!(
1143            "\nAccepted, but report-only, so it can never fail and nothing was accepted: {}\n",
1144            report_only.join(", ")
1145        ));
1146    }
1147    if !unknown.is_empty() {
1148        out.push_str(&format!(
1149            "\nAccepted, but no benchmark by that name was compared on both sides: {}\n",
1150            unknown.join(", ")
1151        ));
1152    }
1153    out
1154}
1155
1156/// An allocation count's change, for display.
1157///
1158/// A zero base has no percentage, and [`signed_pct`] calls that `new`, which
1159/// is right for an instruction count: a benchmark that retired nothing was
1160/// not really measured. A zero allocation count is a real measurement — a
1161/// command that allocated nothing — so `0 → 0` is no change and `0 → N` is
1162/// the rise itself. `new` stays for a series with nothing on the base side,
1163/// which never reaches this table.
1164fn count_delta(ch: &Change) -> String {
1165    match ch.pct() {
1166        Some(p) => signed_pct(Some(p)),
1167        None if ch.head == ch.base => signed_pct(Some(0.0)),
1168        None => format!("+{} (from 0)", thousands(ch.head - ch.base)),
1169    }
1170}
1171
1172/// `text` with every control character written as its escape (`\n`,
1173/// `\u{1b}`), borrowed unchanged in the usual case of there being none.
1174///
1175/// A report is read line by line, and tak's own workflows decide a check by
1176/// what a line starts with. A name holding a newline could begin a line of its
1177/// own that reads as a verdict, so no name reaches the report with one.
1178pub fn escape_control(text: &str) -> std::borrow::Cow<'_, str> {
1179    if !text.chars().any(char::is_control) {
1180        return std::borrow::Cow::Borrowed(text);
1181    }
1182    text.chars()
1183        .map(|c| {
1184            if c.is_control() {
1185                c.escape_default().to_string()
1186            } else {
1187                c.to_string()
1188            }
1189        })
1190        .collect::<String>()
1191        .into()
1192}
1193
1194/// How a series is named in prose: bench, plus the tool when it is not the
1195/// project itself, plus the runner.
1196///
1197/// Dropping the tool made two series that differ only by tool render
1198/// identically, so a report could say the same benchmark both started and
1199/// stopped gating and mean two different programs.
1200///
1201/// Control characters are escaped: `tak detect` names accepted steps through
1202/// this, and a benchmark name comes from the `tak.toml` under test.
1203pub fn describe(key: &Key) -> String {
1204    let (bench, tool, runner) = key;
1205    let (bench, tool, runner) = (
1206        escape_control(bench),
1207        escape_control(tool),
1208        escape_control(runner),
1209    );
1210    if tool == "self" {
1211        format!("`{bench}` on `{runner}`")
1212    } else {
1213        format!("`{bench}` ({tool}) on `{runner}`")
1214    }
1215}
1216
1217/// Series that exist on only one side. Always reported, including when nothing
1218/// overlapped — that is the case where they matter most.
1219fn outliers(c: &Comparison) -> String {
1220    let mut out = String::new();
1221    if !c.added.is_empty() {
1222        out.push_str(&format!(
1223            "\nNew, nothing to compare against: {}\n",
1224            c.added.iter().map(describe).collect::<Vec<_>>().join(", ")
1225        ));
1226    }
1227    if !c.removed.is_empty() {
1228        out.push_str(&format!(
1229            "\nMeasured on the base but not here — a benchmark that stops \
1230             running also stops gating: {}\n",
1231            c.removed
1232                .iter()
1233                .map(describe)
1234                .collect::<Vec<_>>()
1235                .join(", ")
1236        ));
1237    }
1238    out
1239}
1240
1241#[cfg(test)]
1242mod tests {
1243    use super::*;
1244    use crate::accept::Source;
1245
1246    fn key(bench: &str) -> Key {
1247        (bench.to_string(), "self".to_string(), "gha".to_string())
1248    }
1249
1250    fn rec(bench: &str, runner: &str, ins: f64, wall: f64) -> Record {
1251        Record {
1252            v: 1,
1253            bench: bench.into(),
1254            tool: "self".into(),
1255            version: None,
1256            runner: runner.into(),
1257            ts: "2026-01-01T00:00:00Z".into(),
1258            metrics: BTreeMap::from([
1259                (GATED_METRIC.to_string(), ins),
1260                (WALL_METRIC.to_string(), wall),
1261            ]),
1262        }
1263    }
1264
1265    /// One global gate at `pct`, with no floor and no per-benchmark gates.
1266    fn g(pct: f64) -> Gates {
1267        Gates::uniform(Gate::new(pct, 0).unwrap())
1268    }
1269
1270    fn gate(pct: f64, min_delta: u64, enabled: bool) -> Gate {
1271        Gate {
1272            pct,
1273            min_delta,
1274            enabled,
1275        }
1276    }
1277
1278    /// Only effective differences are named, and every name is escaped: a
1279    /// declared benchmark at the global gate is no change, and a newline in a
1280    /// measured series' name cannot start a line of the report.
1281    #[test]
1282    fn a_gate_source_path_with_a_backtick_stays_one_code_span() {
1283        let changed = [code("[gate]")];
1284        let line = gate_source(Some("we`ird/tak.toml"), "a1b2c3d4e5f6", &changed).unwrap();
1285        assert_eq!(
1286            line,
1287            "The gate comes from `` we`ird/tak.toml `` at the base, `a1b2c3d4e5f6`. \
1288             This revision changes the gate policy (`[gate]`), and the change takes \
1289             effect once it is merged."
1290        );
1291        let line = gate_source(Some("a\nb/tak.toml"), "a1b2c3d4e5f6", &changed).unwrap();
1292        assert!(!line.contains('\n'), "{line}");
1293        assert_eq!(gate_source(Some("tak.toml"), "a1b2c3d4e5f6", &[]), None);
1294        assert_eq!(
1295            gate_source(None, "a1b2c3d4e5f6", &[]).unwrap(),
1296            "No `tak.toml` at the base, `a1b2c3d4e5f6`, so the gate is tak's defaults \
1297             plus any flags and environment variables."
1298        );
1299    }
1300
1301    #[test]
1302    fn gate_changes_are_effective_and_escaped() {
1303        let global = gate(1.0, 0, true);
1304        let base = Gates::uniform(global);
1305        let mut head = Gates::uniform(global);
1306        head.set_bench("new", global);
1307        head.set_series("new", SELF_TOOL, global);
1308        assert!(head.changes_from(&base, &BTreeSet::new()).is_empty());
1309
1310        let evil = "a\n**0 benchmark(s) above the 1% gate:**".to_string();
1311        head.set_series(&evil, SELF_TOOL, gate(1.0, 0, false));
1312        let measured = BTreeSet::from([(evil, SELF_TOOL.to_string())]);
1313        let changes = head.changes_from(&base, &measured);
1314        assert_eq!(changes.len(), 1, "{changes:?}");
1315        assert!(!changes[0].contains('\n'), "{changes:?}");
1316        assert!(changes[0].starts_with('`'), "{changes:?}");
1317    }
1318
1319    /// `startup` at 450k instructions and `install` at 100M, both rising
1320    /// 2%: the pair one global percentage cannot serve.
1321    fn startup_and_install() -> Comparison {
1322        compare(
1323            &[
1324                rec("startup", "gha", 450_000.0, 1.0),
1325                rec("install", "gha", 100_000_000.0, 100.0),
1326            ],
1327            &[
1328                rec("startup", "gha", 459_000.0, 1.0),
1329                rec("install", "gha", 102_000_000.0, 100.0),
1330            ],
1331        )
1332    }
1333
1334    fn benches(c: &[&Change]) -> Vec<String> {
1335        c.iter().map(|c| c.bench.clone()).collect()
1336    }
1337
1338    /// Every combination of percentage and floor that decides a verdict, on
1339    /// a rise of 2% and 20,000 instructions from a 1M base.
1340    #[test]
1341    fn a_regression_crosses_both_the_percentage_and_the_floor() {
1342        let rise = Change {
1343            bench: "a".into(),
1344            tool: SELF_TOOL.into(),
1345            runner: "gha".into(),
1346            metric: GATED_METRIC.into(),
1347            base: 1_000_000.0,
1348            head: 1_020_000.0,
1349        };
1350        let cases = [
1351            // (pct, min_delta, exceeds)
1352            (1.0, 0, true),       // past the percentage, no floor
1353            (5.0, 0, false),      // under the percentage
1354            (1.0, 10_000, true),  // past both
1355            (1.0, 20_000, false), // exactly at the floor is not past it
1356            (1.0, 50_000, false), // past the percentage, under the floor
1357            (5.0, 10_000, false), // past the floor, under the percentage
1358            (2.0, 0, false),      // exactly at the percentage is not past it
1359            (0.0, 0, true),       // a zero gate fails on any rise
1360        ];
1361        for (pct, min_delta, want) in cases {
1362            assert_eq!(
1363                rise.exceeds(&gate(pct, min_delta, true)),
1364                want,
1365                "pct {pct}, min_delta {min_delta}"
1366            );
1367            // Enabled or not, the threshold is the same one.
1368            assert_eq!(rise.exceeds(&gate(pct, min_delta, false)), want);
1369        }
1370
1371        let fall = Change {
1372            head: 500_000.0,
1373            ..rise.clone()
1374        };
1375        assert!(
1376            !fall.exceeds(&gate(0.0, 0, true)),
1377            "an improvement never gates"
1378        );
1379        let wall = Change {
1380            metric: WALL_METRIC.into(),
1381            ..rise
1382        };
1383        assert!(!wall.exceeds(&gate(0.0, 0, true)), "wall clock never gates");
1384    }
1385
1386    /// The floor holds from a zero base too: without it, zero to anything
1387    /// fails; with it, zero to less than the floor does not.
1388    #[test]
1389    fn a_zero_base_is_still_held_to_the_floor() {
1390        let c = compare(
1391            &[rec("a", "gha", 0.0, 1.0)],
1392            &[rec("a", "gha", 5_000.0, 1.0)],
1393        );
1394        assert_eq!(c.regressions(&g(1.0)).len(), 1);
1395        let floored = Gates::uniform(Gate::new(1.0, 10_000).unwrap());
1396        assert!(c.regressions(&floored).is_empty());
1397    }
1398
1399    /// A gate of NaN passes everything, since every comparison against it is
1400    /// false. It must not be constructible from a setting.
1401    #[test]
1402    fn a_gate_percentage_must_be_finite_and_not_negative() {
1403        assert!(Gate::new(0.0, 0).is_ok());
1404        assert!(Gate::new(250.0, 0).is_ok());
1405        for bad in [-1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
1406            let err = Gate::new(bad, 0).unwrap_err();
1407            assert!(format!("{err}").contains("gate percentage"), "{err}");
1408        }
1409    }
1410
1411    #[test]
1412    fn a_series_gate_beats_its_benchmarks_which_beats_the_global_one() {
1413        let mut gates = g(1.0);
1414        gates.set_bench("install", gate(5.0, 0, true));
1415        gates.set_series("install", "pnpm", gate(10.0, 0, false));
1416        assert_eq!(gates.get("install", "pnpm"), gate(10.0, 0, false));
1417        assert_eq!(
1418            gates.get("install", "npm"),
1419            gate(5.0, 0, true),
1420            "a subject the benchmark no longer declares gets the benchmark's"
1421        );
1422        assert_eq!(
1423            gates.get("gone", SELF_TOOL),
1424            gate(1.0, 0, true),
1425            "a benchmark no longer in tak.toml gets the global gate"
1426        );
1427    }
1428
1429    /// The motivating case: a loose gate on the small benchmark lets its 2%
1430    /// through while the large one is still held to 1%.
1431    #[test]
1432    fn a_per_benchmark_gate_decides_its_own_series_only() {
1433        let c = startup_and_install();
1434        assert_eq!(benches(&c.regressions(&g(1.0))), ["install", "startup"]);
1435
1436        let mut gates = g(1.0);
1437        gates.set_series("startup", SELF_TOOL, gate(5.0, 0, true));
1438        assert_eq!(benches(&c.regressions(&gates)), ["install"]);
1439
1440        // A tighter one works too: nothing says a per-benchmark gate is looser.
1441        let mut gates = g(5.0);
1442        gates.set_series("install", SELF_TOOL, gate(1.0, 0, true));
1443        assert_eq!(benches(&c.regressions(&gates)), ["install"]);
1444    }
1445
1446    /// Two subjects of one benchmark are two series, and can be held to
1447    /// different gates.
1448    #[test]
1449    fn subjects_of_one_benchmark_take_their_own_gates() {
1450        let with_tool = |tool: &str, ins: f64| Record {
1451            tool: tool.into(),
1452            ..rec("install", "gha", ins, 1.0)
1453        };
1454        let c = compare(
1455            &[
1456                with_tool("mine", 1_000_000.0),
1457                with_tool("theirs", 1_000_000.0),
1458            ],
1459            &[
1460                with_tool("mine", 1_100_000.0),
1461                with_tool("theirs", 1_100_000.0),
1462            ],
1463        );
1464        let mut gates = g(1.0);
1465        gates.set_series("install", "theirs", gate(1.0, 0, false));
1466        let tools = |v: Vec<&Change>| v.iter().map(|c| c.tool.clone()).collect::<Vec<_>>();
1467        assert_eq!(tools(c.regressions(&gates)), ["mine"]);
1468        assert_eq!(tools(c.reported(&gates)), ["theirs"]);
1469    }
1470
1471    /// A report-only series is measured against its threshold and reported
1472    /// when it crosses it, and never fails.
1473    #[test]
1474    fn a_report_only_series_is_flagged_and_never_fails() {
1475        let c = startup_and_install();
1476        let mut gates = g(1.0);
1477        gates.set_series("startup", SELF_TOOL, gate(1.0, 0, false));
1478        assert_eq!(benches(&c.regressions(&gates)), ["install"]);
1479        assert_eq!(benches(&c.reported(&gates)), ["startup"]);
1480
1481        let md = markdown(&c, &Trend::new(), &gates, false);
1482        assert!(md.contains("| gate |"), "{md}");
1483        assert!(md.contains("report only (1%)"), "{md}");
1484        assert!(md.contains("**+2.00%** (not gated)"), "{md}");
1485        assert!(
1486            md.contains("**1 benchmark(s) above their gate:** `install` +2.00% (gate 1%)"),
1487            "{md}"
1488        );
1489        assert!(
1490            md.contains(
1491                "**1 report-only benchmark(s) above their gate, not failing:** \
1492                 `startup` +2.00% (gate 1%)"
1493            ),
1494            "{md}"
1495        );
1496    }
1497
1498    /// A project that never wrote a per-benchmark gate must get the report it
1499    /// got before they existed, byte for byte: scripts grep the verdict.
1500    #[test]
1501    fn uniform_gates_render_the_report_unchanged() {
1502        let md = markdown(&startup_and_install(), &Trend::new(), &g(1.0), false);
1503        assert_eq!(
1504            md,
1505            "| benchmark | instructions | Δ | wall (min) | Δ |\n\
1506             |---|---:|---:|---:|---:|\n\
1507             | install | 100,000,000 → 102,000,000 | **+2.00%** ⚠️ | 100.00 → 100.00ms | +0.00% |\n\
1508             | startup | 450,000 → 459,000 | **+2.00%** ⚠️ | 1.00 → 1.00ms | +0.00% |\n\
1509             \n\
1510             **2 benchmark(s) above the 1% gate:** `install` +2.00%, `startup` +2.00%\n\
1511             \n\
1512             <sub>Only instruction counts gate. Wall clock is shown for context — \
1513             on identical hardware it moves 4-20% run to run.</sub>\n"
1514        );
1515
1516        // A per-benchmark gate equal to the global one is not a difference.
1517        let mut same = g(1.0);
1518        same.set_series("startup", SELF_TOOL, gate(1.0, 0, true));
1519        assert_eq!(
1520            markdown(&startup_and_install(), &Trend::new(), &same, false),
1521            md
1522        );
1523    }
1524
1525    #[test]
1526    fn a_differing_gate_adds_a_column_with_every_rows_gate() {
1527        let mut gates = g(1.0);
1528        gates.set_series("startup", SELF_TOOL, gate(5.0, 20_000, true));
1529        let md = markdown(&startup_and_install(), &Trend::new(), &gates, false);
1530        assert!(
1531            md.contains("| benchmark | instructions | Δ | gate | wall (min) | Δ |\n|---|---:|---:|---|---:|---:|\n"),
1532            "{md}"
1533        );
1534        assert!(md.contains("| **+2.00%** | 5%, floor 20,000 |"), "{md}");
1535        assert!(md.contains("| **+2.00%** ⚠️ | 1% |"), "{md}");
1536        assert!(
1537            md.contains("above their gate:** `install` +2.00% (gate 1%)\n"),
1538            "{md}"
1539        );
1540    }
1541
1542    #[test]
1543    fn nothing_over_any_gate_says_so() {
1544        let mut gates = g(5.0);
1545        gates.set_series("startup", SELF_TOOL, gate(10.0, 0, true));
1546        let md = markdown(&startup_and_install(), &Trend::new(), &gates, false);
1547        assert!(
1548            md.contains("No gated benchmark rose beyond its gate."),
1549            "{md}"
1550        );
1551        assert!(!md.contains("report-only"), "{md}");
1552    }
1553
1554    /// A table with nothing gated must not read as a pass.
1555    #[test]
1556    fn a_table_with_nothing_gated_says_so() {
1557        let mut gates = g(1.0);
1558        gates.set_series("startup", SELF_TOOL, gate(1.0, 0, false));
1559        gates.set_series("install", SELF_TOOL, gate(50.0, 0, false));
1560        let md = markdown(&startup_and_install(), &Trend::new(), &gates, false);
1561        assert!(
1562            md.contains("Every benchmark here is report-only, so none can fail the gate."),
1563            "{md}"
1564        );
1565        assert!(!md.contains("No gated benchmark"), "{md}");
1566        assert!(
1567            md.contains("**1 report-only benchmark(s) above their gate, not failing:** `startup`"),
1568            "{md}"
1569        );
1570    }
1571
1572    /// A global floor has to be visible in the one line that says nothing
1573    /// failed, or a rise under it reads as no rise at all.
1574    #[test]
1575    fn a_global_floor_is_named_in_the_verdict() {
1576        let gates = Gates::uniform(Gate::new(1.0, 20_000).unwrap());
1577        let md = markdown(&startup_and_install(), &Trend::new(), &gates, false);
1578        assert!(
1579            !md.contains("| gate |"),
1580            "the global gate needs no column: {md}"
1581        );
1582        assert!(
1583            md.contains(
1584                "**1 benchmark(s) above the 1% gate \
1585                 (rises of 20,000 instructions or fewer are not counted):** `install` +2.00%"
1586            ),
1587            "{md}"
1588        );
1589        let c = compare(
1590            &[rec("a", "gha", 1_000.0, 1.0)],
1591            &[rec("a", "gha", 1_500.0, 1.0)],
1592        );
1593        let md = markdown(&c, &Trend::new(), &gates, false);
1594        assert!(
1595            md.contains(
1596                "No instruction-count regression above 1% \
1597                 (rises of 20,000 instructions or fewer are not counted)."
1598            ),
1599            "{md}"
1600        );
1601    }
1602
1603    #[test]
1604    fn a_rise_beyond_the_gate_is_a_regression() {
1605        let c = compare(
1606            &[rec("a", "gha", 1_000_000.0, 10.0)],
1607            &[rec("a", "gha", 1_020_000.0, 10.0)],
1608        );
1609        assert_eq!(c.regressions(&g(1.0)).len(), 1, "2% should trip a 1% gate");
1610        assert!(c.regressions(&g(5.0)).is_empty(), "2% should not trip 5%");
1611    }
1612
1613    #[test]
1614    fn an_improvement_never_gates() {
1615        let c = compare(
1616            &[rec("a", "gha", 1_000_000.0, 10.0)],
1617            &[rec("a", "gha", 500_000.0, 10.0)],
1618        );
1619        assert!(c.regressions(&g(1.0)).is_empty());
1620        let ins = c.changes.iter().find(|c| c.metric == GATED_METRIC).unwrap();
1621        assert_eq!(ins.pct().unwrap().round(), -50.0);
1622    }
1623
1624    /// The reason the gate is narrow. A doubling of wall clock is ordinary
1625    /// noise on a shared runner and must not fail anyone's pull request.
1626    #[test]
1627    fn wall_clock_never_gates_however_bad_it_looks() {
1628        let c = compare(
1629            &[rec("a", "gha", 1_000_000.0, 10.0)],
1630            &[rec("a", "gha", 1_000_000.0, 100.0)],
1631        );
1632        assert!(c.regressions(&g(0.001)).is_empty());
1633        let wall = c.changes.iter().find(|c| c.metric == WALL_METRIC).unwrap();
1634        assert_eq!(wall.pct().unwrap().round(), 900.0);
1635    }
1636
1637    /// Different runner classes are different series. Comparing across them
1638    /// would report a machine change as a code change.
1639    #[test]
1640    fn a_different_runner_is_not_a_comparison() {
1641        let c = compare(
1642            &[rec("a", "gha-linux", 1_000_000.0, 10.0)],
1643            &[rec("a", "gha-macos", 2_000_000.0, 10.0)],
1644        );
1645        assert!(c.is_empty(), "nothing should line up");
1646        assert_eq!(c.added.len(), 1);
1647        assert_eq!(c.removed.len(), 1);
1648        assert!(c.regressions(&g(1.0)).is_empty());
1649
1650        // The report has to say so. Asserting only on the struct let an early
1651        // return hide both lists from every reader of the actual output.
1652        let md = markdown(&c, &Trend::new(), &g(1.0), false);
1653        assert!(md.contains("nothing was gated"), "{md}");
1654        assert!(md.contains("gha-macos"), "the new runner is unnamed: {md}");
1655        assert!(md.contains("gha-linux"), "the old runner is unnamed: {md}");
1656    }
1657
1658    /// `allow_empty` changes the report below its first line and never the
1659    /// line itself. Scripts classify an exit-0 run by that line alone —
1660    /// jdx/tak-action matches the whole bold sentence, period included — so a
1661    /// waived empty comparison has to start exactly as a failed one does.
1662    #[test]
1663    fn allowing_an_empty_comparison_keeps_the_first_line() {
1664        const FIRST: &str = "**Nothing was compared, and so nothing was gated.** No series \
1665             appears on both sides: either the base has no measurements recorded, or the two \
1666             were measured on different runner classes, which are deliberately not \
1667             comparable — counts shift between machine types by more than a real regression \
1668             does.";
1669        let mut c = compare(
1670            &[rec("a", "gha-old", 1e6, 1.0)],
1671            &[rec("a", "gha-new", 1e6, 1.0)],
1672        );
1673        let refused = markdown(&c, &Trend::new(), &g(1.0), false);
1674        assert_eq!(refused.lines().next(), Some(FIRST), "{refused}");
1675        assert!(!refused.contains(ALLOWED_EMPTY), "{refused}");
1676
1677        c.allowed_empty = true;
1678        let allowed = markdown(&c, &Trend::new(), &g(1.0), false);
1679        assert_eq!(allowed.lines().next(), Some(FIRST), "{allowed}");
1680        // Its own paragraph, directly after the first, naming the setting.
1681        assert_eq!(allowed.lines().nth(2), Some(ALLOWED_EMPTY), "{allowed}");
1682        assert!(ALLOWED_EMPTY.contains("`allow_empty`"));
1683        // Everything else the report says about an empty comparison stays.
1684        assert!(
1685            allowed.contains("gha-new") && allowed.contains("gha-old"),
1686            "{allowed}"
1687        );
1688    }
1689
1690    /// A head with nothing recorded is the quietest possible failure: every
1691    /// benchmark stops gating at once and the gate still exits 0. It has to be
1692    /// loud in the report, and it has to name what vanished.
1693    #[test]
1694    fn a_head_with_no_measurements_names_what_vanished() {
1695        let c = compare(
1696            &[
1697                rec("a", "gha", 1_000_000.0, 10.0),
1698                rec("b", "gha", 2.0, 2.0),
1699            ],
1700            &[],
1701        );
1702        let md = markdown(&c, &Trend::new(), &g(1.0), false);
1703        assert!(c.regressions(&g(1.0)).is_empty());
1704        assert!(md.contains("nothing was gated"), "{md}");
1705        assert!(md.contains("`a`") && md.contains("`b`"), "{md}");
1706        assert!(md.contains("stops gating"), "{md}");
1707    }
1708
1709    /// The footnote about what gates belongs on every report, including the
1710    /// ones with no table.
1711    #[test]
1712    fn the_gating_caveat_survives_an_empty_comparison() {
1713        let md = markdown(&compare(&[], &[]), &Trend::new(), &g(1.0), false);
1714        assert!(md.contains("Only instruction counts gate"), "{md}");
1715    }
1716
1717    #[test]
1718    fn a_new_benchmark_is_reported_but_not_gated() {
1719        let c = compare(
1720            &[rec("a", "gha", 1_000_000.0, 10.0)],
1721            &[
1722                rec("a", "gha", 1_000_000.0, 10.0),
1723                rec("b", "gha", 9.9e9, 10.0),
1724            ],
1725        );
1726        assert_eq!(
1727            c.added,
1728            vec![("b".to_string(), "self".to_string(), "gha".to_string())]
1729        );
1730        assert!(c.regressions(&g(1.0)).is_empty());
1731    }
1732
1733    /// A benchmark that stops running stops gating, so its absence has to be
1734    /// visible rather than simply making the table shorter.
1735    #[test]
1736    fn a_vanished_benchmark_is_surfaced() {
1737        let c = compare(
1738            &[
1739                rec("a", "gha", 1_000_000.0, 10.0),
1740                rec("b", "gha", 1.0, 1.0),
1741            ],
1742            &[rec("a", "gha", 1_000_000.0, 10.0)],
1743        );
1744        assert_eq!(c.removed.len(), 1);
1745        assert!(markdown(&c, &Trend::new(), &g(1.0), false).contains("stops gating"));
1746    }
1747
1748    /// Several records for one series collapse to the minimum, not the mean:
1749    /// a noisy re-run must not move a number that is meant to be deterministic.
1750    #[test]
1751    fn duplicate_records_reduce_to_the_minimum() {
1752        let c = compare(
1753            &[rec("a", "gha", 1_000_000.0, 10.0)],
1754            &[
1755                rec("a", "gha", 3_000_000.0, 30.0),
1756                rec("a", "gha", 1_000_000.0, 10.0),
1757            ],
1758        );
1759        assert!(
1760            c.regressions(&g(1.0)).is_empty(),
1761            "the clean sample should win"
1762        );
1763    }
1764
1765    #[test]
1766    fn nothing_in_common_says_so_rather_than_passing_quietly() {
1767        let c = compare(&[], &[rec("a", "gha", 1.0, 1.0)]);
1768        assert!(c.is_empty());
1769        assert!(markdown(&c, &Trend::new(), &g(1.0), false).contains("nothing was gated"));
1770    }
1771
1772    /// A percentage of zero is undefined, and the gate used to read that as
1773    /// "no change" — so a base of zero disabled the gate for that benchmark
1774    /// entirely, whatever the head measured.
1775    #[test]
1776    fn a_rise_from_a_zero_base_still_gates() {
1777        let c = compare(
1778            &[rec("a", "gha", 0.0, 10.0)],
1779            &[rec("a", "gha", 5_000_000.0, 10.0)],
1780        );
1781        let ins = c.changes.iter().find(|c| c.metric == GATED_METRIC).unwrap();
1782        assert_eq!(ins.pct(), None, "no percentage exists against zero");
1783        assert_eq!(
1784            c.regressions(&g(1.0)).len(),
1785            1,
1786            "it must still fail the gate"
1787        );
1788        assert!(markdown(&c, &Trend::new(), &g(1.0), false).contains("new"));
1789    }
1790
1791    /// Zero to zero is not a regression; there is nothing to report.
1792    #[test]
1793    fn zero_to_zero_is_not_a_regression() {
1794        let c = compare(&[rec("a", "gha", 0.0, 1.0)], &[rec("a", "gha", 0.0, 1.0)]);
1795        assert!(c.regressions(&g(1.0)).is_empty());
1796    }
1797
1798    /// Two series that differ only by tool must not render identically, or the
1799    /// report can say the same benchmark both started and stopped gating while
1800    /// meaning two different programs.
1801    #[test]
1802    fn outliers_keep_their_tool() {
1803        let mut pnpm = rec("install", "gha", 1.0, 1.0);
1804        pnpm.tool = "pnpm".into();
1805        let c = compare(&[], &[rec("install", "gha", 1.0, 1.0), pnpm]);
1806        let md = markdown(&c, &Trend::new(), &g(1.0), false);
1807        assert!(md.contains("`install` on `gha`"), "{md}");
1808        assert!(md.contains("`install` (pnpm) on `gha`"), "{md}");
1809    }
1810
1811    /// The common case: the revision under comparison is a branch commit, so
1812    /// it is not in trunk history and its point ends the line.
1813    #[test]
1814    fn a_branch_head_is_appended_last() {
1815        let walked = vec![
1816            ("c1".to_string(), vec![rec("a", "gha", 10.0, 1.0)]),
1817            ("c2".to_string(), vec![rec("a", "gha", 20.0, 1.0)]),
1818        ];
1819        let t = build_trend(&walked, "branch", &[rec("a", "gha", 30.0, 1.0)]);
1820        assert_eq!(t[&key("a")], vec![10.0, 20.0, 30.0]);
1821    }
1822
1823    /// Comparing against an ancestor — `tak compare v1.33.0 --rev v1.30.0` —
1824    /// puts the head *inside* the walked history. Appending it at the end as
1825    /// well would draw a line that reads as time and is not in time order.
1826    #[test]
1827    fn a_head_inside_history_stays_in_its_place() {
1828        let walked = vec![
1829            ("c1".to_string(), vec![rec("a", "gha", 10.0, 1.0)]),
1830            ("head".to_string(), vec![rec("a", "gha", 20.0, 1.0)]),
1831            ("c3".to_string(), vec![rec("a", "gha", 30.0, 1.0)]),
1832        ];
1833        let t = build_trend(&walked, "head", &[rec("a", "gha", 99.0, 1.0)]);
1834        assert_eq!(
1835            t[&key("a")],
1836            vec![10.0, 99.0, 30.0],
1837            "the head's own measurement belongs where the head is, once"
1838        );
1839    }
1840
1841    /// Duplicate records within one commit collapse to the minimum, the same
1842    /// rule the table uses — otherwise the two halves of a report disagree.
1843    #[test]
1844    fn a_commit_contributes_one_point() {
1845        let walked = vec![(
1846            "c1".to_string(),
1847            vec![rec("a", "gha", 50.0, 1.0), rec("a", "gha", 10.0, 1.0)],
1848        )];
1849        let t = build_trend(&walked, "branch", &[]);
1850        assert_eq!(t[&key("a")], vec![10.0]);
1851    }
1852
1853    #[test]
1854    fn a_sparkline_spans_the_full_range() {
1855        let s = sparkline(&[1.0, 2.0, 3.0, 4.0, 5.0]);
1856        assert_eq!(s.chars().count(), 5);
1857        assert_eq!(s.chars().next().unwrap(), '▁');
1858        assert_eq!(s.chars().last().unwrap(), '█');
1859    }
1860
1861    /// A deterministic metric that never moves is the best possible outcome.
1862    /// Drawing it at the floor would make it look like the worst.
1863    #[test]
1864    fn a_flat_series_sits_mid_height() {
1865        let s = sparkline(&[7.0, 7.0, 7.0]);
1866        assert_eq!(s, "▅▅▅");
1867    }
1868
1869    /// One point is not a trend, and a single bar would imply a shape that was
1870    /// never measured.
1871    #[test]
1872    fn one_point_draws_nothing() {
1873        assert_eq!(sparkline(&[1.0]), "");
1874        assert_eq!(sparkline(&[]), "");
1875    }
1876
1877    /// Each series is scaled to itself. A shared axis would flatten a 7M
1878    /// startup benchmark into a straight line beside a 100M install one.
1879    #[test]
1880    fn series_are_scaled_independently() {
1881        let small = sparkline(&[7_000_000.0, 7_100_000.0]);
1882        let large = sparkline(&[100_000_000.0, 101_000_000.0]);
1883        assert_eq!(small, large, "both rise by the same shape");
1884    }
1885
1886    #[test]
1887    fn the_trend_column_appears_only_when_there_is_a_trend() {
1888        let c = compare(
1889            &[rec("a", "gha", 1_000_000.0, 10.0)],
1890            &[rec("a", "gha", 1_000_000.0, 10.0)],
1891        );
1892        assert!(!markdown(&c, &Trend::new(), &g(1.0), false).contains("| trend |"));
1893
1894        let mut trend = Trend::new();
1895        trend.insert(
1896            ("a".into(), "self".into(), "gha".into()),
1897            vec![1.0, 2.0, 3.0],
1898        );
1899        let md = markdown(&c, &trend, &g(1.0), false);
1900        assert!(md.contains("| trend |"), "{md}");
1901        assert!(md.contains('█'), "{md}");
1902    }
1903
1904    fn with_allocs(mut r: Record, blocks: f64, bytes: f64, peak: f64) -> Record {
1905        r.metrics.insert("alloc_blocks".into(), blocks);
1906        r.metrics.insert("alloc_bytes".into(), bytes);
1907        r.metrics.insert("alloc_peak_bytes".into(), peak);
1908        r
1909    }
1910
1911    /// A project that never opted in gets the report it always did: no
1912    /// allocation table, no empty columns.
1913    #[test]
1914    fn the_allocation_table_appears_only_when_both_sides_have_allocations() {
1915        let plain = compare(
1916            &[rec("a", "gha", 1_000_000.0, 10.0)],
1917            &[rec("a", "gha", 1_000_000.0, 10.0)],
1918        );
1919        let md = markdown(&plain, &Trend::new(), &g(1.0), false);
1920        assert!(!md.contains("Heap allocations"), "{md}");
1921        assert!(md.contains("| benchmark | instructions | Δ | wall (min) | Δ |"));
1922
1923        // The first run after opting in has nothing to compare against.
1924        let first = compare(
1925            &[rec("a", "gha", 1_000_000.0, 10.0)],
1926            &[with_allocs(
1927                rec("a", "gha", 1_000_000.0, 10.0),
1928                3.0,
1929                4140.0,
1930                4140.0,
1931            )],
1932        );
1933        assert!(!markdown(&first, &Trend::new(), &g(1.0), false).contains("Heap allocations"));
1934    }
1935
1936    /// Allocations are reported beside the gate, never part of it, however
1937    /// far they move.
1938    #[test]
1939    fn allocations_are_reported_and_never_gate() {
1940        let c = compare(
1941            &[with_allocs(
1942                rec("a", "gha", 1_000_000.0, 10.0),
1943                31.0,
1944                7_119.0,
1945                6_847.0,
1946            )],
1947            &[with_allocs(
1948                rec("a", "gha", 1_000_000.0, 10.0),
1949                62.0,
1950                14_238.0,
1951                6_847.0,
1952            )],
1953        );
1954        assert!(c.regressions(&g(0.001)).is_empty());
1955        let md = markdown(&c, &Trend::new(), &g(1.0), false);
1956        assert!(md.contains("reported, not gated"), "{md}");
1957        assert!(
1958            md.contains(
1959                "| a | 31 → 62 | +100.00% | 7,119 → 14,238 | +100.00% | 6,847 → 6,847 | +0.00% |"
1960            ),
1961            "{md}"
1962        );
1963        assert!(md.contains("No instruction-count regression"), "{md}");
1964    }
1965
1966    /// The same benchmark on two runner classes is two rows, and each has
1967    /// to say which runner it is, in both tables. One runner needs no label.
1968    #[test]
1969    fn rows_name_their_runner_only_when_another_shares_the_series() {
1970        let on = |runner| with_allocs(rec("a", runner, 1_000_000.0, 10.0), 3.0, 30.0, 20.0);
1971        let both = [on("linux-x64"), on("linux-arm64")];
1972        let md = markdown(&compare(&both, &both), &Trend::new(), &g(1.0), false);
1973        for runner in ["linux-x64", "linux-arm64"] {
1974            let rows = md
1975                .lines()
1976                .filter(|l| l.starts_with(&format!("| a on {runner} |")))
1977                .count();
1978            assert_eq!(
1979                rows, 2,
1980                "instructions and allocations rows for {runner}: {md}"
1981            );
1982        }
1983
1984        let one = [on("linux-x64")];
1985        let md = markdown(&compare(&one, &one), &Trend::new(), &g(1.0), false);
1986        assert!(
1987            md.contains("| a |") && !md.contains(" on linux-x64 |"),
1988            "{md}"
1989        );
1990    }
1991
1992    /// Declared metrics get a table of their own and never gate, however far
1993    /// they move; the main table is exactly what it was without them.
1994    #[test]
1995    fn custom_metrics_are_a_separate_table_and_never_gate() {
1996        let with = |bytes: f64, kb: f64| {
1997            let mut r = rec("a", "gha", 1_000_000.0, 10.0);
1998            r.metrics.insert("binary_bytes".into(), bytes);
1999            r.metrics.insert("bundle_kb".into(), kb);
2000            r
2001        };
2002        let c = compare(&[with(4_000_000.0, 10.5)], &[with(8_000_000.0, 12.25)]);
2003        assert!(
2004            c.regressions(&g(0.0)).is_empty(),
2005            "a doubled binary must not fail the gate"
2006        );
2007        let md = markdown(&c, &Trend::new(), &g(1.0), false);
2008        assert!(md.contains("| benchmark | metric | value | Δ |"), "{md}");
2009        assert!(
2010            md.contains("| a | binary_bytes | 4,000,000 → 8,000,000 | +100.00% |"),
2011            "{md}"
2012        );
2013        assert!(
2014            md.contains("| a | bundle_kb | 10.5 → 12.25 | +16.67% |"),
2015            "{md}"
2016        );
2017        assert!(md.contains("No instruction-count regression"), "{md}");
2018        assert!(md.contains("never gated"), "{md}");
2019
2020        let plain = compare(
2021            &[rec("a", "gha", 1_000_000.0, 10.0)],
2022            &[rec("a", "gha", 1_000_000.0, 10.0)],
2023        );
2024        let md = markdown(&plain, &Trend::new(), &g(1.0), false);
2025        assert!(!md.contains("| metric |"), "{md}");
2026        assert!(!md.contains("tak.toml"), "{md}");
2027        // The main table has the same columns with or without them.
2028        let header = |md: &str| md.lines().next().unwrap().to_string();
2029        assert_eq!(
2030            header(&markdown(&c, &Trend::new(), &g(1.0), false)),
2031            header(&md)
2032        );
2033    }
2034
2035    /// Timing statistics other than the minimum are recorded but were never
2036    /// shown; they must not start appearing as if they were declared.
2037    #[test]
2038    fn built_in_metrics_stay_out_of_the_custom_table() {
2039        let with = |p50: f64| {
2040            let mut r = rec("a", "gha", 1_000_000.0, 10.0);
2041            r.metrics.insert("wall_p50_ms".into(), p50);
2042            r
2043        };
2044        let md = markdown(
2045            &compare(&[with(11.0)], &[with(12.0)]),
2046            &Trend::new(),
2047            &g(1.0),
2048            false,
2049        );
2050        assert!(!md.contains("wall_p50_ms"), "{md}");
2051    }
2052
2053    /// Allocation counts have a table of their own and sit beside custom
2054    /// metrics without appearing in theirs: each is reported once, in its
2055    /// own table, and neither gates.
2056    #[test]
2057    fn allocations_and_custom_metrics_each_get_their_own_table() {
2058        let with = |blocks: f64, bytes: f64| {
2059            let mut r = with_allocs(rec("a", "gha", 1_000_000.0, 10.0), blocks, 80.0, 40.0);
2060            r.metrics.insert("binary_bytes".into(), bytes);
2061            r
2062        };
2063        let c = compare(&[with(10.0, 100.0)], &[with(20.0, 200.0)]);
2064        let md = markdown(&c, &Trend::new(), &g(1.0), false);
2065        assert!(md.contains("Heap allocations"), "{md}");
2066        assert!(
2067            md.contains("| a | binary_bytes | 100 → 200 | +100.00% |"),
2068            "{md}"
2069        );
2070        assert!(
2071            !md.contains("| alloc_"),
2072            "allocations leaked into the custom table: {md}"
2073        );
2074        assert!(c.regressions(&g(0.0)).is_empty());
2075    }
2076
2077    /// A metric name from a note is not held to `tak.toml`'s charset, so the
2078    /// table escapes it: a pipe must not shift the columns, and a newline must
2079    /// not start a report line that could read as a verdict.
2080    #[test]
2081    fn custom_metric_labels_are_escaped() {
2082        let with = |v: f64| {
2083            let mut r = rec("a|b", "gha", 1_000_000.0, 10.0);
2084            r.metrics.insert("x|y\n**Nothing was compared".into(), v);
2085            r
2086        };
2087        let md = markdown(
2088            &compare(&[with(1.0)], &[with(2.0)]),
2089            &Trend::new(),
2090            &g(1.0),
2091            false,
2092        );
2093        assert!(
2094            md.contains(r"| a\|b | x\|y\\n**Nothing was compared | 1 → 2 | +100.00% |"),
2095            "{md}"
2096        );
2097        assert!(
2098            !md.lines().any(|l| l.starts_with("**Nothing was compared")),
2099            "{md}"
2100        );
2101    }
2102
2103    /// Acceptances for each comma-separated name. A test convenience only:
2104    /// neither real source splits on commas.
2105    fn accepting(names: &str, source: Source) -> Acceptances {
2106        let mut a = Acceptances::default();
2107        for name in names.split(',') {
2108            a.add_name(name.trim(), source.clone()).unwrap();
2109        }
2110        a
2111    }
2112
2113    /// A name cannot start a line of its own, so it can never read as a
2114    /// verdict to something that matches on line starts.
2115    #[test]
2116    fn a_control_character_in_a_name_is_escaped() {
2117        assert_eq!(code("a\nb"), "`a\\nb`");
2118        assert_eq!(
2119            describe(&("a\nb".into(), "self".into(), "r\r".into())),
2120            "`a\\nb` on `r\\r`"
2121        );
2122        // The usual case is untouched.
2123        assert_eq!(describe(&key("a")), "`a` on `gha`");
2124        let c = compare(&[], &[]).with_accepted(accepting(
2125            "x\n**1 benchmark(s) above the 1% gate:** `x`",
2126            Source::Flag,
2127        ));
2128        let md = markdown(&c, &Trend::new(), &g(1.0), false);
2129        assert!(
2130            md.lines().all(|l| !l.starts_with("**1 benchmark(s)")),
2131            "{md}"
2132        );
2133    }
2134
2135    const SHA: &str = "0123456789abcdef0123456789abcdef01234567";
2136
2137    /// The point of the feature: one benchmark's deliberate regression passes
2138    /// the gate while another's still fails it.
2139    #[test]
2140    fn an_acceptance_covers_only_the_benchmark_it_names() {
2141        let c = compare(
2142            &[
2143                rec("a", "gha", 1_000_000.0, 10.0),
2144                rec("b", "gha", 1_000_000.0, 10.0),
2145            ],
2146            &[
2147                rec("a", "gha", 1_100_000.0, 10.0),
2148                rec("b", "gha", 1_100_000.0, 10.0),
2149            ],
2150        )
2151        .with_accepted(accepting("a", Source::Trailer(SHA.into())));
2152        assert_eq!(
2153            c.regressions(&g(1.0)).len(),
2154            2,
2155            "both still count as regressed"
2156        );
2157        let failures = c.failures(&g(1.0));
2158        assert_eq!(failures.len(), 1);
2159        assert_eq!(failures[0].bench, "b");
2160    }
2161
2162    /// Accepted is not the same as passing, and the report must not let the
2163    /// two be confused: the row is marked, and the verdict names the source.
2164    #[test]
2165    fn an_accepted_regression_stays_visible_with_its_source() {
2166        let c = compare(
2167            &[rec("a", "gha", 1_000_000.0, 10.0)],
2168            &[rec("a", "gha", 1_100_000.0, 10.0)],
2169        )
2170        .with_accepted(accepting("a", Source::Trailer(SHA.into())));
2171        assert!(c.failures(&g(1.0)).is_empty());
2172        let md = markdown(&c, &Trend::new(), &g(1.0), false);
2173        assert!(md.contains("**+10.00%** (accepted)"), "{md}");
2174        assert!(
2175            md.contains("**1 accepted regression(s) above the 1% gate, not failing it:** `a` on `gha` +10.00% (`Tak-Accept` in `0123456789ab`)"),
2176            "{md}"
2177        );
2178        assert!(!md.contains("No instruction-count regression"), "{md}");
2179        assert!(!md.contains("⚠️"), "{md}");
2180    }
2181
2182    #[test]
2183    fn failures_and_acceptances_are_reported_separately() {
2184        let c = compare(
2185            &[
2186                rec("a", "gha", 1_000_000.0, 10.0),
2187                rec("b", "gha", 1_000_000.0, 10.0),
2188            ],
2189            &[
2190                rec("a", "gha", 1_100_000.0, 10.0),
2191                rec("b", "gha", 1_200_000.0, 10.0),
2192            ],
2193        )
2194        .with_accepted(accepting("a", Source::Flag));
2195        let md = markdown(&c, &Trend::new(), &g(1.0), false);
2196        assert!(
2197            md.contains("**1 benchmark(s) above the 1% gate:** `b` +20.00%"),
2198            "{md}"
2199        );
2200        assert!(md.contains("`a` on `gha` +10.00% (`--accept`)"), "{md}");
2201    }
2202
2203    /// One name covers every tool and runner the benchmark was measured with.
2204    #[test]
2205    fn an_acceptance_covers_every_series_of_its_benchmark() {
2206        let mut other = rec("a", "gha", 1_000_000.0, 10.0);
2207        other.tool = "other".into();
2208        let mut other_head = other.clone();
2209        other_head.metrics.insert(GATED_METRIC.into(), 2_000_000.0);
2210        let c = compare(
2211            &[
2212                rec("a", "gha", 1_000_000.0, 10.0),
2213                rec("a", "arm", 1_000_000.0, 10.0),
2214                other,
2215            ],
2216            &[
2217                rec("a", "gha", 2_000_000.0, 10.0),
2218                rec("a", "arm", 2_000_000.0, 10.0),
2219                other_head,
2220            ],
2221        )
2222        .with_accepted(accepting("a", Source::Flag));
2223        assert_eq!(c.regressions(&g(1.0)).len(), 3);
2224        assert!(c.failures(&g(1.0)).is_empty());
2225        let md = markdown(&c, &Trend::new(), &g(1.0), false);
2226        assert!(md.contains("`a (other)` on `gha` +100.00%"), "{md}");
2227    }
2228
2229    /// An acceptance that accepted nothing is reported: stale, it would
2230    /// silently cover the next real regression; misspelt, it explains why the
2231    /// gate still failed. Neither fails the gate on its own.
2232    #[test]
2233    fn an_acceptance_with_nothing_to_accept_is_reported() {
2234        let c = compare(
2235            &[
2236                rec("a", "gha", 1_000_000.0, 10.0),
2237                rec("b", "gha", 1_000_000.0, 10.0),
2238            ],
2239            &[
2240                rec("a", "gha", 1_000_000.0, 10.0),
2241                rec("b", "gha", 1_100_000.0, 10.0),
2242            ],
2243        )
2244        .with_accepted(accepting("a,bb", Source::Flag));
2245        assert_eq!(c.failures(&g(1.0)).len(), 1, "a typo must not accept `b`");
2246        let md = markdown(&c, &Trend::new(), &g(1.0), false);
2247        assert!(
2248            md.contains(
2249                "Accepted, but not above its gate, so nothing was accepted: `a` (`--accept`)"
2250            ),
2251            "{md}"
2252        );
2253        assert!(
2254            md.contains("no benchmark by that name was compared on both sides: `bb` (`--accept`)"),
2255            "{md}"
2256        );
2257    }
2258
2259    /// A `|` in a name is escaped, so it cannot add a column.
2260    #[test]
2261    fn a_pipe_in_a_row_name_is_escaped() {
2262        let on = |runner| rec("a|b", runner, 1_000_000.0, 10.0);
2263        let both = [on("ci|x64"), on("ci|arm64")];
2264        let md = markdown(&compare(&both, &both), &Trend::new(), &g(1.0), false);
2265        assert!(md.contains("| a\\|b on ci\\|x64 |"), "{md}");
2266        let row = md.lines().find(|l| l.contains("ci\\|arm64")).unwrap();
2267        let cells = row.replace("\\|", "").matches('|').count();
2268        assert_eq!(cells, 6, "a benchmark cell and four numbers: {row}");
2269    }
2270
2271    /// The allocation table's labels go through the same escaping as every
2272    /// other report site: a control character in a bench, tool or runner
2273    /// name from an old note cannot start a line of its own, and a
2274    /// backslash is kept as written.
2275    #[test]
2276    fn allocation_labels_are_escaped_like_the_rest_of_the_report() {
2277        let on = |runner| {
2278            let mut r = with_allocs(rec("a\nb", runner, 1.0, 1.0), 3.0, 30.0, 20.0);
2279            r.tool = "t\\x".into();
2280            r
2281        };
2282        let both = [on("ci\rx64"), on("ci-arm64")];
2283        let md = markdown(&compare(&both, &both), &Trend::new(), &g(1.0), false);
2284        let allocs = md
2285            .lines()
2286            .skip_while(|l| !l.starts_with("Heap allocations"))
2287            .collect::<Vec<_>>();
2288        assert!(
2289            allocs
2290                .iter()
2291                .any(|l| l.starts_with(r"| a\\nb (t\\x) on ci\\rx64 |")),
2292            "{md}"
2293        );
2294        assert!(!md.contains('\r'), "{md:?}");
2295    }
2296
2297    /// A zero allocation count is a measurement, not a missing base: no
2298    /// change reads as such, and a rise from zero gives the rise.
2299    #[test]
2300    fn a_zero_allocation_base_is_a_measurement_not_new() {
2301        let c = compare(
2302            &[with_allocs(
2303                rec("a", "gha", 1_000_000.0, 10.0),
2304                0.0,
2305                0.0,
2306                0.0,
2307            )],
2308            &[with_allocs(
2309                rec("a", "gha", 1_000_000.0, 10.0),
2310                0.0,
2311                4_140.0,
2312                0.0,
2313            )],
2314        );
2315        let md = markdown(&c, &Trend::new(), &g(1.0), false);
2316        let row = md
2317            .lines()
2318            .skip_while(|l| !l.starts_with("Heap allocations"))
2319            .find(|l| l.starts_with("| a |"))
2320            .unwrap();
2321        assert_eq!(
2322            row,
2323            "| a | 0 → 0 | +0.00% | 0 → 4,140 | +4,140 (from 0) | 0 → 0 | +0.00% |"
2324        );
2325        assert!(!row.contains("new"), "{row}");
2326        assert!(c.regressions(&g(0.001)).is_empty(), "still never gates");
2327    }
2328
2329    /// With nothing compared there is no table, but an acceptance still has
2330    /// to be accounted for — this is the state a runner migration produces.
2331    #[test]
2332    fn an_acceptance_is_reported_when_nothing_was_compared() {
2333        let c =
2334            compare(&[], &[rec("a", "gha", 1.0, 1.0)]).with_accepted(accepting("a", Source::Flag));
2335        let md = markdown(&c, &Trend::new(), &g(1.0), false);
2336        assert!(md.contains("nothing was gated"), "{md}");
2337        assert!(
2338            md.contains("no benchmark by that name was compared"),
2339            "{md}"
2340        );
2341    }
2342
2343    /// Acceptance only ever relaxes the gate for a regression. An improvement
2344    /// under an acceptance is still just an improvement.
2345    #[test]
2346    fn an_acceptance_never_invents_a_regression() {
2347        let c = compare(
2348            &[rec("a", "gha", 1_000_000.0, 10.0)],
2349            &[rec("a", "gha", 500_000.0, 10.0)],
2350        )
2351        .with_accepted(accepting("a", Source::Flag));
2352        let md = markdown(&c, &Trend::new(), &g(1.0), false);
2353        assert!(
2354            md.contains("No instruction-count regression above 1%"),
2355            "{md}"
2356        );
2357        assert!(!md.contains("(accepted)"), "{md}");
2358    }
2359
2360    /// Ignored trailers are reported and change nothing else: the regression
2361    /// still fails, and nothing is marked accepted.
2362    #[test]
2363    fn an_ignored_trailer_is_named_and_accepts_nothing() {
2364        let c = compare(
2365            &[rec("a", "gha", 1_000_000.0, 10.0)],
2366            &[rec("a", "gha", 1_100_000.0, 10.0)],
2367        )
2368        .with_ignored_trailers(accepting("a", Source::Trailer(SHA.into())));
2369        assert_eq!(c.failures(&g(1.0)).len(), 1);
2370        let md = markdown(&c, &Trend::new(), &g(1.0), false);
2371        assert!(
2372            md.contains("trailers were found but not honoured, because `gate.accept_trailers` is off: `a` (`Tak-Accept` in `0123456789ab`)"),
2373            "{md}"
2374        );
2375        assert!(!md.contains("(accepted)"), "{md}");
2376    }
2377
2378    /// A backtick in a name must not close the code span it is shown in.
2379    #[test]
2380    fn a_name_with_backticks_keeps_its_code_span() {
2381        assert_eq!(code("startup"), "`startup`");
2382        assert_eq!(code("a`b"), "`` a`b ``");
2383        assert_eq!(code("``x"), "``` ``x ```");
2384        let c = compare(&[], &[]).with_accepted(accepting("we`ird", Source::Flag));
2385        let md = markdown(&c, &Trend::new(), &g(1.0), false);
2386        assert!(md.contains("`` we`ird `` (`--accept`)"), "{md}");
2387    }
2388
2389    /// CommonMark strips one space from each side of a span that has both, so
2390    /// a name with edge spaces is padded to survive that and render as itself.
2391    /// Unpadded, `" startup "` and `startup` rendered identically on GitHub.
2392    #[test]
2393    fn a_name_with_edge_spaces_keeps_them() {
2394        assert_eq!(code(" startup "), "`  startup  `");
2395        assert_eq!(code(" startup"), "`  startup `");
2396        assert_eq!(code("startup "), "` startup  `");
2397        assert_ne!(code(" startup "), code("startup"));
2398        // A span of only spaces is not stripped, so it needs no padding.
2399        assert_eq!(code("  "), "`  `");
2400    }
2401
2402    #[test]
2403    fn a_cell_escapes_backslashes_before_pipes() {
2404        assert_eq!(cell("startup"), "startup");
2405        assert_eq!(cell("a|b"), r"a\|b");
2406        // Doubled so the inline parse gives them back as written: comrak
2407        // renders `a\\\|b` as `a\|b` and `win\\arm` as `win\arm`.
2408        assert_eq!(cell(r"a\|b"), r"a\\\|b");
2409        assert_eq!(cell(r"win\arm"), r"win\\arm");
2410    }
2411
2412    /// Inside a code span a backslash is shown as written, so only pipes are
2413    /// escaped: comrak renders `` `win\arm` `` as `win\arm` and `` `a\|b` ``
2414    /// as `a|b`, each in one cell.
2415    #[test]
2416    fn a_code_cell_escapes_only_pipes() {
2417        assert_eq!(code_cell("`win\\arm`"), "`win\\arm`");
2418        assert_eq!(code_cell("`a|b`"), r"`a\|b`");
2419        // The one inexact case: this renders as `a\\|b`, still in one cell.
2420        assert_eq!(code_cell(r"`a\|b`"), r"`a\\|b`");
2421    }
2422
2423    /// A name with a pipe in it stays in its own cell, so every row keeps the
2424    /// header's column count — the baseline report renders through here too.
2425    #[test]
2426    fn a_pipe_in_a_name_does_not_split_the_row() {
2427        let mut base = rec("a|b", "gha", 100.0, 1.0);
2428        let mut head = rec("a|b", "gha", 101.0, 1.0);
2429        base.tool = "x|y".into();
2430        head.tool = "x|y".into();
2431        let md = markdown(&compare(&[base], &[head]), &Trend::new(), &g(1.0), false);
2432        assert!(md.contains(r"| a\|b (x\|y) |"), "{md}");
2433        let columns = |l: &str| l.replace(r"\|", "").matches('|').count();
2434        let rows: Vec<&str> = md.lines().filter(|l| l.starts_with('|')).collect();
2435        assert_eq!(rows.len(), 3, "{md}");
2436        assert!(rows.iter().all(|r| columns(r) == columns(rows[0])), "{md}");
2437    }
2438
2439    /// Two runner classes of one accepted benchmark are two entries, and the
2440    /// verdict has to say which is which.
2441    #[test]
2442    fn an_accepted_entry_names_its_runner() {
2443        let c = compare(
2444            &[
2445                rec("a", "gha", 1_000_000.0, 10.0),
2446                rec("a", "arm", 1_000_000.0, 10.0),
2447            ],
2448            &[
2449                rec("a", "gha", 1_100_000.0, 10.0),
2450                rec("a", "arm", 1_200_000.0, 10.0),
2451            ],
2452        )
2453        .with_accepted(accepting("a", Source::Flag));
2454        let md = markdown(&c, &Trend::new(), &g(1.0), false);
2455        assert!(md.contains("`a` on `arm` +20.00% (`--accept`)"), "{md}");
2456        assert!(md.contains("`a` on `gha` +10.00% (`--accept`)"), "{md}");
2457    }
2458
2459    /// Each series is judged against its own effective gate before acceptance
2460    /// is consulted. `startup` at 5% with a floor did not regress, so accepting
2461    /// it waived nothing; `install` at the global 1% did, and was waived.
2462    #[test]
2463    fn an_acceptance_is_judged_against_the_series_own_gate() {
2464        let mut gates = g(1.0);
2465        gates.set_series("startup", SELF_TOOL, gate(5.0, 20_000, true));
2466        let c = startup_and_install().with_accepted(accepting("startup, install", Source::Flag));
2467        assert!(c.failures(&gates).is_empty());
2468        assert_eq!(benches(&c.accepted_regressions(&gates)), ["install"]);
2469        let md = markdown(&c, &Trend::new(), &gates, false);
2470        assert!(
2471            md.contains(
2472                "**1 accepted regression(s) above their gate, not failing it:** \
2473                 `install` on `gha` +2.00% (gate 1%) (`--accept`)\n"
2474            ),
2475            "{md}"
2476        );
2477        assert!(
2478            md.contains("Accepted, but not above its gate, so nothing was accepted: `startup`"),
2479            "{md}"
2480        );
2481        assert!(!md.contains("No gated benchmark rose"), "{md}");
2482    }
2483
2484    /// The floor decides first. A rise under `min_delta` is not a regression,
2485    /// so an acceptance naming it accepted nothing and the report says so.
2486    #[test]
2487    fn an_acceptance_does_not_count_a_rise_under_the_floor() {
2488        let gates = Gates::uniform(Gate::new(1.0, 10_000).unwrap());
2489        let c = startup_and_install().with_accepted(accepting("startup, install", Source::Flag));
2490        assert!(c.failures(&gates).is_empty());
2491        assert_eq!(benches(&c.accepted_regressions(&gates)), ["install"]);
2492        let md = markdown(&c, &Trend::new(), &gates, false);
2493        assert!(
2494            md.contains(
2495                "**1 accepted regression(s) above the 1% gate, not failing it:** \
2496                 `install` on `gha` +2.00% (`--accept`)\n"
2497            ),
2498            "{md}"
2499        );
2500        assert!(
2501            md.contains("not above its gate, so nothing was accepted: `startup`"),
2502            "{md}"
2503        );
2504    }
2505
2506    /// A report-only series can never fail, so it never needs accepting. An
2507    /// acceptance naming one is listed with that reason, and the row keeps its
2508    /// report-only marking rather than claiming an acceptance happened.
2509    #[test]
2510    fn accepting_a_report_only_benchmark_accepts_nothing() {
2511        let mut gates = g(1.0);
2512        gates.set_series("startup", SELF_TOOL, gate(1.0, 0, false));
2513        let c = startup_and_install().with_accepted(accepting("startup", Source::Flag));
2514        assert_eq!(benches(&c.failures(&gates)), ["install"]);
2515        assert!(c.accepted_regressions(&gates).is_empty());
2516        let md = markdown(&c, &Trend::new(), &gates, false);
2517        assert!(md.contains("**+2.00%** (not gated)"), "{md}");
2518        assert!(!md.contains("(accepted)"), "{md}");
2519        assert!(
2520            md.contains(
2521                "Accepted, but report-only, so it can never fail and nothing was \
2522                 accepted: `startup` (`--accept`)"
2523            ),
2524            "{md}"
2525        );
2526        assert!(
2527            md.contains("**1 report-only benchmark(s) above their gate, not failing:**"),
2528            "{md}"
2529        );
2530    }
2531
2532    /// With nothing accepted, a per-benchmark report is exactly what it was
2533    /// without acceptance support: every line this adds is conditional.
2534    #[test]
2535    fn an_empty_acceptance_leaves_a_per_benchmark_report_unchanged() {
2536        let mut gates = g(1.0);
2537        gates.set_series("startup", SELF_TOOL, gate(5.0, 20_000, true));
2538        let plain = markdown(&startup_and_install(), &Trend::new(), &gates, false);
2539        let c = startup_and_install()
2540            .with_accepted(Acceptances::default())
2541            .with_ignored_trailers(Acceptances::default());
2542        assert_eq!(markdown(&c, &Trend::new(), &gates, false), plain);
2543        assert!(!plain.contains("accepted"), "{plain}");
2544    }
2545
2546    #[test]
2547    fn thousands_separates() {
2548        assert_eq!(thousands(1234567.0), "1,234,567");
2549        assert_eq!(thousands(999.0), "999");
2550        assert_eq!(thousands(1000.0), "1,000");
2551    }
2552}