use anyhow::Result;
use std::collections::{BTreeMap, BTreeSet};
use crate::accept::{Acceptances, TRAILER};
use crate::compare::{
CREDIT, Change, GATED_METRIC, Gate, Gates, Key, Trend, WALL_METRIC, code, code_cell, describe,
signed_pct, sparkline, thousands,
};
use crate::notes;
use crate::record::Record;
pub const SCAN_LIMIT: usize = 10_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Cutoff {
Shallow,
ScanLimit,
}
pub fn cutoff(
recorded: usize,
window: usize,
truncated: bool,
shallow: impl FnOnce() -> Result<bool>,
) -> Result<Option<Cutoff>> {
if recorded >= window {
return Ok(None);
}
if truncated {
return Ok(Some(Cutoff::ScanLimit));
}
Ok(shallow()?.then_some(Cutoff::Shallow))
}
#[derive(Debug, Clone, Copy)]
struct Point {
at: usize,
instructions: f64,
wall: Option<f64>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Step {
pub key: Key,
pub from: String,
pub to: String,
pub commits: usize,
pub instructions: Change,
pub wall: Option<Change>,
}
impl Step {
pub fn gate(&self, gates: &Gates) -> Gate {
gates.get(&self.key.0, &self.key.1)
}
pub fn exceeds(&self, gates: &Gates) -> bool {
self.instructions.exceeds(&self.gate(gates))
}
pub fn fails(&self, gates: &Gates) -> bool {
self.gate(gates).enabled && self.exceeds(gates)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Drift {
pub key: Key,
pub since: String,
pub points: usize,
pub change: Change,
}
#[derive(Debug, PartialEq)]
pub struct Detection {
pub head: String,
pub gates: Gates,
pub walked: usize,
pub recorded: usize,
pub latest: Vec<Step>,
pub earlier: Vec<Step>,
pub drift: Vec<Drift>,
pub new_at_head: Vec<Key>,
pub missing_at_head: Vec<Key>,
pub trend: Trend,
pub cutoff: Option<Cutoff>,
pub allow_empty: bool,
pub no_gate: bool,
pub accepted: BTreeMap<Key, Acceptances>,
pub offered: Acceptances,
pub ignored_trailers: Acceptances,
}
impl Detection {
pub fn new(head: String, gates: Gates) -> Self {
Self {
head,
gates,
walked: 0,
recorded: 0,
latest: vec![],
earlier: vec![],
drift: vec![],
new_at_head: vec![],
missing_at_head: vec![],
trend: Trend::new(),
cutoff: None,
allow_empty: false,
no_gate: false,
accepted: BTreeMap::new(),
offered: Acceptances::default(),
ignored_trailers: Acceptances::default(),
}
}
pub fn accept(&mut self, flags: &Acceptances, trailer_logs: &BTreeMap<String, String>) {
self.offered = flags.clone();
for log in trailer_logs.values() {
self.offered.add_trailer_log(log);
}
for s in &self.latest {
let mut a = flags.clone();
if let Some(log) = trailer_logs.get(&s.from) {
a.add_trailer_log(log);
}
if !a.is_empty() {
self.accepted.insert(s.key.clone(), a);
}
}
}
fn acceptance(&self, s: &Step) -> Option<&Acceptances> {
if s.to != self.head {
return None;
}
self.accepted.get(&s.key).filter(|a| a.covers(&s.key.0))
}
pub fn accepted_steps(&self) -> Vec<&Step> {
self.latest
.iter()
.filter(|s| s.fails(&self.gates) && self.acceptance(s).is_some())
.collect()
}
fn unused_acceptances(&self) -> Vec<&str> {
let used: BTreeSet<&str> = self
.accepted_steps()
.iter()
.map(|s| s.key.0.as_str())
.collect();
self.offered
.iter()
.map(|(name, _)| name)
.filter(|name| !used.contains(name))
.collect()
}
pub fn failures(&self) -> Vec<&Step> {
self.latest
.iter()
.filter(|s| s.fails(&self.gates) && self.acceptance(s).is_none())
.collect()
}
pub fn reported(&self) -> Vec<&Step> {
self.latest
.iter()
.filter(|s| !s.gate(&self.gates).enabled && s.exceeds(&self.gates))
.collect()
}
pub fn uniform(&self) -> bool {
let keys = self
.latest
.iter()
.chain(&self.earlier)
.map(|s| &s.key)
.chain(self.drift.iter().map(|d| &d.key));
keys.into_iter()
.all(|k| self.gates.get(&k.0, &k.1) == self.gates.global)
}
pub fn nothing_compared(&self) -> bool {
self.latest.is_empty()
}
pub fn empty_fails(&self) -> bool {
self.nothing_compared() && !self.allow_empty && !self.no_gate
}
}
pub fn select(newest_first: &[String], annotated: &BTreeSet<String>, window: usize) -> Vec<String> {
let mut seen = 0;
let mut end = newest_first.len().min(1);
for (i, sha) in newest_first.iter().enumerate() {
if annotated.contains(sha) {
seen += 1;
end = i + 1;
if seen >= window {
break;
}
}
}
newest_first[..end].iter().rev().cloned().collect()
}
pub type Walk = Vec<(String, Vec<Record>)>;
pub fn gather(head: &str, window: usize) -> Result<(Walk, Option<Cutoff>)> {
let mut logged = notes::log(head, Some(SCAN_LIMIT + 1))?;
let truncated = logged.len() > SCAN_LIMIT;
logged.truncate(SCAN_LIMIT);
let oldest = logged.last().map(|l| l.sha.clone());
let shas: Vec<String> = logged.iter().map(|l| l.sha.clone()).collect();
let recorded_at: BTreeSet<String> = logged
.iter()
.filter(|l| !l.records.is_empty())
.map(|l| l.sha.clone())
.collect();
let kept = select(&shas, &recorded_at, window).len();
logged.truncate(kept);
let walked: Walk = logged
.into_iter()
.rev()
.map(|l| (l.sha, l.records))
.collect();
let recorded = walked.iter().filter(|(_, r)| !r.is_empty()).count();
let cut = cutoff(recorded, window, truncated, || {
Ok(oldest.as_deref().is_some_and(notes::is_shallow_boundary))
})?;
Ok((walked, cut))
}
fn fold(records: &[Record]) -> BTreeMap<Key, (f64, Option<f64>)> {
let mut ins: BTreeMap<Key, f64> = BTreeMap::new();
let mut wall: BTreeMap<Key, f64> = BTreeMap::new();
for r in records {
let key: Key = (r.bench.clone(), r.tool.clone(), r.runner.clone());
if let Some(&v) = r.metrics.get(GATED_METRIC) {
ins.entry(key.clone())
.and_modify(|e| *e = e.min(v))
.or_insert(v);
}
if let Some(&v) = r.metrics.get(WALL_METRIC) {
wall.entry(key).and_modify(|e| *e = e.min(v)).or_insert(v);
}
}
ins.into_iter()
.map(|(k, v)| {
let w = wall.get(&k).copied();
(k, (v, w))
})
.collect()
}
fn step(key: &Key, walked: &[(String, Vec<Record>)], a: Point, b: Point) -> Step {
let change = |metric: &str, base: f64, head: f64| Change {
bench: key.0.clone(),
tool: key.1.clone(),
runner: key.2.clone(),
metric: metric.to_string(),
base,
head,
};
Step {
key: key.clone(),
from: walked[a.at].0.clone(),
to: walked[b.at].0.clone(),
commits: b.at - a.at,
instructions: change(GATED_METRIC, a.instructions, b.instructions),
wall: match (a.wall, b.wall) {
(Some(x), Some(y)) => Some(change(WALL_METRIC, x, y)),
_ => None,
},
}
}
pub fn analyze(walked: &[(String, Vec<Record>)], gates: &Gates) -> Detection {
let Some((head, _)) = walked.last() else {
return Detection::new(String::new(), gates.clone());
};
let head_at = walked.len() - 1;
let mut series: BTreeMap<Key, Vec<Point>> = BTreeMap::new();
for (at, (_, records)) in walked.iter().enumerate() {
for (key, (instructions, wall)) in fold(records) {
series.entry(key).or_default().push(Point {
at,
instructions,
wall,
});
}
}
let mut d = Detection {
walked: walked.len(),
recorded: walked.iter().filter(|(_, r)| !r.is_empty()).count(),
..Detection::new(head.clone(), gates.clone())
};
for (key, points) in &series {
d.trend
.insert(key.clone(), points.iter().map(|p| p.instructions).collect());
let steps: Vec<Step> = points
.windows(2)
.map(|w| step(key, walked, w[0], w[1]))
.collect();
let at_head = points.last().is_some_and(|p| p.at == head_at);
match (at_head, steps.split_last()) {
(true, Some((last, rest))) => {
d.latest.push(last.clone());
d.earlier
.extend(rest.iter().filter(|s| s.exceeds(gates)).cloned());
}
(true, None) => d.new_at_head.push(key.clone()),
(false, _) => {
d.missing_at_head.push(key.clone());
d.earlier
.extend(steps.iter().filter(|s| s.exceeds(gates)).cloned());
}
}
let gate = gates.get(&key.0, &key.1);
if at_head && let Some(drift) = drift(key, walked, points, &steps, &gate) {
d.drift.push(drift);
}
}
d.earlier
.sort_by_key(|s| walked.iter().position(|(sha, _)| sha == &s.to));
d
}
fn drift(
key: &Key,
walked: &[(String, Vec<Record>)],
points: &[Point],
steps: &[Step],
gate: &Gate,
) -> Option<Drift> {
let start = steps
.iter()
.rposition(|s| s.instructions.exceeds(gate))
.map_or(0, |i| i + 1);
let run = &points[start..];
if run.len() < 3 {
return None;
}
let total = step(key, walked, run[0], run[run.len() - 1]);
if !total.instructions.exceeds(gate) {
return None;
}
Some(Drift {
key: key.clone(),
since: total.from,
points: run.len(),
change: total.instructions,
})
}
pub fn short(sha: &str) -> &str {
&sha[..sha.len().min(12)]
}
fn span(s: &Step) -> String {
if s.commits <= 1 {
format!("`{}`", short(&s.to))
} else {
format!(
"`{}..{}` ({} commits)",
short(&s.from),
short(&s.to),
s.commits
)
}
}
fn instructions_cells(s: &Step, d: &Detection) -> (String, String) {
let gates = &d.gates;
let ch = &s.instructions;
let flag = match (s.exceeds(gates), s.gate(gates).enabled) {
(true, true) if d.acceptance(s).is_some() => " (accepted)",
(true, true) => " ⚠️",
(true, false) => " (not gated)",
(false, _) => "",
};
(
format!("{} → {}", thousands(ch.base), thousands(ch.head)),
format!("**{}**{flag}", signed_pct(ch.pct())),
)
}
pub fn markdown(d: &Detection, credit: bool) -> String {
let gates = &d.gates;
let global = gates.global;
let uniform = d.uniform();
let the_gate = if uniform {
format!("the {}% gate", global.pct)
} else {
"their gate".to_string()
};
let floor = if uniform && global.min_delta > 0 {
format!(
" (rises of {} instructions or fewer are not counted)",
thousands(global.min_delta as f64)
)
} else {
String::new()
};
let listed = |steps: &[&Step]| {
steps
.iter()
.map(|s| {
let mut out = format!("{} {}", describe(&s.key), signed_pct(s.instructions.pct()));
if !uniform {
out.push_str(&format!(" (gate {})", s.gate(gates).threshold()));
}
out
})
.collect::<Vec<_>>()
.join(", ")
};
let head = short(&d.head);
let mut out = format!(
"Walked {} first-parent commit(s) ending at `{head}`, {} with measurements recorded.\n\n",
d.walked, d.recorded
);
if d.nothing_compared() {
let why = if d.new_at_head.is_empty() {
"No instruction counts are recorded for this commit. Record it with \
`tak run --record` before running `tak detect`."
} else {
"No series measured here has an earlier recorded point in the window: \
this is the first recording, the history is too short or shallow, or \
the runner class changed, which deliberately starts a new series."
};
if d.no_gate {
out.push_str(&format!(
"**Nothing was compared at `{head}`, and so nothing was gated** \
(`--no-gate`). {why}\n"
));
} else if !d.empty_fails() {
out.push_str(&format!(
"**Nothing was compared at `{head}`, and so nothing was gated** \
(`allow_empty`). {why}\n\n{}\n",
crate::compare::ALLOWED_EMPTY
));
} else {
out.push_str(&format!(
"**Nothing was compared at `{head}`, so this check fails.** {why} \
When that is expected — the first recording, or the first on a new \
runner class — pass `--allow-empty` or set `[gate] allow_empty = true`, \
or record an earlier commit on the same runner class first.\n"
));
}
} else {
if uniform {
out.push_str(
"| benchmark | trend | step | instructions | Δ | wall (min) | Δ |\n\
|---|---|---|---:|---:|---:|---:|\n",
);
} else {
out.push_str(
"| benchmark | trend | step | instructions | Δ | gate | wall (min) | Δ |\n\
|---|---|---|---:|---:|---|---:|---:|\n",
);
}
for s in &d.latest {
let spark = d
.trend
.get(&s.key)
.map(|v| sparkline(v))
.filter(|v| !v.is_empty())
.map(|v| format!("`{v}`"))
.unwrap_or_else(|| "—".into());
let (ins, ins_delta) = instructions_cells(s, d);
let gate_cell = if uniform {
String::new()
} else {
format!(" {} |", s.gate(gates).describe())
};
let (wall, wall_delta) = match &s.wall {
Some(w) => (
format!("{:.2} → {:.2}ms", w.base, w.head),
signed_pct(w.pct()),
),
None => ("—".into(), "—".into()),
};
out.push_str(&format!(
"| {} | {spark} | {} | {ins} | {ins_delta} |{gate_cell} {wall} | {wall_delta} |\n",
code_cell(&describe(&s.key)),
span(s),
));
}
let failures = d.failures();
let accepted = d.accepted_steps();
let any_gated = d.latest.iter().any(|s| s.gate(gates).enabled);
out.push('\n');
if !any_gated {
out.push_str("Every benchmark here is report-only, so none can fail the gate.\n");
} else if failures.is_empty() && !accepted.is_empty() {
} else if failures.is_empty() {
if uniform {
out.push_str(&format!(
"No instruction-count step above {}% at `{head}`{floor}.\n",
global.pct
));
} else {
out.push_str(&format!(
"No gated benchmark stepped beyond its gate at `{head}`.\n"
));
}
} else {
out.push_str(&format!(
"**{} benchmark(s) stepped above {the_gate} at `{head}`{floor}:** {}\n",
failures.len(),
listed(&failures)
));
if failures.iter().any(|s| s.commits > 1) {
out.push_str(
"\nA step shown as a range happened somewhere in commits that were \
not measured individually; `git log --first-parent` over that \
range lists the candidates.\n",
);
}
}
if !accepted.is_empty() {
let gap = if failures.is_empty() { "" } else { "\n" };
out.push_str(&format!(
"{gap}**{} accepted step(s) above {the_gate} at `{head}`, not failing:** {}\n",
accepted.len(),
accepted
.iter()
.map(|s| {
let by = d.acceptance(s).map(|a| a.describe(&s.key.0));
format!("{} (accepted by {})", listed(&[*s]), by.unwrap_or_default())
})
.collect::<Vec<_>>()
.join(", ")
));
}
let reported = d.reported();
if !reported.is_empty() {
out.push_str(&format!(
"\n**{} report-only benchmark(s) stepped above their gate at `{head}`, \
not failing:** {}\n",
reported.len(),
listed(&reported)
));
}
}
let unused = d.unused_acceptances();
if !unused.is_empty() {
out.push_str(&format!(
"\nAccepted, but no step onto `{head}` needed it, so nothing was accepted: {}\n",
unused
.iter()
.map(|name| format!("{} ({})", code(name), d.offered.describe(name)))
.collect::<Vec<_>>()
.join(", ")
));
}
if !d.ignored_trailers.is_empty() {
out.push_str(&format!(
"\n`{TRAILER}` trailers were found but not honoured, because \
`gate.accept_trailers` is off: {}\n",
d.ignored_trailers
.iter()
.map(|(name, _)| format!("{} ({})", code(name), d.ignored_trailers.describe(name)))
.collect::<Vec<_>>()
.join(", ")
));
}
if !d.earlier.is_empty() {
out.push_str(&format!(
"\n**Earlier steps above {the_gate}**, reported and not gated — \
a step fails only the run for the commit that introduced it:\n\n"
));
if uniform {
out.push_str("| benchmark | step | instructions | Δ |\n|---|---|---:|---:|\n");
} else {
out.push_str(
"| benchmark | step | instructions | Δ | gate |\n|---|---|---:|---:|---|\n",
);
}
for s in &d.earlier {
let (ins, delta) = instructions_cells(s, d);
let gate_cell = if uniform {
String::new()
} else {
format!(" {} |", s.gate(gates).describe())
};
out.push_str(&format!(
"| {} | {} | {ins} | {delta} |{gate_cell}\n",
code_cell(&describe(&s.key)),
span(s)
));
}
}
if !d.drift.is_empty() {
out.push_str(&format!(
"\n**Sustained drift**, reported and not gated — every step stayed within \
{the_gate} and the total did not:\n\n"
));
for dr in &d.drift {
let gate = if uniform {
String::new()
} else {
format!(" (gate {})", gates.get(&dr.key.0, &dr.key.1).describe())
};
out.push_str(&format!(
"- {}: {} ({} → {}) over {} recorded commits since `{}`{gate}\n",
describe(&dr.key),
signed_pct(dr.change.pct()),
thousands(dr.change.base),
thousands(dr.change.head),
dr.points,
short(&dr.since),
));
}
}
if !d.new_at_head.is_empty() {
out.push_str(&format!(
"\nNo earlier point in the window, nothing to compare against: {}\n",
list(&d.new_at_head)
));
}
if !d.missing_at_head.is_empty() {
out.push_str(&format!(
"\nRecorded earlier in the window but not at `{head}` — a benchmark that \
stops running also stops being checked: {}\n",
list(&d.missing_at_head)
));
}
match d.cutoff {
Some(Cutoff::Shallow) => out.push_str(
"\nThis checkout is shallow, and the walk reached its boundary before \
the window filled. Fetch more history (`fetch-depth: 0` with \
`actions/checkout`) so earlier recordings are visible.\n",
),
Some(Cutoff::ScanLimit) => out.push_str(&format!(
"\nThe walk stopped at its limit of {} first-parent commits before the \
window filled. Recordings older than that were not compared.\n",
thousands(SCAN_LIMIT as f64)
)),
None => {}
}
out.push_str(
"\n<sub>Only instruction counts gate, and only a step onto the newest commit. Wall clock \
is shown for context — on identical hardware it moves 4-20% run to run.</sub>\n",
);
if credit {
out.push_str(CREDIT);
}
out
}
fn list(keys: &[Key]) -> String {
keys.iter().map(describe).collect::<Vec<_>>().join(", ")
}
#[cfg(test)]
mod tests {
use super::*;
fn pct(p: f64) -> Gates {
Gates::uniform(Gate::new(p, 0).unwrap())
}
fn rec(bench: &str, runner: &str, ins: f64) -> Record {
Record {
v: 1,
bench: bench.into(),
tool: "self".into(),
version: None,
runner: runner.into(),
ts: "2026-01-01T00:00:00Z".into(),
metrics: BTreeMap::from([
(GATED_METRIC.to_string(), ins),
(WALL_METRIC.to_string(), 10.0),
]),
}
}
fn walk(values: &[Option<f64>]) -> Vec<(String, Vec<Record>)> {
values
.iter()
.enumerate()
.map(|(i, v)| {
(
format!("c{i}"),
v.map(|v| vec![rec("a", "gha", v)]).unwrap_or_default(),
)
})
.collect()
}
fn shas(names: &[&str]) -> Vec<String> {
names.iter().map(|s| s.to_string()).collect()
}
#[test]
fn a_step_onto_the_head_fails() {
let d = analyze(
&walk(&[Some(1000.0), Some(1000.0), Some(1100.0)]),
&pct(1.0),
);
let f = d.failures();
assert_eq!(f.len(), 1);
assert_eq!((f[0].from.as_str(), f[0].to.as_str()), ("c1", "c2"));
assert_eq!(f[0].commits, 1);
assert!(d.earlier.is_empty());
}
#[test]
fn a_pipe_in_a_name_does_not_split_the_row() {
let named = |v: f64| vec![rec("a|b", r"win\arm", v)];
let d = analyze(
&[
("c0".to_string(), named(1000.0)),
("c1".to_string(), named(1100.0)),
("c2".to_string(), named(1100.0)),
("c3".to_string(), named(1210.0)),
],
&pct(1.0),
);
assert_eq!((d.latest.len(), d.earlier.len()), (1, 1));
let md = markdown(&d, false);
assert_eq!(md.matches(r"| `a\|b` on `win\arm` |").count(), 2, "{md}");
}
#[test]
fn a_step_below_the_gate_passes() {
let d = analyze(&walk(&[Some(1000.0), Some(1005.0)]), &pct(1.0));
assert!(d.failures().is_empty());
assert_eq!(d.latest.len(), 1, "it is still reported");
}
#[test]
fn an_improvement_never_fails() {
let d = analyze(&walk(&[Some(1000.0), Some(500.0)]), &pct(1.0));
assert!(d.failures().is_empty());
}
#[test]
fn an_older_step_is_reported_not_failed() {
let d = analyze(
&walk(&[Some(1000.0), Some(1100.0), Some(1100.0)]),
&pct(1.0),
);
assert!(d.failures().is_empty());
assert_eq!(d.earlier.len(), 1);
assert_eq!(d.earlier[0].to, "c1");
assert!(markdown(&d, false).contains("Earlier steps above the 1% gate"));
}
#[test]
fn a_step_across_unrecorded_commits_is_a_range() {
let d = analyze(&walk(&[Some(1000.0), None, None, Some(1100.0)]), &pct(1.0));
let f = d.failures();
assert_eq!(f.len(), 1, "a range onto the head still fails");
assert_eq!((f[0].from.as_str(), f[0].to.as_str()), ("c0", "c3"));
assert_eq!(f[0].commits, 3);
let md = markdown(&d, false);
assert!(md.contains("`c0..c3` (3 commits)"), "{md}");
assert!(md.contains("not measured individually"), "{md}");
}
#[test]
fn ranges_are_per_series() {
let mut w = walk(&[Some(1000.0), Some(1000.0), Some(1000.0)]);
w[0].1.push(rec("b", "gha", 50.0));
w[2].1.push(rec("b", "gha", 60.0));
let d = analyze(&w, &pct(1.0));
let b = d.latest.iter().find(|s| s.key.0 == "b").unwrap();
assert_eq!(b.commits, 2);
let a = d.latest.iter().find(|s| s.key.0 == "a").unwrap();
assert_eq!(a.commits, 1);
assert_eq!(d.failures().len(), 1);
}
#[test]
fn runners_never_line_up() {
let w = vec![
("c0".to_string(), vec![rec("a", "gha-linux", 1000.0)]),
("c1".to_string(), vec![rec("a", "gha-macos", 9000.0)]),
];
let d = analyze(&w, &pct(1.0));
assert!(d.failures().is_empty());
assert!(d.nothing_compared());
assert_eq!(d.new_at_head.len(), 1);
assert_eq!(d.missing_at_head.len(), 1);
let md = markdown(&d, false);
assert!(md.contains("Nothing was compared"), "{md}");
assert!(md.contains("gha-linux") && md.contains("gha-macos"), "{md}");
}
#[test]
fn runners_are_partitioned_within_a_walk() {
let w = vec![
(
"c0".to_string(),
vec![rec("a", "fast", 1000.0), rec("a", "slow", 5000.0)],
),
(
"c1".to_string(),
vec![rec("a", "fast", 1000.0), rec("a", "slow", 5200.0)],
),
];
let d = analyze(&w, &pct(1.0));
let f = d.failures();
assert_eq!(f.len(), 1);
assert_eq!(f[0].key.2, "slow");
assert_eq!(f[0].instructions.base, 5000.0, "never the other runner's");
}
#[test]
fn creeping_sub_threshold_steps_are_drift() {
let d = analyze(
&walk(&[Some(1000.0), Some(1004.0), Some(1008.0), Some(1012.0)]),
&pct(1.0),
);
assert!(d.failures().is_empty(), "drift never fails");
assert!(d.earlier.is_empty());
assert_eq!(d.drift.len(), 1);
assert_eq!(d.drift[0].since, "c0");
assert_eq!(d.drift[0].points, 4);
let md = markdown(&d, false);
assert!(md.contains("Sustained drift"), "{md}");
assert!(md.contains("+1.20%"), "{md}");
}
#[test]
fn a_flat_series_is_not_drift() {
let d = analyze(&walk(&[Some(1000.0), Some(1003.0), Some(999.0)]), &pct(1.0));
assert!(d.drift.is_empty());
}
#[test]
fn drift_starts_after_the_last_step() {
let d = analyze(
&walk(&[
Some(1000.0),
Some(1100.0),
Some(1105.0),
Some(1110.0),
Some(1115.0),
]),
&pct(1.0),
);
assert_eq!(d.earlier.len(), 1);
assert_eq!(d.drift.len(), 1);
assert_eq!(d.drift[0].since, "c1");
assert_eq!(d.drift[0].change.base, 1100.0);
let d = analyze(
&walk(&[Some(1000.0), Some(1100.0), Some(1100.0)]),
&pct(1.0),
);
assert!(d.drift.is_empty());
}
#[test]
fn an_unrecorded_head_says_so() {
let d = analyze(&walk(&[Some(1000.0), Some(1000.0), None]), &pct(1.0));
assert!(d.nothing_compared());
assert!(d.failures().is_empty());
let md = markdown(&d, false);
assert!(md.contains("No instruction counts are recorded"), "{md}");
assert!(md.contains("not at `c2`"), "{md}");
}
#[test]
fn a_filled_window_is_never_cut_short() {
let shallow = || -> Result<bool> { panic!("no need to ask") };
assert_eq!(cutoff(20, 20, true, shallow).unwrap(), None);
}
#[test]
fn hitting_the_scan_limit_is_a_cutoff() {
let shallow = || -> Result<bool> { panic!("the limit decides first") };
assert_eq!(
cutoff(3, 20, true, shallow).unwrap(),
Some(Cutoff::ScanLimit)
);
}
#[test]
fn the_end_of_history_is_a_cutoff_only_when_shallow() {
assert_eq!(
cutoff(3, 20, false, || Ok(true)).unwrap(),
Some(Cutoff::Shallow)
);
assert_eq!(cutoff(3, 20, false, || Ok(false)).unwrap(), None);
}
#[test]
fn each_cutoff_is_named_in_the_report() {
let mut d = analyze(&walk(&[Some(1000.0), Some(1000.0)]), &pct(1.0));
d.cutoff = Some(Cutoff::ScanLimit);
let md = markdown(&d, false);
assert!(md.contains("limit of 10,000 first-parent commits"), "{md}");
d.cutoff = Some(Cutoff::Shallow);
assert!(markdown(&d, false).contains("This checkout is shallow"));
d.cutoff = None;
let md = markdown(&d, false);
assert!(!md.contains("shallow") && !md.contains("limit of"), "{md}");
}
#[test]
fn nothing_compared_fails_unless_allowed() {
let mut d = analyze(&walk(&[Some(1000.0)]), &pct(1.0));
assert!(d.nothing_compared());
assert!(d.empty_fails(), "empty is a failure by default");
let md = markdown(&d, false);
assert!(md.contains("so this check fails.**"), "{md}");
assert!(md.contains("pass `--allow-empty`"), "{md}");
assert!(md.contains("set `[gate] allow_empty = true`"), "{md}");
assert!(!md.contains("nothing was gated"), "{md}");
assert!(!md.contains(crate::compare::ALLOWED_EMPTY), "{md}");
d.allow_empty = true;
assert!(!d.empty_fails());
let md = markdown(&d, false);
assert!(md.contains("nothing was gated** (`allow_empty`)"), "{md}");
assert!(md.contains(crate::compare::ALLOWED_EMPTY), "{md}");
assert!(!md.contains("this check fails"), "{md}");
}
#[test]
fn no_gate_waives_an_empty_comparison() {
let mut d = analyze(&walk(&[Some(1000.0)]), &pct(1.0));
d.no_gate = true;
assert!(!d.empty_fails());
let md = markdown(&d, false);
assert!(md.contains("nothing was gated** (`--no-gate`)"), "{md}");
assert!(!md.contains("this check fails"), "{md}");
d.allow_empty = true;
let md = markdown(&d, false);
assert!(md.contains("nothing was gated** (`--no-gate`)"), "{md}");
assert!(!md.contains(crate::compare::ALLOWED_EMPTY), "{md}");
}
#[test]
fn allow_empty_does_not_waive_a_step() {
let mut d = analyze(&walk(&[Some(1000.0), Some(1100.0)]), &pct(1.0));
d.allow_empty = true;
assert!(!d.nothing_compared());
assert!(!d.empty_fails());
assert_eq!(d.failures().len(), 1);
assert!(!markdown(&d, false).contains(crate::compare::ALLOWED_EMPTY));
}
#[test]
fn a_real_comparison_is_not_empty() {
let d = analyze(&walk(&[Some(1000.0), Some(1000.0)]), &pct(1.0));
assert!(!d.empty_fails());
}
#[test]
fn wall_clock_never_gates() {
let mut w = walk(&[Some(1000.0), Some(1000.0)]);
w[1].1[0].metrics.insert(WALL_METRIC.into(), 1000.0);
for (at, wall) in [(0, 1.0), (1, 100.0)] {
let mut r = rec("w", "gha", 0.0);
r.metrics = BTreeMap::from([(WALL_METRIC.to_string(), wall)]);
w[at].1.push(r);
}
let d = analyze(&w, &pct(0.001));
assert!(d.failures().is_empty());
assert!(d.latest.iter().all(|s| s.key.0 == "a"));
}
#[test]
fn duplicates_reduce_to_the_minimum() {
let mut w = walk(&[Some(1000.0), Some(1000.0)]);
w[1].1.push(rec("a", "gha", 3000.0));
assert!(analyze(&w, &pct(1.0)).failures().is_empty());
}
#[test]
fn a_rise_from_zero_fails() {
let d = analyze(&walk(&[Some(0.0), Some(5.0)]), &pct(1.0));
assert_eq!(d.failures().len(), 1);
}
#[test]
fn an_empty_walk_is_nothing_compared() {
let d = analyze(&[], &pct(1.0));
assert!(d.nothing_compared());
assert!(markdown(&d, false).contains("Only instruction counts gate"));
}
#[test]
fn the_window_counts_recorded_commits() {
let newest_first = shas(&["h", "x1", "r1", "x2", "r2", "r3", "x3"]);
let annotated: BTreeSet<String> = shas(&["h", "r1", "r2", "r3"]).into_iter().collect();
assert_eq!(
select(&newest_first, &annotated, 3),
shas(&["r2", "x2", "r1", "x1", "h"])
);
}
#[test]
fn the_head_is_always_walked() {
let newest_first = shas(&["h", "x1", "r1", "x2"]);
let annotated: BTreeSet<String> = shas(&["r1"]).into_iter().collect();
assert_eq!(
select(&newest_first, &annotated, 20),
shas(&["r1", "x1", "h"])
);
assert_eq!(select(&shas(&["h"]), &BTreeSet::new(), 20), shas(&["h"]));
assert!(select(&[], &BTreeSet::new(), 20).is_empty());
}
#[test]
fn the_trend_covers_the_window() {
let d = analyze(&walk(&[Some(1.0), None, Some(2.0), Some(3.0)]), &pct(1.0));
let key = ("a".to_string(), "self".to_string(), "gha".to_string());
assert_eq!(d.trend[&key], vec![1.0, 2.0, 3.0]);
}
fn gates_with_a(a_pct: f64, min_delta: u64, enabled: bool) -> Gates {
let mut g = pct(1.0);
g.set_bench(
"a",
Gate {
pct: a_pct,
min_delta,
enabled,
},
);
g
}
fn two_series_step() -> Vec<(String, Vec<Record>)> {
vec![
(
"c0".to_string(),
vec![rec("a", "gha", 1000.0), rec("b", "gha", 1000.0)],
),
(
"c1".to_string(),
vec![rec("a", "gha", 1100.0), rec("b", "gha", 1100.0)],
),
]
}
#[test]
fn a_step_is_held_to_its_own_series_gate() {
let d = analyze(&two_series_step(), &gates_with_a(20.0, 0, true));
let f = d.failures();
assert_eq!(f.len(), 1);
assert_eq!(f[0].key.0, "b");
assert!(!d.uniform());
let md = markdown(&d, false);
assert!(md.contains("| gate |"), "{md}");
assert!(md.contains("stepped above their gate"), "{md}");
assert!(md.contains("(gate 1%)"), "{md}");
}
#[test]
fn a_step_within_its_floor_passes() {
let d = analyze(&two_series_step(), &gates_with_a(1.0, 500, true));
let f = d.failures();
assert_eq!(f.len(), 1);
assert_eq!(f[0].key.0, "b");
assert!(markdown(&d, false).contains("floor 500"));
}
#[test]
fn a_report_only_step_is_reported_and_never_fails() {
let d = analyze(&two_series_step(), &gates_with_a(1.0, 0, false));
let f = d.failures();
assert_eq!(f.len(), 1, "only the gated one fails");
assert_eq!(f[0].key.0, "b");
assert_eq!(d.reported().len(), 1);
assert_eq!(d.reported()[0].key.0, "a");
let md = markdown(&d, false);
assert!(md.contains("**+10.00%** (not gated)"), "{md}");
assert!(md.contains("report only (1%)"), "{md}");
assert!(
md.contains("1 report-only benchmark(s) stepped above their gate"),
"{md}"
);
let mut all = gates_with_a(1.0, 0, false);
all.set_bench(
"b",
Gate {
pct: 1.0,
min_delta: 0,
enabled: false,
},
);
let d = analyze(&two_series_step(), &all);
assert!(d.failures().is_empty());
assert!(!d.empty_fails());
assert!(markdown(&d, false).contains("Every benchmark here is report-only"));
}
#[test]
fn earlier_steps_use_the_series_gate() {
let w = walk(&[Some(1000.0), Some(1100.0), Some(1100.0)]);
assert_eq!(analyze(&w, &gates_with_a(20.0, 0, true)).earlier.len(), 0);
assert_eq!(analyze(&w, &gates_with_a(1.0, 0, false)).earlier.len(), 1);
}
#[test]
fn drift_uses_the_series_gate() {
let w = walk(&[Some(1000.0), Some(1004.0), Some(1008.0), Some(1012.0)]);
assert_eq!(analyze(&w, &pct(1.0)).drift.len(), 1);
assert!(analyze(&w, &gates_with_a(5.0, 0, true)).drift.is_empty());
assert!(analyze(&w, &gates_with_a(1.0, 50, true)).drift.is_empty());
let d = analyze(&w, &gates_with_a(1.0, 0, false));
assert_eq!(d.drift.len(), 1);
assert!(markdown(&d, false).contains("(gate report only (1%))"));
}
#[test]
fn a_uniform_report_keeps_its_wording() {
let d = analyze(&two_series_step(), &pct(1.0));
assert!(d.uniform());
let md = markdown(&d, false);
assert!(!md.contains("| gate |"), "{md}");
assert!(md.contains("stepped above the 1% gate"), "{md}");
}
fn flags(names: &[&str]) -> Acceptances {
let mut a = Acceptances::default();
for n in names {
a.add_name(n, crate::accept::Source::Flag).unwrap();
}
a
}
#[test]
fn an_accepted_step_is_reported_and_does_not_fail() {
let mut d = analyze(&two_series_step(), &pct(1.0));
d.accept(&flags(&["a"]), &BTreeMap::new());
let f = d.failures();
assert_eq!(f.len(), 1, "b is not accepted");
assert_eq!(f[0].key.0, "b");
assert_eq!(d.accepted_steps().len(), 1);
let md = markdown(&d, false);
assert!(md.contains("**+10.00%** (accepted)"), "{md}");
assert!(
md.contains("1 accepted step(s) above the 1% gate at `c1`, not failing:"),
"{md}"
);
assert!(md.contains("(accepted by `--accept`)"), "{md}");
d.accept(&flags(&["a", "b"]), &BTreeMap::new());
assert!(d.failures().is_empty());
let md = markdown(&d, false);
assert!(!md.contains("No instruction-count step"), "{md}");
assert!(md.contains("2 accepted step(s)"), "{md}");
}
#[test]
fn a_trailer_counts_only_in_its_steps_range() {
let w = vec![
("c0".to_string(), vec![rec("a", "gha", 1000.0)]),
("c1".to_string(), vec![rec("b", "gha", 1000.0)]),
(
"c2".to_string(),
vec![rec("a", "gha", 1100.0), rec("b", "gha", 1100.0)],
),
];
let mut d = analyze(&w, &pct(1.0));
let a = d.latest.iter().find(|s| s.key.0 == "a").unwrap();
assert_eq!(a.from, "c0");
let logs = BTreeMap::from([
("c0".to_string(), "c2\0\nc1\0a\0b\n".to_string()),
("c1".to_string(), "c2\0\n".to_string()),
]);
d.accept(&Acceptances::default(), &logs);
let f = d.failures();
assert_eq!(f.len(), 1);
assert_eq!(f[0].key.0, "b", "c1 is outside b's range");
let md = markdown(&d, false);
assert!(md.contains("(accepted by `Tak-Accept` in `c1`)"), "{md}");
}
#[test]
fn an_unused_acceptance_is_reported() {
let mut d = analyze(&walk(&[Some(1000.0), Some(1000.0)]), &pct(1.0));
d.accept(&flags(&["a", "nope"]), &BTreeMap::new());
let md = markdown(&d, false);
assert!(
md.contains("no step onto `c1` needed it, so nothing was accepted: `a` (`--accept`), `nope` (`--accept`)"),
"{md}"
);
}
#[test]
fn an_unused_acceptance_is_reported_when_nothing_was_compared() {
let mut d = analyze(&walk(&[Some(1000.0)]), &pct(1.0));
d.allow_empty = true;
d.accept(&flags(&["startupp"]), &BTreeMap::new());
assert!(d.nothing_compared());
let md = markdown(&d, false);
assert!(md.contains("Nothing was compared"), "{md}");
assert!(
md.contains("so nothing was accepted: `startupp` (`--accept`)"),
"{md}"
);
}
#[test]
fn an_older_step_is_never_marked_accepted() {
let mut d = analyze(
&walk(&[Some(1000.0), Some(1100.0), Some(1100.0)]),
&pct(1.0),
);
d.accept(&flags(&["a"]), &BTreeMap::new());
assert_eq!(d.earlier.len(), 1);
let md = markdown(&d, false);
assert!(!md.contains("(accepted)"), "{md}");
assert!(md.contains("**+10.00%** ⚠️"), "{md}");
}
#[test]
fn a_comma_trailer_names_one_benchmark() {
let mut d = analyze(&two_series_step(), &pct(1.0));
let logs = BTreeMap::from([
("c0".to_string(), "c1\0a,b\n".to_string()),
("c1".to_string(), "c1\0a,b\n".to_string()),
]);
d.accept(&Acceptances::default(), &logs);
assert_eq!(d.failures().len(), 2, "neither `a` nor `b` was named");
let md = markdown(&d, false);
assert!(!md.contains("(accepted"), "{md}");
assert!(md.contains("so nothing was accepted: `a,b`"), "{md}");
}
#[test]
fn a_control_character_in_an_acceptance_is_escaped() {
let mut d = analyze(&two_series_step(), &pct(1.0));
d.accept(
&flags(&["x\n**1 benchmark(s) stepped above"]),
&BTreeMap::new(),
);
d.ignored_trailers.add_trailer_log("c1\0y\u{1b}z\n");
let md = markdown(&d, false);
assert!(md.contains("`x\\n**1 benchmark(s) stepped above`"), "{md}");
assert!(md.contains("`y\\u{1b}z`"), "{md}");
assert_eq!(
md.lines()
.filter(|l| l.starts_with("**1 benchmark(s) stepped above"))
.count(),
0,
"{md}"
);
}
#[test]
fn ignored_trailers_are_named() {
let mut d = analyze(&two_series_step(), &pct(1.0));
d.ignored_trailers.add_trailer_log("c1\0a\n");
assert_eq!(d.failures().len(), 2, "an ignored trailer accepts nothing");
let md = markdown(&d, false);
assert!(
md.contains("`Tak-Accept` trailers were found but not honoured, because `gate.accept_trailers` is off: `a` (`Tak-Accept` in `c1`)"),
"{md}"
);
}
}