Skip to main content

greengate_runtime/
gate_evidence.rs

1//! What the stamps ADD UP TO — the statistics side of
2//! [`crate::gate_stamp`].
3//!
4//! Every push that runs a gate leaves a `run` line in a note keyed by the
5//! tree the gate ran against (see that module's "second half of the note").
6//! Across a few weeks that is a per-gate outcome dataset, already on the
7//! machine, that nothing read. This module reads it, and answers two
8//! questions with it:
9//!
10//! 1. **Is a gate still doing its job?** The fleet audit of 2026-09-19 found
11//!    four mechanisms that had stopped checking anything and said nothing
12//!    about it: a nested lockfile audited from the repository root, a
13//!    `govulncheck` built with a Go too old for the database, `uv` invoked
14//!    without a `.venv`, and an `npm` that silently timed out. Each one went
15//!    green. Each one, on the record here, also went from minutes to
16//!    milliseconds on the day it broke. [`summarise`] is that comparison,
17//!    made explicit.
18//! 2. **Which gate should run first?** With `order = evidence`, the push
19//!    gates are ordered by what the record says they cost and how often they
20//!    catch something, so a push that is going to fail fails early. See
21//!    [`order_by_evidence`].
22//!
23//! # Three rules this module obeys
24//!
25//! **It never skips a check.** Ordering is a permutation; nothing here
26//! removes a gate, shortens one or lets one be assumed to pass. A prediction
27//! that a gate will pass is not evidence that it did, and a check that does
28//! not run cannot be stamped or attested — the whole chain from
29//! [`crate::gate_stamp`] to [`crate::attest`] rests on a record of a run that
30//! happened, and a statistical model of one is not that.
31//!
32//! **It abstains rather than guessing.** Under [`Thresholds::min_runs`]
33//! verdicts a gate is reported with its counts and NO flags, and the report
34//! says why in words (`insufficient history (2 runs)`). A dashboard that
35//! calls a two-run gate "flaky" teaches people to ignore the column.
36//!
37//! **Its thresholds are numbers, written down.** Every flag below names the
38//! comparison it made and the number it made it against, both in the report
39//! and in `docs/gate-evidence.md`, and every one of them is a flag on the
40//! command line. A heuristic nobody can see the inside of is a heuristic
41//! nobody can argue with.
42
43use std::collections::BTreeMap;
44use std::path::Path;
45
46use crate::gate_stamp::{Note, Run, RunOutcome, NOTES_REF};
47
48/// Seconds since the epoch, or 0 if the clock is before it. The record is
49/// local and single-machine, so this is the same clock on both sides of every
50/// comparison made here.
51pub fn now() -> u64 {
52    std::time::SystemTime::now()
53        .duration_since(std::time::UNIX_EPOCH)
54        .map(|d| d.as_secs())
55        .unwrap_or(0)
56}
57
58/// Every run recorded in one repository, with the fingerprint each was
59/// recorded against.
60///
61/// The fingerprint is the note's key — the git tree the gate ran on. Two runs
62/// with the same fingerprint read identical content, which is what makes
63/// disagreement between them evidence of flakiness rather than of a change.
64#[derive(Debug, Clone, Default, PartialEq, Eq)]
65pub struct History {
66    pub runs: Vec<(String, Run)>,
67}
68
69impl History {
70    pub fn is_empty(&self) -> bool {
71        self.runs.is_empty()
72    }
73
74    /// The runs inside the window, newest last. `window_days` of 0 means
75    /// "everything recorded".
76    fn within(&self, now: u64, window_days: u64) -> Vec<(&str, &Run)> {
77        let floor = if window_days == 0 {
78            0
79        } else {
80            now.saturating_sub(window_days.saturating_mul(86_400))
81        };
82        let mut runs: Vec<(&str, &Run)> = self
83            .runs
84            .iter()
85            .filter(|(_, r)| r.at >= floor)
86            .map(|(fp, r)| (fp.as_str(), r))
87            .collect();
88        // Ties broken by gate name so the order is total, and the report of
89        // one repository is the same on two machines reading one ref.
90        runs.sort_by(|a, b| a.1.at.cmp(&b.1.at).then_with(|| a.1.gate.cmp(&b.1.gate)));
91        runs
92    }
93}
94
95/// Read one repository's recorded runs.
96///
97/// Two spawns whatever the size of the history: `notes list` names every note
98/// and its object, and one `cat-file --batch` reads all the bodies. A git
99/// that will not answer, an absent ref and a repository with no history are
100/// the same empty answer — a report that cannot be built is reported as
101/// missing, never as zero.
102pub fn history_in(repo: &Path) -> History {
103    // holds-until: Phase 4 of the notes-names plan flips `WRITE`; this
104    // reader moves to both name sets in that same change.
105    let Some(list) = crate::git::stdout_in(repo, &["notes", "--ref", NOTES_REF, "list"]) else {
106        return History::default();
107    };
108    // `<note blob> <annotated object>` per line. The annotated object is the
109    // fingerprint; the blob is what `cat-file` is about to be asked for.
110    let mut keyed: BTreeMap<String, String> = BTreeMap::new();
111    let mut stdin = String::new();
112    for line in list.lines() {
113        let mut t = line.split_whitespace();
114        if let (Some(blob), Some(object)) = (t.next(), t.next()) {
115            keyed.insert(blob.to_string(), object.to_string());
116            stdin.push_str(blob);
117            stdin.push('\n');
118        }
119    }
120    if keyed.is_empty() {
121        return History::default();
122    }
123    let Some(batch) = crate::git::stdout_piped_in(repo, &["cat-file", "--batch"], stdin.as_bytes())
124    else {
125        return History::default();
126    };
127    let mut history = History::default();
128    for (blob, body) in parse_batch(&batch) {
129        let Some(fingerprint) = keyed.get(&blob) else {
130            continue;
131        };
132        for run in Note::parse(&body).runs {
133            history.runs.push((fingerprint.clone(), run));
134        }
135    }
136    history
137}
138
139/// Split `git cat-file --batch` output into `(object id, body)`.
140///
141/// Line-oriented rather than byte-counted, and that is a deliberate trade.
142/// The header git writes is `<oid> <type> <size>`, and a body line could in
143/// principle look like one — but every body this ref holds was written by
144/// [`crate::gate_stamp`], whose lines begin `amont-gate-` or `run `. The
145/// alternative, honouring the byte count, cannot be written against a helper
146/// that trims its output, and a note this reader misreads costs a row in a
147/// report rather than a verdict.
148fn parse_batch(out: &str) -> Vec<(String, String)> {
149    let mut found = Vec::new();
150    let mut current: Option<(String, Vec<&str>)> = None;
151    for line in out.lines() {
152        let mut t = line.split_whitespace();
153        let (oid, kind, size) = (t.next(), t.next(), t.next());
154        let is_header = matches!((oid, kind, size), (Some(o), Some("blob"), Some(s))
155            if o.len() >= 40
156                && o.chars().all(|c| c.is_ascii_hexdigit())
157                && s.parse::<u64>().is_ok()
158                && t.next().is_none());
159        if is_header {
160            if let Some((oid, body)) = current.take() {
161                found.push((oid, body.join("\n")));
162            }
163            current = Some((oid.unwrap_or_default().to_string(), Vec::new()));
164            continue;
165        }
166        if let Some((_, body)) = current.as_mut() {
167            body.push(line);
168        }
169    }
170    if let Some((oid, body)) = current.take() {
171        found.push((oid, body.join("\n")));
172    }
173    found
174}
175
176/// The numbers every flag below is decided against. Defaults are documented
177/// in `docs/gate-evidence.md` and overridable per invocation.
178#[derive(Debug, Clone, Copy, PartialEq, Eq)]
179pub struct Thresholds {
180    /// How far back the report looks, in days. 0 means the whole record.
181    pub window_days: u64,
182    /// Verdicts below which no flag is computed and the report says so.
183    pub min_runs: usize,
184    /// A last duration below this percentage of the median is a collapse.
185    pub noop_ratio_percent: u64,
186    /// …but only for a gate whose median is at least this many seconds. A
187    /// gate that has always taken 200 ms has no collapse to detect.
188    pub noop_median_secs: u64,
189    /// A pass faster than this, from a gate that has never once passed this
190    /// fast, is the other shape of the same failure.
191    pub fast_pass_ms: u64,
192    /// How many later fingerprints may go by without this gate running before
193    /// it is called stale.
194    pub stale_runs: usize,
195    /// …or how many days, when other gates have run more recently.
196    pub stale_days: u64,
197}
198
199impl Default for Thresholds {
200    fn default() -> Self {
201        Thresholds {
202            window_days: 90,
203            min_runs: 5,
204            noop_ratio_percent: 10,
205            noop_median_secs: 30,
206            fast_pass_ms: 1_000,
207            stale_runs: 10,
208            stale_days: 30,
209        }
210    }
211}
212
213#[derive(Debug, Clone, Copy, PartialEq, Eq)]
214pub enum FlagKind {
215    /// The gate stopped doing the work it used to do.
216    NoOpSuspect,
217    /// One fingerprint, two answers.
218    Flaky,
219    /// It has not run while its neighbours have.
220    Stale,
221}
222
223impl FlagKind {
224    pub fn as_str(self) -> &'static str {
225        match self {
226            FlagKind::NoOpSuspect => "no-op suspect",
227            FlagKind::Flaky => "flaky",
228            FlagKind::Stale => "stale",
229        }
230    }
231}
232
233/// A flag and the comparison that raised it. The reason travels WITH the
234/// flag: a dashboard cell saying "no-op suspect" and nothing else is an
235/// accusation, and nobody can check an accusation.
236#[derive(Debug, Clone, PartialEq, Eq)]
237pub struct Flag {
238    pub kind: FlagKind,
239    pub why: String,
240}
241
242/// What the record says about one gate in one repository.
243#[derive(Debug, Clone, PartialEq, Eq)]
244pub struct GateReport {
245    pub gate: String,
246    /// Runs in the window, of every outcome.
247    pub runs: usize,
248    pub passed: usize,
249    pub failed: usize,
250    /// Ran and did not judge: the tool was missing, or the repository lacks
251    /// what turns the gate on. Counted apart from a pass, always — this is
252    /// the number the fleet audit was blind to.
253    pub unavailable: usize,
254    /// Median wall-clock of the runs that reached a verdict, milliseconds.
255    pub median_ms: u64,
256    pub last_ms: u64,
257    pub last_at: u64,
258    pub last_outcome: Option<RunOutcome>,
259    /// Distinct fingerprints this gate ran against.
260    pub fingerprints: usize,
261    /// Fingerprints that other gates judged AFTER this gate last ran, and
262    /// that this gate did not. The "in pushes" half of staleness.
263    pub missed: usize,
264    pub flags: Vec<Flag>,
265    /// Set when the history is too short to say anything, with the count in
266    /// words. A report that abstains says so; it does not print an empty
267    /// flags column that reads as "all clear".
268    pub abstained: Option<String>,
269}
270
271impl GateReport {
272    /// Age of the last run in whole days.
273    pub fn last_age_days(&self, now: u64) -> u64 {
274        now.saturating_sub(self.last_at) / 86_400
275    }
276}
277
278/// The per-gate report for one repository's history.
279///
280/// Pure over `now`, so a test can hand it a clock. Gates appear in name
281/// order; a gate that has never run does not appear at all, because this
282/// record only knows what ran — `amont list` is the answer to what is
283/// declared.
284pub fn summarise(history: &History, now: u64, t: &Thresholds) -> Vec<GateReport> {
285    let runs = history.within(now, t.window_days);
286    let mut by_gate: BTreeMap<&str, Vec<(&str, &Run)>> = BTreeMap::new();
287    for &(fp, run) in &runs {
288        by_gate
289            .entry(run.gate.as_str())
290            .or_default()
291            .push((fp, run));
292    }
293    by_gate
294        .into_iter()
295        .map(|(gate, mine)| one_gate(gate, &mine, &runs, now, t))
296        .collect()
297}
298
299fn one_gate(
300    gate: &str,
301    mine: &[(&str, &Run)],
302    all: &[(&str, &Run)],
303    now: u64,
304    t: &Thresholds,
305) -> GateReport {
306    let verdicts: Vec<(&str, &Run)> = mine
307        .iter()
308        .filter(|(_, r)| r.outcome.is_verdict())
309        .copied()
310        .collect();
311    let passed = verdicts
312        .iter()
313        .filter(|(_, r)| r.outcome == RunOutcome::Passed)
314        .count();
315    let failed = verdicts.len() - passed;
316    let unavailable = mine
317        .iter()
318        .filter(|(_, r)| r.outcome == RunOutcome::Unavailable)
319        .count();
320    let median_ms = median(&verdicts.iter().map(|(_, r)| r.ms).collect::<Vec<_>>());
321    let last = mine.last().copied();
322    let mut fingerprints: Vec<&str> = mine.iter().map(|(fp, _)| *fp).collect();
323    fingerprints.sort_unstable();
324    fingerprints.dedup();
325
326    // Fingerprints judged by ANY gate after this one last ran, minus the ones
327    // this gate was part of. "Other gates kept working and this one did not"
328    // is the whole claim, so it is counted rather than inferred from a date.
329    let last_at = last.map(|(_, r)| r.at).unwrap_or(0);
330    let mut later: Vec<&str> = all
331        .iter()
332        .filter(|(_, r)| r.at > last_at && r.gate != gate)
333        .map(|(fp, _)| *fp)
334        .collect();
335    later.sort_unstable();
336    later.dedup();
337    let missed = later
338        .iter()
339        .filter(|fp| !fingerprints.contains(*fp))
340        .count();
341
342    let mut report = GateReport {
343        gate: gate.to_string(),
344        runs: mine.len(),
345        passed,
346        failed,
347        unavailable,
348        median_ms,
349        last_ms: last.map(|(_, r)| r.ms).unwrap_or(0),
350        last_at,
351        last_outcome: last.map(|(_, r)| r.outcome),
352        fingerprints: fingerprints.len(),
353        missed,
354        flags: Vec::new(),
355        abstained: None,
356    };
357
358    // Staleness is decided first, because it is the one question a short
359    // history can still answer: it is a claim about the OTHER gates' record,
360    // not about the distribution of this one's.
361    if let Some(flag) = stale_flag(&report, all, now, t) {
362        report.flags.push(flag);
363    }
364
365    if verdicts.len() < t.min_runs {
366        report.abstained = Some(format!(
367            "insufficient history ({} verdict{})",
368            verdicts.len(),
369            if verdicts.len() == 1 { "" } else { "s" }
370        ));
371        return report;
372    }
373
374    if let Some(flag) = noop_flag(&verdicts, median_ms, t) {
375        report.flags.push(flag);
376    }
377    if let Some(flag) = flaky_flag(gate, &verdicts) {
378        report.flags.push(flag);
379    }
380    report
381}
382
383/// Did the gate's cost collapse?
384///
385/// Two shapes of the same failure, and both are needed: a suite that used to
386/// take eleven minutes and now takes 0.4 s is caught by the ratio; a gate
387/// installed broken — passing in milliseconds from its very first run — has
388/// no earlier median to collapse from, and is caught by the second rule only
389/// once it has enough verdicts to be sure it never once did real work.
390fn noop_flag(verdicts: &[(&str, &Run)], median_ms: u64, t: &Thresholds) -> Option<Flag> {
391    let (_, last) = *verdicts.last()?;
392    if median_ms >= t.noop_median_secs.saturating_mul(1_000)
393        && last.ms.saturating_mul(100) < median_ms.saturating_mul(t.noop_ratio_percent)
394    {
395        return Some(Flag {
396            kind: FlagKind::NoOpSuspect,
397            why: format!(
398                "last run {} against a median of {} ({}% of it, threshold {}%)",
399                duration(last.ms),
400                duration(median_ms),
401                last.ms.saturating_mul(100) / median_ms.max(1),
402                t.noop_ratio_percent
403            ),
404        });
405    }
406    if last.outcome == RunOutcome::Passed
407        && last.ms < t.fast_pass_ms
408        && verdicts[..verdicts.len() - 1]
409            .iter()
410            .all(|(_, r)| r.ms >= t.fast_pass_ms)
411    {
412        return Some(Flag {
413            kind: FlagKind::NoOpSuspect,
414            why: format!(
415                "passed in {}, and none of the {} earlier runs ever finished under {}",
416                duration(last.ms),
417                verdicts.len() - 1,
418                duration(t.fast_pass_ms)
419            ),
420        });
421    }
422    None
423}
424
425/// One fingerprint, two answers. The content did not change between them, so
426/// something else decided the verdict.
427fn flaky_flag(gate: &str, verdicts: &[(&str, &Run)]) -> Option<Flag> {
428    let mut by_fp: BTreeMap<&str, (usize, usize)> = BTreeMap::new();
429    for &(fp, run) in verdicts {
430        let e = by_fp.entry(fp).or_insert((0, 0));
431        if run.outcome == RunOutcome::Passed {
432            e.0 += 1;
433        } else {
434            e.1 += 1;
435        }
436    }
437    let split: Vec<(&str, usize, usize)> = by_fp
438        .into_iter()
439        .filter(|(_, (pass, fail))| *pass > 0 && *fail > 0)
440        .map(|(fp, (pass, fail))| (fp, pass, fail))
441        .collect();
442    let (fp, pass, fail) = *split.first()?;
443    Some(Flag {
444        kind: FlagKind::Flaky,
445        why: format!(
446            "{gate} both passed ({pass}) and failed ({fail}) on tree {}{}",
447            short(fp),
448            if split.len() > 1 {
449                format!(", and on {} other tree(s)", split.len() - 1)
450            } else {
451                String::new()
452            }
453        ),
454    })
455}
456
457/// Has it stopped running while its neighbours kept going?
458fn stale_flag(report: &GateReport, all: &[(&str, &Run)], now: u64, t: &Thresholds) -> Option<Flag> {
459    if report.runs == 0 {
460        return None;
461    }
462    let newest_other = all
463        .iter()
464        .filter(|(_, r)| r.gate != report.gate)
465        .map(|(_, r)| r.at)
466        .max()?;
467    if newest_other <= report.last_at {
468        return None;
469    }
470    if report.missed >= t.stale_runs {
471        return Some(Flag {
472            kind: FlagKind::Stale,
473            why: format!(
474                "{} later tree(s) were judged by other gates and not by this one (threshold {})",
475                report.missed, t.stale_runs
476            ),
477        });
478    }
479    let age = report.last_age_days(now);
480    if age >= t.stale_days {
481        return Some(Flag {
482            kind: FlagKind::Stale,
483            why: format!(
484                "last ran {age} days ago (threshold {}), while another gate ran {} days ago",
485                t.stale_days,
486                now.saturating_sub(newest_other) / 86_400
487            ),
488        });
489    }
490    None
491}
492
493/// The order the push gates should be attempted in, as a permutation of the
494/// indices of `gates`.
495///
496/// **What this is not.** It is not a prediction that a gate will fail, and
497/// nothing is skipped on the strength of it: every gate in `gates` appears in
498/// the result exactly once. Fail-fast is what makes the order worth anything
499/// — pre-push already stops at the first blocking failure — so ordering only
500/// changes WHEN the news arrives, never WHETHER it does.
501///
502/// **The rule.** Gates that have actually failed in the window are promoted,
503/// ordered by failures per unit of time: `failures / runs / median duration`,
504/// compared as integers by cross-multiplication so the order is exact and the
505/// same everywhere. That ratio, and not the failure rate alone, is what
506/// minimises the expected time spent before a failing push fails — a gate
507/// that fails one push in ten and takes five seconds is worth attempting
508/// before one that fails one in three and takes twenty minutes.
509///
510/// Everything else — a gate that has never failed, and every gate with no
511/// record at all — keeps its declared order, after the promoted ones. The
512/// declared index is the final tie-break, so the result is deterministic for
513/// a given history.
514pub fn order_by_evidence(
515    gates: &[String],
516    history: &History,
517    now: u64,
518    window_days: u64,
519) -> Vec<usize> {
520    let runs = history.within(now, window_days);
521    let mut stats: BTreeMap<&str, (u64, u64, Vec<u64>)> = BTreeMap::new();
522    for (_, run) in &runs {
523        if !run.outcome.is_verdict() {
524            continue;
525        }
526        let e = stats.entry(run.gate.as_str()).or_insert((0, 0, Vec::new()));
527        e.0 += 1;
528        if run.outcome == RunOutcome::Failed {
529            e.1 += 1;
530        }
531        e.2.push(run.ms);
532    }
533    // (failures, runs, median ms) per declared gate, or None with no record.
534    let weight = |name: &String| -> Option<(u64, u64, u64)> {
535        let (runs, fails, ms) = stats.get(name.as_str())?;
536        (*fails > 0).then(|| (*fails, *runs, median(ms).max(1)))
537    };
538    let mut order: Vec<usize> = (0..gates.len()).collect();
539    order.sort_by(|&a, &b| {
540        match (weight(&gates[a]), weight(&gates[b])) {
541            (Some((fa, ra, ma)), Some((fb, rb, mb))) => {
542                // fa/(ra*ma) vs fb/(rb*mb), cross-multiplied in u128 so no
543                // float ever decides the order of a hook.
544                let left = u128::from(fa) * u128::from(rb) * u128::from(mb);
545                let right = u128::from(fb) * u128::from(ra) * u128::from(ma);
546                right.cmp(&left).then(a.cmp(&b))
547            }
548            (Some(_), None) => std::cmp::Ordering::Less,
549            (None, Some(_)) => std::cmp::Ordering::Greater,
550            (None, None) => a.cmp(&b),
551        }
552    });
553    order
554}
555
556fn median(values: &[u64]) -> u64 {
557    if values.is_empty() {
558        return 0;
559    }
560    let mut v = values.to_vec();
561    v.sort_unstable();
562    let mid = v.len() / 2;
563    if v.len() % 2 == 1 {
564        v[mid]
565    } else {
566        // The lower of the two middles rather than their mean: the numbers
567        // are durations, and an average of two invents a duration nothing
568        // ever took.
569        v[mid - 1]
570    }
571}
572
573/// A duration a person can read. Milliseconds up to a second, then seconds,
574/// then minutes — the report is scanned, not computed with.
575pub fn duration(ms: u64) -> String {
576    if ms < 1_000 {
577        return format!("{ms} ms");
578    }
579    if ms < 60_000 {
580        return format!("{}.{} s", ms / 1000, (ms % 1000) / 100);
581    }
582    format!("{} m {:02} s", ms / 60_000, (ms % 60_000) / 1000)
583}
584
585/// A fingerprint, shortened the way git shortens one.
586pub(crate) fn short(oid: &str) -> &str {
587    oid.get(..8).unwrap_or(oid)
588}
589
590#[cfg(test)]
591mod tests {
592    use super::*;
593
594    fn run(at: u64, gate: &str, outcome: RunOutcome, ms: u64) -> Run {
595        Run {
596            at,
597            gate: gate.to_string(),
598            outcome,
599            ms,
600        }
601    }
602
603    fn history(rows: &[(&str, Run)]) -> History {
604        History {
605            runs: rows
606                .iter()
607                .map(|(fp, r)| ((*fp).to_string(), r.clone()))
608                .collect(),
609        }
610    }
611
612    /// The same, where a test builds its fingerprints rather than spelling
613    /// them out.
614    fn owned_history(rows: Vec<(String, Run)>) -> History {
615        History { runs: rows }
616    }
617
618    const NOW: u64 = 1_800_000_000;
619    const DAY: u64 = 86_400;
620
621    fn of<'a>(reports: &'a [GateReport], gate: &str) -> &'a GateReport {
622        reports
623            .iter()
624            .find(|r| r.gate == gate)
625            .unwrap_or_else(|| panic!("no report for {gate}: {reports:?}"))
626    }
627
628    fn kinds(r: &GateReport) -> Vec<FlagKind> {
629        r.flags.iter().map(|f| f.kind).collect()
630    }
631
632    /// The signature the fleet audit of 2026-09-19 found four times: a gate
633    /// that used to take minutes returns in milliseconds and still passes.
634    /// Nothing in the hook can see it — the exit code is 0 — and this is the
635    /// only place the collapse is visible.
636    #[test]
637    fn a_suite_that_collapsed_to_milliseconds_is_a_no_op_suspect() {
638        let mut rows: Vec<(&str, Run)> = (0..8)
639            .map(|i| {
640                (
641                    "tree0",
642                    run(
643                        NOW - (10 - i) * DAY,
644                        "pre-push-cargo-test",
645                        RunOutcome::Passed,
646                        600_000,
647                    ),
648                )
649            })
650            .collect();
651        rows.push((
652            "tree9",
653            run(NOW - DAY, "pre-push-cargo-test", RunOutcome::Passed, 400),
654        ));
655        let reports = summarise(&history(&rows), NOW, &Thresholds::default());
656        let r = of(&reports, "pre-push-cargo-test");
657        assert_eq!(kinds(r), vec![FlagKind::NoOpSuspect]);
658        assert!(
659            r.flags[0].why.contains("400 ms") && r.flags[0].why.contains("threshold 10%"),
660            "the flag must carry the comparison it made: {:?}",
661            r.flags[0].why
662        );
663    }
664
665    /// The other shape: a gate that has ALWAYS returned instantly has no
666    /// collapse to measure, so the rule is "it has never once done real
667    /// work", and it only fires once there is enough history to say so.
668    #[test]
669    fn a_gate_that_never_once_took_real_time_is_also_suspect() {
670        let rows: Vec<(&str, Run)> = (0..6)
671            .map(|i| {
672                (
673                    "tree0",
674                    run(
675                        NOW - (7 - i) * DAY,
676                        "pre-push-audit-python",
677                        RunOutcome::Passed,
678                        if i == 5 { 30 } else { 4_000 },
679                    ),
680                )
681            })
682            .collect();
683        let reports = summarise(&history(&rows), NOW, &Thresholds::default());
684        assert_eq!(
685            kinds(of(&reports, "pre-push-audit-python")),
686            vec![FlagKind::NoOpSuspect]
687        );
688    }
689
690    /// Two verdicts, one tree. The content could not have changed between
691    /// them, so the gate did.
692    #[test]
693    fn one_fingerprint_with_two_answers_is_flaky() {
694        let rows = [
695            (
696                "treeA",
697                run(NOW - 6 * DAY, "pre-push-pytest", RunOutcome::Passed, 90_000),
698            ),
699            (
700                "treeA",
701                run(NOW - 5 * DAY, "pre-push-pytest", RunOutcome::Failed, 88_000),
702            ),
703            (
704                "treeA",
705                run(NOW - 4 * DAY, "pre-push-pytest", RunOutcome::Passed, 91_000),
706            ),
707            (
708                "treeB",
709                run(NOW - 3 * DAY, "pre-push-pytest", RunOutcome::Passed, 92_000),
710            ),
711            (
712                "treeB",
713                run(NOW - 2 * DAY, "pre-push-pytest", RunOutcome::Passed, 90_500),
714            ),
715        ];
716        let r = summarise(&history(&rows), NOW, &Thresholds::default());
717        let r = of(&r, "pre-push-pytest");
718        assert_eq!(kinds(r), vec![FlagKind::Flaky]);
719        assert!(r.flags[0].why.contains("treeA"), "{:?}", r.flags[0].why);
720    }
721
722    /// Stale is a claim about the NEIGHBOURS: other gates kept judging trees
723    /// this one did not. A quiet repository where nothing ran is not stale.
724    #[test]
725    fn a_gate_left_behind_by_its_neighbours_is_stale() {
726        let mut rows = vec![(
727            "tree0".to_string(),
728            run(
729                NOW - 40 * DAY,
730                "pre-push-go-test",
731                RunOutcome::Passed,
732                5_000,
733            ),
734        )];
735        for i in 0..12u64 {
736            rows.push((
737                format!("tree{}", i + 1),
738                run(
739                    NOW - (12 - i) * DAY,
740                    "pre-push-cargo-test",
741                    RunOutcome::Passed,
742                    5_000,
743                ),
744            ));
745        }
746        let reports = summarise(&owned_history(rows), NOW, &Thresholds::default());
747        let stale = of(&reports, "pre-push-go-test");
748        assert!(kinds(stale).contains(&FlagKind::Stale), "{:?}", stale.flags);
749        assert!(
750            of(&reports, "pre-push-cargo-test").flags.is_empty(),
751            "the gate that kept running is not stale"
752        );
753    }
754
755    /// The refusal that matters most: two runs say nothing, and the report
756    /// says THAT rather than an empty flags column.
757    #[test]
758    fn too_little_history_abstains_out_loud() {
759        let rows = [
760            (
761                "tree0",
762                run(
763                    NOW - 2 * DAY,
764                    "pre-push-cargo-test",
765                    RunOutcome::Passed,
766                    600_000,
767                ),
768            ),
769            (
770                "tree1",
771                run(NOW - DAY, "pre-push-cargo-test", RunOutcome::Passed, 300),
772            ),
773        ];
774        let reports = summarise(&history(&rows), NOW, &Thresholds::default());
775        let r = of(&reports, "pre-push-cargo-test");
776        assert_eq!(
777            r.abstained.as_deref(),
778            Some("insufficient history (2 verdicts)")
779        );
780        assert!(
781            r.flags.is_empty(),
782            "a two-run history must not raise a flag: {:?}",
783            r.flags
784        );
785        assert_eq!((r.runs, r.passed), (2, 2), "the counts are still reported");
786    }
787
788    /// A gate that could not run is not a gate that passed. The count is
789    /// kept separately, because the audit this module exists for found four
790    /// mechanisms whose whole failure mode was that nobody counted it.
791    #[test]
792    fn an_unavailable_run_is_never_counted_as_a_pass() {
793        let rows = [
794            (
795                "tree0",
796                run(
797                    NOW - 2 * DAY,
798                    "pre-push-audit-go",
799                    RunOutcome::Unavailable,
800                    200,
801                ),
802            ),
803            (
804                "tree1",
805                run(NOW - DAY, "pre-push-audit-go", RunOutcome::Unavailable, 210),
806            ),
807        ];
808        let reports = summarise(&history(&rows), NOW, &Thresholds::default());
809        let r = of(&reports, "pre-push-audit-go");
810        assert_eq!((r.passed, r.failed, r.unavailable), (0, 0, 2));
811    }
812
813    /// Outside the window is outside the report.
814    #[test]
815    fn the_window_excludes_what_is_older_than_it() {
816        let rows = [
817            (
818                "tree0",
819                run(
820                    NOW - 200 * DAY,
821                    "pre-push-cargo-test",
822                    RunOutcome::Failed,
823                    500,
824                ),
825            ),
826            (
827                "tree1",
828                run(NOW - DAY, "pre-push-cargo-test", RunOutcome::Passed, 500),
829            ),
830        ];
831        let reports = summarise(&history(&rows), NOW, &Thresholds::default());
832        assert_eq!(of(&reports, "pre-push-cargo-test").runs, 1);
833    }
834
835    /// Ordering promotes the gate that catches the most per second spent —
836    /// not the one that fails most often. A five-second audit failing one
837    /// push in six beats a twenty-minute suite failing one in three.
838    #[test]
839    fn ordering_prefers_failures_per_second_not_failure_rate() {
840        let gates: Vec<String> = ["suite", "audit"].iter().map(|s| s.to_string()).collect();
841        let mut rows: Vec<(&str, Run)> = Vec::new();
842        for i in 0..6u64 {
843            rows.push((
844                "tree0",
845                run(
846                    NOW - (10 - i) * DAY,
847                    "suite",
848                    if i < 2 {
849                        RunOutcome::Failed
850                    } else {
851                        RunOutcome::Passed
852                    },
853                    1_200_000,
854                ),
855            ));
856            rows.push((
857                "tree0",
858                run(
859                    NOW - (10 - i) * DAY,
860                    "audit",
861                    if i < 1 {
862                        RunOutcome::Failed
863                    } else {
864                        RunOutcome::Passed
865                    },
866                    5_000,
867                ),
868            ));
869        }
870        let order = order_by_evidence(&gates, &history(&rows), NOW, 90);
871        assert_eq!(order, vec![1, 0], "the cheap audit runs first");
872    }
873
874    /// With no record at all, the declared order is the order. This is the
875    /// fallback every repository starts in, and it must be exact.
876    #[test]
877    fn with_no_history_the_declared_order_is_kept() {
878        let gates: Vec<String> = ["a", "b", "c"].iter().map(|s| s.to_string()).collect();
879        assert_eq!(
880            order_by_evidence(&gates, &History::default(), NOW, 90),
881            vec![0, 1, 2]
882        );
883    }
884
885    /// A gate that has never failed is not promoted over one that has, and
886    /// the never-failed ones keep their order among themselves.
887    #[test]
888    fn only_gates_that_actually_failed_are_promoted() {
889        let gates: Vec<String> = ["a", "b", "c"].iter().map(|s| s.to_string()).collect();
890        let rows = [
891            ("t", run(NOW - 3 * DAY, "a", RunOutcome::Passed, 1_000)),
892            ("t", run(NOW - 3 * DAY, "b", RunOutcome::Passed, 1_000)),
893            ("t", run(NOW - 2 * DAY, "c", RunOutcome::Failed, 1_000)),
894            ("t", run(NOW - DAY, "c", RunOutcome::Passed, 1_000)),
895        ];
896        assert_eq!(
897            order_by_evidence(&gates, &history(&rows), NOW, 90),
898            vec![2, 0, 1]
899        );
900    }
901
902    /// Every gate handed in comes back out, exactly once — the property that
903    /// makes this a permutation and not a filter.
904    #[test]
905    fn ordering_is_a_permutation_and_never_drops_a_gate() {
906        let gates: Vec<String> = ["a", "b", "c", "d"].iter().map(|s| s.to_string()).collect();
907        let rows = [
908            ("t", run(NOW - DAY, "b", RunOutcome::Failed, 10)),
909            ("t", run(NOW - DAY, "d", RunOutcome::Failed, 10_000)),
910        ];
911        let mut order = order_by_evidence(&gates, &history(&rows), NOW, 90);
912        assert_eq!(order.len(), gates.len());
913        order.sort_unstable();
914        assert_eq!(order, vec![0, 1, 2, 3]);
915    }
916
917    /// The batch reader, against the shape git actually prints.
918    #[test]
919    fn cat_file_batch_output_splits_into_bodies() {
920        let oid = "0123456789abcdef0123456789abcdef01234567";
921        let other = "89abcdef0123456789abcdef0123456789abcdef";
922        let out = format!(
923            "{oid} blob 42\namont-gate-v1 pre-push-cargo-test\nrun 10 pre-push-cargo-test pass 5\n\
924             {other} blob 14\namont-gate-v1\n"
925        );
926        let got = parse_batch(&out);
927        assert_eq!(got.len(), 2);
928        assert_eq!(got[0].0, oid);
929        assert!(got[0].1.contains("run 10"));
930        assert_eq!(got[1].0, other);
931    }
932
933    #[test]
934    fn durations_read_like_durations() {
935        assert_eq!(duration(400), "400 ms");
936        assert_eq!(duration(5_400), "5.4 s");
937        assert_eq!(duration(662_000), "11 m 02 s");
938    }
939}