1use anyhow::{Result, bail};
14use std::collections::{BTreeMap, BTreeSet};
15use std::fmt::Write as _;
16
17use crate::compare::{self, GATED_METRIC, Key, WALL_METRIC};
18use crate::config::SELF_TOOL;
19use crate::notes::Logged;
20use crate::record::Record;
21
22#[derive(Debug, Clone, PartialEq)]
24pub struct Point {
25 pub commit: usize,
27 pub instructions: Option<f64>,
28 pub wall_min_ms: Option<f64>,
29}
30
31#[derive(Debug, Clone, PartialEq)]
37pub struct Series {
38 pub key: Key,
39 pub points: Vec<Point>,
40}
41
42impl Series {
43 fn deltas(&self) -> Vec<Option<f64>> {
50 let mut prev: Option<f64> = None;
51 self.points
52 .iter()
53 .map(|p| {
54 let d = match (prev, p.instructions) {
55 (Some(base), Some(head)) => pct(base, head),
56 _ => None,
57 };
58 if p.instructions.is_some() {
59 prev = p.instructions;
60 }
61 d
62 })
63 .collect()
64 }
65}
66
67fn pct(base: f64, head: f64) -> Option<f64> {
71 (base != 0.0).then_some((head - base) / base * 100.0)
72}
73
74#[derive(Debug, Clone)]
76pub struct History {
77 pub commits: Vec<Logged>,
81 pub series: Vec<Series>,
82 pub walked: usize,
84 pub older: bool,
88 pub undrawable: usize,
92 pub shallow: bool,
95}
96
97pub fn build(
111 walked: Vec<Logged>,
112 limit: usize,
113 benches: &[String],
114 shallow: bool,
115) -> Result<History> {
116 let walked_n = walked.len();
117 if !benches.is_empty() {
118 check_benches(&walked, benches)?;
119 }
120
121 let mut undrawable = 0;
122 let mut recorded: Vec<Logged> = walked
123 .into_iter()
124 .filter_map(|mut c| {
125 c.records
126 .retain(|r| benches.is_empty() || benches.contains(&r.bench));
127 let had_records = !c.records.is_empty();
128 c.records.retain(drawable);
133 if had_records && c.records.is_empty() {
134 undrawable += 1;
135 }
136 (!c.records.is_empty()).then_some(c)
137 })
138 .collect();
139 let older = recorded.len() > limit;
140 recorded.truncate(limit);
141 recorded.reverse();
143
144 let mut series: BTreeMap<Key, Vec<Point>> = BTreeMap::new();
145 for (i, c) in recorded.iter().enumerate() {
146 let values = compare::index(&c.records);
147 let keys: BTreeSet<&Key> = values.keys().map(|(k, _)| k).collect();
148 for key in keys {
149 let get = |metric: &str| values.get(&(key.clone(), metric.to_string())).copied();
150 series.entry(key.clone()).or_default().push(Point {
153 commit: i,
154 instructions: get(GATED_METRIC),
155 wall_min_ms: get(WALL_METRIC),
156 });
157 }
158 }
159
160 Ok(History {
161 commits: recorded,
162 series: series
163 .into_iter()
164 .map(|(key, points)| Series { key, points })
165 .collect(),
166 walked: walked_n,
167 older,
168 undrawable,
169 shallow,
170 })
171}
172
173pub struct Enough<'a> {
186 limit: usize,
187 benches: &'a [String],
188 recorded: usize,
189 drawn: BTreeSet<String>,
190}
191
192impl<'a> Enough<'a> {
193 pub fn new(limit: usize, benches: &'a [String]) -> Self {
194 Enough {
195 limit,
196 benches,
197 recorded: 0,
198 drawn: BTreeSet::new(),
199 }
200 }
201
202 pub fn after(&mut self, c: &Logged) -> bool {
205 let mut counted = false;
206 for r in c.records.iter().filter(|r| drawable(r)) {
207 if self.benches.is_empty() || self.benches.contains(&r.bench) {
208 counted = true;
209 self.drawn.insert(r.bench.clone());
210 }
211 }
212 self.recorded += usize::from(counted);
213 self.recorded > self.limit && self.benches.iter().all(|b| self.drawn.contains(b))
214 }
215}
216
217fn drawable(r: &Record) -> bool {
219 r.metrics.contains_key(GATED_METRIC) || r.metrics.contains_key(WALL_METRIC)
220}
221
222fn check_benches(walked: &[Logged], benches: &[String]) -> Result<()> {
235 let records = || walked.iter().flat_map(|c| c.records.iter());
236 let seen: BTreeSet<&str> = records().map(|r| r.bench.as_str()).collect();
237 let drawn: BTreeSet<&str> = records()
238 .filter(|r| drawable(r))
239 .map(|r| r.bench.as_str())
240 .collect();
241 let named = |names: Vec<&String>| {
242 names
243 .iter()
244 .map(|b| format!("`{b}`"))
245 .collect::<Vec<_>>()
246 .join(", ")
247 };
248
249 let missing: Vec<&String> = benches
250 .iter()
251 .filter(|b| !seen.contains(b.as_str()))
252 .collect();
253 if !missing.is_empty() {
254 bail!(
255 "no measurements of {} in {} commit(s) of history (recorded: {})",
256 named(missing),
257 walked.len(),
258 if seen.is_empty() {
259 "none".to_string()
260 } else {
261 seen.into_iter().collect::<Vec<_>>().join(", ")
262 }
263 );
264 }
265 let blank: Vec<&String> = benches
266 .iter()
267 .filter(|b| !drawn.contains(b.as_str()))
268 .collect();
269 if !blank.is_empty() {
270 bail!(
271 "{} has no {GATED_METRIC} or {WALL_METRIC} measurements in {} commit(s) of \
272 history; its records carry only other metrics, which `tak log` does not show",
273 named(blank),
274 walked.len()
275 );
276 }
277 Ok(())
278}
279
280fn short(sha: &str) -> &str {
282 &sha[..sha.len().min(7)]
283}
284
285fn day(date: &str) -> &str {
287 &date[..date.len().min(10)]
288}
289
290const SUBJECT_CHARS: usize = 72;
293
294fn clip(s: &str) -> String {
295 if s.chars().count() <= SUBJECT_CHARS {
296 return s.to_string();
297 }
298 let mut out: String = s.chars().take(SUBJECT_CHARS - 1).collect();
299 out.push('…');
300 out
301}
302
303fn coverage(h: &History, rev: &str) -> String {
306 let mut out = if h.commits.is_empty() && h.undrawable > 0 {
307 format!(
308 "No {GATED_METRIC} or {WALL_METRIC} measurements on the first-parent history of \
309 `{rev}` ({} commit(s) walked; {} carried only other metrics, which this report \
310 does not show).",
311 h.walked, h.undrawable
312 )
313 } else if h.commits.is_empty() {
314 format!(
315 "No measurements recorded on the first-parent history of `{rev}` ({} commit(s) walked).",
316 h.walked
317 )
318 } else {
319 format!(
320 "{} recorded commit(s) on the first-parent history of `{rev}`, {} to {} ({} commit(s) walked).",
321 h.commits.len(),
322 day(&h.commits[0].date),
323 day(&h.commits[h.commits.len() - 1].date),
324 h.walked
325 )
326 };
327 if h.older {
328 out.push_str(" Older recorded commits are not shown; `-n` shows more.");
329 } else if h.shallow {
330 out.push_str(
332 " This clone is shallow, so older measurements may exist beyond where the \
333 walk stopped; `git fetch --unshallow` reaches them.",
334 );
335 }
336 out
337}
338
339const WALL_CAVEAT: &str = "Only instruction counts gate. Wall clock is shown for context — on \
342 identical hardware it moves 4-20% run to run.";
343
344fn table(header: &[&str], right: &[bool], rows: &[Vec<String>]) -> String {
349 let mut width: Vec<usize> = header.iter().map(|h| h.chars().count()).collect();
350 for row in rows {
351 for (w, cell) in width.iter_mut().zip(row) {
352 *w = (*w).max(cell.chars().count());
353 }
354 }
355 let line = |cells: Vec<String>| -> String {
356 let mut s = String::from("|");
357 for (i, cell) in cells.iter().enumerate() {
358 let pad = width[i].saturating_sub(cell.chars().count());
359 if i + 1 == cells.len() && !right[i] {
362 let _ = write!(s, " {cell} |");
363 } else if right[i] {
364 let _ = write!(s, " {}{cell} |", " ".repeat(pad));
365 } else {
366 let _ = write!(s, " {cell}{} |", " ".repeat(pad));
367 }
368 }
369 s.push('\n');
370 s
371 };
372 let mut out = line(header.iter().map(|h| h.to_string()).collect());
373 out.push('|');
374 for (i, w) in width.iter().enumerate() {
375 let w = if i + 1 == width.len() && !right[i] {
377 header[i].chars().count().max(1)
378 } else {
379 *w
380 };
381 let dashes = "-".repeat(w + 2);
383 if right[i] {
384 let _ = write!(out, "{}:|", &dashes[1..]);
385 } else {
386 let _ = write!(out, "{dashes}|");
387 }
388 }
389 out.push('\n');
390 for row in rows {
391 out.push_str(&line(row.clone()));
392 }
393 out
394}
395
396fn rows<'h>(h: &'h History, s: &Series) -> Vec<(&'h Logged, Vec<String>)> {
400 let deltas = s.deltas();
401 s.points
402 .iter()
403 .zip(deltas)
404 .rev()
405 .map(|(p, d)| {
406 let c = &h.commits[p.commit];
407 let cells = vec![
408 short(&c.sha).to_string(),
409 day(&c.date).to_string(),
410 p.instructions
411 .map(compare::thousands)
412 .unwrap_or_else(|| "—".into()),
413 match (p.instructions, d) {
414 (Some(_), Some(d)) => compare::signed_pct(Some(d)),
415 _ => "—".into(),
416 },
417 p.wall_min_ms
418 .map(|w| format!("{w:.2}ms"))
419 .unwrap_or_else(|| "—".into()),
420 clip(&c.subject),
421 ];
422 (c, cells)
423 })
424 .collect()
425}
426
427const HEADER: [&str; 6] = [
428 "commit",
429 "date",
430 "instructions",
431 "Δ",
432 "wall (min)",
433 "subject",
434];
435const RIGHT: [bool; 6] = [false, false, true, true, true, false];
436
437pub fn markdown(h: &History, rev: &str, credit: bool) -> String {
442 let mut out = coverage(h, rev);
443 out.push('\n');
444 for s in &h.series {
445 let _ = write!(out, "\n### {}\n\n", compare::describe(&s.key));
446 let body: Vec<Vec<String>> = rows(h, s)
448 .into_iter()
449 .map(|(_, mut r)| {
450 r[0] = format!("`{}`", r[0]);
451 let last = r.len() - 1;
452 r[last] = compare::cell(&r[last]);
453 r
454 })
455 .collect();
456 out.push_str(&table(&HEADER, &RIGHT, &body));
457 }
458 if !h.series.is_empty() {
459 let _ = write!(out, "\n<sub>{WALL_CAVEAT}</sub>\n");
460 }
461 if credit {
462 out.push_str(compare::CREDIT);
463 }
464 out
465}
466
467fn esc(s: &str) -> String {
469 let mut out = String::with_capacity(s.len());
470 for c in s.chars() {
471 match c {
472 '&' => out.push_str("&"),
473 '<' => out.push_str("<"),
474 '>' => out.push_str(">"),
475 '"' => out.push_str("""),
476 '\'' => out.push_str("'"),
477 c => out.push(c),
478 }
479 }
480 out
481}
482
483const WIDTH: f64 = 720.0;
486const LEFT: f64 = 76.0;
487const RIGHT_PAD: f64 = 12.0;
488const INS_PLOT: f64 = 150.0;
491const WALL_PLOT: f64 = 56.0;
492const TOP: f64 = 24.0;
494const AXIS_BOTTOM: f64 = 28.0;
497const BARE_BOTTOM: f64 = 8.0;
498
499const MIN_DOT_SPACING: f64 = 12.0;
506
507const INS_MIN_SPAN: f64 = 0.02;
516const WALL_MIN_SPAN: f64 = 0.25;
519
520fn domain(values: &[f64], min_span: f64) -> (f64, f64) {
527 let lo = values.iter().copied().fold(f64::INFINITY, f64::min);
528 let hi = values.iter().copied().fold(f64::NEG_INFINITY, f64::max);
529 let mid = (lo + hi) / 2.0;
530 let span = (hi - lo).max(mid.abs() * min_span).max(1.0);
532 let margin = span * 0.1;
533 let (mut a, mut b) = (mid - span / 2.0 - margin, mid + span / 2.0 + margin);
534 if a < 0.0 && lo >= 0.0 {
537 b -= a;
538 a = 0.0;
539 }
540 (a, b)
541}
542
543fn si(v: f64) -> String {
548 let (scaled, suffix) = match v.abs() {
549 a if a >= 1e9 => (v / 1e9, "G"),
550 a if a >= 1e6 => (v / 1e6, "M"),
551 a if a >= 1e3 => (v / 1e3, "k"),
552 _ => (v, ""),
553 };
554 let digits = if scaled.abs() >= 100.0 {
555 1
556 } else if scaled.abs() >= 10.0 {
557 2
558 } else {
559 3
560 };
561 format!("{scaled:.digits$}{suffix}")
562}
563
564fn x_of(i: usize, n: usize) -> f64 {
568 let plot = WIDTH - LEFT - RIGHT_PAD;
569 if n <= 1 {
570 LEFT + plot / 2.0
571 } else {
572 LEFT + plot * i as f64 / (n - 1) as f64
573 }
574}
575
576fn tooltip(c: &Logged, p: &Point, delta: Option<f64>) -> String {
578 let mut t = format!("{} · {}\n{}", short(&c.sha), day(&c.date), c.subject);
579 if let Some(v) = p.instructions {
580 let _ = write!(t, "\ninstructions: {}", compare::thousands(v));
581 if let Some(d) = delta {
582 let _ = write!(t, " ({})", compare::signed_pct(Some(d)));
583 }
584 }
585 if let Some(w) = p.wall_min_ms {
586 let _ = write!(t, "\nwall (min): {w:.2} ms");
587 }
588 t
589}
590
591fn commit_url(repo: Option<&str>, sha: &str) -> Option<String> {
593 repo.map(|r| format!("https://github.com/{r}/commit/{sha}"))
594}
595
596#[derive(Clone, Copy)]
598enum Metric {
599 Instructions,
600 Wall,
601}
602
603fn chart(h: &History, s: &Series, metric: Metric, repo: Option<&str>, x_axis: bool) -> String {
607 let (plot, min_span, class, label) = match metric {
608 Metric::Instructions => (INS_PLOT, INS_MIN_SPAN, "ins", "instructions"),
609 Metric::Wall => (
610 WALL_PLOT,
611 WALL_MIN_SPAN,
612 "wall",
613 "wall (min), ms · context only, never gates",
614 ),
615 };
616 let bottom = TOP + plot;
617 let height = bottom + if x_axis { AXIS_BOTTOM } else { BARE_BOTTOM };
618 let value = |p: &Point| match metric {
619 Metric::Instructions => p.instructions,
620 Metric::Wall => p.wall_min_ms,
621 };
622 let n = h.commits.len();
623 let pts: Vec<(usize, f64)> = s
624 .points
625 .iter()
626 .filter_map(|p| value(p).map(|v| (p.commit, v)))
627 .collect();
628 let values: Vec<f64> = pts.iter().map(|(_, v)| *v).collect();
629 let (lo, hi) = domain(&values, min_span);
630 let y_of = |v: f64| bottom - (v - lo) / (hi - lo) * (bottom - TOP);
631 let fmt_tick = |v: f64| match metric {
632 Metric::Instructions => si(v),
633 Metric::Wall => format!("{v:.1}"),
634 };
635
636 let mut svg = String::new();
637 let _ = write!(
638 svg,
639 "<svg class=\"chart {class}-chart\" viewBox=\"0 0 {WIDTH} {height}\" role=\"img\" \
640 aria-label=\"{} for {}, {} point(s)\">",
641 esc(label),
642 esc(&compare::describe(&s.key).replace('`', "")),
643 pts.len()
644 );
645
646 for t in [0.0, 0.5, 1.0] {
649 let v = lo + (hi - lo) * t;
650 let y = y_of(v);
651 let _ = write!(
652 svg,
653 "<line class=\"grid\" x1=\"{LEFT}\" x2=\"{:.1}\" y1=\"{y:.1}\" y2=\"{y:.1}\"/>\
654 <text class=\"tick\" x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"end\">{}</text>",
655 WIDTH - RIGHT_PAD,
656 LEFT - 8.0,
657 y + 4.0,
658 esc(&fmt_tick(v))
659 );
660 }
661 let _ = write!(
662 svg,
663 "<text class=\"label\" x=\"{LEFT}\" y=\"{:.1}\">{}</text>",
664 TOP - 10.0,
665 esc(label)
666 );
667 if x_axis && n > 0 {
668 let first = &h.commits[0];
671 let last = &h.commits[n - 1];
672 let mut ends = vec![(x_of(0, n), "start", first)];
673 if n > 1 {
674 ends.push((x_of(n - 1, n), "end", last));
675 } else {
676 ends[0].1 = "middle";
677 }
678 for (x, anchor, c) in ends {
679 let _ = write!(
680 svg,
681 "<text class=\"tick\" x=\"{x:.1}\" y=\"{:.1}\" text-anchor=\"{anchor}\">{} · {}</text>",
682 bottom + 18.0,
683 esc(day(&c.date)),
684 esc(short(&c.sha))
685 );
686 }
687 }
688
689 if pts.len() > 1 {
690 let d: Vec<String> = pts
691 .iter()
692 .enumerate()
693 .map(|(i, (c, v))| {
694 format!(
695 "{}{:.1} {:.1}",
696 if i == 0 { "M" } else { "L" },
697 x_of(*c, n),
698 y_of(*v)
699 )
700 })
701 .collect();
702 let _ = write!(svg, "<path class=\"line {class}\" d=\"{}\"/>", d.join(" "));
703 }
704 let spaced = n <= 1 || (WIDTH - LEFT - RIGHT_PAD) / (n - 1) as f64 >= MIN_DOT_SPACING;
705 for (k, (c, v)) in pts.iter().enumerate() {
706 if spaced || k + 1 == pts.len() {
708 let _ = write!(
709 svg,
710 "<circle class=\"dot {class}\" cx=\"{:.1}\" cy=\"{:.1}\" r=\"4\"/>",
711 x_of(*c, n),
712 y_of(*v)
713 );
714 }
715 }
716
717 let deltas = s.deltas();
721 let step = if n > 1 {
722 (WIDTH - LEFT - RIGHT_PAD) / (n - 1) as f64
723 } else {
724 WIDTH - LEFT - RIGHT_PAD
725 };
726 for (p, d) in s.points.iter().zip(deltas) {
727 if value(p).is_none() {
728 continue;
729 }
730 let c = &h.commits[p.commit];
731 let x = x_of(p.commit, n) - step / 2.0;
732 let rect = format!(
733 "<rect class=\"hit\" x=\"{:.1}\" y=\"{TOP}\" width=\"{:.1}\" height=\"{:.1}\">\
734 <title>{}</title></rect>",
735 x.max(LEFT - 8.0),
736 step,
737 bottom - TOP,
738 esc(&tooltip(c, p, d))
739 );
740 match commit_url(repo, &c.sha) {
741 Some(url) => {
742 let _ = write!(svg, "<a href=\"{}\">{rect}</a>", esc(&url));
743 }
744 None => svg.push_str(&rect),
745 }
746 }
747 svg.push_str("</svg>");
748 svg
749}
750
751const STYLE: &str = r#"
756:root {
757 color-scheme: light dark;
758 --surface: #fcfcfb; --text: #0b0b0b; --muted: #52514e; --grid: #e4e3df;
759 --ins: #2a78d6; --wall: #8a8983; --hover: rgba(42, 120, 214, 0.10);
760}
761@media (prefers-color-scheme: dark) {
762 :root {
763 --surface: #1a1a19; --text: #ffffff; --muted: #c3c2b7; --grid: #383835;
764 --ins: #3987e5; --wall: #8f8e86; --hover: rgba(57, 135, 229, 0.18);
765 }
766}
767* { box-sizing: border-box; }
768body { margin: 0; background: var(--surface); color: var(--text);
769 font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
770main { max-width: 780px; margin: 0 auto; padding: 24px 16px 48px; }
771h1 { font-size: 1.5rem; margin: 0 0 8px; }
772h2 { font-size: 1.1rem; margin: 40px 0 4px; }
773h2 .runner { color: var(--muted); font-weight: normal; }
774p { margin: 8px 0; }
775.muted, .latest { color: var(--muted); }
776code { font: 0.9em ui-monospace, SFMono-Regular, Menlo, monospace; }
777.charts { overflow-x: auto; }
778svg.chart { display: block; width: 100%; min-width: 540px; height: auto; }
779.grid { stroke: var(--grid); stroke-width: 1; }
780.tick, .label { fill: var(--muted); font-size: 11px; font-variant-numeric: tabular-nums; }
781.line { fill: none; stroke-linejoin: round; stroke-linecap: round; }
782.line.ins { stroke: var(--ins); stroke-width: 2; }
783.line.wall { stroke: var(--wall); stroke-width: 1.5; }
784.dot { stroke: var(--surface); stroke-width: 2; }
785.dot.ins { fill: var(--ins); }
786.dot.wall { fill: var(--wall); }
787.hit { fill: transparent; }
788.hit:hover { fill: var(--hover); }
789details { margin-top: 8px; }
790summary { cursor: pointer; color: var(--muted); }
791table { border-collapse: collapse; font-size: 13px; margin-top: 8px; width: 100%; }
792th, td { padding: 3px 8px; border-bottom: 1px solid var(--grid); text-align: left;
793 vertical-align: top; }
794td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
795a { color: inherit; }
796footer { margin-top: 48px; font-size: 13px; color: var(--muted); }
797"#;
798
799pub fn html(h: &History, rev: &str, repo: Option<&str>, credit: bool) -> String {
810 let mut out = String::new();
811 out.push_str(
812 "<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n\
813 <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\
814 <title>Benchmark history</title>\n<style>",
815 );
816 out.push_str(STYLE);
817 out.push_str("</style>\n</head>\n<body>\n<main>\n<h1>Benchmark history</h1>\n");
818 let _ = writeln!(
819 out,
820 "<p class=\"muted\">{}</p>",
821 md_code(&esc(&coverage(h, rev)))
822 );
823 if !h.series.is_empty() {
824 let _ = writeln!(
825 out,
826 "<p class=\"muted\">One chart per benchmark and runner class; measurements \
827 from different runner classes are never joined into one line. Each chart is \
828 scaled to its own range, never narrower than {:.0}% of its values, so \
829 run-to-run noise in instruction counts stays flat. {}</p>",
830 INS_MIN_SPAN * 100.0,
831 esc(WALL_CAVEAT)
832 );
833 }
834
835 let header: String = HEADER
836 .iter()
837 .zip(RIGHT)
838 .map(|(h, r)| {
839 if r {
840 format!("<th class=\"num\">{}</th>", esc(h))
841 } else {
842 format!("<th>{}</th>", esc(h))
843 }
844 })
845 .collect();
846
847 for s in &h.series {
848 let (bench, tool, runner) = &s.key;
849 let name = if tool == SELF_TOOL {
850 esc(bench)
851 } else {
852 format!("{} ({})", esc(bench), esc(tool))
853 };
854 let _ = writeln!(
855 out,
856 "<section>\n<h2><code>{name}</code> <span class=\"runner\">on <code>{}</code></span></h2>",
857 esc(runner)
858 );
859 let deltas = s.deltas();
860 let latest = s
861 .points
862 .iter()
863 .zip(&deltas)
864 .rev()
865 .find(|(p, _)| p.instructions.is_some());
866 match latest {
867 Some((p, d)) => {
868 let c = &h.commits[p.commit];
869 let change = match d {
870 Some(d) => format!(
871 ", {} from the previous measurement",
872 compare::signed_pct(Some(*d))
873 ),
874 None => String::new(),
875 };
876 let _ = writeln!(
877 out,
878 "<p class=\"latest\">{} instructions at <code>{}</code>{change}</p>",
879 compare::thousands(p.instructions.unwrap_or_default()),
880 esc(short(&c.sha))
881 );
882 }
883 None => out.push_str(
884 "<p class=\"latest\">No instruction counts recorded for this series; \
885 timing only.</p>\n",
886 ),
887 }
888 out.push_str("<div class=\"charts\">");
889 let has_wall = s.points.iter().any(|p| p.wall_min_ms.is_some());
890 if s.points.iter().any(|p| p.instructions.is_some()) {
891 out.push_str(&chart(h, s, Metric::Instructions, repo, !has_wall));
892 }
893 if has_wall {
894 out.push_str(&chart(h, s, Metric::Wall, repo, true));
895 }
896 out.push_str("</div>\n");
897
898 let _ = write!(
899 out,
900 "<details><summary>{} measurement(s)</summary>\n<table><thead><tr>{header}</tr></thead><tbody>",
901 s.points.len()
902 );
903 for (c, row) in rows(h, s) {
904 out.push_str("<tr>");
905 for (i, cell) in row.iter().enumerate() {
906 let content = match (i, commit_url(repo, &c.sha)) {
907 (0, Some(url)) => {
908 format!("<a href=\"{}\"><code>{}</code></a>", esc(&url), esc(cell))
909 }
910 (0, None) => format!("<code>{}</code>", esc(cell)),
911 _ => esc(cell),
912 };
913 if RIGHT[i] {
914 let _ = write!(out, "<td class=\"num\">{content}</td>");
915 } else {
916 let _ = write!(out, "<td>{content}</td>");
917 }
918 }
919 out.push_str("</tr>");
920 }
921 out.push_str("</tbody></table></details>\n</section>\n");
922 }
923
924 out.push_str("<footer>");
925 if credit {
926 out.push_str(
927 "Generated by <a href=\"https://github.com/jdx/tak\">tak</a>, which counts \
928 instructions with Valgrind and stores measurements in this repository's git \
929 notes. ",
930 );
931 }
932 out.push_str("tak is pre-v1; this report's format may change between releases.</footer>\n");
933 out.push_str("</main>\n</body>\n</html>\n");
934 out
935}
936
937fn md_code(s: &str) -> String {
940 let mut out = String::new();
941 for (i, part) in s.split('`').enumerate() {
942 if i % 2 == 1 {
943 let _ = write!(out, "<code>{part}</code>");
944 } else {
945 out.push_str(part);
946 }
947 }
948 out
949}
950
951#[cfg(test)]
952mod tests {
953 use super::*;
954
955 fn rec(bench: &str, runner: &str, ins: f64, wall: f64) -> Record {
956 Record {
957 v: 1,
958 bench: bench.into(),
959 tool: "self".into(),
960 version: None,
961 runner: runner.into(),
962 ts: "2026-01-01T00:00:00Z".into(),
963 metrics: BTreeMap::from([
964 (GATED_METRIC.to_string(), ins),
965 (WALL_METRIC.to_string(), wall),
966 ]),
967 }
968 }
969
970 fn commit(n: usize, records: Vec<Record>) -> Logged {
971 Logged {
972 sha: format!("{n:040x}"),
973 date: format!("2026-01-{:02}T00:00:00+00:00", n + 1),
974 subject: format!("commit {n}"),
975 records,
976 }
977 }
978
979 fn walk(commits: Vec<Vec<Record>>) -> Vec<Logged> {
981 let mut out: Vec<Logged> = commits
982 .into_iter()
983 .enumerate()
984 .map(|(i, r)| commit(i, r))
985 .collect();
986 out.reverse();
987 out
988 }
989
990 fn ins(s: &Series) -> Vec<Option<f64>> {
991 s.points.iter().map(|p| p.instructions).collect()
992 }
993
994 #[test]
995 fn a_series_reads_oldest_to_newest() {
996 let h = build(
997 walk(vec![
998 vec![rec("a", "r", 10.0, 1.0)],
999 vec![rec("a", "r", 20.0, 1.0)],
1000 vec![rec("a", "r", 30.0, 1.0)],
1001 ]),
1002 10,
1003 &[],
1004 false,
1005 )
1006 .unwrap();
1007 assert_eq!(h.series.len(), 1);
1008 assert_eq!(ins(&h.series[0]), vec![Some(10.0), Some(20.0), Some(30.0)]);
1009 assert_eq!(h.commits[0].subject, "commit 0");
1010 }
1011
1012 #[test]
1015 fn unrecorded_commits_are_walked_not_shown() {
1016 let h = build(
1017 walk(vec![
1018 vec![rec("a", "r", 10.0, 1.0)],
1019 vec![],
1020 vec![],
1021 vec![rec("a", "r", 30.0, 1.0)],
1022 ]),
1023 10,
1024 &[],
1025 false,
1026 )
1027 .unwrap();
1028 assert_eq!(h.walked, 4);
1029 assert_eq!(h.commits.len(), 2);
1030 assert_eq!(h.series[0].deltas(), vec![None, Some(200.0)]);
1031 }
1032
1033 #[test]
1036 fn several_records_on_one_commit_reduce_to_the_minimum() {
1037 let h = build(
1038 walk(vec![vec![
1039 rec("a", "r", 50.0, 9.0),
1040 rec("a", "r", 10.0, 3.0),
1041 ]]),
1042 10,
1043 &[],
1044 false,
1045 )
1046 .unwrap();
1047 assert_eq!(h.series[0].points.len(), 1);
1048 assert_eq!(h.series[0].points[0].instructions, Some(10.0));
1049 assert_eq!(h.series[0].points[0].wall_min_ms, Some(3.0));
1050 }
1051
1052 #[test]
1055 fn runners_are_never_mixed() {
1056 let h = build(
1057 walk(vec![
1058 vec![rec("a", "old", 10.0, 1.0)],
1059 vec![rec("a", "new", 99.0, 1.0)],
1060 ]),
1061 10,
1062 &[],
1063 false,
1064 )
1065 .unwrap();
1066 assert_eq!(h.series.len(), 2);
1067 for s in &h.series {
1068 assert_eq!(s.points.len(), 1, "{:?}", s.key);
1069 assert_eq!(s.deltas(), vec![None], "no delta across runners");
1070 }
1071 }
1072
1073 #[test]
1076 fn a_series_can_appear_and_disappear() {
1077 let h = build(
1078 walk(vec![
1079 vec![rec("a", "r", 1.0, 1.0)],
1080 vec![rec("a", "r", 1.0, 1.0), rec("b", "r", 5.0, 1.0)],
1081 vec![rec("b", "r", 6.0, 1.0)],
1082 ]),
1083 10,
1084 &[],
1085 false,
1086 )
1087 .unwrap();
1088 let a = &h.series[0];
1089 let b = &h.series[1];
1090 assert_eq!(
1091 a.points.iter().map(|p| p.commit).collect::<Vec<_>>(),
1092 [0, 1]
1093 );
1094 assert_eq!(
1095 b.points.iter().map(|p| p.commit).collect::<Vec<_>>(),
1096 [1, 2]
1097 );
1098 assert_eq!(b.deltas(), vec![None, Some(20.0)]);
1099 }
1100
1101 #[test]
1104 fn the_limit_keeps_the_newest_and_counts_the_rest() {
1105 let h = build(
1106 walk((0..5).map(|i| vec![rec("a", "r", i as f64, 1.0)]).collect()),
1107 2,
1108 &[],
1109 false,
1110 )
1111 .unwrap();
1112 assert_eq!(ins(&h.series[0]), vec![Some(3.0), Some(4.0)]);
1113 assert!(h.older);
1114 let md = markdown(&h, "HEAD", false);
1115 assert!(md.contains("Older recorded commits are not shown"), "{md}");
1116 }
1117
1118 #[test]
1121 fn the_limit_counts_commits_of_the_selected_bench() {
1122 let h = build(
1123 walk(vec![
1124 vec![rec("a", "r", 1.0, 1.0)],
1125 vec![rec("b", "r", 1.0, 1.0)],
1126 vec![rec("a", "r", 2.0, 1.0)],
1127 vec![rec("b", "r", 1.0, 1.0)],
1128 ]),
1129 2,
1130 &["a".to_string()],
1131 false,
1132 )
1133 .unwrap();
1134 assert_eq!(h.series.len(), 1);
1135 assert_eq!(ins(&h.series[0]), vec![Some(1.0), Some(2.0)]);
1136 assert!(!h.older);
1137 }
1138
1139 #[test]
1141 fn an_unknown_bench_is_an_error_that_names_what_exists() {
1142 let err = build(
1143 walk(vec![vec![rec("startup", "r", 1.0, 1.0)]]),
1144 10,
1145 &["statrup".to_string()],
1146 false,
1147 )
1148 .unwrap_err()
1149 .to_string();
1150 assert!(err.contains("`statrup`"), "{err}");
1151 assert!(err.contains("startup"), "{err}");
1152 }
1153
1154 #[test]
1157 fn a_shallow_walk_says_so() {
1158 let h = build(walk(vec![vec![rec("a", "r", 1.0, 1.0)]]), 10, &[], true).unwrap();
1159 assert!(markdown(&h, "HEAD", false).contains("shallow"));
1160 assert!(html(&h, "HEAD", None, false).contains("shallow"));
1161 let h = build(
1163 walk(vec![
1164 vec![rec("a", "r", 1.0, 1.0)],
1165 vec![rec("a", "r", 1.0, 1.0)],
1166 ]),
1167 1,
1168 &[],
1169 true,
1170 )
1171 .unwrap();
1172 assert!(!markdown(&h, "HEAD", false).contains("shallow"));
1173 }
1174
1175 #[test]
1176 fn nothing_recorded_says_so() {
1177 let h = build(walk(vec![vec![], vec![]]), 10, &[], false).unwrap();
1178 let md = markdown(&h, "main", false);
1179 assert!(md.contains("No measurements recorded"), "{md}");
1180 assert!(md.contains("2 commit(s) walked"), "{md}");
1181 assert!(html(&h, "main", None, false).contains("</html>"));
1183 }
1184
1185 #[test]
1186 fn markdown_rows_are_newest_first_with_deltas() {
1187 let h = build(
1188 walk(vec![
1189 vec![rec("a", "r", 1_000_000.0, 10.0)],
1190 vec![rec("a", "r", 1_020_000.0, 11.0)],
1191 ]),
1192 10,
1193 &[],
1194 false,
1195 )
1196 .unwrap();
1197 let md = markdown(&h, "HEAD", false);
1198 let newest = md.find("1,020,000").unwrap();
1199 let oldest = md.find("1,000,000").unwrap();
1200 assert!(newest < oldest, "{md}");
1201 assert!(md.contains("+2.00%"), "{md}");
1202 assert!(md.contains("### `a` on `r`"), "{md}");
1203 assert!(md.contains("Only instruction counts gate"), "{md}");
1204 let starts: BTreeSet<usize> = md
1206 .lines()
1207 .filter(|l| l.starts_with('|'))
1208 .map(|l| {
1209 l.chars()
1210 .enumerate()
1211 .filter(|(_, c)| *c == '|')
1212 .nth(5)
1213 .unwrap()
1214 .0
1215 })
1216 .collect();
1217 assert_eq!(starts.len(), 1, "{starts:?}\n{md}");
1218 }
1219
1220 #[test]
1223 fn backslashes_in_subjects_are_escaped_first() {
1224 let mut w = walk(vec![vec![rec("a", "r", 1.0, 1.0)]]);
1225 w[0].subject = r"fix(a\|b)".into();
1226 let h = build(w, 10, &[], false).unwrap();
1227 let md = markdown(&h, "HEAD", false);
1228 assert!(md.contains(r"fix(a\\\|b)"), "{md}");
1229 let row = md.lines().find(|l| l.contains("fix(")).unwrap();
1232 let bare = row
1233 .char_indices()
1234 .filter(|&(i, c)| {
1235 c == '|' && row[..i].chars().rev().take_while(|&b| b == '\\').count() % 2 == 0
1236 })
1237 .count();
1238 assert_eq!(bare, 7, "{row}");
1239 }
1240
1241 #[test]
1244 fn undrawable_records_do_not_count_toward_the_limit() {
1245 let mut custom = rec("a", "r", 0.0, 0.0);
1246 custom.metrics = BTreeMap::from([("binary_bytes".to_string(), 9.0)]);
1247 let h = build(
1248 walk(vec![
1249 vec![rec("a", "r", 1.0, 1.0)],
1250 vec![rec("a", "r", 2.0, 1.0)],
1251 vec![custom.clone()],
1252 vec![custom],
1253 ]),
1254 2,
1255 &[],
1256 false,
1257 )
1258 .unwrap();
1259 assert_eq!(h.commits.len(), 2);
1260 assert_eq!(ins(&h.series[0]), vec![Some(1.0), Some(2.0)]);
1261 assert!(!h.older);
1262 }
1263
1264 #[test]
1267 fn a_selected_bench_with_nothing_drawable_is_an_error() {
1268 let mut custom = rec("size", "r", 0.0, 0.0);
1269 custom.metrics = BTreeMap::from([("binary_bytes".to_string(), 9.0)]);
1270 let err = build(
1271 walk(vec![vec![rec("a", "r", 1.0, 1.0), custom]]),
1272 10,
1273 &["size".to_string()],
1274 false,
1275 )
1276 .unwrap_err()
1277 .to_string();
1278 assert!(err.contains("`size` has no instructions"), "{err}");
1279 assert!(err.contains("only other metrics"), "{err}");
1280 }
1281
1282 #[test]
1285 fn an_all_undrawable_history_says_what_it_skipped() {
1286 let mut custom = rec("size", "r", 0.0, 0.0);
1287 custom.metrics = BTreeMap::from([("binary_bytes".to_string(), 9.0)]);
1288 let h = build(walk(vec![vec![custom], vec![]]), 10, &[], false).unwrap();
1289 assert!(h.series.is_empty());
1290 let md = markdown(&h, "HEAD", false);
1291 assert!(md.contains("1 carried only other metrics"), "{md}");
1292 assert!(!md.contains("No measurements recorded"), "{md}");
1293 }
1294
1295 #[test]
1297 fn subjects_cannot_break_the_table() {
1298 let mut w = walk(vec![vec![rec("a", "r", 1.0, 1.0)]]);
1299 w[0].subject = "fix(a|b): <thing>".into();
1300 let h = build(w, 10, &[], false).unwrap();
1301 assert!(markdown(&h, "HEAD", false).contains("fix(a\\|b)"));
1302 let page = html(&h, "HEAD", None, false);
1303 assert!(page.contains("fix(a|b): <thing>"), "{page}");
1304 assert!(!page.contains("<thing>"));
1305 }
1306
1307 #[test]
1308 fn the_credit_line_follows_the_setting() {
1309 let h = build(walk(vec![vec![rec("a", "r", 1.0, 1.0)]]), 10, &[], false).unwrap();
1310 assert!(markdown(&h, "HEAD", true).contains("Measured by [tak]"));
1311 assert!(!markdown(&h, "HEAD", false).contains("Measured by [tak]"));
1312 assert!(html(&h, "HEAD", None, true).contains("Generated by"));
1313 assert!(!html(&h, "HEAD", None, false).contains("Generated by"));
1314 }
1315
1316 #[test]
1317 fn the_page_is_self_contained() {
1318 let h = build(
1319 walk(vec![
1320 vec![rec("a", "r", 1.0, 1.0)],
1321 vec![rec("a", "r", 2.0, 1.0)],
1322 ]),
1323 10,
1324 &[],
1325 false,
1326 )
1327 .unwrap();
1328 let page = html(&h, "HEAD", Some("o/r"), true);
1329 assert!(!page.contains("<script"), "no script");
1330 assert!(!page.contains("<link"), "no external stylesheet");
1331 assert!(!page.contains("src="), "nothing loaded");
1332 assert!(page.contains("prefers-color-scheme: dark"));
1333 assert_eq!(page.matches("<svg").count(), 2, "{page}");
1335 assert!(page.contains("<title>"), "hover titles");
1336 }
1337
1338 #[test]
1339 fn commits_link_to_the_forge_only_when_there_is_one() {
1340 let h = build(walk(vec![vec![rec("a", "r", 1.0, 1.0)]]), 10, &[], false).unwrap();
1341 let sha = &h.commits[0].sha;
1342 let linked = html(&h, "HEAD", Some("jdx/tak"), false);
1343 assert!(
1344 linked.contains(&format!("https://github.com/jdx/tak/commit/{sha}")),
1345 "{linked}"
1346 );
1347 assert!(!html(&h, "HEAD", None, false).contains("https://github.com/jdx/tak/commit"));
1348 }
1349
1350 #[test]
1353 fn a_timing_only_series_draws_only_timing() {
1354 let mut r = rec("install", "r", 0.0, 12.0);
1355 r.tool = "pnpm".into();
1356 r.metrics.remove(GATED_METRIC);
1357 let h = build(walk(vec![vec![r]]), 10, &[], false).unwrap();
1358 let page = html(&h, "HEAD", None, false);
1359 assert!(page.contains("timing only"), "{page}");
1360 assert_eq!(page.matches("<svg").count(), 1);
1361 assert!(page.contains("install (pnpm)"), "{page}");
1362 }
1363
1364 #[test]
1367 fn noise_does_not_fill_the_chart() {
1368 let (lo, hi) = domain(&[29_413_235.0, 29_419_117.0], INS_MIN_SPAN);
1369 assert!(hi - lo >= 29_413_235.0 * INS_MIN_SPAN, "{lo} {hi}");
1370 let (lo, hi) = domain(&[100.0, 150.0], INS_MIN_SPAN);
1372 assert!(lo < 100.0 && hi > 150.0);
1373 }
1374
1375 #[test]
1377 fn a_flat_series_is_centred() {
1378 let (lo, hi) = domain(&[500.0, 500.0], INS_MIN_SPAN);
1379 assert!(((lo + hi) / 2.0 - 500.0).abs() < 1e-9);
1380 let (lo, hi) = domain(&[0.0], INS_MIN_SPAN);
1382 assert!(hi > lo && lo >= 0.0);
1383 }
1384
1385 #[test]
1386 fn si_keeps_enough_figures_to_tell_ticks_apart() {
1387 assert_eq!(si(29_413_235.0), "29.41M");
1388 assert_eq!(si(1_500.0), "1.500k");
1389 assert_eq!(si(2_300_000_000.0), "2.300G");
1390 assert_eq!(si(12.0), "12.00");
1391 let (lo, hi) = domain(&[29_413_235.0], INS_MIN_SPAN);
1393 assert_ne!(si(lo), si(hi));
1394 }
1395
1396 #[test]
1397 fn a_zero_base_has_no_percentage() {
1398 let h = build(
1399 walk(vec![
1400 vec![rec("a", "r", 0.0, 1.0)],
1401 vec![rec("a", "r", 5.0, 1.0)],
1402 ]),
1403 10,
1404 &[],
1405 false,
1406 )
1407 .unwrap();
1408 assert_eq!(h.series[0].deltas(), vec![None, None]);
1409 }
1410}