Skip to main content

tak_cli/
detect.rs

1//! Find instruction-count steps that have already landed on a branch.
2//!
3//! `tak compare` gates a pull request before it merges. Nothing looked at what
4//! merged anyway: a gate that was not required, an override, a direct push, or
5//! several changes that each stayed under the threshold. This walks a branch's
6//! recorded first-parent history and reports where each series stepped.
7//!
8//! A step detector, deliberately, not a change-point engine. E-divisive means
9//! (Hunter) and its relatives exist to find shifts in noisy data. Instruction
10//! counts reproduce to ~0.02%, so a move between consecutive recorded points
11//! larger than a 1% gate *is* the change point, and a statistical model would
12//! only add ways to be wrong. Wall clock is noisy enough to need one, and it is
13//! exactly the metric that must never fail a build — so it is shown beside a
14//! step for context and never examined for one.
15//!
16//! Everything below [`gather`] is a pure function over `(sha, records)`
17//! sequences, so the rules are tested without a repository.
18
19use anyhow::Result;
20use std::collections::{BTreeMap, BTreeSet};
21
22use crate::accept::{Acceptances, TRAILER};
23use crate::compare::{
24    CREDIT, Change, GATED_METRIC, Gate, Gates, Key, Trend, WALL_METRIC, code, code_cell, describe,
25    signed_pct, sparkline, thousands,
26};
27use crate::notes;
28use crate::record::Record;
29
30/// How many first-parent commits a walk may cover while filling its window.
31///
32/// A bound rather than the whole history because `rev-list` output is held in
33/// memory and a monorepo trunk can run to hundreds of thousands of commits. Ten
34/// thousand is far more than any window needs unless recordings are extremely
35/// sparse, and still lists in tens of milliseconds. Reaching it before the
36/// window fills is reported as a [`Cutoff`], never passed over silently.
37pub const SCAN_LIMIT: usize = 10_000;
38
39/// Why a walk stopped before its window filled, when the reason is the walk's
40/// and not the project's.
41///
42/// Either way a recording further back exists, or may exist, and was never
43/// compared. Without saying so, a series whose previous point lay just past
44/// the boundary reads as brand new, and a step onto the head goes unchecked.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum Cutoff {
47    /// The checkout is a shallow clone and the walk reached its boundary.
48    Shallow,
49    /// The walk covered [`SCAN_LIMIT`] first-parent commits.
50    ScanLimit,
51}
52
53/// Decide whether the walk was cut short, and by what.
54///
55/// `truncated` says history continued past [`SCAN_LIMIT`] — see [`gather`]
56/// for how that is known rather than guessed. Otherwise the walk reached the
57/// end of the history this checkout has: the root, or a shallow clone's
58/// boundary, which only `shallow` can tell apart. A window that filled was cut
59/// short by neither, however deep the history.
60pub fn cutoff(
61    recorded: usize,
62    window: usize,
63    truncated: bool,
64    shallow: impl FnOnce() -> Result<bool>,
65) -> Result<Option<Cutoff>> {
66    if recorded >= window {
67        return Ok(None);
68    }
69    if truncated {
70        return Ok(Some(Cutoff::ScanLimit));
71    }
72    Ok(shallow()?.then_some(Cutoff::Shallow))
73}
74
75/// One series' reduced value at one commit.
76#[derive(Debug, Clone, Copy)]
77struct Point {
78    /// Index into the walked commits, oldest first.
79    at: usize,
80    instructions: f64,
81    wall: Option<f64>,
82}
83
84/// A move between two consecutive recorded points of one series.
85#[derive(Debug, Clone, PartialEq)]
86pub struct Step {
87    pub key: Key,
88    /// The earlier recorded commit, which the step is measured from.
89    pub from: String,
90    /// The later recorded commit, where the new value was first seen.
91    pub to: String,
92    /// First-parent commits in `from..to`. One means the step belongs to `to`
93    /// alone; more means it happened somewhere in the range and the report must
94    /// say so, because naming `to` would blame a commit that may be innocent.
95    pub commits: usize,
96    pub instructions: Change,
97    /// For context only. [`Change::exceeds`] refuses to gate on it.
98    pub wall: Option<Change>,
99}
100
101impl Step {
102    /// The gate this step's series is held to — the same lookup `tak compare`
103    /// uses, so a benchmark's `tak.toml` gate means the same thing before a
104    /// merge and after it.
105    pub fn gate(&self, gates: &Gates) -> Gate {
106        gates.get(&self.key.0, &self.key.1)
107    }
108
109    /// Beyond its series' threshold and floor, whether or not that gate is
110    /// enabled. A report-only series still crosses its threshold, and the
111    /// report says so.
112    pub fn exceeds(&self, gates: &Gates) -> bool {
113        self.instructions.exceeds(&self.gate(gates))
114    }
115
116    /// Beyond an enabled gate: a step that is allowed to fail the command.
117    pub fn fails(&self, gates: &Gates) -> bool {
118        self.gate(gates).enabled && self.exceeds(gates)
119    }
120}
121
122/// A rise that no single step explains.
123#[derive(Debug, Clone, PartialEq)]
124pub struct Drift {
125    pub key: Key,
126    /// Where the run of sub-threshold steps began.
127    pub since: String,
128    /// Recorded points in that run, both ends included.
129    pub points: usize,
130    pub change: Change,
131}
132
133#[derive(Debug, PartialEq)]
134pub struct Detection {
135    pub head: String,
136    /// Every series' gate, from `tak.toml` and `[gate]`. Policy of whoever runs
137    /// the check, as for `tak compare`: never read from the notes.
138    pub gates: Gates,
139    /// First-parent commits in the walk, recorded or not.
140    pub walked: usize,
141    /// How many of them carry any measurement.
142    pub recorded: usize,
143    /// For every series measured at the head with an earlier point in the
144    /// window: its step onto the head. The only steps that can fail.
145    pub latest: Vec<Step>,
146    /// Steps above the gate that end before the head. Report-only.
147    pub earlier: Vec<Step>,
148    /// Report-only.
149    pub drift: Vec<Drift>,
150    /// Measured at the head with nothing earlier in the window to compare to.
151    pub new_at_head: Vec<Key>,
152    /// Measured earlier in the window and not at the head.
153    pub missing_at_head: Vec<Key>,
154    pub trend: Trend,
155    /// Set when the walk stopped before the window filled for a reason of its
156    /// own, so a short history here may be the walk's rather than the project's.
157    pub cutoff: Option<Cutoff>,
158    /// Whether an empty comparison is accepted (`allow_empty`, from `tak.toml`,
159    /// `TAK_ALLOW_EMPTY` or `--allow-empty`) rather than failed. Carried here so
160    /// the report and the exit status cannot disagree.
161    pub allow_empty: bool,
162    /// Report-only (`--no-gate`): nothing fails, an empty comparison included.
163    /// The same promise `tak compare --no-gate` makes, so a workflow that must
164    /// always exit successfully needs one flag, not two.
165    pub no_gate: bool,
166    /// What each step onto the head may be accepted by: `--accept`, plus the
167    /// `Tak-Accept` trailers in that step's own range. Per series, because two
168    /// series' previous points can lie at different commits, and a trailer
169    /// outside a step's range says nothing about that step.
170    pub accepted: BTreeMap<Key, Acceptances>,
171    /// Every acceptance offered, across all ranges, for reporting the ones
172    /// that accepted nothing.
173    pub offered: Acceptances,
174    /// Trailers found but not honoured because `accept_trailers` is off.
175    pub ignored_trailers: Acceptances,
176}
177
178impl Detection {
179    /// A walk that found nothing, held to `gates`.
180    pub fn new(head: String, gates: Gates) -> Self {
181        Self {
182            head,
183            gates,
184            walked: 0,
185            recorded: 0,
186            latest: vec![],
187            earlier: vec![],
188            drift: vec![],
189            new_at_head: vec![],
190            missing_at_head: vec![],
191            trend: Trend::new(),
192            cutoff: None,
193            allow_empty: false,
194            no_gate: false,
195            accepted: BTreeMap::new(),
196            offered: Acceptances::default(),
197            ignored_trailers: Acceptances::default(),
198        }
199    }
200
201    /// Apply acceptances to the steps onto the head.
202    ///
203    /// `flags` is `--accept`, which covers every step. `trailer_logs` maps a
204    /// step's `from` commit to the [`crate::notes::trailers`] output for
205    /// `from..head`, which is exactly that step's range: pass it only when
206    /// `accept_trailers` is on. A benchmark name covers every tool and runner
207    /// class it was measured on, as in `tak compare`.
208    pub fn accept(&mut self, flags: &Acceptances, trailer_logs: &BTreeMap<String, String>) {
209        self.offered = flags.clone();
210        for log in trailer_logs.values() {
211            self.offered.add_trailer_log(log);
212        }
213        for s in &self.latest {
214            let mut a = flags.clone();
215            if let Some(log) = trailer_logs.get(&s.from) {
216                a.add_trailer_log(log);
217            }
218            if !a.is_empty() {
219                self.accepted.insert(s.key.clone(), a);
220            }
221        }
222    }
223
224    /// The acceptance covering `s`, if `s` is a step onto the head that one
225    /// names. An older step of the same series is never "accepted": only the
226    /// head's step can fail, so only it can need to be.
227    fn acceptance(&self, s: &Step) -> Option<&Acceptances> {
228        if s.to != self.head {
229            return None;
230        }
231        self.accepted.get(&s.key).filter(|a| a.covers(&s.key.0))
232    }
233
234    /// Steps onto the head that would fail, waived by an acceptance.
235    pub fn accepted_steps(&self) -> Vec<&Step> {
236        self.latest
237            .iter()
238            .filter(|s| s.fails(&self.gates) && self.acceptance(s).is_some())
239            .collect()
240    }
241
242    /// Offered acceptances that waived nothing, in name order.
243    fn unused_acceptances(&self) -> Vec<&str> {
244        let used: BTreeSet<&str> = self
245            .accepted_steps()
246            .iter()
247            .map(|s| s.key.0.as_str())
248            .collect();
249        self.offered
250            .iter()
251            .map(|(name, _)| name)
252            .filter(|name| !used.contains(name))
253            .collect()
254    }
255
256    /// Steps onto the head beyond an enabled gate: what makes the command fail.
257    ///
258    /// Only the head's. A main-branch workflow runs this once per push, so
259    /// failing on an older step would fail every run after the one that caused
260    /// it, and a job that is always red is a job nobody reads.
261    pub fn failures(&self) -> Vec<&Step> {
262        self.latest
263            .iter()
264            .filter(|s| s.fails(&self.gates) && self.acceptance(s).is_none())
265            .collect()
266    }
267
268    /// Steps onto the head beyond a report-only gate: flagged, never failed on.
269    pub fn reported(&self) -> Vec<&Step> {
270        self.latest
271            .iter()
272            .filter(|s| !s.gate(&self.gates).enabled && s.exceeds(&self.gates))
273            .collect()
274    }
275
276    /// Whether every series in the report is held to the global gate.
277    ///
278    /// When it is, the report reads exactly as it did before per-benchmark
279    /// gates existed — one `N%` in the prose, no gate column — for the same
280    /// reason `tak compare` keeps its wording: a project that never wrote a
281    /// per-benchmark gate should not have its output change under it.
282    pub fn uniform(&self) -> bool {
283        let keys = self
284            .latest
285            .iter()
286            .chain(&self.earlier)
287            .map(|s| &s.key)
288            .chain(self.drift.iter().map(|d| &d.key));
289        keys.into_iter()
290            .all(|k| self.gates.get(&k.0, &k.1) == self.gates.global)
291    }
292
293    /// No series at the head had anything to be compared against.
294    pub fn nothing_compared(&self) -> bool {
295        self.latest.is_empty()
296    }
297
298    /// Whether comparing nothing fails the command.
299    ///
300    /// By default it does. A check that passes when it examined nothing is
301    /// indistinguishable, from the outside, from one that examined everything
302    /// and found it clean — and the ways to get here by accident (a shallow
303    /// checkout, a recording step that stopped producing instruction counts, a
304    /// runner class that drifted) are exactly the ones nobody reads a green
305    /// job's summary to find. The legitimate cases, a first recording or a new
306    /// runner class, are rare and known in advance, so they are the ones asked
307    /// to opt out.
308    pub fn empty_fails(&self) -> bool {
309        self.nothing_compared() && !self.allow_empty && !self.no_gate
310    }
311}
312
313/// Choose the commits to walk: from the head back to the `window`-th recorded
314/// commit, returned oldest first.
315///
316/// The window counts *recorded* commits, not commits. A push of several commits
317/// records only its tip, so a window of twenty commits could hold two points,
318/// and whether it held enough would depend on how people happened to push.
319///
320/// The head is always included, recorded or not — "the head has nothing
321/// recorded" is itself something the report has to say. Unrecorded commits
322/// older than the oldest recorded one are dropped: they belong to no range.
323pub fn select(newest_first: &[String], annotated: &BTreeSet<String>, window: usize) -> Vec<String> {
324    let mut seen = 0;
325    let mut end = newest_first.len().min(1);
326    for (i, sha) in newest_first.iter().enumerate() {
327        if annotated.contains(sha) {
328            seen += 1;
329            end = i + 1;
330            if seen >= window {
331                break;
332            }
333        }
334    }
335    newest_first[..end].iter().rev().cloned().collect()
336}
337
338/// Commits oldest first, each with the records attached to it — empty where
339/// nothing was recorded, which is what makes a range visible.
340pub type Walk = Vec<(String, Vec<Record>)>;
341
342/// Walk `head`'s first-parent history and read the notes along it.
343///
344/// Returns the walk oldest first, plus what cut it short, if anything did.
345pub fn gather(head: &str, window: usize) -> Result<(Walk, Option<Cutoff>)> {
346    // One more than the limit, then drop it. Returning exactly SCAN_LIMIT is
347    // ambiguous — a history of exactly that length returns it too — and
348    // reading it as a cut-off sent people looking for recordings that did not
349    // exist. An extra commit is proof that history goes on.
350    //
351    // The same first-parent walker as `tak log`: one `git log` with every note
352    // inlined, rather than a `notes show` per recorded commit.
353    let mut logged = notes::log(head, Some(SCAN_LIMIT + 1))?;
354    let truncated = logged.len() > SCAN_LIMIT;
355    logged.truncate(SCAN_LIMIT);
356    // The oldest commit the walk reached, not the oldest one kept: the walk
357    // ended there, so that is where a shallow boundary would have stopped it.
358    let oldest = logged.last().map(|l| l.sha.clone());
359
360    // A commit counts as recorded when tak can read a record on it. A note
361    // with nothing parseable in it holds no point, so it must not use up a
362    // place in the window either.
363    let shas: Vec<String> = logged.iter().map(|l| l.sha.clone()).collect();
364    let recorded_at: BTreeSet<String> = logged
365        .iter()
366        .filter(|l| !l.records.is_empty())
367        .map(|l| l.sha.clone())
368        .collect();
369    // `select` keeps a newest-first prefix and reverses it, so its length is
370    // all that is needed to take the same commits, records and all.
371    let kept = select(&shas, &recorded_at, window).len();
372    logged.truncate(kept);
373    let walked: Walk = logged
374        .into_iter()
375        .rev()
376        .map(|l| (l.sha, l.records))
377        .collect();
378    let recorded = walked.iter().filter(|(_, r)| !r.is_empty()).count();
379
380    let cut = cutoff(recorded, window, truncated, || {
381        Ok(oldest.as_deref().is_some_and(notes::is_shallow_boundary))
382    })?;
383    Ok((walked, cut))
384}
385
386/// One value per instruction-counted series at one commit, minimum across its
387/// records — the same reducer `compare` uses, for the same reason: the extra
388/// work a machine sometimes does is one-sided, and a re-run must not put a
389/// spike in a number meant to be deterministic.
390///
391/// Series with no instruction count are left out entirely. They cannot gate,
392/// and a wall-only series examined for steps would report scheduler noise.
393fn fold(records: &[Record]) -> BTreeMap<Key, (f64, Option<f64>)> {
394    let mut ins: BTreeMap<Key, f64> = BTreeMap::new();
395    let mut wall: BTreeMap<Key, f64> = BTreeMap::new();
396    for r in records {
397        let key: Key = (r.bench.clone(), r.tool.clone(), r.runner.clone());
398        if let Some(&v) = r.metrics.get(GATED_METRIC) {
399            ins.entry(key.clone())
400                .and_modify(|e| *e = e.min(v))
401                .or_insert(v);
402        }
403        if let Some(&v) = r.metrics.get(WALL_METRIC) {
404            wall.entry(key).and_modify(|e| *e = e.min(v)).or_insert(v);
405        }
406    }
407    ins.into_iter()
408        .map(|(k, v)| {
409            let w = wall.get(&k).copied();
410            (k, (v, w))
411        })
412        .collect()
413}
414
415fn step(key: &Key, walked: &[(String, Vec<Record>)], a: Point, b: Point) -> Step {
416    let change = |metric: &str, base: f64, head: f64| Change {
417        bench: key.0.clone(),
418        tool: key.1.clone(),
419        runner: key.2.clone(),
420        metric: metric.to_string(),
421        base,
422        head,
423    };
424    Step {
425        key: key.clone(),
426        from: walked[a.at].0.clone(),
427        to: walked[b.at].0.clone(),
428        commits: b.at - a.at,
429        instructions: change(GATED_METRIC, a.instructions, b.instructions),
430        wall: match (a.wall, b.wall) {
431            (Some(x), Some(y)) => Some(change(WALL_METRIC, x, y)),
432            _ => None,
433        },
434    }
435}
436
437/// Find the steps in a walk. `walked` is oldest first and ends at the head.
438///
439/// Each series is keyed on (bench, tool, runner) and only ever compared with
440/// itself. Runner is in the key because it has to be: absolute counts shift
441/// between machine classes by more than a real regression does, so a runner
442/// change must start a new series rather than read as a step.
443///
444/// Every threshold is the series' own gate: a report-only benchmark is examined
445/// like any other and can never fail, and a floor (`min_delta`) applies to
446/// steps and drift alike.
447pub fn analyze(walked: &[(String, Vec<Record>)], gates: &Gates) -> Detection {
448    let Some((head, _)) = walked.last() else {
449        return Detection::new(String::new(), gates.clone());
450    };
451    let head_at = walked.len() - 1;
452
453    let mut series: BTreeMap<Key, Vec<Point>> = BTreeMap::new();
454    for (at, (_, records)) in walked.iter().enumerate() {
455        for (key, (instructions, wall)) in fold(records) {
456            series.entry(key).or_default().push(Point {
457                at,
458                instructions,
459                wall,
460            });
461        }
462    }
463
464    let mut d = Detection {
465        walked: walked.len(),
466        recorded: walked.iter().filter(|(_, r)| !r.is_empty()).count(),
467        ..Detection::new(head.clone(), gates.clone())
468    };
469
470    for (key, points) in &series {
471        d.trend
472            .insert(key.clone(), points.iter().map(|p| p.instructions).collect());
473
474        let steps: Vec<Step> = points
475            .windows(2)
476            .map(|w| step(key, walked, w[0], w[1]))
477            .collect();
478        let at_head = points.last().is_some_and(|p| p.at == head_at);
479
480        match (at_head, steps.split_last()) {
481            (true, Some((last, rest))) => {
482                d.latest.push(last.clone());
483                d.earlier
484                    .extend(rest.iter().filter(|s| s.exceeds(gates)).cloned());
485            }
486            (true, None) => d.new_at_head.push(key.clone()),
487            (false, _) => {
488                d.missing_at_head.push(key.clone());
489                d.earlier
490                    .extend(steps.iter().filter(|s| s.exceeds(gates)).cloned());
491            }
492        }
493
494        let gate = gates.get(&key.0, &key.1);
495        if at_head && let Some(drift) = drift(key, walked, points, &steps, &gate) {
496            d.drift.push(drift);
497        }
498    }
499
500    // Oldest first reads as a history; series order within one commit stays
501    // the stable key order.
502    d.earlier
503        .sort_by_key(|s| walked.iter().position(|(sha, _)| sha == &s.to));
504    d
505}
506
507/// A cumulative rise beyond the series' gate made only of steps within it.
508///
509/// The same gate as the steps, floor included: drift is the rise the gate was
510/// meant to catch arriving in pieces, so it is held to what one piece would
511/// have been.
512///
513/// Measured from the last above-gate step, or the start of the window when
514/// there was none. Starting after the step matters: a series that jumped 10%
515/// and then crept another 2% would otherwise report that 10% twice, once as a
516/// step and again as drift, and the creep after it — the part nobody has been
517/// told about — would be buried in the total.
518///
519/// From the first point of that run rather than its minimum. "Since `abc`, up
520/// 1.5%" is something a reader can check with one `tak compare`; a floor picked
521/// out of the middle of the run is not.
522fn drift(
523    key: &Key,
524    walked: &[(String, Vec<Record>)],
525    points: &[Point],
526    steps: &[Step],
527    gate: &Gate,
528) -> Option<Drift> {
529    // steps[i] runs from points[i] to points[i + 1].
530    let start = steps
531        .iter()
532        .rposition(|s| s.instructions.exceeds(gate))
533        .map_or(0, |i| i + 1);
534    let run = &points[start..];
535    // Two points are one step, and that step is below the gate by construction.
536    if run.len() < 3 {
537        return None;
538    }
539    let total = step(key, walked, run[0], run[run.len() - 1]);
540    if !total.instructions.exceeds(gate) {
541        return None;
542    }
543    Some(Drift {
544        key: key.clone(),
545        since: total.from,
546        points: run.len(),
547        change: total.instructions,
548    })
549}
550
551/// The first 12 characters of a SHA, for display. Bounded rather than sliced
552/// at a fixed 12, so an abbreviated or empty name can never panic a report.
553pub fn short(sha: &str) -> &str {
554    &sha[..sha.len().min(12)]
555}
556
557/// The commit a step belongs to, or the range when it cannot be narrowed.
558///
559/// Written as a git range so it can be pasted into `git log` as it stands:
560/// `from..to` is exactly the commits that could have caused it.
561fn span(s: &Step) -> String {
562    if s.commits <= 1 {
563        format!("`{}`", short(&s.to))
564    } else {
565        format!(
566            "`{}..{}` ({} commits)",
567            short(&s.from),
568            short(&s.to),
569            s.commits
570        )
571    }
572}
573
574fn instructions_cells(s: &Step, d: &Detection) -> (String, String) {
575    let gates = &d.gates;
576    let ch = &s.instructions;
577    // As in `compare`: the warning sign means "this fails", and a report-only
578    // or accepted row that crossed its threshold says so in words instead.
579    let flag = match (s.exceeds(gates), s.gate(gates).enabled) {
580        (true, true) if d.acceptance(s).is_some() => " (accepted)",
581        (true, true) => " ⚠️",
582        (true, false) => " (not gated)",
583        (false, _) => "",
584    };
585    (
586        format!("{} → {}", thousands(ch.base), thousands(ch.head)),
587        format!("**{}**{flag}", signed_pct(ch.pct())),
588    )
589}
590
591/// Render a detection as markdown, in the same shape as `compare`'s report so
592/// the two read alike in a job summary.
593pub fn markdown(d: &Detection, credit: bool) -> String {
594    let gates = &d.gates;
595    let global = gates.global;
596    let uniform = d.uniform();
597    // With every series at the global gate the prose names it once, as it did
598    // before per-benchmark gates; otherwise each row carries its own.
599    let the_gate = if uniform {
600        format!("the {}% gate", global.pct)
601    } else {
602        "their gate".to_string()
603    };
604    let floor = if uniform && global.min_delta > 0 {
605        format!(
606            " (rises of {} instructions or fewer are not counted)",
607            thousands(global.min_delta as f64)
608        )
609    } else {
610        String::new()
611    };
612    let listed = |steps: &[&Step]| {
613        steps
614            .iter()
615            .map(|s| {
616                let mut out = format!("{} {}", describe(&s.key), signed_pct(s.instructions.pct()));
617                if !uniform {
618                    out.push_str(&format!(" (gate {})", s.gate(gates).threshold()));
619                }
620                out
621            })
622            .collect::<Vec<_>>()
623            .join(", ")
624    };
625    let head = short(&d.head);
626    let mut out = format!(
627        "Walked {} first-parent commit(s) ending at `{head}`, {} with measurements recorded.\n\n",
628        d.walked, d.recorded
629    );
630
631    if d.nothing_compared() {
632        let why = if d.new_at_head.is_empty() {
633            "No instruction counts are recorded for this commit. Record it with \
634             `tak run --record` before running `tak detect`."
635        } else {
636            "No series measured here has an earlier recorded point in the window: \
637             this is the first recording, the history is too short or shallow, or \
638             the runner class changed, which deliberately starts a new series."
639        };
640        if d.no_gate {
641            out.push_str(&format!(
642                "**Nothing was compared at `{head}`, and so nothing was gated** \
643                 (`--no-gate`). {why}\n"
644            ));
645        } else if !d.empty_fails() {
646            // The setting, not a flag: `--allow-empty` is one of its spellings,
647            // and the report cannot know which one a run used.
648            out.push_str(&format!(
649                "**Nothing was compared at `{head}`, and so nothing was gated** \
650                 (`allow_empty`). {why}\n\n{}\n",
651                crate::compare::ALLOWED_EMPTY
652            ));
653        } else {
654            out.push_str(&format!(
655                "**Nothing was compared at `{head}`, so this check fails.** {why} \
656                 When that is expected — the first recording, or the first on a new \
657                 runner class — pass `--allow-empty` or set `[gate] allow_empty = true`, \
658                 or record an earlier commit on the same runner class first.\n"
659            ));
660        }
661    } else {
662        if uniform {
663            out.push_str(
664                "| benchmark | trend | step | instructions | Δ | wall (min) | Δ |\n\
665                 |---|---|---|---:|---:|---:|---:|\n",
666            );
667        } else {
668            out.push_str(
669                "| benchmark | trend | step | instructions | Δ | gate | wall (min) | Δ |\n\
670                 |---|---|---|---:|---:|---|---:|---:|\n",
671            );
672        }
673        for s in &d.latest {
674            let spark = d
675                .trend
676                .get(&s.key)
677                .map(|v| sparkline(v))
678                .filter(|v| !v.is_empty())
679                .map(|v| format!("`{v}`"))
680                .unwrap_or_else(|| "—".into());
681            let (ins, ins_delta) = instructions_cells(s, d);
682            let gate_cell = if uniform {
683                String::new()
684            } else {
685                format!(" {} |", s.gate(gates).describe())
686            };
687            let (wall, wall_delta) = match &s.wall {
688                Some(w) => (
689                    format!("{:.2} → {:.2}ms", w.base, w.head),
690                    signed_pct(w.pct()),
691                ),
692                None => ("—".into(), "—".into()),
693            };
694            out.push_str(&format!(
695                "| {} | {spark} | {} | {ins} | {ins_delta} |{gate_cell} {wall} | {wall_delta} |\n",
696                code_cell(&describe(&s.key)),
697                span(s),
698            ));
699        }
700
701        let failures = d.failures();
702        let accepted = d.accepted_steps();
703        let any_gated = d.latest.iter().any(|s| s.gate(gates).enabled);
704        out.push('\n');
705        if !any_gated {
706            // "No step above the gate" is true of a report with nothing that
707            // could fail, and reads as a pass. Say there was nothing to fail.
708            out.push_str("Every benchmark here is report-only, so none can fail the gate.\n");
709        } else if failures.is_empty() && !accepted.is_empty() {
710            // Nothing fails, but "no step above the gate" would be false: the
711            // accepted line below is the verdict, as in `tak compare`.
712        } else if failures.is_empty() {
713            if uniform {
714                out.push_str(&format!(
715                    "No instruction-count step above {}% at `{head}`{floor}.\n",
716                    global.pct
717                ));
718            } else {
719                out.push_str(&format!(
720                    "No gated benchmark stepped beyond its gate at `{head}`.\n"
721                ));
722            }
723        } else {
724            out.push_str(&format!(
725                "**{} benchmark(s) stepped above {the_gate} at `{head}`{floor}:** {}\n",
726                failures.len(),
727                listed(&failures)
728            ));
729            if failures.iter().any(|s| s.commits > 1) {
730                out.push_str(
731                    "\nA step shown as a range happened somewhere in commits that were \
732                     not measured individually; `git log --first-parent` over that \
733                     range lists the candidates.\n",
734                );
735            }
736        }
737        if !accepted.is_empty() {
738            // Its own bold line, with where each acceptance came from: an
739            // override of the gate must be as visible as what it overrides.
740            // Separated from a failure verdict above it; alone, it is the verdict.
741            let gap = if failures.is_empty() { "" } else { "\n" };
742            out.push_str(&format!(
743                "{gap}**{} accepted step(s) above {the_gate} at `{head}`, not failing:** {}\n",
744                accepted.len(),
745                accepted
746                    .iter()
747                    .map(|s| {
748                        let by = d.acceptance(s).map(|a| a.describe(&s.key.0));
749                        format!("{} (accepted by {})", listed(&[*s]), by.unwrap_or_default())
750                    })
751                    .collect::<Vec<_>>()
752                    .join(", ")
753            ));
754        }
755        let reported = d.reported();
756        if !reported.is_empty() {
757            out.push_str(&format!(
758                "\n**{} report-only benchmark(s) stepped above their gate at `{head}`, \
759                 not failing:** {}\n",
760                reported.len(),
761                listed(&reported)
762            ));
763        }
764    }
765
766    // Outside the branch above, as in `tak compare`: an acceptance that
767    // waived nothing matters most when nothing was compared, because a stale
768    // or misspelt name is otherwise silent under `--allow-empty`.
769    let unused = d.unused_acceptances();
770    if !unused.is_empty() {
771        out.push_str(&format!(
772            "\nAccepted, but no step onto `{head}` needed it, so nothing was accepted: {}\n",
773            unused
774                .iter()
775                .map(|name| format!("{} ({})", code(name), d.offered.describe(name)))
776                .collect::<Vec<_>>()
777                .join(", ")
778        ));
779    }
780    if !d.ignored_trailers.is_empty() {
781        out.push_str(&format!(
782            "\n`{TRAILER}` trailers were found but not honoured, because \
783             `gate.accept_trailers` is off: {}\n",
784            d.ignored_trailers
785                .iter()
786                .map(|(name, _)| format!("{} ({})", code(name), d.ignored_trailers.describe(name)))
787                .collect::<Vec<_>>()
788                .join(", ")
789        ));
790    }
791
792    if !d.earlier.is_empty() {
793        out.push_str(&format!(
794            "\n**Earlier steps above {the_gate}**, reported and not gated — \
795             a step fails only the run for the commit that introduced it:\n\n"
796        ));
797        if uniform {
798            out.push_str("| benchmark | step | instructions | Δ |\n|---|---|---:|---:|\n");
799        } else {
800            out.push_str(
801                "| benchmark | step | instructions | Δ | gate |\n|---|---|---:|---:|---|\n",
802            );
803        }
804        for s in &d.earlier {
805            let (ins, delta) = instructions_cells(s, d);
806            let gate_cell = if uniform {
807                String::new()
808            } else {
809                format!(" {} |", s.gate(gates).describe())
810            };
811            out.push_str(&format!(
812                "| {} | {} | {ins} | {delta} |{gate_cell}\n",
813                code_cell(&describe(&s.key)),
814                span(s)
815            ));
816        }
817    }
818
819    if !d.drift.is_empty() {
820        out.push_str(&format!(
821            "\n**Sustained drift**, reported and not gated — every step stayed within \
822             {the_gate} and the total did not:\n\n"
823        ));
824        for dr in &d.drift {
825            let gate = if uniform {
826                String::new()
827            } else {
828                format!(" (gate {})", gates.get(&dr.key.0, &dr.key.1).describe())
829            };
830            out.push_str(&format!(
831                "- {}: {} ({} → {}) over {} recorded commits since `{}`{gate}\n",
832                describe(&dr.key),
833                signed_pct(dr.change.pct()),
834                thousands(dr.change.base),
835                thousands(dr.change.head),
836                dr.points,
837                short(&dr.since),
838            ));
839        }
840    }
841
842    if !d.new_at_head.is_empty() {
843        out.push_str(&format!(
844            "\nNo earlier point in the window, nothing to compare against: {}\n",
845            list(&d.new_at_head)
846        ));
847    }
848    if !d.missing_at_head.is_empty() {
849        out.push_str(&format!(
850            "\nRecorded earlier in the window but not at `{head}` — a benchmark that \
851             stops running also stops being checked: {}\n",
852            list(&d.missing_at_head)
853        ));
854    }
855    match d.cutoff {
856        Some(Cutoff::Shallow) => out.push_str(
857            "\nThis checkout is shallow, and the walk reached its boundary before \
858             the window filled. Fetch more history (`fetch-depth: 0` with \
859             `actions/checkout`) so earlier recordings are visible.\n",
860        ),
861        Some(Cutoff::ScanLimit) => out.push_str(&format!(
862            "\nThe walk stopped at its limit of {} first-parent commits before the \
863             window filled. Recordings older than that were not compared.\n",
864            thousands(SCAN_LIMIT as f64)
865        )),
866        None => {}
867    }
868
869    out.push_str(
870        "\n<sub>Only instruction counts gate, and only a step onto the newest commit. Wall clock \
871         is shown for context — on identical hardware it moves 4-20% run to run.</sub>\n",
872    );
873    if credit {
874        out.push_str(CREDIT);
875    }
876    out
877}
878
879fn list(keys: &[Key]) -> String {
880    keys.iter().map(describe).collect::<Vec<_>>().join(", ")
881}
882
883#[cfg(test)]
884mod tests {
885    use super::*;
886
887    /// The global gate alone, as with no `tak.toml`.
888    fn pct(p: f64) -> Gates {
889        Gates::uniform(Gate::new(p, 0).unwrap())
890    }
891
892    fn rec(bench: &str, runner: &str, ins: f64) -> Record {
893        Record {
894            v: 1,
895            bench: bench.into(),
896            tool: "self".into(),
897            version: None,
898            runner: runner.into(),
899            ts: "2026-01-01T00:00:00Z".into(),
900            metrics: BTreeMap::from([
901                (GATED_METRIC.to_string(), ins),
902                (WALL_METRIC.to_string(), 10.0),
903            ]),
904        }
905    }
906
907    /// A walk named c0, c1, … oldest first, one `a`-on-`gha` value per entry;
908    /// `None` is a commit with nothing recorded.
909    fn walk(values: &[Option<f64>]) -> Vec<(String, Vec<Record>)> {
910        values
911            .iter()
912            .enumerate()
913            .map(|(i, v)| {
914                (
915                    format!("c{i}"),
916                    v.map(|v| vec![rec("a", "gha", v)]).unwrap_or_default(),
917                )
918            })
919            .collect()
920    }
921
922    fn shas(names: &[&str]) -> Vec<String> {
923        names.iter().map(|s| s.to_string()).collect()
924    }
925
926    #[test]
927    fn a_step_onto_the_head_fails() {
928        let d = analyze(
929            &walk(&[Some(1000.0), Some(1000.0), Some(1100.0)]),
930            &pct(1.0),
931        );
932        let f = d.failures();
933        assert_eq!(f.len(), 1);
934        assert_eq!((f[0].from.as_str(), f[0].to.as_str()), ("c1", "c2"));
935        assert_eq!(f[0].commits, 1);
936        assert!(d.earlier.is_empty());
937    }
938
939    /// Both tables name a series in their first cell, inside code spans; a
940    /// pipe in the name must not add a column to either, and a backslash must
941    /// show as recorded rather than doubled.
942    #[test]
943    fn a_pipe_in_a_name_does_not_split_the_row() {
944        let named = |v: f64| vec![rec("a|b", r"win\arm", v)];
945        let d = analyze(
946            &[
947                ("c0".to_string(), named(1000.0)),
948                ("c1".to_string(), named(1100.0)),
949                ("c2".to_string(), named(1100.0)),
950                ("c3".to_string(), named(1210.0)),
951            ],
952            &pct(1.0),
953        );
954        assert_eq!((d.latest.len(), d.earlier.len()), (1, 1));
955        let md = markdown(&d, false);
956        assert_eq!(md.matches(r"| `a\|b` on `win\arm` |").count(), 2, "{md}");
957    }
958
959    #[test]
960    fn a_step_below_the_gate_passes() {
961        let d = analyze(&walk(&[Some(1000.0), Some(1005.0)]), &pct(1.0));
962        assert!(d.failures().is_empty());
963        assert_eq!(d.latest.len(), 1, "it is still reported");
964    }
965
966    #[test]
967    fn an_improvement_never_fails() {
968        let d = analyze(&walk(&[Some(1000.0), Some(500.0)]), &pct(1.0));
969        assert!(d.failures().is_empty());
970    }
971
972    /// The point of gating only the head: the commit after a regression must
973    /// pass, or a main workflow stays red until someone reverts the step.
974    #[test]
975    fn an_older_step_is_reported_not_failed() {
976        let d = analyze(
977            &walk(&[Some(1000.0), Some(1100.0), Some(1100.0)]),
978            &pct(1.0),
979        );
980        assert!(d.failures().is_empty());
981        assert_eq!(d.earlier.len(), 1);
982        assert_eq!(d.earlier[0].to, "c1");
983        assert!(markdown(&d, false).contains("Earlier steps above the 1% gate"));
984    }
985
986    /// Unrecorded commits between two points: the step can only be attributed
987    /// to the range, and naming the later commit alone would blame one that may
988    /// be innocent.
989    #[test]
990    fn a_step_across_unrecorded_commits_is_a_range() {
991        let d = analyze(&walk(&[Some(1000.0), None, None, Some(1100.0)]), &pct(1.0));
992        let f = d.failures();
993        assert_eq!(f.len(), 1, "a range onto the head still fails");
994        assert_eq!((f[0].from.as_str(), f[0].to.as_str()), ("c0", "c3"));
995        assert_eq!(f[0].commits, 3);
996        let md = markdown(&d, false);
997        assert!(md.contains("`c0..c3` (3 commits)"), "{md}");
998        assert!(md.contains("not measured individually"), "{md}");
999    }
1000
1001    /// Ranges are per series. A commit that recorded one benchmark and not
1002    /// another is a point for the first and part of a range for the second.
1003    #[test]
1004    fn ranges_are_per_series() {
1005        let mut w = walk(&[Some(1000.0), Some(1000.0), Some(1000.0)]);
1006        w[0].1.push(rec("b", "gha", 50.0));
1007        w[2].1.push(rec("b", "gha", 60.0));
1008        let d = analyze(&w, &pct(1.0));
1009        let b = d.latest.iter().find(|s| s.key.0 == "b").unwrap();
1010        assert_eq!(b.commits, 2);
1011        let a = d.latest.iter().find(|s| s.key.0 == "a").unwrap();
1012        assert_eq!(a.commits, 1);
1013        assert_eq!(d.failures().len(), 1);
1014    }
1015
1016    /// A runner change starts a new series; it is never a step.
1017    #[test]
1018    fn runners_never_line_up() {
1019        let w = vec![
1020            ("c0".to_string(), vec![rec("a", "gha-linux", 1000.0)]),
1021            ("c1".to_string(), vec![rec("a", "gha-macos", 9000.0)]),
1022        ];
1023        let d = analyze(&w, &pct(1.0));
1024        assert!(d.failures().is_empty());
1025        assert!(d.nothing_compared());
1026        assert_eq!(d.new_at_head.len(), 1);
1027        assert_eq!(d.missing_at_head.len(), 1);
1028        let md = markdown(&d, false);
1029        assert!(md.contains("Nothing was compared"), "{md}");
1030        assert!(md.contains("gha-linux") && md.contains("gha-macos"), "{md}");
1031    }
1032
1033    /// Two runners in the same walk are two independent series, each stepping
1034    /// against itself only.
1035    #[test]
1036    fn runners_are_partitioned_within_a_walk() {
1037        let w = vec![
1038            (
1039                "c0".to_string(),
1040                vec![rec("a", "fast", 1000.0), rec("a", "slow", 5000.0)],
1041            ),
1042            (
1043                "c1".to_string(),
1044                vec![rec("a", "fast", 1000.0), rec("a", "slow", 5200.0)],
1045            ),
1046        ];
1047        let d = analyze(&w, &pct(1.0));
1048        let f = d.failures();
1049        assert_eq!(f.len(), 1);
1050        assert_eq!(f[0].key.2, "slow");
1051        assert_eq!(f[0].instructions.base, 5000.0, "never the other runner's");
1052    }
1053
1054    #[test]
1055    fn creeping_sub_threshold_steps_are_drift() {
1056        let d = analyze(
1057            &walk(&[Some(1000.0), Some(1004.0), Some(1008.0), Some(1012.0)]),
1058            &pct(1.0),
1059        );
1060        assert!(d.failures().is_empty(), "drift never fails");
1061        assert!(d.earlier.is_empty());
1062        assert_eq!(d.drift.len(), 1);
1063        assert_eq!(d.drift[0].since, "c0");
1064        assert_eq!(d.drift[0].points, 4);
1065        let md = markdown(&d, false);
1066        assert!(md.contains("Sustained drift"), "{md}");
1067        assert!(md.contains("+1.20%"), "{md}");
1068    }
1069
1070    #[test]
1071    fn a_flat_series_is_not_drift() {
1072        let d = analyze(&walk(&[Some(1000.0), Some(1003.0), Some(999.0)]), &pct(1.0));
1073        assert!(d.drift.is_empty());
1074    }
1075
1076    /// Drift is measured from after the last real step, so the step is not
1077    /// counted twice and the creep since it is what gets reported.
1078    #[test]
1079    fn drift_starts_after_the_last_step() {
1080        let d = analyze(
1081            &walk(&[
1082                Some(1000.0),
1083                Some(1100.0),
1084                Some(1105.0),
1085                Some(1110.0),
1086                Some(1115.0),
1087            ]),
1088            &pct(1.0),
1089        );
1090        assert_eq!(d.earlier.len(), 1);
1091        assert_eq!(d.drift.len(), 1);
1092        assert_eq!(d.drift[0].since, "c1");
1093        assert_eq!(d.drift[0].change.base, 1100.0);
1094
1095        // Without the creep, the step alone is not drift.
1096        let d = analyze(
1097            &walk(&[Some(1000.0), Some(1100.0), Some(1100.0)]),
1098            &pct(1.0),
1099        );
1100        assert!(d.drift.is_empty());
1101    }
1102
1103    /// A head with nothing recorded compares nothing. It must say so rather
1104    /// than read like a clean pass.
1105    #[test]
1106    fn an_unrecorded_head_says_so() {
1107        let d = analyze(&walk(&[Some(1000.0), Some(1000.0), None]), &pct(1.0));
1108        assert!(d.nothing_compared());
1109        assert!(d.failures().is_empty());
1110        let md = markdown(&d, false);
1111        assert!(md.contains("No instruction counts are recorded"), "{md}");
1112        assert!(md.contains("not at `c2`"), "{md}");
1113    }
1114
1115    #[test]
1116    fn a_filled_window_is_never_cut_short() {
1117        let shallow = || -> Result<bool> { panic!("no need to ask") };
1118        assert_eq!(cutoff(20, 20, true, shallow).unwrap(), None);
1119    }
1120
1121    /// History that goes on past the walk has to be reported, not read as the
1122    /// end of the project.
1123    #[test]
1124    fn hitting_the_scan_limit_is_a_cutoff() {
1125        let shallow = || -> Result<bool> { panic!("the limit decides first") };
1126        assert_eq!(
1127            cutoff(3, 20, true, shallow).unwrap(),
1128            Some(Cutoff::ScanLimit)
1129        );
1130    }
1131
1132    /// Fewer commits than the limit is the end of the available history:
1133    /// a shallow boundary when the clone is shallow, the real root otherwise.
1134    #[test]
1135    fn the_end_of_history_is_a_cutoff_only_when_shallow() {
1136        assert_eq!(
1137            cutoff(3, 20, false, || Ok(true)).unwrap(),
1138            Some(Cutoff::Shallow)
1139        );
1140        assert_eq!(cutoff(3, 20, false, || Ok(false)).unwrap(), None);
1141    }
1142
1143    #[test]
1144    fn each_cutoff_is_named_in_the_report() {
1145        let mut d = analyze(&walk(&[Some(1000.0), Some(1000.0)]), &pct(1.0));
1146        d.cutoff = Some(Cutoff::ScanLimit);
1147        let md = markdown(&d, false);
1148        assert!(md.contains("limit of 10,000 first-parent commits"), "{md}");
1149        d.cutoff = Some(Cutoff::Shallow);
1150        assert!(markdown(&d, false).contains("This checkout is shallow"));
1151        d.cutoff = None;
1152        let md = markdown(&d, false);
1153        assert!(!md.contains("shallow") && !md.contains("limit of"), "{md}");
1154    }
1155
1156    /// Comparing nothing fails unless it was explicitly accepted, and the
1157    /// report says which of the two happened and what to do about it.
1158    #[test]
1159    fn nothing_compared_fails_unless_allowed() {
1160        let mut d = analyze(&walk(&[Some(1000.0)]), &pct(1.0));
1161        assert!(d.nothing_compared());
1162        assert!(d.empty_fails(), "empty is a failure by default");
1163        let md = markdown(&d, false);
1164        assert!(md.contains("so this check fails.**"), "{md}");
1165        assert!(md.contains("pass `--allow-empty`"), "{md}");
1166        assert!(md.contains("set `[gate] allow_empty = true`"), "{md}");
1167        assert!(!md.contains("nothing was gated"), "{md}");
1168        assert!(!md.contains(crate::compare::ALLOWED_EMPTY), "{md}");
1169
1170        d.allow_empty = true;
1171        assert!(!d.empty_fails());
1172        let md = markdown(&d, false);
1173        // The setting's name, whichever of its spellings turned it on, and the
1174        // line saying it passed with a warning and what that can hide.
1175        assert!(md.contains("nothing was gated** (`allow_empty`)"), "{md}");
1176        assert!(md.contains(crate::compare::ALLOWED_EMPTY), "{md}");
1177        assert!(!md.contains("this check fails"), "{md}");
1178    }
1179
1180    /// `--no-gate` means never fail, so it waives an empty comparison too, and
1181    /// the report names it rather than `allow_empty` — even with both on,
1182    /// since `--no-gate` is what decided, and it asked for no warning.
1183    #[test]
1184    fn no_gate_waives_an_empty_comparison() {
1185        let mut d = analyze(&walk(&[Some(1000.0)]), &pct(1.0));
1186        d.no_gate = true;
1187        assert!(!d.empty_fails());
1188        let md = markdown(&d, false);
1189        assert!(md.contains("nothing was gated** (`--no-gate`)"), "{md}");
1190        assert!(!md.contains("this check fails"), "{md}");
1191        d.allow_empty = true;
1192        let md = markdown(&d, false);
1193        assert!(md.contains("nothing was gated** (`--no-gate`)"), "{md}");
1194        assert!(!md.contains(crate::compare::ALLOWED_EMPTY), "{md}");
1195    }
1196
1197    /// `allow_empty` waives the empty case and nothing else: a step onto the
1198    /// head beyond its gate still fails with the setting on.
1199    #[test]
1200    fn allow_empty_does_not_waive_a_step() {
1201        let mut d = analyze(&walk(&[Some(1000.0), Some(1100.0)]), &pct(1.0));
1202        d.allow_empty = true;
1203        assert!(!d.nothing_compared());
1204        assert!(!d.empty_fails());
1205        assert_eq!(d.failures().len(), 1);
1206        assert!(!markdown(&d, false).contains(crate::compare::ALLOWED_EMPTY));
1207    }
1208
1209    /// A comparison that happened is never an empty one, whatever the flag.
1210    #[test]
1211    fn a_real_comparison_is_not_empty() {
1212        let d = analyze(&walk(&[Some(1000.0), Some(1000.0)]), &pct(1.0));
1213        assert!(!d.empty_fails());
1214    }
1215
1216    /// Only instruction counts may drive a failure, however much wall clock
1217    /// moved. A series with no instruction counts is not examined at all.
1218    #[test]
1219    fn wall_clock_never_gates() {
1220        let mut w = walk(&[Some(1000.0), Some(1000.0)]);
1221        w[1].1[0].metrics.insert(WALL_METRIC.into(), 1000.0);
1222        for (at, wall) in [(0, 1.0), (1, 100.0)] {
1223            let mut r = rec("w", "gha", 0.0);
1224            r.metrics = BTreeMap::from([(WALL_METRIC.to_string(), wall)]);
1225            w[at].1.push(r);
1226        }
1227        let d = analyze(&w, &pct(0.001));
1228        assert!(d.failures().is_empty());
1229        assert!(d.latest.iter().all(|s| s.key.0 == "a"));
1230    }
1231
1232    /// A re-run's noisy duplicate collapses to the minimum, as in `compare`.
1233    #[test]
1234    fn duplicates_reduce_to_the_minimum() {
1235        let mut w = walk(&[Some(1000.0), Some(1000.0)]);
1236        w[1].1.push(rec("a", "gha", 3000.0));
1237        assert!(analyze(&w, &pct(1.0)).failures().is_empty());
1238    }
1239
1240    #[test]
1241    fn a_rise_from_zero_fails() {
1242        let d = analyze(&walk(&[Some(0.0), Some(5.0)]), &pct(1.0));
1243        assert_eq!(d.failures().len(), 1);
1244    }
1245
1246    #[test]
1247    fn an_empty_walk_is_nothing_compared() {
1248        let d = analyze(&[], &pct(1.0));
1249        assert!(d.nothing_compared());
1250        assert!(markdown(&d, false).contains("Only instruction counts gate"));
1251    }
1252
1253    #[test]
1254    fn the_window_counts_recorded_commits() {
1255        let newest_first = shas(&["h", "x1", "r1", "x2", "r2", "r3", "x3"]);
1256        let annotated: BTreeSet<String> = shas(&["h", "r1", "r2", "r3"]).into_iter().collect();
1257        assert_eq!(
1258            select(&newest_first, &annotated, 3),
1259            shas(&["r2", "x2", "r1", "x1", "h"])
1260        );
1261    }
1262
1263    /// The head belongs to the walk even with nothing recorded, and history
1264    /// older than the oldest recorded commit does not.
1265    #[test]
1266    fn the_head_is_always_walked() {
1267        let newest_first = shas(&["h", "x1", "r1", "x2"]);
1268        let annotated: BTreeSet<String> = shas(&["r1"]).into_iter().collect();
1269        assert_eq!(
1270            select(&newest_first, &annotated, 20),
1271            shas(&["r1", "x1", "h"])
1272        );
1273        assert_eq!(select(&shas(&["h"]), &BTreeSet::new(), 20), shas(&["h"]));
1274        assert!(select(&[], &BTreeSet::new(), 20).is_empty());
1275    }
1276
1277    #[test]
1278    fn the_trend_covers_the_window() {
1279        let d = analyze(&walk(&[Some(1.0), None, Some(2.0), Some(3.0)]), &pct(1.0));
1280        let key = ("a".to_string(), "self".to_string(), "gha".to_string());
1281        assert_eq!(d.trend[&key], vec![1.0, 2.0, 3.0]);
1282    }
1283
1284    /// A 1% global gate, with benchmark `a` given its own.
1285    fn gates_with_a(a_pct: f64, min_delta: u64, enabled: bool) -> Gates {
1286        let mut g = pct(1.0);
1287        g.set_bench(
1288            "a",
1289            Gate {
1290                pct: a_pct,
1291                min_delta,
1292                enabled,
1293            },
1294        );
1295        g
1296    }
1297
1298    /// `a` and `b` both step +10% onto the head.
1299    fn two_series_step() -> Vec<(String, Vec<Record>)> {
1300        vec![
1301            (
1302                "c0".to_string(),
1303                vec![rec("a", "gha", 1000.0), rec("b", "gha", 1000.0)],
1304            ),
1305            (
1306                "c1".to_string(),
1307                vec![rec("a", "gha", 1100.0), rec("b", "gha", 1100.0)],
1308            ),
1309        ]
1310    }
1311
1312    /// Each series is held to its own gate: `a`'s 20% lets its 10% step
1313    /// through while `b`, at the global 1%, fails on the same step.
1314    #[test]
1315    fn a_step_is_held_to_its_own_series_gate() {
1316        let d = analyze(&two_series_step(), &gates_with_a(20.0, 0, true));
1317        let f = d.failures();
1318        assert_eq!(f.len(), 1);
1319        assert_eq!(f[0].key.0, "b");
1320        assert!(!d.uniform());
1321        let md = markdown(&d, false);
1322        assert!(md.contains("| gate |"), "{md}");
1323        assert!(md.contains("stepped above their gate"), "{md}");
1324        assert!(md.contains("(gate 1%)"), "{md}");
1325    }
1326
1327    /// The floor applies as well: a 100-instruction step is 10% of `a`, far
1328    /// past its percentage, and still within a 500-instruction floor.
1329    #[test]
1330    fn a_step_within_its_floor_passes() {
1331        let d = analyze(&two_series_step(), &gates_with_a(1.0, 500, true));
1332        let f = d.failures();
1333        assert_eq!(f.len(), 1);
1334        assert_eq!(f[0].key.0, "b");
1335        assert!(markdown(&d, false).contains("floor 500"));
1336    }
1337
1338    /// A report-only benchmark is examined like any other and flagged when it
1339    /// crosses its threshold, but it can never fail the command.
1340    #[test]
1341    fn a_report_only_step_is_reported_and_never_fails() {
1342        let d = analyze(&two_series_step(), &gates_with_a(1.0, 0, false));
1343        let f = d.failures();
1344        assert_eq!(f.len(), 1, "only the gated one fails");
1345        assert_eq!(f[0].key.0, "b");
1346        assert_eq!(d.reported().len(), 1);
1347        assert_eq!(d.reported()[0].key.0, "a");
1348        let md = markdown(&d, false);
1349        assert!(md.contains("**+10.00%** (not gated)"), "{md}");
1350        assert!(md.contains("report only (1%)"), "{md}");
1351        assert!(
1352            md.contains("1 report-only benchmark(s) stepped above their gate"),
1353            "{md}"
1354        );
1355
1356        // With nothing gated at all, the verdict says so rather than passing.
1357        let mut all = gates_with_a(1.0, 0, false);
1358        all.set_bench(
1359            "b",
1360            Gate {
1361                pct: 1.0,
1362                min_delta: 0,
1363                enabled: false,
1364            },
1365        );
1366        let d = analyze(&two_series_step(), &all);
1367        assert!(d.failures().is_empty());
1368        assert!(!d.empty_fails());
1369        assert!(markdown(&d, false).contains("Every benchmark here is report-only"));
1370    }
1371
1372    /// An earlier step on a report-only benchmark is listed like any other.
1373    #[test]
1374    fn earlier_steps_use_the_series_gate() {
1375        let w = walk(&[Some(1000.0), Some(1100.0), Some(1100.0)]);
1376        assert_eq!(analyze(&w, &gates_with_a(20.0, 0, true)).earlier.len(), 0);
1377        assert_eq!(analyze(&w, &gates_with_a(1.0, 0, false)).earlier.len(), 1);
1378    }
1379
1380    /// Drift is held to the series' gate too: a 1.2% creep is drift at the
1381    /// global 1%, not under `a`'s own 5%, and not within a floor of 50.
1382    #[test]
1383    fn drift_uses_the_series_gate() {
1384        let w = walk(&[Some(1000.0), Some(1004.0), Some(1008.0), Some(1012.0)]);
1385        assert_eq!(analyze(&w, &pct(1.0)).drift.len(), 1);
1386        assert!(analyze(&w, &gates_with_a(5.0, 0, true)).drift.is_empty());
1387        assert!(analyze(&w, &gates_with_a(1.0, 50, true)).drift.is_empty());
1388
1389        // Report-only drift is still reported: reporting is all drift does.
1390        let d = analyze(&w, &gates_with_a(1.0, 0, false));
1391        assert_eq!(d.drift.len(), 1);
1392        assert!(markdown(&d, false).contains("(gate report only (1%))"));
1393    }
1394
1395    /// With every series at the global gate, the report reads as it did
1396    /// before per-benchmark gates: no gate column, one `N%` in the prose.
1397    #[test]
1398    fn a_uniform_report_keeps_its_wording() {
1399        let d = analyze(&two_series_step(), &pct(1.0));
1400        assert!(d.uniform());
1401        let md = markdown(&d, false);
1402        assert!(!md.contains("| gate |"), "{md}");
1403        assert!(md.contains("stepped above the 1% gate"), "{md}");
1404    }
1405
1406    fn flags(names: &[&str]) -> Acceptances {
1407        let mut a = Acceptances::default();
1408        for n in names {
1409            a.add_name(n, crate::accept::Source::Flag).unwrap();
1410        }
1411        a
1412    }
1413
1414    /// `--accept` waives the step onto the head for the benchmark it names,
1415    /// and only that one; the report says it was accepted and by what.
1416    #[test]
1417    fn an_accepted_step_is_reported_and_does_not_fail() {
1418        let mut d = analyze(&two_series_step(), &pct(1.0));
1419        d.accept(&flags(&["a"]), &BTreeMap::new());
1420        let f = d.failures();
1421        assert_eq!(f.len(), 1, "b is not accepted");
1422        assert_eq!(f[0].key.0, "b");
1423        assert_eq!(d.accepted_steps().len(), 1);
1424        let md = markdown(&d, false);
1425        assert!(md.contains("**+10.00%** (accepted)"), "{md}");
1426        assert!(
1427            md.contains("1 accepted step(s) above the 1% gate at `c1`, not failing:"),
1428            "{md}"
1429        );
1430        assert!(md.contains("(accepted by `--accept`)"), "{md}");
1431
1432        d.accept(&flags(&["a", "b"]), &BTreeMap::new());
1433        assert!(d.failures().is_empty());
1434        // Nothing fails, but claiming no step crossed the gate would be false.
1435        let md = markdown(&d, false);
1436        assert!(!md.contains("No instruction-count step"), "{md}");
1437        assert!(md.contains("2 accepted step(s)"), "{md}");
1438    }
1439
1440    /// A trailer counts only for a step whose range holds it. The log is keyed
1441    /// by each step's `from`, so a trailer read for one range never accepts a
1442    /// step from another.
1443    #[test]
1444    fn a_trailer_counts_only_in_its_steps_range() {
1445        let w = vec![
1446            ("c0".to_string(), vec![rec("a", "gha", 1000.0)]),
1447            ("c1".to_string(), vec![rec("b", "gha", 1000.0)]),
1448            (
1449                "c2".to_string(),
1450                vec![rec("a", "gha", 1100.0), rec("b", "gha", 1100.0)],
1451            ),
1452        ];
1453        let mut d = analyze(&w, &pct(1.0));
1454        let a = d.latest.iter().find(|s| s.key.0 == "a").unwrap();
1455        assert_eq!(a.from, "c0");
1456        // `Tak-Accept: a` and `Tak-Accept: b` on c1, which is in c0..c2 but
1457        // not in c1..c2. The log joins a commit's trailers with NUL.
1458        let logs = BTreeMap::from([
1459            ("c0".to_string(), "c2\0\nc1\0a\0b\n".to_string()),
1460            ("c1".to_string(), "c2\0\n".to_string()),
1461        ]);
1462        d.accept(&Acceptances::default(), &logs);
1463        let f = d.failures();
1464        assert_eq!(f.len(), 1);
1465        assert_eq!(f[0].key.0, "b", "c1 is outside b's range");
1466        let md = markdown(&d, false);
1467        assert!(md.contains("(accepted by `Tak-Accept` in `c1`)"), "{md}");
1468    }
1469
1470    /// An acceptance that waived nothing is reported, not dropped, so a stale
1471    /// one is visible before it matters.
1472    #[test]
1473    fn an_unused_acceptance_is_reported() {
1474        let mut d = analyze(&walk(&[Some(1000.0), Some(1000.0)]), &pct(1.0));
1475        d.accept(&flags(&["a", "nope"]), &BTreeMap::new());
1476        let md = markdown(&d, false);
1477        assert!(
1478            md.contains("no step onto `c1` needed it, so nothing was accepted: `a` (`--accept`), `nope` (`--accept`)"),
1479            "{md}"
1480        );
1481    }
1482
1483    /// Including when nothing was compared, where it matters most: with
1484    /// `allow_empty` a stale or misspelt acceptance would otherwise pass
1485    /// without a word. `tak compare` prints its line on that path too.
1486    #[test]
1487    fn an_unused_acceptance_is_reported_when_nothing_was_compared() {
1488        let mut d = analyze(&walk(&[Some(1000.0)]), &pct(1.0));
1489        d.allow_empty = true;
1490        d.accept(&flags(&["startupp"]), &BTreeMap::new());
1491        assert!(d.nothing_compared());
1492        let md = markdown(&d, false);
1493        assert!(md.contains("Nothing was compared"), "{md}");
1494        assert!(
1495            md.contains("so nothing was accepted: `startupp` (`--accept`)"),
1496            "{md}"
1497        );
1498    }
1499
1500    /// Only the head's step can be accepted: an older step of an accepted
1501    /// benchmark is still listed as an earlier step, not as accepted.
1502    #[test]
1503    fn an_older_step_is_never_marked_accepted() {
1504        let mut d = analyze(
1505            &walk(&[Some(1000.0), Some(1100.0), Some(1100.0)]),
1506            &pct(1.0),
1507        );
1508        d.accept(&flags(&["a"]), &BTreeMap::new());
1509        assert_eq!(d.earlier.len(), 1);
1510        let md = markdown(&d, false);
1511        assert!(!md.contains("(accepted)"), "{md}");
1512        assert!(md.contains("**+10.00%** ⚠️"), "{md}");
1513    }
1514
1515    /// The trailer parser is shared with `tak compare`: one trailer names one
1516    /// benchmark, commas included. `Tak-Accept: a,b` names neither `a` nor `b`,
1517    /// so both steps still fail and `a,b` is reported as waiving nothing.
1518    #[test]
1519    fn a_comma_trailer_names_one_benchmark() {
1520        let mut d = analyze(&two_series_step(), &pct(1.0));
1521        let logs = BTreeMap::from([
1522            ("c0".to_string(), "c1\0a,b\n".to_string()),
1523            ("c1".to_string(), "c1\0a,b\n".to_string()),
1524        ]);
1525        d.accept(&Acceptances::default(), &logs);
1526        assert_eq!(d.failures().len(), 2, "neither `a` nor `b` was named");
1527        let md = markdown(&d, false);
1528        assert!(!md.contains("(accepted"), "{md}");
1529        assert!(md.contains("so nothing was accepted: `a,b`"), "{md}");
1530    }
1531
1532    /// Names in the acceptance lines cannot start a report line of their own:
1533    /// a newline is written as `\n`, so no echoed name reads as a verdict to a
1534    /// check that matches on line starts.
1535    #[test]
1536    fn a_control_character_in_an_acceptance_is_escaped() {
1537        let mut d = analyze(&two_series_step(), &pct(1.0));
1538        d.accept(
1539            &flags(&["x\n**1 benchmark(s) stepped above"]),
1540            &BTreeMap::new(),
1541        );
1542        d.ignored_trailers.add_trailer_log("c1\0y\u{1b}z\n");
1543        let md = markdown(&d, false);
1544        assert!(md.contains("`x\\n**1 benchmark(s) stepped above`"), "{md}");
1545        assert!(md.contains("`y\\u{1b}z`"), "{md}");
1546        assert_eq!(
1547            md.lines()
1548                .filter(|l| l.starts_with("**1 benchmark(s) stepped above"))
1549                .count(),
1550            0,
1551            "{md}"
1552        );
1553    }
1554
1555    #[test]
1556    fn ignored_trailers_are_named() {
1557        let mut d = analyze(&two_series_step(), &pct(1.0));
1558        d.ignored_trailers.add_trailer_log("c1\0a\n");
1559        assert_eq!(d.failures().len(), 2, "an ignored trailer accepts nothing");
1560        let md = markdown(&d, false);
1561        assert!(
1562            md.contains("`Tak-Accept` trailers were found but not honoured, because `gate.accept_trailers` is off: `a` (`Tak-Accept` in `c1`)"),
1563            "{md}"
1564        );
1565    }
1566}