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