use crate::accept::Acceptances;
use crate::config::SELF_TOOL;
use crate::record::{Record, is_builtin_metric};
use std::collections::{BTreeMap, BTreeSet};
pub const GATED_METRIC: &str = "instructions";
pub(crate) const WALL_METRIC: &str = "wall_min_ms";
const ALLOC_METRICS: [(&str, &str); 3] = [
("alloc_blocks", "allocations"),
("alloc_bytes", "bytes allocated"),
("alloc_peak_bytes", "peak heap"),
];
pub type Key = (String, String, String);
#[derive(Debug, Clone, PartialEq)]
pub struct Change {
pub bench: String,
pub tool: String,
pub runner: String,
pub metric: String,
pub base: f64,
pub head: f64,
}
impl Change {
pub fn pct(&self) -> Option<f64> {
if self.base == 0.0 {
return None;
}
Some((self.head - self.base) / self.base * 100.0)
}
pub fn exceeds(&self, gate: &Gate) -> bool {
if self.metric != GATED_METRIC {
return false;
}
if self.head - self.base <= gate.min_delta as f64 {
return false;
}
match self.pct() {
Some(p) => p > gate.pct,
None => self.head > 0.0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Gate {
pub pct: f64,
pub min_delta: u64,
pub enabled: bool,
}
impl Gate {
pub fn new(pct: f64, min_delta: u64) -> anyhow::Result<Self> {
check_pct(pct)?;
Ok(Self {
pct,
min_delta,
enabled: true,
})
}
pub(crate) fn threshold(&self) -> String {
if self.min_delta == 0 {
format!("{}%", self.pct)
} else {
format!("{}%, floor {}", self.pct, thousands(self.min_delta as f64))
}
}
pub(crate) fn describe(&self) -> String {
if self.enabled {
self.threshold()
} else {
format!("report only ({})", self.threshold())
}
}
}
pub fn check_pct(pct: f64) -> anyhow::Result<()> {
if !pct.is_finite() || pct < 0.0 {
anyhow::bail!("a gate percentage must be a finite number, 0 or more, not {pct}");
}
Ok(())
}
#[derive(Debug, Clone, PartialEq)]
pub struct Gates {
pub global: Gate,
benches: BTreeMap<String, Gate>,
series: BTreeMap<(String, String), Gate>,
}
impl Gates {
pub fn uniform(global: Gate) -> Self {
Self {
global,
benches: BTreeMap::new(),
series: BTreeMap::new(),
}
}
pub fn set_bench(&mut self, bench: &str, gate: Gate) {
self.benches.insert(bench.to_string(), gate);
}
pub fn set_series(&mut self, bench: &str, tool: &str, gate: Gate) {
self.series
.insert((bench.to_string(), tool.to_string()), gate);
}
pub fn get(&self, bench: &str, tool: &str) -> Gate {
self.series
.get(&(bench.to_string(), tool.to_string()))
.or_else(|| self.benches.get(bench))
.copied()
.unwrap_or(self.global)
}
fn of(&self, c: &Change) -> Gate {
self.get(&c.bench, &c.tool)
}
pub fn changes_from(&self, base: &Gates, measured: &BTreeSet<(String, String)>) -> Vec<String> {
let mut out = Vec::new();
if self.global != base.global {
out.push(code("[gate]"));
}
let follows = |g: &Gates, gate: Gate| gate == g.global;
let mut named = BTreeSet::new();
for bench in self.benches.keys().chain(base.benches.keys()) {
let of = |g: &Gates| g.benches.get(bench).copied().unwrap_or(g.global);
let (mine, theirs) = (of(self), of(base));
if mine != theirs && !(follows(self, mine) && follows(base, theirs)) {
named.insert(bench.clone());
}
}
let series = self
.series
.keys()
.chain(base.series.keys())
.chain(measured.iter());
for (bench, tool) in series {
let (mine, theirs) = (self.get(bench, tool), base.get(bench, tool));
if mine != theirs && !(follows(self, mine) && follows(base, theirs)) {
named.insert(name(bench, tool));
}
}
out.extend(named.iter().map(|n| code(n)));
out
}
}
#[derive(Debug, Default, PartialEq)]
pub struct Comparison {
pub changes: Vec<Change>,
pub added: Vec<Key>,
pub removed: Vec<Key>,
pub accepted: Acceptances,
pub ignored_trailers: Acceptances,
pub gate_source: Option<String>,
pub allowed_empty: bool,
}
impl Comparison {
pub fn regressions(&self, gates: &Gates) -> Vec<&Change> {
self.changes
.iter()
.filter(|c| {
let gate = gates.of(c);
gate.enabled && c.exceeds(&gate)
})
.collect()
}
pub fn failures(&self, gates: &Gates) -> Vec<&Change> {
self.regressions(gates)
.into_iter()
.filter(|c| !self.accepted.covers(&c.bench))
.collect()
}
pub fn accepted_regressions(&self, gates: &Gates) -> Vec<&Change> {
self.regressions(gates)
.into_iter()
.filter(|c| self.accepted.covers(&c.bench))
.collect()
}
pub fn with_accepted(mut self, accepted: Acceptances) -> Self {
self.accepted = accepted;
self
}
pub fn with_ignored_trailers(mut self, ignored: Acceptances) -> Self {
self.ignored_trailers = ignored;
self
}
pub fn reported(&self, gates: &Gates) -> Vec<&Change> {
self.changes
.iter()
.filter(|c| {
let gate = gates.of(c);
!gate.enabled && c.exceeds(&gate)
})
.collect()
}
pub fn gated_uniformly(&self, gates: &Gates) -> bool {
self.changes
.iter()
.filter(|c| c.metric == GATED_METRIC)
.all(|c| gates.of(c) == gates.global)
}
pub fn is_empty(&self) -> bool {
self.changes.is_empty()
}
}
pub(crate) fn index(records: &[Record]) -> BTreeMap<(Key, String), f64> {
let mut out: BTreeMap<(Key, String), f64> = BTreeMap::new();
for r in records {
let key: Key = (r.bench.clone(), r.tool.clone(), r.runner.clone());
for (metric, value) in &r.metrics {
out.entry((key.clone(), metric.clone()))
.and_modify(|existing| {
if value < existing {
*existing = *value;
}
})
.or_insert(*value);
}
}
out
}
pub fn compare(base: &[Record], head: &[Record]) -> Comparison {
let (b, h) = (index(base), index(head));
let mut changes = Vec::new();
for ((key, metric), head_value) in &h {
if let Some(base_value) = b.get(&(key.clone(), metric.clone())) {
changes.push(Change {
bench: key.0.clone(),
tool: key.1.clone(),
runner: key.2.clone(),
metric: metric.clone(),
base: *base_value,
head: *head_value,
});
}
}
let base_keys: BTreeSet<Key> = b.keys().map(|(k, _)| k.clone()).collect();
let head_keys: BTreeSet<Key> = h.keys().map(|(k, _)| k.clone()).collect();
Comparison {
changes,
added: head_keys.difference(&base_keys).cloned().collect(),
removed: base_keys.difference(&head_keys).cloned().collect(),
accepted: Acceptances::default(),
ignored_trailers: Acceptances::default(),
gate_source: None,
allowed_empty: false,
}
}
pub type Trend = BTreeMap<Key, Vec<f64>>;
pub fn build_trend(
walked: &[(String, Vec<Record>)],
head_sha: &str,
head_records: &[Record],
) -> Trend {
let mut trend = Trend::new();
let mut head_in_history = false;
for (sha, records) in walked {
if sha == head_sha {
head_in_history = true;
add_point(&mut trend, head_records);
} else {
add_point(&mut trend, records);
}
}
if !head_in_history {
add_point(&mut trend, head_records);
}
trend
}
fn add_point(trend: &mut Trend, records: &[Record]) {
let mut lowest: BTreeMap<Key, f64> = BTreeMap::new();
for r in records {
if let Some(v) = r.metrics.get(GATED_METRIC) {
lowest
.entry((r.bench.clone(), r.tool.clone(), r.runner.clone()))
.and_modify(|e| {
if v < e {
*e = *v;
}
})
.or_insert(*v);
}
}
for (key, value) in lowest {
trend.entry(key).or_default().push(value);
}
}
const BARS: [char; 8] = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
pub fn sparkline(values: &[f64]) -> String {
if values.len() < 2 {
return String::new();
}
let min = values.iter().copied().fold(f64::INFINITY, f64::min);
let max = values.iter().copied().fold(f64::NEG_INFINITY, f64::max);
if max <= min {
return BARS[BARS.len() / 2].to_string().repeat(values.len());
}
values
.iter()
.map(|v| {
let t = (v - min) / (max - min);
let i = (t * (BARS.len() - 1) as f64).round() as usize;
BARS[i.min(BARS.len() - 1)]
})
.collect()
}
pub(crate) fn thousands(v: f64) -> String {
let n = format!("{:.0}", v.abs());
let mut out = String::new();
for (i, c) in n.chars().enumerate() {
if i > 0 && (n.len() - i) % 3 == 0 {
out.push(',');
}
out.push(c);
}
if v < 0.0 { format!("-{out}") } else { out }
}
pub(crate) fn signed_pct(p: Option<f64>) -> String {
match p {
Some(p) => format!("{}{:.2}%", if p >= 0.0 { "+" } else { "" }, p),
None => "new".to_string(),
}
}
pub(crate) const CREDIT: &str = "\n<sub>Measured by [tak](https://github.com/jdx/tak) — instruction-counted \
CLI benchmarks, stored in this repository's git notes.</sub>\n";
pub const ALLOWED_EMPTY: &str = "This passes with a warning instead of failing, because \
`allow_empty` is on. That is expected on a new runner class, for a new benchmark, or on \
a first recording. It is also what history that was never recorded or never fetched \
looks like, so check which this is.";
pub fn markdown(c: &Comparison, trend: &Trend, gates: &Gates, credit: bool) -> String {
let mut out = String::new();
if c.is_empty() {
out.push_str(
"**Nothing was compared, and so nothing was gated.** No series \
appears on both sides: either the base has no measurements \
recorded, or the two were measured on different runner classes, \
which are deliberately not comparable — counts shift between \
machine types by more than a real regression does.\n",
);
if c.allowed_empty {
out.push_str(&format!("\n{ALLOWED_EMPTY}\n"));
}
} else {
out.push_str(&table(c, trend, gates));
out.push_str(&allocations(c));
out.push_str(&custom_table(c));
}
if let Some(line) = &c.gate_source {
out.push_str(&format!("\n{line}\n"));
}
out.push_str(&unused_acceptances(c, gates));
out.push_str(&ignored_trailers(c));
out.push_str(&outliers(c));
out.push_str(
"\n<sub>Only instruction counts gate. 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 row_name<'a>(key: &Key, keys: impl IntoIterator<Item = &'a Key>) -> String {
let (bench, tool, runner) = key;
let shared = keys
.into_iter()
.any(|(b, t, r)| b == bench && t == tool && r != runner);
let text = if shared {
format!("{} on {}", name(bench, tool), escape_control(runner))
} else {
name(bench, tool)
};
cell(&text)
}
fn name(bench: &str, tool: &str) -> String {
let bench = escape_control(bench);
if tool == SELF_TOOL {
bench.into_owned()
} else {
format!("{bench} ({})", escape_control(tool))
}
}
fn table(c: &Comparison, trend: &Trend, gates: &Gates) -> String {
let mut out = String::new();
let mut series: BTreeMap<Key, (Option<&Change>, Option<&Change>)> = BTreeMap::new();
for change in &c.changes {
let key = (
change.bench.clone(),
change.tool.clone(),
change.runner.clone(),
);
let slot = series.entry(key).or_insert((None, None));
match change.metric.as_str() {
GATED_METRIC => slot.0 = Some(change),
WALL_METRIC => slot.1 = Some(change),
_ => {}
}
}
let any_trend = series
.keys()
.any(|k| trend.get(k).is_some_and(|v| v.len() > 1));
let uniform = c.gated_uniformly(gates);
let mut header = vec![("benchmark", "---")];
if any_trend {
header.push(("trend", "---"));
}
header.extend([("instructions", "---:"), ("Δ", "---:")]);
if !uniform {
header.push(("gate", "---"));
}
header.extend([("wall (min)", "---:"), ("Δ", "---:")]);
let row = |cells: &[String]| format!("| {} |\n", cells.join(" | "));
out.push_str(&row(&header
.iter()
.map(|(h, _)| h.to_string())
.collect::<Vec<_>>()));
out.push_str(&format!(
"|{}|\n",
header.iter().map(|(_, a)| *a).collect::<Vec<_>>().join("|")
));
for (key, (ins, wall)) in &series {
let (bench, tool, _runner) = key;
let gate = gates.get(bench, tool);
let mut cells = vec![row_name(key, series.keys())];
if any_trend {
cells.push(
trend
.get(key)
.map(|v| sparkline(v))
.filter(|s| !s.is_empty())
.map(|s| format!("`{s}`"))
.unwrap_or_else(|| "—".into()),
);
}
match ins {
Some(ch) => {
let flag = match (ch.exceeds(&gate), gate.enabled) {
(true, true) if c.accepted.covers(bench) => " (accepted)",
(true, true) => " ⚠️",
(true, false) => " (not gated)",
(false, _) => "",
};
cells.push(format!("{} → {}", thousands(ch.base), thousands(ch.head)));
cells.push(format!("**{}**{flag}", signed_pct(ch.pct())));
}
None => cells.extend(["—".into(), "—".into()]),
}
if !uniform {
cells.push(if ins.is_some() {
gate.describe()
} else {
"—".into()
});
}
match wall {
Some(ch) => {
cells.push(format!("{:.2} → {:.2}ms", ch.base, ch.head));
cells.push(signed_pct(ch.pct()));
}
None => cells.extend(["—".into(), "—".into()]),
}
out.push_str(&row(&cells));
}
out.push('\n');
out.push_str(&verdict(c, gates, uniform));
out
}
fn verdict(c: &Comparison, gates: &Gates, uniform: bool) -> String {
let mut out = String::new();
let global = gates.global;
let listed = |changes: &[&Change], annotate: bool| {
changes
.iter()
.map(|ch| {
let mut s = format!("`{}` {}", name(&ch.bench, &ch.tool), signed_pct(ch.pct()));
if annotate {
s.push_str(&format!(" (gate {})", gates.of(ch).threshold()));
}
s
})
.collect::<Vec<_>>()
.join(", ")
};
let regressions = c.regressions(gates);
let failures = c.failures(gates);
let accepted = c.accepted_regressions(gates);
if uniform {
let floor = if global.min_delta == 0 {
String::new()
} else {
format!(
" (rises of {} instructions or fewer are not counted)",
thousands(global.min_delta as f64)
)
};
if regressions.is_empty() {
out.push_str(&format!(
"No instruction-count regression above {}%{floor}.\n",
global.pct,
));
} else if !failures.is_empty() {
out.push_str(&format!(
"**{} benchmark(s) above the {}% gate{floor}:** {}\n",
failures.len(),
global.pct,
listed(&failures, false)
));
}
out.push_str(&accepted_line(
c,
&accepted,
&format!("the {}% gate", global.pct),
!failures.is_empty(),
|_| String::new(),
));
return out;
}
let any_gated = c
.changes
.iter()
.any(|ch| ch.metric == GATED_METRIC && gates.of(ch).enabled);
if !any_gated {
out.push_str("Every benchmark here is report-only, so none can fail the gate.\n");
} else if regressions.is_empty() {
out.push_str("No gated benchmark rose beyond its gate.\n");
} else if !failures.is_empty() {
out.push_str(&format!(
"**{} benchmark(s) above their gate:** {}\n",
failures.len(),
listed(&failures, true)
));
}
out.push_str(&accepted_line(
c,
&accepted,
"their gate",
!failures.is_empty(),
|ch| format!(" (gate {})", gates.of(ch).threshold()),
));
let reported = c.reported(gates);
if !reported.is_empty() {
out.push_str(&format!(
"\n**{} report-only benchmark(s) above their gate, not failing:** {}\n",
reported.len(),
listed(&reported, true)
));
}
out
}
fn allocations(c: &Comparison) -> String {
let mut series: BTreeMap<Key, BTreeMap<&str, &Change>> = BTreeMap::new();
for change in &c.changes {
if ALLOC_METRICS.iter().any(|(m, _)| *m == change.metric) {
series
.entry((
change.bench.clone(),
change.tool.clone(),
change.runner.clone(),
))
.or_default()
.insert(change.metric.as_str(), change);
}
}
if series.is_empty() {
return String::new();
}
let mut out = String::from("\nHeap allocations, counted by DHAT; reported, not gated:\n\n");
out.push_str("| benchmark |");
for (_, title) in ALLOC_METRICS {
out.push_str(&format!(" {title} | Δ |"));
}
out.push_str("\n|---|");
out.push_str(&"---:|---:|".repeat(ALLOC_METRICS.len()));
out.push('\n');
for (key, metrics) in &series {
out.push_str(&format!("| {} |", row_name(key, series.keys())));
for (metric, _) in ALLOC_METRICS {
match metrics.get(metric) {
Some(ch) => out.push_str(&format!(
" {} → {} | {} |",
thousands(ch.base),
thousands(ch.head),
count_delta(ch)
)),
None => out.push_str(" — | — |"),
}
}
out.push('\n');
}
out
}
fn custom_table(c: &Comparison) -> String {
let rows: Vec<&Change> = c
.changes
.iter()
.filter(|ch| !is_builtin_metric(&ch.metric))
.collect();
if rows.is_empty() {
return String::new();
}
let mut out = String::from("\n| benchmark | metric | value | Δ |\n|---|---|---:|---:|\n");
for ch in rows {
out.push_str(&format!(
"| {} | {} | {} → {} | {} |\n",
cell(&name(&ch.bench, &ch.tool)),
cell(&escape_control(&ch.metric)),
plain(ch.base),
plain(ch.head),
signed_pct(ch.pct())
));
}
out.push_str(
"\n<sub>Metrics declared in tak.toml are reported, never gated. As for every \
metric, lower is taken as better.</sub>\n",
);
out
}
fn plain(v: f64) -> String {
if v.fract() == 0.0 && v.abs() < 1e15 {
thousands(v)
} else {
v.to_string()
}
}
fn accepted_line(
c: &Comparison,
accepted: &[&Change],
which: &str,
after_failures: bool,
gate_of: impl Fn(&Change) -> String,
) -> String {
if accepted.is_empty() {
return String::new();
}
format!(
"{}**{} accepted regression(s) above {which}, not failing it:** {}\n",
if after_failures { "\n" } else { "" },
accepted.len(),
accepted
.iter()
.map(|ch| format!(
"{} on {} {}{} ({})",
code(&name(&ch.bench, &ch.tool)),
code(&ch.runner),
signed_pct(ch.pct()),
gate_of(ch),
c.accepted.describe(&ch.bench)
))
.collect::<Vec<_>>()
.join(", ")
)
}
pub(crate) fn code(text: &str) -> String {
let text = escape_control(text);
let text = text.as_ref();
let mut longest = 0;
let mut run = 0;
for ch in text.chars() {
run = if ch == '`' { run + 1 } else { 0 };
longest = longest.max(run);
}
let fence = "`".repeat(longest + 1);
let edge_space = text.starts_with(' ') || text.ends_with(' ');
let only_spaces = text.chars().all(|c| c == ' ');
if (longest > 0 || edge_space) && !only_spaces {
format!("{fence} {text} {fence}")
} else {
format!("{fence}{text}{fence}")
}
}
pub(crate) fn cell(text: &str) -> String {
text.replace('\\', "\\\\").replace('|', "\\|")
}
pub(crate) fn code_cell(text: &str) -> String {
text.replace('|', "\\|")
}
pub fn gate_source(path: Option<&str>, at: &str, changed: &[String]) -> Option<String> {
let later = (!changed.is_empty()).then(|| {
format!(
" This revision changes the gate policy ({}), and the change takes effect \
once it is merged.",
changed.join(", ")
)
});
match (path, later) {
(None, later) => Some(format!(
"No {} at the base, {}, so the gate is tak's defaults plus any flags and \
environment variables.{}",
code(crate::config::FILE_NAME),
code(at),
later.unwrap_or_default()
)),
(Some(path), Some(later)) => Some(format!(
"The gate comes from {} at the base, {}.{later}",
code(path),
code(at)
)),
(Some(_), None) => None,
}
}
fn ignored_trailers(c: &Comparison) -> String {
if c.ignored_trailers.is_empty() {
return String::new();
}
format!(
"\n`{}` trailers were found but not honoured, because `gate.accept_trailers` is \
off: {}\n",
crate::accept::TRAILER,
c.ignored_trailers
.iter()
.map(|(bench, _)| format!("{} ({})", code(bench), c.ignored_trailers.describe(bench)))
.collect::<Vec<_>>()
.join(", ")
)
}
fn unused_acceptances(c: &Comparison, gates: &Gates) -> String {
let mut quiet = Vec::new();
let mut report_only = Vec::new();
let mut unknown = Vec::new();
for (bench, _) in c.accepted.iter() {
let entry = format!("{} ({})", code(bench), c.accepted.describe(bench));
let counted: Vec<&Change> = c
.changes
.iter()
.filter(|ch| ch.bench == bench && ch.metric == GATED_METRIC)
.collect();
if !c.changes.iter().any(|ch| ch.bench == bench) {
unknown.push(entry);
} else if counted.iter().any(|ch| {
let gate = gates.of(ch);
gate.enabled && ch.exceeds(&gate)
}) {
} else if !counted.is_empty() && counted.iter().all(|ch| !gates.of(ch).enabled) {
report_only.push(entry);
} else {
quiet.push(entry);
}
}
let mut out = String::new();
if !quiet.is_empty() {
out.push_str(&format!(
"\nAccepted, but not above its gate, so nothing was accepted: {}\n",
quiet.join(", ")
));
}
if !report_only.is_empty() {
out.push_str(&format!(
"\nAccepted, but report-only, so it can never fail and nothing was accepted: {}\n",
report_only.join(", ")
));
}
if !unknown.is_empty() {
out.push_str(&format!(
"\nAccepted, but no benchmark by that name was compared on both sides: {}\n",
unknown.join(", ")
));
}
out
}
fn count_delta(ch: &Change) -> String {
match ch.pct() {
Some(p) => signed_pct(Some(p)),
None if ch.head == ch.base => signed_pct(Some(0.0)),
None => format!("+{} (from 0)", thousands(ch.head - ch.base)),
}
}
pub fn escape_control(text: &str) -> std::borrow::Cow<'_, str> {
if !text.chars().any(char::is_control) {
return std::borrow::Cow::Borrowed(text);
}
text.chars()
.map(|c| {
if c.is_control() {
c.escape_default().to_string()
} else {
c.to_string()
}
})
.collect::<String>()
.into()
}
pub fn describe(key: &Key) -> String {
let (bench, tool, runner) = key;
let (bench, tool, runner) = (
escape_control(bench),
escape_control(tool),
escape_control(runner),
);
if tool == "self" {
format!("`{bench}` on `{runner}`")
} else {
format!("`{bench}` ({tool}) on `{runner}`")
}
}
fn outliers(c: &Comparison) -> String {
let mut out = String::new();
if !c.added.is_empty() {
out.push_str(&format!(
"\nNew, nothing to compare against: {}\n",
c.added.iter().map(describe).collect::<Vec<_>>().join(", ")
));
}
if !c.removed.is_empty() {
out.push_str(&format!(
"\nMeasured on the base but not here — a benchmark that stops \
running also stops gating: {}\n",
c.removed
.iter()
.map(describe)
.collect::<Vec<_>>()
.join(", ")
));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::accept::Source;
fn key(bench: &str) -> Key {
(bench.to_string(), "self".to_string(), "gha".to_string())
}
fn rec(bench: &str, runner: &str, ins: f64, wall: 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(), wall),
]),
}
}
fn g(pct: f64) -> Gates {
Gates::uniform(Gate::new(pct, 0).unwrap())
}
fn gate(pct: f64, min_delta: u64, enabled: bool) -> Gate {
Gate {
pct,
min_delta,
enabled,
}
}
#[test]
fn a_gate_source_path_with_a_backtick_stays_one_code_span() {
let changed = [code("[gate]")];
let line = gate_source(Some("we`ird/tak.toml"), "a1b2c3d4e5f6", &changed).unwrap();
assert_eq!(
line,
"The gate comes from `` we`ird/tak.toml `` at the base, `a1b2c3d4e5f6`. \
This revision changes the gate policy (`[gate]`), and the change takes \
effect once it is merged."
);
let line = gate_source(Some("a\nb/tak.toml"), "a1b2c3d4e5f6", &changed).unwrap();
assert!(!line.contains('\n'), "{line}");
assert_eq!(gate_source(Some("tak.toml"), "a1b2c3d4e5f6", &[]), None);
assert_eq!(
gate_source(None, "a1b2c3d4e5f6", &[]).unwrap(),
"No `tak.toml` at the base, `a1b2c3d4e5f6`, so the gate is tak's defaults \
plus any flags and environment variables."
);
}
#[test]
fn gate_changes_are_effective_and_escaped() {
let global = gate(1.0, 0, true);
let base = Gates::uniform(global);
let mut head = Gates::uniform(global);
head.set_bench("new", global);
head.set_series("new", SELF_TOOL, global);
assert!(head.changes_from(&base, &BTreeSet::new()).is_empty());
let evil = "a\n**0 benchmark(s) above the 1% gate:**".to_string();
head.set_series(&evil, SELF_TOOL, gate(1.0, 0, false));
let measured = BTreeSet::from([(evil, SELF_TOOL.to_string())]);
let changes = head.changes_from(&base, &measured);
assert_eq!(changes.len(), 1, "{changes:?}");
assert!(!changes[0].contains('\n'), "{changes:?}");
assert!(changes[0].starts_with('`'), "{changes:?}");
}
fn startup_and_install() -> Comparison {
compare(
&[
rec("startup", "gha", 450_000.0, 1.0),
rec("install", "gha", 100_000_000.0, 100.0),
],
&[
rec("startup", "gha", 459_000.0, 1.0),
rec("install", "gha", 102_000_000.0, 100.0),
],
)
}
fn benches(c: &[&Change]) -> Vec<String> {
c.iter().map(|c| c.bench.clone()).collect()
}
#[test]
fn a_regression_crosses_both_the_percentage_and_the_floor() {
let rise = Change {
bench: "a".into(),
tool: SELF_TOOL.into(),
runner: "gha".into(),
metric: GATED_METRIC.into(),
base: 1_000_000.0,
head: 1_020_000.0,
};
let cases = [
(1.0, 0, true), (5.0, 0, false), (1.0, 10_000, true), (1.0, 20_000, false), (1.0, 50_000, false), (5.0, 10_000, false), (2.0, 0, false), (0.0, 0, true), ];
for (pct, min_delta, want) in cases {
assert_eq!(
rise.exceeds(&gate(pct, min_delta, true)),
want,
"pct {pct}, min_delta {min_delta}"
);
assert_eq!(rise.exceeds(&gate(pct, min_delta, false)), want);
}
let fall = Change {
head: 500_000.0,
..rise.clone()
};
assert!(
!fall.exceeds(&gate(0.0, 0, true)),
"an improvement never gates"
);
let wall = Change {
metric: WALL_METRIC.into(),
..rise
};
assert!(!wall.exceeds(&gate(0.0, 0, true)), "wall clock never gates");
}
#[test]
fn a_zero_base_is_still_held_to_the_floor() {
let c = compare(
&[rec("a", "gha", 0.0, 1.0)],
&[rec("a", "gha", 5_000.0, 1.0)],
);
assert_eq!(c.regressions(&g(1.0)).len(), 1);
let floored = Gates::uniform(Gate::new(1.0, 10_000).unwrap());
assert!(c.regressions(&floored).is_empty());
}
#[test]
fn a_gate_percentage_must_be_finite_and_not_negative() {
assert!(Gate::new(0.0, 0).is_ok());
assert!(Gate::new(250.0, 0).is_ok());
for bad in [-1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
let err = Gate::new(bad, 0).unwrap_err();
assert!(format!("{err}").contains("gate percentage"), "{err}");
}
}
#[test]
fn a_series_gate_beats_its_benchmarks_which_beats_the_global_one() {
let mut gates = g(1.0);
gates.set_bench("install", gate(5.0, 0, true));
gates.set_series("install", "pnpm", gate(10.0, 0, false));
assert_eq!(gates.get("install", "pnpm"), gate(10.0, 0, false));
assert_eq!(
gates.get("install", "npm"),
gate(5.0, 0, true),
"a subject the benchmark no longer declares gets the benchmark's"
);
assert_eq!(
gates.get("gone", SELF_TOOL),
gate(1.0, 0, true),
"a benchmark no longer in tak.toml gets the global gate"
);
}
#[test]
fn a_per_benchmark_gate_decides_its_own_series_only() {
let c = startup_and_install();
assert_eq!(benches(&c.regressions(&g(1.0))), ["install", "startup"]);
let mut gates = g(1.0);
gates.set_series("startup", SELF_TOOL, gate(5.0, 0, true));
assert_eq!(benches(&c.regressions(&gates)), ["install"]);
let mut gates = g(5.0);
gates.set_series("install", SELF_TOOL, gate(1.0, 0, true));
assert_eq!(benches(&c.regressions(&gates)), ["install"]);
}
#[test]
fn subjects_of_one_benchmark_take_their_own_gates() {
let with_tool = |tool: &str, ins: f64| Record {
tool: tool.into(),
..rec("install", "gha", ins, 1.0)
};
let c = compare(
&[
with_tool("mine", 1_000_000.0),
with_tool("theirs", 1_000_000.0),
],
&[
with_tool("mine", 1_100_000.0),
with_tool("theirs", 1_100_000.0),
],
);
let mut gates = g(1.0);
gates.set_series("install", "theirs", gate(1.0, 0, false));
let tools = |v: Vec<&Change>| v.iter().map(|c| c.tool.clone()).collect::<Vec<_>>();
assert_eq!(tools(c.regressions(&gates)), ["mine"]);
assert_eq!(tools(c.reported(&gates)), ["theirs"]);
}
#[test]
fn a_report_only_series_is_flagged_and_never_fails() {
let c = startup_and_install();
let mut gates = g(1.0);
gates.set_series("startup", SELF_TOOL, gate(1.0, 0, false));
assert_eq!(benches(&c.regressions(&gates)), ["install"]);
assert_eq!(benches(&c.reported(&gates)), ["startup"]);
let md = markdown(&c, &Trend::new(), &gates, false);
assert!(md.contains("| gate |"), "{md}");
assert!(md.contains("report only (1%)"), "{md}");
assert!(md.contains("**+2.00%** (not gated)"), "{md}");
assert!(
md.contains("**1 benchmark(s) above their gate:** `install` +2.00% (gate 1%)"),
"{md}"
);
assert!(
md.contains(
"**1 report-only benchmark(s) above their gate, not failing:** \
`startup` +2.00% (gate 1%)"
),
"{md}"
);
}
#[test]
fn uniform_gates_render_the_report_unchanged() {
let md = markdown(&startup_and_install(), &Trend::new(), &g(1.0), false);
assert_eq!(
md,
"| benchmark | instructions | Δ | wall (min) | Δ |\n\
|---|---:|---:|---:|---:|\n\
| install | 100,000,000 → 102,000,000 | **+2.00%** ⚠️ | 100.00 → 100.00ms | +0.00% |\n\
| startup | 450,000 → 459,000 | **+2.00%** ⚠️ | 1.00 → 1.00ms | +0.00% |\n\
\n\
**2 benchmark(s) above the 1% gate:** `install` +2.00%, `startup` +2.00%\n\
\n\
<sub>Only instruction counts gate. Wall clock is shown for context — \
on identical hardware it moves 4-20% run to run.</sub>\n"
);
let mut same = g(1.0);
same.set_series("startup", SELF_TOOL, gate(1.0, 0, true));
assert_eq!(
markdown(&startup_and_install(), &Trend::new(), &same, false),
md
);
}
#[test]
fn a_differing_gate_adds_a_column_with_every_rows_gate() {
let mut gates = g(1.0);
gates.set_series("startup", SELF_TOOL, gate(5.0, 20_000, true));
let md = markdown(&startup_and_install(), &Trend::new(), &gates, false);
assert!(
md.contains("| benchmark | instructions | Δ | gate | wall (min) | Δ |\n|---|---:|---:|---|---:|---:|\n"),
"{md}"
);
assert!(md.contains("| **+2.00%** | 5%, floor 20,000 |"), "{md}");
assert!(md.contains("| **+2.00%** ⚠️ | 1% |"), "{md}");
assert!(
md.contains("above their gate:** `install` +2.00% (gate 1%)\n"),
"{md}"
);
}
#[test]
fn nothing_over_any_gate_says_so() {
let mut gates = g(5.0);
gates.set_series("startup", SELF_TOOL, gate(10.0, 0, true));
let md = markdown(&startup_and_install(), &Trend::new(), &gates, false);
assert!(
md.contains("No gated benchmark rose beyond its gate."),
"{md}"
);
assert!(!md.contains("report-only"), "{md}");
}
#[test]
fn a_table_with_nothing_gated_says_so() {
let mut gates = g(1.0);
gates.set_series("startup", SELF_TOOL, gate(1.0, 0, false));
gates.set_series("install", SELF_TOOL, gate(50.0, 0, false));
let md = markdown(&startup_and_install(), &Trend::new(), &gates, false);
assert!(
md.contains("Every benchmark here is report-only, so none can fail the gate."),
"{md}"
);
assert!(!md.contains("No gated benchmark"), "{md}");
assert!(
md.contains("**1 report-only benchmark(s) above their gate, not failing:** `startup`"),
"{md}"
);
}
#[test]
fn a_global_floor_is_named_in_the_verdict() {
let gates = Gates::uniform(Gate::new(1.0, 20_000).unwrap());
let md = markdown(&startup_and_install(), &Trend::new(), &gates, false);
assert!(
!md.contains("| gate |"),
"the global gate needs no column: {md}"
);
assert!(
md.contains(
"**1 benchmark(s) above the 1% gate \
(rises of 20,000 instructions or fewer are not counted):** `install` +2.00%"
),
"{md}"
);
let c = compare(
&[rec("a", "gha", 1_000.0, 1.0)],
&[rec("a", "gha", 1_500.0, 1.0)],
);
let md = markdown(&c, &Trend::new(), &gates, false);
assert!(
md.contains(
"No instruction-count regression above 1% \
(rises of 20,000 instructions or fewer are not counted)."
),
"{md}"
);
}
#[test]
fn a_rise_beyond_the_gate_is_a_regression() {
let c = compare(
&[rec("a", "gha", 1_000_000.0, 10.0)],
&[rec("a", "gha", 1_020_000.0, 10.0)],
);
assert_eq!(c.regressions(&g(1.0)).len(), 1, "2% should trip a 1% gate");
assert!(c.regressions(&g(5.0)).is_empty(), "2% should not trip 5%");
}
#[test]
fn an_improvement_never_gates() {
let c = compare(
&[rec("a", "gha", 1_000_000.0, 10.0)],
&[rec("a", "gha", 500_000.0, 10.0)],
);
assert!(c.regressions(&g(1.0)).is_empty());
let ins = c.changes.iter().find(|c| c.metric == GATED_METRIC).unwrap();
assert_eq!(ins.pct().unwrap().round(), -50.0);
}
#[test]
fn wall_clock_never_gates_however_bad_it_looks() {
let c = compare(
&[rec("a", "gha", 1_000_000.0, 10.0)],
&[rec("a", "gha", 1_000_000.0, 100.0)],
);
assert!(c.regressions(&g(0.001)).is_empty());
let wall = c.changes.iter().find(|c| c.metric == WALL_METRIC).unwrap();
assert_eq!(wall.pct().unwrap().round(), 900.0);
}
#[test]
fn a_different_runner_is_not_a_comparison() {
let c = compare(
&[rec("a", "gha-linux", 1_000_000.0, 10.0)],
&[rec("a", "gha-macos", 2_000_000.0, 10.0)],
);
assert!(c.is_empty(), "nothing should line up");
assert_eq!(c.added.len(), 1);
assert_eq!(c.removed.len(), 1);
assert!(c.regressions(&g(1.0)).is_empty());
let md = markdown(&c, &Trend::new(), &g(1.0), false);
assert!(md.contains("nothing was gated"), "{md}");
assert!(md.contains("gha-macos"), "the new runner is unnamed: {md}");
assert!(md.contains("gha-linux"), "the old runner is unnamed: {md}");
}
#[test]
fn allowing_an_empty_comparison_keeps_the_first_line() {
const FIRST: &str = "**Nothing was compared, and so nothing was gated.** No series \
appears on both sides: either the base has no measurements recorded, or the two \
were measured on different runner classes, which are deliberately not \
comparable — counts shift between machine types by more than a real regression \
does.";
let mut c = compare(
&[rec("a", "gha-old", 1e6, 1.0)],
&[rec("a", "gha-new", 1e6, 1.0)],
);
let refused = markdown(&c, &Trend::new(), &g(1.0), false);
assert_eq!(refused.lines().next(), Some(FIRST), "{refused}");
assert!(!refused.contains(ALLOWED_EMPTY), "{refused}");
c.allowed_empty = true;
let allowed = markdown(&c, &Trend::new(), &g(1.0), false);
assert_eq!(allowed.lines().next(), Some(FIRST), "{allowed}");
assert_eq!(allowed.lines().nth(2), Some(ALLOWED_EMPTY), "{allowed}");
assert!(ALLOWED_EMPTY.contains("`allow_empty`"));
assert!(
allowed.contains("gha-new") && allowed.contains("gha-old"),
"{allowed}"
);
}
#[test]
fn a_head_with_no_measurements_names_what_vanished() {
let c = compare(
&[
rec("a", "gha", 1_000_000.0, 10.0),
rec("b", "gha", 2.0, 2.0),
],
&[],
);
let md = markdown(&c, &Trend::new(), &g(1.0), false);
assert!(c.regressions(&g(1.0)).is_empty());
assert!(md.contains("nothing was gated"), "{md}");
assert!(md.contains("`a`") && md.contains("`b`"), "{md}");
assert!(md.contains("stops gating"), "{md}");
}
#[test]
fn the_gating_caveat_survives_an_empty_comparison() {
let md = markdown(&compare(&[], &[]), &Trend::new(), &g(1.0), false);
assert!(md.contains("Only instruction counts gate"), "{md}");
}
#[test]
fn a_new_benchmark_is_reported_but_not_gated() {
let c = compare(
&[rec("a", "gha", 1_000_000.0, 10.0)],
&[
rec("a", "gha", 1_000_000.0, 10.0),
rec("b", "gha", 9.9e9, 10.0),
],
);
assert_eq!(
c.added,
vec![("b".to_string(), "self".to_string(), "gha".to_string())]
);
assert!(c.regressions(&g(1.0)).is_empty());
}
#[test]
fn a_vanished_benchmark_is_surfaced() {
let c = compare(
&[
rec("a", "gha", 1_000_000.0, 10.0),
rec("b", "gha", 1.0, 1.0),
],
&[rec("a", "gha", 1_000_000.0, 10.0)],
);
assert_eq!(c.removed.len(), 1);
assert!(markdown(&c, &Trend::new(), &g(1.0), false).contains("stops gating"));
}
#[test]
fn duplicate_records_reduce_to_the_minimum() {
let c = compare(
&[rec("a", "gha", 1_000_000.0, 10.0)],
&[
rec("a", "gha", 3_000_000.0, 30.0),
rec("a", "gha", 1_000_000.0, 10.0),
],
);
assert!(
c.regressions(&g(1.0)).is_empty(),
"the clean sample should win"
);
}
#[test]
fn nothing_in_common_says_so_rather_than_passing_quietly() {
let c = compare(&[], &[rec("a", "gha", 1.0, 1.0)]);
assert!(c.is_empty());
assert!(markdown(&c, &Trend::new(), &g(1.0), false).contains("nothing was gated"));
}
#[test]
fn a_rise_from_a_zero_base_still_gates() {
let c = compare(
&[rec("a", "gha", 0.0, 10.0)],
&[rec("a", "gha", 5_000_000.0, 10.0)],
);
let ins = c.changes.iter().find(|c| c.metric == GATED_METRIC).unwrap();
assert_eq!(ins.pct(), None, "no percentage exists against zero");
assert_eq!(
c.regressions(&g(1.0)).len(),
1,
"it must still fail the gate"
);
assert!(markdown(&c, &Trend::new(), &g(1.0), false).contains("new"));
}
#[test]
fn zero_to_zero_is_not_a_regression() {
let c = compare(&[rec("a", "gha", 0.0, 1.0)], &[rec("a", "gha", 0.0, 1.0)]);
assert!(c.regressions(&g(1.0)).is_empty());
}
#[test]
fn outliers_keep_their_tool() {
let mut pnpm = rec("install", "gha", 1.0, 1.0);
pnpm.tool = "pnpm".into();
let c = compare(&[], &[rec("install", "gha", 1.0, 1.0), pnpm]);
let md = markdown(&c, &Trend::new(), &g(1.0), false);
assert!(md.contains("`install` on `gha`"), "{md}");
assert!(md.contains("`install` (pnpm) on `gha`"), "{md}");
}
#[test]
fn a_branch_head_is_appended_last() {
let walked = vec![
("c1".to_string(), vec![rec("a", "gha", 10.0, 1.0)]),
("c2".to_string(), vec![rec("a", "gha", 20.0, 1.0)]),
];
let t = build_trend(&walked, "branch", &[rec("a", "gha", 30.0, 1.0)]);
assert_eq!(t[&key("a")], vec![10.0, 20.0, 30.0]);
}
#[test]
fn a_head_inside_history_stays_in_its_place() {
let walked = vec![
("c1".to_string(), vec![rec("a", "gha", 10.0, 1.0)]),
("head".to_string(), vec![rec("a", "gha", 20.0, 1.0)]),
("c3".to_string(), vec![rec("a", "gha", 30.0, 1.0)]),
];
let t = build_trend(&walked, "head", &[rec("a", "gha", 99.0, 1.0)]);
assert_eq!(
t[&key("a")],
vec![10.0, 99.0, 30.0],
"the head's own measurement belongs where the head is, once"
);
}
#[test]
fn a_commit_contributes_one_point() {
let walked = vec![(
"c1".to_string(),
vec![rec("a", "gha", 50.0, 1.0), rec("a", "gha", 10.0, 1.0)],
)];
let t = build_trend(&walked, "branch", &[]);
assert_eq!(t[&key("a")], vec![10.0]);
}
#[test]
fn a_sparkline_spans_the_full_range() {
let s = sparkline(&[1.0, 2.0, 3.0, 4.0, 5.0]);
assert_eq!(s.chars().count(), 5);
assert_eq!(s.chars().next().unwrap(), '▁');
assert_eq!(s.chars().last().unwrap(), '█');
}
#[test]
fn a_flat_series_sits_mid_height() {
let s = sparkline(&[7.0, 7.0, 7.0]);
assert_eq!(s, "▅▅▅");
}
#[test]
fn one_point_draws_nothing() {
assert_eq!(sparkline(&[1.0]), "");
assert_eq!(sparkline(&[]), "");
}
#[test]
fn series_are_scaled_independently() {
let small = sparkline(&[7_000_000.0, 7_100_000.0]);
let large = sparkline(&[100_000_000.0, 101_000_000.0]);
assert_eq!(small, large, "both rise by the same shape");
}
#[test]
fn the_trend_column_appears_only_when_there_is_a_trend() {
let c = compare(
&[rec("a", "gha", 1_000_000.0, 10.0)],
&[rec("a", "gha", 1_000_000.0, 10.0)],
);
assert!(!markdown(&c, &Trend::new(), &g(1.0), false).contains("| trend |"));
let mut trend = Trend::new();
trend.insert(
("a".into(), "self".into(), "gha".into()),
vec![1.0, 2.0, 3.0],
);
let md = markdown(&c, &trend, &g(1.0), false);
assert!(md.contains("| trend |"), "{md}");
assert!(md.contains('█'), "{md}");
}
fn with_allocs(mut r: Record, blocks: f64, bytes: f64, peak: f64) -> Record {
r.metrics.insert("alloc_blocks".into(), blocks);
r.metrics.insert("alloc_bytes".into(), bytes);
r.metrics.insert("alloc_peak_bytes".into(), peak);
r
}
#[test]
fn the_allocation_table_appears_only_when_both_sides_have_allocations() {
let plain = compare(
&[rec("a", "gha", 1_000_000.0, 10.0)],
&[rec("a", "gha", 1_000_000.0, 10.0)],
);
let md = markdown(&plain, &Trend::new(), &g(1.0), false);
assert!(!md.contains("Heap allocations"), "{md}");
assert!(md.contains("| benchmark | instructions | Δ | wall (min) | Δ |"));
let first = compare(
&[rec("a", "gha", 1_000_000.0, 10.0)],
&[with_allocs(
rec("a", "gha", 1_000_000.0, 10.0),
3.0,
4140.0,
4140.0,
)],
);
assert!(!markdown(&first, &Trend::new(), &g(1.0), false).contains("Heap allocations"));
}
#[test]
fn allocations_are_reported_and_never_gate() {
let c = compare(
&[with_allocs(
rec("a", "gha", 1_000_000.0, 10.0),
31.0,
7_119.0,
6_847.0,
)],
&[with_allocs(
rec("a", "gha", 1_000_000.0, 10.0),
62.0,
14_238.0,
6_847.0,
)],
);
assert!(c.regressions(&g(0.001)).is_empty());
let md = markdown(&c, &Trend::new(), &g(1.0), false);
assert!(md.contains("reported, not gated"), "{md}");
assert!(
md.contains(
"| a | 31 → 62 | +100.00% | 7,119 → 14,238 | +100.00% | 6,847 → 6,847 | +0.00% |"
),
"{md}"
);
assert!(md.contains("No instruction-count regression"), "{md}");
}
#[test]
fn rows_name_their_runner_only_when_another_shares_the_series() {
let on = |runner| with_allocs(rec("a", runner, 1_000_000.0, 10.0), 3.0, 30.0, 20.0);
let both = [on("linux-x64"), on("linux-arm64")];
let md = markdown(&compare(&both, &both), &Trend::new(), &g(1.0), false);
for runner in ["linux-x64", "linux-arm64"] {
let rows = md
.lines()
.filter(|l| l.starts_with(&format!("| a on {runner} |")))
.count();
assert_eq!(
rows, 2,
"instructions and allocations rows for {runner}: {md}"
);
}
let one = [on("linux-x64")];
let md = markdown(&compare(&one, &one), &Trend::new(), &g(1.0), false);
assert!(
md.contains("| a |") && !md.contains(" on linux-x64 |"),
"{md}"
);
}
#[test]
fn custom_metrics_are_a_separate_table_and_never_gate() {
let with = |bytes: f64, kb: f64| {
let mut r = rec("a", "gha", 1_000_000.0, 10.0);
r.metrics.insert("binary_bytes".into(), bytes);
r.metrics.insert("bundle_kb".into(), kb);
r
};
let c = compare(&[with(4_000_000.0, 10.5)], &[with(8_000_000.0, 12.25)]);
assert!(
c.regressions(&g(0.0)).is_empty(),
"a doubled binary must not fail the gate"
);
let md = markdown(&c, &Trend::new(), &g(1.0), false);
assert!(md.contains("| benchmark | metric | value | Δ |"), "{md}");
assert!(
md.contains("| a | binary_bytes | 4,000,000 → 8,000,000 | +100.00% |"),
"{md}"
);
assert!(
md.contains("| a | bundle_kb | 10.5 → 12.25 | +16.67% |"),
"{md}"
);
assert!(md.contains("No instruction-count regression"), "{md}");
assert!(md.contains("never gated"), "{md}");
let plain = compare(
&[rec("a", "gha", 1_000_000.0, 10.0)],
&[rec("a", "gha", 1_000_000.0, 10.0)],
);
let md = markdown(&plain, &Trend::new(), &g(1.0), false);
assert!(!md.contains("| metric |"), "{md}");
assert!(!md.contains("tak.toml"), "{md}");
let header = |md: &str| md.lines().next().unwrap().to_string();
assert_eq!(
header(&markdown(&c, &Trend::new(), &g(1.0), false)),
header(&md)
);
}
#[test]
fn built_in_metrics_stay_out_of_the_custom_table() {
let with = |p50: f64| {
let mut r = rec("a", "gha", 1_000_000.0, 10.0);
r.metrics.insert("wall_p50_ms".into(), p50);
r
};
let md = markdown(
&compare(&[with(11.0)], &[with(12.0)]),
&Trend::new(),
&g(1.0),
false,
);
assert!(!md.contains("wall_p50_ms"), "{md}");
}
#[test]
fn allocations_and_custom_metrics_each_get_their_own_table() {
let with = |blocks: f64, bytes: f64| {
let mut r = with_allocs(rec("a", "gha", 1_000_000.0, 10.0), blocks, 80.0, 40.0);
r.metrics.insert("binary_bytes".into(), bytes);
r
};
let c = compare(&[with(10.0, 100.0)], &[with(20.0, 200.0)]);
let md = markdown(&c, &Trend::new(), &g(1.0), false);
assert!(md.contains("Heap allocations"), "{md}");
assert!(
md.contains("| a | binary_bytes | 100 → 200 | +100.00% |"),
"{md}"
);
assert!(
!md.contains("| alloc_"),
"allocations leaked into the custom table: {md}"
);
assert!(c.regressions(&g(0.0)).is_empty());
}
#[test]
fn custom_metric_labels_are_escaped() {
let with = |v: f64| {
let mut r = rec("a|b", "gha", 1_000_000.0, 10.0);
r.metrics.insert("x|y\n**Nothing was compared".into(), v);
r
};
let md = markdown(
&compare(&[with(1.0)], &[with(2.0)]),
&Trend::new(),
&g(1.0),
false,
);
assert!(
md.contains(r"| a\|b | x\|y\\n**Nothing was compared | 1 → 2 | +100.00% |"),
"{md}"
);
assert!(
!md.lines().any(|l| l.starts_with("**Nothing was compared")),
"{md}"
);
}
fn accepting(names: &str, source: Source) -> Acceptances {
let mut a = Acceptances::default();
for name in names.split(',') {
a.add_name(name.trim(), source.clone()).unwrap();
}
a
}
#[test]
fn a_control_character_in_a_name_is_escaped() {
assert_eq!(code("a\nb"), "`a\\nb`");
assert_eq!(
describe(&("a\nb".into(), "self".into(), "r\r".into())),
"`a\\nb` on `r\\r`"
);
assert_eq!(describe(&key("a")), "`a` on `gha`");
let c = compare(&[], &[]).with_accepted(accepting(
"x\n**1 benchmark(s) above the 1% gate:** `x`",
Source::Flag,
));
let md = markdown(&c, &Trend::new(), &g(1.0), false);
assert!(
md.lines().all(|l| !l.starts_with("**1 benchmark(s)")),
"{md}"
);
}
const SHA: &str = "0123456789abcdef0123456789abcdef01234567";
#[test]
fn an_acceptance_covers_only_the_benchmark_it_names() {
let c = compare(
&[
rec("a", "gha", 1_000_000.0, 10.0),
rec("b", "gha", 1_000_000.0, 10.0),
],
&[
rec("a", "gha", 1_100_000.0, 10.0),
rec("b", "gha", 1_100_000.0, 10.0),
],
)
.with_accepted(accepting("a", Source::Trailer(SHA.into())));
assert_eq!(
c.regressions(&g(1.0)).len(),
2,
"both still count as regressed"
);
let failures = c.failures(&g(1.0));
assert_eq!(failures.len(), 1);
assert_eq!(failures[0].bench, "b");
}
#[test]
fn an_accepted_regression_stays_visible_with_its_source() {
let c = compare(
&[rec("a", "gha", 1_000_000.0, 10.0)],
&[rec("a", "gha", 1_100_000.0, 10.0)],
)
.with_accepted(accepting("a", Source::Trailer(SHA.into())));
assert!(c.failures(&g(1.0)).is_empty());
let md = markdown(&c, &Trend::new(), &g(1.0), false);
assert!(md.contains("**+10.00%** (accepted)"), "{md}");
assert!(
md.contains("**1 accepted regression(s) above the 1% gate, not failing it:** `a` on `gha` +10.00% (`Tak-Accept` in `0123456789ab`)"),
"{md}"
);
assert!(!md.contains("No instruction-count regression"), "{md}");
assert!(!md.contains("⚠️"), "{md}");
}
#[test]
fn failures_and_acceptances_are_reported_separately() {
let c = compare(
&[
rec("a", "gha", 1_000_000.0, 10.0),
rec("b", "gha", 1_000_000.0, 10.0),
],
&[
rec("a", "gha", 1_100_000.0, 10.0),
rec("b", "gha", 1_200_000.0, 10.0),
],
)
.with_accepted(accepting("a", Source::Flag));
let md = markdown(&c, &Trend::new(), &g(1.0), false);
assert!(
md.contains("**1 benchmark(s) above the 1% gate:** `b` +20.00%"),
"{md}"
);
assert!(md.contains("`a` on `gha` +10.00% (`--accept`)"), "{md}");
}
#[test]
fn an_acceptance_covers_every_series_of_its_benchmark() {
let mut other = rec("a", "gha", 1_000_000.0, 10.0);
other.tool = "other".into();
let mut other_head = other.clone();
other_head.metrics.insert(GATED_METRIC.into(), 2_000_000.0);
let c = compare(
&[
rec("a", "gha", 1_000_000.0, 10.0),
rec("a", "arm", 1_000_000.0, 10.0),
other,
],
&[
rec("a", "gha", 2_000_000.0, 10.0),
rec("a", "arm", 2_000_000.0, 10.0),
other_head,
],
)
.with_accepted(accepting("a", Source::Flag));
assert_eq!(c.regressions(&g(1.0)).len(), 3);
assert!(c.failures(&g(1.0)).is_empty());
let md = markdown(&c, &Trend::new(), &g(1.0), false);
assert!(md.contains("`a (other)` on `gha` +100.00%"), "{md}");
}
#[test]
fn an_acceptance_with_nothing_to_accept_is_reported() {
let c = compare(
&[
rec("a", "gha", 1_000_000.0, 10.0),
rec("b", "gha", 1_000_000.0, 10.0),
],
&[
rec("a", "gha", 1_000_000.0, 10.0),
rec("b", "gha", 1_100_000.0, 10.0),
],
)
.with_accepted(accepting("a,bb", Source::Flag));
assert_eq!(c.failures(&g(1.0)).len(), 1, "a typo must not accept `b`");
let md = markdown(&c, &Trend::new(), &g(1.0), false);
assert!(
md.contains(
"Accepted, but not above its gate, so nothing was accepted: `a` (`--accept`)"
),
"{md}"
);
assert!(
md.contains("no benchmark by that name was compared on both sides: `bb` (`--accept`)"),
"{md}"
);
}
#[test]
fn a_pipe_in_a_row_name_is_escaped() {
let on = |runner| rec("a|b", runner, 1_000_000.0, 10.0);
let both = [on("ci|x64"), on("ci|arm64")];
let md = markdown(&compare(&both, &both), &Trend::new(), &g(1.0), false);
assert!(md.contains("| a\\|b on ci\\|x64 |"), "{md}");
let row = md.lines().find(|l| l.contains("ci\\|arm64")).unwrap();
let cells = row.replace("\\|", "").matches('|').count();
assert_eq!(cells, 6, "a benchmark cell and four numbers: {row}");
}
#[test]
fn allocation_labels_are_escaped_like_the_rest_of_the_report() {
let on = |runner| {
let mut r = with_allocs(rec("a\nb", runner, 1.0, 1.0), 3.0, 30.0, 20.0);
r.tool = "t\\x".into();
r
};
let both = [on("ci\rx64"), on("ci-arm64")];
let md = markdown(&compare(&both, &both), &Trend::new(), &g(1.0), false);
let allocs = md
.lines()
.skip_while(|l| !l.starts_with("Heap allocations"))
.collect::<Vec<_>>();
assert!(
allocs
.iter()
.any(|l| l.starts_with(r"| a\\nb (t\\x) on ci\\rx64 |")),
"{md}"
);
assert!(!md.contains('\r'), "{md:?}");
}
#[test]
fn a_zero_allocation_base_is_a_measurement_not_new() {
let c = compare(
&[with_allocs(
rec("a", "gha", 1_000_000.0, 10.0),
0.0,
0.0,
0.0,
)],
&[with_allocs(
rec("a", "gha", 1_000_000.0, 10.0),
0.0,
4_140.0,
0.0,
)],
);
let md = markdown(&c, &Trend::new(), &g(1.0), false);
let row = md
.lines()
.skip_while(|l| !l.starts_with("Heap allocations"))
.find(|l| l.starts_with("| a |"))
.unwrap();
assert_eq!(
row,
"| a | 0 → 0 | +0.00% | 0 → 4,140 | +4,140 (from 0) | 0 → 0 | +0.00% |"
);
assert!(!row.contains("new"), "{row}");
assert!(c.regressions(&g(0.001)).is_empty(), "still never gates");
}
#[test]
fn an_acceptance_is_reported_when_nothing_was_compared() {
let c =
compare(&[], &[rec("a", "gha", 1.0, 1.0)]).with_accepted(accepting("a", Source::Flag));
let md = markdown(&c, &Trend::new(), &g(1.0), false);
assert!(md.contains("nothing was gated"), "{md}");
assert!(
md.contains("no benchmark by that name was compared"),
"{md}"
);
}
#[test]
fn an_acceptance_never_invents_a_regression() {
let c = compare(
&[rec("a", "gha", 1_000_000.0, 10.0)],
&[rec("a", "gha", 500_000.0, 10.0)],
)
.with_accepted(accepting("a", Source::Flag));
let md = markdown(&c, &Trend::new(), &g(1.0), false);
assert!(
md.contains("No instruction-count regression above 1%"),
"{md}"
);
assert!(!md.contains("(accepted)"), "{md}");
}
#[test]
fn an_ignored_trailer_is_named_and_accepts_nothing() {
let c = compare(
&[rec("a", "gha", 1_000_000.0, 10.0)],
&[rec("a", "gha", 1_100_000.0, 10.0)],
)
.with_ignored_trailers(accepting("a", Source::Trailer(SHA.into())));
assert_eq!(c.failures(&g(1.0)).len(), 1);
let md = markdown(&c, &Trend::new(), &g(1.0), false);
assert!(
md.contains("trailers were found but not honoured, because `gate.accept_trailers` is off: `a` (`Tak-Accept` in `0123456789ab`)"),
"{md}"
);
assert!(!md.contains("(accepted)"), "{md}");
}
#[test]
fn a_name_with_backticks_keeps_its_code_span() {
assert_eq!(code("startup"), "`startup`");
assert_eq!(code("a`b"), "`` a`b ``");
assert_eq!(code("``x"), "``` ``x ```");
let c = compare(&[], &[]).with_accepted(accepting("we`ird", Source::Flag));
let md = markdown(&c, &Trend::new(), &g(1.0), false);
assert!(md.contains("`` we`ird `` (`--accept`)"), "{md}");
}
#[test]
fn a_name_with_edge_spaces_keeps_them() {
assert_eq!(code(" startup "), "` startup `");
assert_eq!(code(" startup"), "` startup `");
assert_eq!(code("startup "), "` startup `");
assert_ne!(code(" startup "), code("startup"));
assert_eq!(code(" "), "` `");
}
#[test]
fn a_cell_escapes_backslashes_before_pipes() {
assert_eq!(cell("startup"), "startup");
assert_eq!(cell("a|b"), r"a\|b");
assert_eq!(cell(r"a\|b"), r"a\\\|b");
assert_eq!(cell(r"win\arm"), r"win\\arm");
}
#[test]
fn a_code_cell_escapes_only_pipes() {
assert_eq!(code_cell("`win\\arm`"), "`win\\arm`");
assert_eq!(code_cell("`a|b`"), r"`a\|b`");
assert_eq!(code_cell(r"`a\|b`"), r"`a\\|b`");
}
#[test]
fn a_pipe_in_a_name_does_not_split_the_row() {
let mut base = rec("a|b", "gha", 100.0, 1.0);
let mut head = rec("a|b", "gha", 101.0, 1.0);
base.tool = "x|y".into();
head.tool = "x|y".into();
let md = markdown(&compare(&[base], &[head]), &Trend::new(), &g(1.0), false);
assert!(md.contains(r"| a\|b (x\|y) |"), "{md}");
let columns = |l: &str| l.replace(r"\|", "").matches('|').count();
let rows: Vec<&str> = md.lines().filter(|l| l.starts_with('|')).collect();
assert_eq!(rows.len(), 3, "{md}");
assert!(rows.iter().all(|r| columns(r) == columns(rows[0])), "{md}");
}
#[test]
fn an_accepted_entry_names_its_runner() {
let c = compare(
&[
rec("a", "gha", 1_000_000.0, 10.0),
rec("a", "arm", 1_000_000.0, 10.0),
],
&[
rec("a", "gha", 1_100_000.0, 10.0),
rec("a", "arm", 1_200_000.0, 10.0),
],
)
.with_accepted(accepting("a", Source::Flag));
let md = markdown(&c, &Trend::new(), &g(1.0), false);
assert!(md.contains("`a` on `arm` +20.00% (`--accept`)"), "{md}");
assert!(md.contains("`a` on `gha` +10.00% (`--accept`)"), "{md}");
}
#[test]
fn an_acceptance_is_judged_against_the_series_own_gate() {
let mut gates = g(1.0);
gates.set_series("startup", SELF_TOOL, gate(5.0, 20_000, true));
let c = startup_and_install().with_accepted(accepting("startup, install", Source::Flag));
assert!(c.failures(&gates).is_empty());
assert_eq!(benches(&c.accepted_regressions(&gates)), ["install"]);
let md = markdown(&c, &Trend::new(), &gates, false);
assert!(
md.contains(
"**1 accepted regression(s) above their gate, not failing it:** \
`install` on `gha` +2.00% (gate 1%) (`--accept`)\n"
),
"{md}"
);
assert!(
md.contains("Accepted, but not above its gate, so nothing was accepted: `startup`"),
"{md}"
);
assert!(!md.contains("No gated benchmark rose"), "{md}");
}
#[test]
fn an_acceptance_does_not_count_a_rise_under_the_floor() {
let gates = Gates::uniform(Gate::new(1.0, 10_000).unwrap());
let c = startup_and_install().with_accepted(accepting("startup, install", Source::Flag));
assert!(c.failures(&gates).is_empty());
assert_eq!(benches(&c.accepted_regressions(&gates)), ["install"]);
let md = markdown(&c, &Trend::new(), &gates, false);
assert!(
md.contains(
"**1 accepted regression(s) above the 1% gate, not failing it:** \
`install` on `gha` +2.00% (`--accept`)\n"
),
"{md}"
);
assert!(
md.contains("not above its gate, so nothing was accepted: `startup`"),
"{md}"
);
}
#[test]
fn accepting_a_report_only_benchmark_accepts_nothing() {
let mut gates = g(1.0);
gates.set_series("startup", SELF_TOOL, gate(1.0, 0, false));
let c = startup_and_install().with_accepted(accepting("startup", Source::Flag));
assert_eq!(benches(&c.failures(&gates)), ["install"]);
assert!(c.accepted_regressions(&gates).is_empty());
let md = markdown(&c, &Trend::new(), &gates, false);
assert!(md.contains("**+2.00%** (not gated)"), "{md}");
assert!(!md.contains("(accepted)"), "{md}");
assert!(
md.contains(
"Accepted, but report-only, so it can never fail and nothing was \
accepted: `startup` (`--accept`)"
),
"{md}"
);
assert!(
md.contains("**1 report-only benchmark(s) above their gate, not failing:**"),
"{md}"
);
}
#[test]
fn an_empty_acceptance_leaves_a_per_benchmark_report_unchanged() {
let mut gates = g(1.0);
gates.set_series("startup", SELF_TOOL, gate(5.0, 20_000, true));
let plain = markdown(&startup_and_install(), &Trend::new(), &gates, false);
let c = startup_and_install()
.with_accepted(Acceptances::default())
.with_ignored_trailers(Acceptances::default());
assert_eq!(markdown(&c, &Trend::new(), &gates, false), plain);
assert!(!plain.contains("accepted"), "{plain}");
}
#[test]
fn thousands_separates() {
assert_eq!(thousands(1234567.0), "1,234,567");
assert_eq!(thousands(999.0), "999");
assert_eq!(thousands(1000.0), "1,000");
}
}