use anyhow::{Result, bail};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;
use crate::compare::{self, GATED_METRIC, Key, WALL_METRIC};
use crate::config::SELF_TOOL;
use crate::notes::Logged;
use crate::record::Record;
#[derive(Debug, Clone, PartialEq)]
pub struct Point {
pub commit: usize,
pub instructions: Option<f64>,
pub wall_min_ms: Option<f64>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Series {
pub key: Key,
pub points: Vec<Point>,
}
impl Series {
fn deltas(&self) -> Vec<Option<f64>> {
let mut prev: Option<f64> = None;
self.points
.iter()
.map(|p| {
let d = match (prev, p.instructions) {
(Some(base), Some(head)) => pct(base, head),
_ => None,
};
if p.instructions.is_some() {
prev = p.instructions;
}
d
})
.collect()
}
}
fn pct(base: f64, head: f64) -> Option<f64> {
(base != 0.0).then(|| (head - base) / base * 100.0)
}
#[derive(Debug, Clone)]
pub struct History {
pub commits: Vec<Logged>,
pub series: Vec<Series>,
pub walked: usize,
pub older: bool,
pub undrawable: usize,
pub shallow: bool,
}
pub fn build(
walked: Vec<Logged>,
limit: usize,
benches: &[String],
shallow: bool,
) -> Result<History> {
let walked_n = walked.len();
if !benches.is_empty() {
check_benches(&walked, benches)?;
}
let mut undrawable = 0;
let mut recorded: Vec<Logged> = walked
.into_iter()
.filter_map(|mut c| {
c.records
.retain(|r| benches.is_empty() || benches.contains(&r.bench));
let had_records = !c.records.is_empty();
c.records.retain(drawable);
if had_records && c.records.is_empty() {
undrawable += 1;
}
(!c.records.is_empty()).then_some(c)
})
.collect();
let older = recorded.len() > limit;
recorded.truncate(limit);
recorded.reverse();
let mut series: BTreeMap<Key, Vec<Point>> = BTreeMap::new();
for (i, c) in recorded.iter().enumerate() {
let values = compare::index(&c.records);
let keys: BTreeSet<&Key> = values.keys().map(|(k, _)| k).collect();
for key in keys {
let get = |metric: &str| values.get(&(key.clone(), metric.to_string())).copied();
series.entry(key.clone()).or_default().push(Point {
commit: i,
instructions: get(GATED_METRIC),
wall_min_ms: get(WALL_METRIC),
});
}
}
Ok(History {
commits: recorded,
series: series
.into_iter()
.map(|(key, points)| Series { key, points })
.collect(),
walked: walked_n,
older,
undrawable,
shallow,
})
}
pub struct Enough<'a> {
limit: usize,
benches: &'a [String],
recorded: usize,
drawn: BTreeSet<String>,
}
impl<'a> Enough<'a> {
pub fn new(limit: usize, benches: &'a [String]) -> Self {
Enough {
limit,
benches,
recorded: 0,
drawn: BTreeSet::new(),
}
}
pub fn after(&mut self, c: &Logged) -> bool {
let mut counted = false;
for r in c.records.iter().filter(|r| drawable(r)) {
if self.benches.is_empty() || self.benches.contains(&r.bench) {
counted = true;
self.drawn.insert(r.bench.clone());
}
}
self.recorded += usize::from(counted);
self.recorded > self.limit && self.benches.iter().all(|b| self.drawn.contains(b))
}
}
fn drawable(r: &Record) -> bool {
r.metrics.contains_key(GATED_METRIC) || r.metrics.contains_key(WALL_METRIC)
}
fn check_benches(walked: &[Logged], benches: &[String]) -> Result<()> {
let records = || walked.iter().flat_map(|c| c.records.iter());
let seen: BTreeSet<&str> = records().map(|r| r.bench.as_str()).collect();
let drawn: BTreeSet<&str> = records()
.filter(|r| drawable(r))
.map(|r| r.bench.as_str())
.collect();
let named = |names: Vec<&String>| {
names
.iter()
.map(|b| format!("`{b}`"))
.collect::<Vec<_>>()
.join(", ")
};
let missing: Vec<&String> = benches
.iter()
.filter(|b| !seen.contains(b.as_str()))
.collect();
if !missing.is_empty() {
bail!(
"no measurements of {} in {} commit(s) of history (recorded: {})",
named(missing),
walked.len(),
if seen.is_empty() {
"none".to_string()
} else {
seen.into_iter().collect::<Vec<_>>().join(", ")
}
);
}
let blank: Vec<&String> = benches
.iter()
.filter(|b| !drawn.contains(b.as_str()))
.collect();
if !blank.is_empty() {
bail!(
"{} has no {GATED_METRIC} or {WALL_METRIC} measurements in {} commit(s) of \
history; its records carry only other metrics, which `tak log` does not show",
named(blank),
walked.len()
);
}
Ok(())
}
fn short(sha: &str) -> &str {
&sha[..sha.len().min(7)]
}
fn day(date: &str) -> &str {
&date[..date.len().min(10)]
}
const SUBJECT_CHARS: usize = 72;
fn clip(s: &str) -> String {
if s.chars().count() <= SUBJECT_CHARS {
return s.to_string();
}
let mut out: String = s.chars().take(SUBJECT_CHARS - 1).collect();
out.push('…');
out
}
fn coverage(h: &History, rev: &str) -> String {
let mut out = if h.commits.is_empty() && h.undrawable > 0 {
format!(
"No {GATED_METRIC} or {WALL_METRIC} measurements on the first-parent history of \
`{rev}` ({} commit(s) walked; {} carried only other metrics, which this report \
does not show).",
h.walked, h.undrawable
)
} else if h.commits.is_empty() {
format!(
"No measurements recorded on the first-parent history of `{rev}` ({} commit(s) walked).",
h.walked
)
} else {
format!(
"{} recorded commit(s) on the first-parent history of `{rev}`, {} to {} ({} commit(s) walked).",
h.commits.len(),
day(&h.commits[0].date),
day(&h.commits[h.commits.len() - 1].date),
h.walked
)
};
if h.older {
out.push_str(" Older recorded commits are not shown; `-n` shows more.");
} else if h.shallow {
out.push_str(
" This clone is shallow, so older measurements may exist beyond where the \
walk stopped; `git fetch --unshallow` reaches them.",
);
}
out
}
const WALL_CAVEAT: &str = "Only instruction counts gate. Wall clock is shown for context — on \
identical hardware it moves 4-20% run to run.";
fn table(header: &[&str], right: &[bool], rows: &[Vec<String>]) -> String {
let mut width: Vec<usize> = header.iter().map(|h| h.chars().count()).collect();
for row in rows {
for (w, cell) in width.iter_mut().zip(row) {
*w = (*w).max(cell.chars().count());
}
}
let line = |cells: Vec<String>| -> String {
let mut s = String::from("|");
for (i, cell) in cells.iter().enumerate() {
let pad = width[i].saturating_sub(cell.chars().count());
if i + 1 == cells.len() && !right[i] {
let _ = write!(s, " {cell} |");
} else if right[i] {
let _ = write!(s, " {}{cell} |", " ".repeat(pad));
} else {
let _ = write!(s, " {cell}{} |", " ".repeat(pad));
}
}
s.push('\n');
s
};
let mut out = line(header.iter().map(|h| h.to_string()).collect());
out.push('|');
for (i, w) in width.iter().enumerate() {
let w = if i + 1 == width.len() && !right[i] {
header[i].chars().count().max(1)
} else {
*w
};
let dashes = "-".repeat(w + 2);
if right[i] {
let _ = write!(out, "{}:|", &dashes[1..]);
} else {
let _ = write!(out, "{dashes}|");
}
}
out.push('\n');
for row in rows {
out.push_str(&line(row.clone()));
}
out
}
fn rows<'h>(h: &'h History, s: &Series) -> Vec<(&'h Logged, Vec<String>)> {
let deltas = s.deltas();
s.points
.iter()
.zip(deltas)
.rev()
.map(|(p, d)| {
let c = &h.commits[p.commit];
let cells = vec![
short(&c.sha).to_string(),
day(&c.date).to_string(),
p.instructions
.map(compare::thousands)
.unwrap_or_else(|| "—".into()),
match (p.instructions, d) {
(Some(_), Some(d)) => compare::signed_pct(Some(d)),
_ => "—".into(),
},
p.wall_min_ms
.map(|w| format!("{w:.2}ms"))
.unwrap_or_else(|| "—".into()),
clip(&c.subject),
];
(c, cells)
})
.collect()
}
const HEADER: [&str; 6] = [
"commit",
"date",
"instructions",
"Δ",
"wall (min)",
"subject",
];
const RIGHT: [bool; 6] = [false, false, true, true, true, false];
pub fn markdown(h: &History, rev: &str, credit: bool) -> String {
let mut out = coverage(h, rev);
out.push('\n');
for s in &h.series {
let _ = write!(out, "\n### {}\n\n", compare::describe(&s.key));
let body: Vec<Vec<String>> = rows(h, s)
.into_iter()
.map(|(_, mut r)| {
r[0] = format!("`{}`", r[0]);
let last = r.len() - 1;
r[last] = compare::cell(&r[last]);
r
})
.collect();
out.push_str(&table(&HEADER, &RIGHT, &body));
}
if !h.series.is_empty() {
let _ = write!(out, "\n<sub>{WALL_CAVEAT}</sub>\n");
}
if credit {
out.push_str(compare::CREDIT);
}
out
}
fn esc(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
c => out.push(c),
}
}
out
}
const WIDTH: f64 = 720.0;
const LEFT: f64 = 76.0;
const RIGHT_PAD: f64 = 12.0;
const INS_PLOT: f64 = 150.0;
const WALL_PLOT: f64 = 56.0;
const TOP: f64 = 24.0;
const AXIS_BOTTOM: f64 = 28.0;
const BARE_BOTTOM: f64 = 8.0;
const MIN_DOT_SPACING: f64 = 12.0;
const INS_MIN_SPAN: f64 = 0.02;
const WALL_MIN_SPAN: f64 = 0.25;
fn domain(values: &[f64], min_span: f64) -> (f64, f64) {
let lo = values.iter().copied().fold(f64::INFINITY, f64::min);
let hi = values.iter().copied().fold(f64::NEG_INFINITY, f64::max);
let mid = (lo + hi) / 2.0;
let span = (hi - lo).max(mid.abs() * min_span).max(1.0);
let margin = span * 0.1;
let (mut a, mut b) = (mid - span / 2.0 - margin, mid + span / 2.0 + margin);
if a < 0.0 && lo >= 0.0 {
b -= a;
a = 0.0;
}
(a, b)
}
fn si(v: f64) -> String {
let (scaled, suffix) = match v.abs() {
a if a >= 1e9 => (v / 1e9, "G"),
a if a >= 1e6 => (v / 1e6, "M"),
a if a >= 1e3 => (v / 1e3, "k"),
_ => (v, ""),
};
let digits = if scaled.abs() >= 100.0 {
1
} else if scaled.abs() >= 10.0 {
2
} else {
3
};
format!("{scaled:.digits$}{suffix}")
}
fn x_of(i: usize, n: usize) -> f64 {
let plot = WIDTH - LEFT - RIGHT_PAD;
if n <= 1 {
LEFT + plot / 2.0
} else {
LEFT + plot * i as f64 / (n - 1) as f64
}
}
fn tooltip(c: &Logged, p: &Point, delta: Option<f64>) -> String {
let mut t = format!("{} · {}\n{}", short(&c.sha), day(&c.date), c.subject);
if let Some(v) = p.instructions {
let _ = write!(t, "\ninstructions: {}", compare::thousands(v));
if let Some(d) = delta {
let _ = write!(t, " ({})", compare::signed_pct(Some(d)));
}
}
if let Some(w) = p.wall_min_ms {
let _ = write!(t, "\nwall (min): {w:.2} ms");
}
t
}
fn commit_url(repo: Option<&str>, sha: &str) -> Option<String> {
repo.map(|r| format!("https://github.com/{r}/commit/{sha}"))
}
#[derive(Clone, Copy)]
enum Metric {
Instructions,
Wall,
}
fn chart(h: &History, s: &Series, metric: Metric, repo: Option<&str>, x_axis: bool) -> String {
let (plot, min_span, class, label) = match metric {
Metric::Instructions => (INS_PLOT, INS_MIN_SPAN, "ins", "instructions"),
Metric::Wall => (
WALL_PLOT,
WALL_MIN_SPAN,
"wall",
"wall (min), ms · context only, never gates",
),
};
let bottom = TOP + plot;
let height = bottom + if x_axis { AXIS_BOTTOM } else { BARE_BOTTOM };
let value = |p: &Point| match metric {
Metric::Instructions => p.instructions,
Metric::Wall => p.wall_min_ms,
};
let n = h.commits.len();
let pts: Vec<(usize, f64)> = s
.points
.iter()
.filter_map(|p| value(p).map(|v| (p.commit, v)))
.collect();
let values: Vec<f64> = pts.iter().map(|(_, v)| *v).collect();
let (lo, hi) = domain(&values, min_span);
let y_of = |v: f64| bottom - (v - lo) / (hi - lo) * (bottom - TOP);
let fmt_tick = |v: f64| match metric {
Metric::Instructions => si(v),
Metric::Wall => format!("{v:.1}"),
};
let mut svg = String::new();
let _ = write!(
svg,
"<svg class=\"chart {class}-chart\" viewBox=\"0 0 {WIDTH} {height}\" role=\"img\" \
aria-label=\"{} for {}, {} point(s)\">",
esc(label),
esc(&compare::describe(&s.key).replace('`', "")),
pts.len()
);
for t in [0.0, 0.5, 1.0] {
let v = lo + (hi - lo) * t;
let y = y_of(v);
let _ = write!(
svg,
"<line class=\"grid\" x1=\"{LEFT}\" x2=\"{:.1}\" y1=\"{y:.1}\" y2=\"{y:.1}\"/>\
<text class=\"tick\" x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"end\">{}</text>",
WIDTH - RIGHT_PAD,
LEFT - 8.0,
y + 4.0,
esc(&fmt_tick(v))
);
}
let _ = write!(
svg,
"<text class=\"label\" x=\"{LEFT}\" y=\"{:.1}\">{}</text>",
TOP - 10.0,
esc(label)
);
if x_axis && n > 0 {
let first = &h.commits[0];
let last = &h.commits[n - 1];
let mut ends = vec![(x_of(0, n), "start", first)];
if n > 1 {
ends.push((x_of(n - 1, n), "end", last));
} else {
ends[0].1 = "middle";
}
for (x, anchor, c) in ends {
let _ = write!(
svg,
"<text class=\"tick\" x=\"{x:.1}\" y=\"{:.1}\" text-anchor=\"{anchor}\">{} · {}</text>",
bottom + 18.0,
esc(day(&c.date)),
esc(short(&c.sha))
);
}
}
if pts.len() > 1 {
let d: Vec<String> = pts
.iter()
.enumerate()
.map(|(i, (c, v))| {
format!(
"{}{:.1} {:.1}",
if i == 0 { "M" } else { "L" },
x_of(*c, n),
y_of(*v)
)
})
.collect();
let _ = write!(svg, "<path class=\"line {class}\" d=\"{}\"/>", d.join(" "));
}
let spaced = n <= 1 || (WIDTH - LEFT - RIGHT_PAD) / (n - 1) as f64 >= MIN_DOT_SPACING;
for (k, (c, v)) in pts.iter().enumerate() {
if spaced || k + 1 == pts.len() {
let _ = write!(
svg,
"<circle class=\"dot {class}\" cx=\"{:.1}\" cy=\"{:.1}\" r=\"4\"/>",
x_of(*c, n),
y_of(*v)
);
}
}
let deltas = s.deltas();
let step = if n > 1 {
(WIDTH - LEFT - RIGHT_PAD) / (n - 1) as f64
} else {
WIDTH - LEFT - RIGHT_PAD
};
for (p, d) in s.points.iter().zip(deltas) {
if value(p).is_none() {
continue;
}
let c = &h.commits[p.commit];
let x = x_of(p.commit, n) - step / 2.0;
let rect = format!(
"<rect class=\"hit\" x=\"{:.1}\" y=\"{TOP}\" width=\"{:.1}\" height=\"{:.1}\">\
<title>{}</title></rect>",
x.max(LEFT - 8.0),
step,
bottom - TOP,
esc(&tooltip(c, p, d))
);
match commit_url(repo, &c.sha) {
Some(url) => {
let _ = write!(svg, "<a href=\"{}\">{rect}</a>", esc(&url));
}
None => svg.push_str(&rect),
}
}
svg.push_str("</svg>");
svg
}
const STYLE: &str = r#"
:root {
color-scheme: light dark;
--surface: #fcfcfb; --text: #0b0b0b; --muted: #52514e; --grid: #e4e3df;
--ins: #2a78d6; --wall: #8a8983; --hover: rgba(42, 120, 214, 0.10);
}
@media (prefers-color-scheme: dark) {
:root {
--surface: #1a1a19; --text: #ffffff; --muted: #c3c2b7; --grid: #383835;
--ins: #3987e5; --wall: #8f8e86; --hover: rgba(57, 135, 229, 0.18);
}
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--surface); color: var(--text);
font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
main { max-width: 780px; margin: 0 auto; padding: 24px 16px 48px; }
h1 { font-size: 1.5rem; margin: 0 0 8px; }
h2 { font-size: 1.1rem; margin: 40px 0 4px; }
h2 .runner { color: var(--muted); font-weight: normal; }
p { margin: 8px 0; }
.muted, .latest { color: var(--muted); }
code { font: 0.9em ui-monospace, SFMono-Regular, Menlo, monospace; }
.charts { overflow-x: auto; }
svg.chart { display: block; width: 100%; min-width: 540px; height: auto; }
.grid { stroke: var(--grid); stroke-width: 1; }
.tick, .label { fill: var(--muted); font-size: 11px; font-variant-numeric: tabular-nums; }
.line { fill: none; stroke-linejoin: round; stroke-linecap: round; }
.line.ins { stroke: var(--ins); stroke-width: 2; }
.line.wall { stroke: var(--wall); stroke-width: 1.5; }
.dot { stroke: var(--surface); stroke-width: 2; }
.dot.ins { fill: var(--ins); }
.dot.wall { fill: var(--wall); }
.hit { fill: transparent; }
.hit:hover { fill: var(--hover); }
details { margin-top: 8px; }
summary { cursor: pointer; color: var(--muted); }
table { border-collapse: collapse; font-size: 13px; margin-top: 8px; width: 100%; }
th, td { padding: 3px 8px; border-bottom: 1px solid var(--grid); text-align: left;
vertical-align: top; }
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
a { color: inherit; }
footer { margin-top: 48px; font-size: 13px; color: var(--muted); }
"#;
pub fn html(h: &History, rev: &str, repo: Option<&str>, credit: bool) -> String {
let mut out = String::new();
out.push_str(
"<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n\
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\
<title>Benchmark history</title>\n<style>",
);
out.push_str(STYLE);
out.push_str("</style>\n</head>\n<body>\n<main>\n<h1>Benchmark history</h1>\n");
let _ = writeln!(
out,
"<p class=\"muted\">{}</p>",
md_code(&esc(&coverage(h, rev)))
);
if !h.series.is_empty() {
let _ = writeln!(
out,
"<p class=\"muted\">One chart per benchmark and runner class; measurements \
from different runner classes are never joined into one line. Each chart is \
scaled to its own range, never narrower than {:.0}% of its values, so \
run-to-run noise in instruction counts stays flat. {}</p>",
INS_MIN_SPAN * 100.0,
esc(WALL_CAVEAT)
);
}
let header: String = HEADER
.iter()
.zip(RIGHT)
.map(|(h, r)| {
if r {
format!("<th class=\"num\">{}</th>", esc(h))
} else {
format!("<th>{}</th>", esc(h))
}
})
.collect();
for s in &h.series {
let (bench, tool, runner) = &s.key;
let name = if tool == SELF_TOOL {
esc(bench)
} else {
format!("{} ({})", esc(bench), esc(tool))
};
let _ = writeln!(
out,
"<section>\n<h2><code>{name}</code> <span class=\"runner\">on <code>{}</code></span></h2>",
esc(runner)
);
let deltas = s.deltas();
let latest = s
.points
.iter()
.zip(&deltas)
.rev()
.find(|(p, _)| p.instructions.is_some());
match latest {
Some((p, d)) => {
let c = &h.commits[p.commit];
let change = match d {
Some(d) => format!(
", {} from the previous measurement",
compare::signed_pct(Some(*d))
),
None => String::new(),
};
let _ = writeln!(
out,
"<p class=\"latest\">{} instructions at <code>{}</code>{change}</p>",
compare::thousands(p.instructions.unwrap_or_default()),
esc(short(&c.sha))
);
}
None => out.push_str(
"<p class=\"latest\">No instruction counts recorded for this series; \
timing only.</p>\n",
),
}
out.push_str("<div class=\"charts\">");
let has_wall = s.points.iter().any(|p| p.wall_min_ms.is_some());
if s.points.iter().any(|p| p.instructions.is_some()) {
out.push_str(&chart(h, s, Metric::Instructions, repo, !has_wall));
}
if has_wall {
out.push_str(&chart(h, s, Metric::Wall, repo, true));
}
out.push_str("</div>\n");
let _ = write!(
out,
"<details><summary>{} measurement(s)</summary>\n<table><thead><tr>{header}</tr></thead><tbody>",
s.points.len()
);
for (c, row) in rows(h, s) {
out.push_str("<tr>");
for (i, cell) in row.iter().enumerate() {
let content = match (i, commit_url(repo, &c.sha)) {
(0, Some(url)) => {
format!("<a href=\"{}\"><code>{}</code></a>", esc(&url), esc(cell))
}
(0, None) => format!("<code>{}</code>", esc(cell)),
_ => esc(cell),
};
if RIGHT[i] {
let _ = write!(out, "<td class=\"num\">{content}</td>");
} else {
let _ = write!(out, "<td>{content}</td>");
}
}
out.push_str("</tr>");
}
out.push_str("</tbody></table></details>\n</section>\n");
}
out.push_str("<footer>");
if credit {
out.push_str(
"Generated by <a href=\"https://github.com/jdx/tak\">tak</a>, which counts \
instructions with Valgrind and stores measurements in this repository's git \
notes. ",
);
}
out.push_str("tak is pre-v1; this report's format may change between releases.</footer>\n");
out.push_str("</main>\n</body>\n</html>\n");
out
}
fn md_code(s: &str) -> String {
let mut out = String::new();
for (i, part) in s.split('`').enumerate() {
if i % 2 == 1 {
let _ = write!(out, "<code>{part}</code>");
} else {
out.push_str(part);
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
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 commit(n: usize, records: Vec<Record>) -> Logged {
Logged {
sha: format!("{n:040x}"),
date: format!("2026-01-{:02}T00:00:00+00:00", n + 1),
subject: format!("commit {n}"),
records,
}
}
fn walk(commits: Vec<Vec<Record>>) -> Vec<Logged> {
let mut out: Vec<Logged> = commits
.into_iter()
.enumerate()
.map(|(i, r)| commit(i, r))
.collect();
out.reverse();
out
}
fn ins(s: &Series) -> Vec<Option<f64>> {
s.points.iter().map(|p| p.instructions).collect()
}
#[test]
fn a_series_reads_oldest_to_newest() {
let h = build(
walk(vec![
vec![rec("a", "r", 10.0, 1.0)],
vec![rec("a", "r", 20.0, 1.0)],
vec![rec("a", "r", 30.0, 1.0)],
]),
10,
&[],
false,
)
.unwrap();
assert_eq!(h.series.len(), 1);
assert_eq!(ins(&h.series[0]), vec![Some(10.0), Some(20.0), Some(30.0)]);
assert_eq!(h.commits[0].subject, "commit 0");
}
#[test]
fn unrecorded_commits_are_walked_not_shown() {
let h = build(
walk(vec![
vec![rec("a", "r", 10.0, 1.0)],
vec![],
vec![],
vec![rec("a", "r", 30.0, 1.0)],
]),
10,
&[],
false,
)
.unwrap();
assert_eq!(h.walked, 4);
assert_eq!(h.commits.len(), 2);
assert_eq!(h.series[0].deltas(), vec![None, Some(200.0)]);
}
#[test]
fn several_records_on_one_commit_reduce_to_the_minimum() {
let h = build(
walk(vec![vec![
rec("a", "r", 50.0, 9.0),
rec("a", "r", 10.0, 3.0),
]]),
10,
&[],
false,
)
.unwrap();
assert_eq!(h.series[0].points.len(), 1);
assert_eq!(h.series[0].points[0].instructions, Some(10.0));
assert_eq!(h.series[0].points[0].wall_min_ms, Some(3.0));
}
#[test]
fn runners_are_never_mixed() {
let h = build(
walk(vec![
vec![rec("a", "old", 10.0, 1.0)],
vec![rec("a", "new", 99.0, 1.0)],
]),
10,
&[],
false,
)
.unwrap();
assert_eq!(h.series.len(), 2);
for s in &h.series {
assert_eq!(s.points.len(), 1, "{:?}", s.key);
assert_eq!(s.deltas(), vec![None], "no delta across runners");
}
}
#[test]
fn a_series_can_appear_and_disappear() {
let h = build(
walk(vec![
vec![rec("a", "r", 1.0, 1.0)],
vec![rec("a", "r", 1.0, 1.0), rec("b", "r", 5.0, 1.0)],
vec![rec("b", "r", 6.0, 1.0)],
]),
10,
&[],
false,
)
.unwrap();
let a = &h.series[0];
let b = &h.series[1];
assert_eq!(
a.points.iter().map(|p| p.commit).collect::<Vec<_>>(),
[0, 1]
);
assert_eq!(
b.points.iter().map(|p| p.commit).collect::<Vec<_>>(),
[1, 2]
);
assert_eq!(b.deltas(), vec![None, Some(20.0)]);
}
#[test]
fn the_limit_keeps_the_newest_and_counts_the_rest() {
let h = build(
walk((0..5).map(|i| vec![rec("a", "r", i as f64, 1.0)]).collect()),
2,
&[],
false,
)
.unwrap();
assert_eq!(ins(&h.series[0]), vec![Some(3.0), Some(4.0)]);
assert!(h.older);
let md = markdown(&h, "HEAD", false);
assert!(md.contains("Older recorded commits are not shown"), "{md}");
}
#[test]
fn the_limit_counts_commits_of_the_selected_bench() {
let h = build(
walk(vec![
vec![rec("a", "r", 1.0, 1.0)],
vec![rec("b", "r", 1.0, 1.0)],
vec![rec("a", "r", 2.0, 1.0)],
vec![rec("b", "r", 1.0, 1.0)],
]),
2,
&["a".to_string()],
false,
)
.unwrap();
assert_eq!(h.series.len(), 1);
assert_eq!(ins(&h.series[0]), vec![Some(1.0), Some(2.0)]);
assert!(!h.older);
}
#[test]
fn an_unknown_bench_is_an_error_that_names_what_exists() {
let err = build(
walk(vec![vec![rec("startup", "r", 1.0, 1.0)]]),
10,
&["statrup".to_string()],
false,
)
.unwrap_err()
.to_string();
assert!(err.contains("`statrup`"), "{err}");
assert!(err.contains("startup"), "{err}");
}
#[test]
fn a_shallow_walk_says_so() {
let h = build(walk(vec![vec![rec("a", "r", 1.0, 1.0)]]), 10, &[], true).unwrap();
assert!(markdown(&h, "HEAD", false).contains("shallow"));
assert!(html(&h, "HEAD", None, false).contains("shallow"));
let h = build(
walk(vec![
vec![rec("a", "r", 1.0, 1.0)],
vec![rec("a", "r", 1.0, 1.0)],
]),
1,
&[],
true,
)
.unwrap();
assert!(!markdown(&h, "HEAD", false).contains("shallow"));
}
#[test]
fn nothing_recorded_says_so() {
let h = build(walk(vec![vec![], vec![]]), 10, &[], false).unwrap();
let md = markdown(&h, "main", false);
assert!(md.contains("No measurements recorded"), "{md}");
assert!(md.contains("2 commit(s) walked"), "{md}");
assert!(html(&h, "main", None, false).contains("</html>"));
}
#[test]
fn markdown_rows_are_newest_first_with_deltas() {
let h = build(
walk(vec![
vec![rec("a", "r", 1_000_000.0, 10.0)],
vec![rec("a", "r", 1_020_000.0, 11.0)],
]),
10,
&[],
false,
)
.unwrap();
let md = markdown(&h, "HEAD", false);
let newest = md.find("1,020,000").unwrap();
let oldest = md.find("1,000,000").unwrap();
assert!(newest < oldest, "{md}");
assert!(md.contains("+2.00%"), "{md}");
assert!(md.contains("### `a` on `r`"), "{md}");
assert!(md.contains("Only instruction counts gate"), "{md}");
let starts: BTreeSet<usize> = md
.lines()
.filter(|l| l.starts_with('|'))
.map(|l| {
l.chars()
.enumerate()
.filter(|(_, c)| *c == '|')
.nth(5)
.unwrap()
.0
})
.collect();
assert_eq!(starts.len(), 1, "{starts:?}\n{md}");
}
#[test]
fn backslashes_in_subjects_are_escaped_first() {
let mut w = walk(vec![vec![rec("a", "r", 1.0, 1.0)]]);
w[0].subject = r"fix(a\|b)".into();
let h = build(w, 10, &[], false).unwrap();
let md = markdown(&h, "HEAD", false);
assert!(md.contains(r"fix(a\\\|b)"), "{md}");
let row = md.lines().find(|l| l.contains("fix(")).unwrap();
let bare = row
.char_indices()
.filter(|&(i, c)| {
c == '|' && row[..i].chars().rev().take_while(|&b| b == '\\').count() % 2 == 0
})
.count();
assert_eq!(bare, 7, "{row}");
}
#[test]
fn undrawable_records_do_not_count_toward_the_limit() {
let mut custom = rec("a", "r", 0.0, 0.0);
custom.metrics = BTreeMap::from([("binary_bytes".to_string(), 9.0)]);
let h = build(
walk(vec![
vec![rec("a", "r", 1.0, 1.0)],
vec![rec("a", "r", 2.0, 1.0)],
vec![custom.clone()],
vec![custom],
]),
2,
&[],
false,
)
.unwrap();
assert_eq!(h.commits.len(), 2);
assert_eq!(ins(&h.series[0]), vec![Some(1.0), Some(2.0)]);
assert!(!h.older);
}
#[test]
fn a_selected_bench_with_nothing_drawable_is_an_error() {
let mut custom = rec("size", "r", 0.0, 0.0);
custom.metrics = BTreeMap::from([("binary_bytes".to_string(), 9.0)]);
let err = build(
walk(vec![vec![rec("a", "r", 1.0, 1.0), custom]]),
10,
&["size".to_string()],
false,
)
.unwrap_err()
.to_string();
assert!(err.contains("`size` has no instructions"), "{err}");
assert!(err.contains("only other metrics"), "{err}");
}
#[test]
fn an_all_undrawable_history_says_what_it_skipped() {
let mut custom = rec("size", "r", 0.0, 0.0);
custom.metrics = BTreeMap::from([("binary_bytes".to_string(), 9.0)]);
let h = build(walk(vec![vec![custom], vec![]]), 10, &[], false).unwrap();
assert!(h.series.is_empty());
let md = markdown(&h, "HEAD", false);
assert!(md.contains("1 carried only other metrics"), "{md}");
assert!(!md.contains("No measurements recorded"), "{md}");
}
#[test]
fn subjects_cannot_break_the_table() {
let mut w = walk(vec![vec![rec("a", "r", 1.0, 1.0)]]);
w[0].subject = "fix(a|b): <thing>".into();
let h = build(w, 10, &[], false).unwrap();
assert!(markdown(&h, "HEAD", false).contains("fix(a\\|b)"));
let page = html(&h, "HEAD", None, false);
assert!(page.contains("fix(a|b): <thing>"), "{page}");
assert!(!page.contains("<thing>"));
}
#[test]
fn the_credit_line_follows_the_setting() {
let h = build(walk(vec![vec![rec("a", "r", 1.0, 1.0)]]), 10, &[], false).unwrap();
assert!(markdown(&h, "HEAD", true).contains("Measured by [tak]"));
assert!(!markdown(&h, "HEAD", false).contains("Measured by [tak]"));
assert!(html(&h, "HEAD", None, true).contains("Generated by"));
assert!(!html(&h, "HEAD", None, false).contains("Generated by"));
}
#[test]
fn the_page_is_self_contained() {
let h = build(
walk(vec![
vec![rec("a", "r", 1.0, 1.0)],
vec![rec("a", "r", 2.0, 1.0)],
]),
10,
&[],
false,
)
.unwrap();
let page = html(&h, "HEAD", Some("o/r"), true);
assert!(!page.contains("<script"), "no script");
assert!(!page.contains("<link"), "no external stylesheet");
assert!(!page.contains("src="), "nothing loaded");
assert!(page.contains("prefers-color-scheme: dark"));
assert_eq!(page.matches("<svg").count(), 2, "{page}");
assert!(page.contains("<title>"), "hover titles");
}
#[test]
fn commits_link_to_the_forge_only_when_there_is_one() {
let h = build(walk(vec![vec![rec("a", "r", 1.0, 1.0)]]), 10, &[], false).unwrap();
let sha = &h.commits[0].sha;
let linked = html(&h, "HEAD", Some("jdx/tak"), false);
assert!(
linked.contains(&format!("https://github.com/jdx/tak/commit/{sha}")),
"{linked}"
);
assert!(!html(&h, "HEAD", None, false).contains("https://github.com/jdx/tak/commit"));
}
#[test]
fn a_timing_only_series_draws_only_timing() {
let mut r = rec("install", "r", 0.0, 12.0);
r.tool = "pnpm".into();
r.metrics.remove(GATED_METRIC);
let h = build(walk(vec![vec![r]]), 10, &[], false).unwrap();
let page = html(&h, "HEAD", None, false);
assert!(page.contains("timing only"), "{page}");
assert_eq!(page.matches("<svg").count(), 1);
assert!(page.contains("install (pnpm)"), "{page}");
}
#[test]
fn noise_does_not_fill_the_chart() {
let (lo, hi) = domain(&[29_413_235.0, 29_419_117.0], INS_MIN_SPAN);
assert!(hi - lo >= 29_413_235.0 * INS_MIN_SPAN, "{lo} {hi}");
let (lo, hi) = domain(&[100.0, 150.0], INS_MIN_SPAN);
assert!(lo < 100.0 && hi > 150.0);
}
#[test]
fn a_flat_series_is_centred() {
let (lo, hi) = domain(&[500.0, 500.0], INS_MIN_SPAN);
assert!(((lo + hi) / 2.0 - 500.0).abs() < 1e-9);
let (lo, hi) = domain(&[0.0], INS_MIN_SPAN);
assert!(hi > lo && lo >= 0.0);
}
#[test]
fn si_keeps_enough_figures_to_tell_ticks_apart() {
assert_eq!(si(29_413_235.0), "29.41M");
assert_eq!(si(1_500.0), "1.500k");
assert_eq!(si(2_300_000_000.0), "2.300G");
assert_eq!(si(12.0), "12.00");
let (lo, hi) = domain(&[29_413_235.0], INS_MIN_SPAN);
assert_ne!(si(lo), si(hi));
}
#[test]
fn a_zero_base_has_no_percentage() {
let h = build(
walk(vec![
vec![rec("a", "r", 0.0, 1.0)],
vec![rec("a", "r", 5.0, 1.0)],
]),
10,
&[],
false,
)
.unwrap();
assert_eq!(h.series[0].deltas(), vec![None, None]);
}
}