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