Skip to main content

tak_cli/
report.rs

1//! A benchmark's history: each series' measurements over first-parent commits.
2//!
3//! `tak compare` answers whether one change moved anything; this answers how a
4//! number got to where it is. The two are read together — a value that has
5//! drifted for weeks and a value one commit just moved look identical in a
6//! two-column comparison, and nothing alike here.
7//!
8//! Everything in this module is pure, over commits already read by
9//! [`crate::notes::log`], so both renderings are tested without a repository.
10//! It deliberately detects nothing: it draws what was recorded and leaves the
11//! judgement of what counts as a step to the reader and to the gate.
12
13use 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/// One series' values on one recorded commit.
23#[derive(Debug, Clone, PartialEq)]
24pub struct Point {
25    /// Index into [`History::commits`].
26    pub commit: usize,
27    pub instructions: Option<f64>,
28    pub wall_min_ms: Option<f64>,
29}
30
31/// One benchmark, on one tool, on one runner class, oldest point first.
32///
33/// Runner is in the key for the reason it is everywhere else: a line that
34/// crossed from one machine class to another would draw an infrastructure
35/// change as a code change.
36#[derive(Debug, Clone, PartialEq)]
37pub struct Series {
38    pub key: Key,
39    pub points: Vec<Point>,
40}
41
42impl Series {
43    /// Each instruction-count point with its change from the previous one that
44    /// has an instruction count, oldest first.
45    ///
46    /// The previous *measured* point, not the previous commit: a series is
47    /// often absent from a commit — a benchmark added later, a run that
48    /// failed — and the gap says nothing about which way the number moved.
49    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
67/// Change as a percentage, `None` against zero — the rule
68/// [`compare::Change::pct`] uses, for the same reason: a percentage of nothing
69/// is undefined, and printing `+0.00%` would say the opposite of what happened.
70fn pct(base: f64, head: f64) -> Option<f64> {
71    (base != 0.0).then_some((head - base) / base * 100.0)
72}
73
74/// What a walk found, reduced to series.
75#[derive(Debug, Clone)]
76pub struct History {
77    /// Recorded commits in the window, oldest first. Commits with nothing drawable
78    /// recorded are not here: most commits on a trunk that records push tips
79    /// have no measurement, and a row each would bury the ones that do.
80    pub commits: Vec<Logged>,
81    pub series: Vec<Series>,
82    /// First-parent commits walked, recorded or not.
83    pub walked: usize,
84    /// Recorded commits exist further back than the limit reached. Whether,
85    /// not how many: counting them meant reading every note on the trunk, and
86    /// [`Enough`] stops the walk at the first one instead.
87    pub older: bool,
88    /// Commits whose records carry neither metric this report draws. Said
89    /// aloud when nothing else was found, so an empty report does not claim
90    /// that nothing was recorded when something was.
91    pub undrawable: usize,
92    /// The clone is shallow, so the walk may have stopped short of the project's
93    /// first commit rather than at it.
94    pub shallow: bool,
95}
96
97/// Reduce a first-parent walk, newest first, to at most `limit` recorded
98/// commits and the series across them.
99///
100/// `benches`, when non-empty, keeps only those benchmarks, and a commit counts
101/// as recorded only if one of them is on it — otherwise `-n 20 --bench x`
102/// could show three points because seventeen of the twenty carried only other
103/// benchmarks. A name that appears nowhere in the walk is an error rather than
104/// an empty report: a typo in a CI step would otherwise publish a blank page
105/// every day and nobody would notice.
106///
107/// Several records for one series on one commit reduce to the minimum, through
108/// the same [`compare::index`] the comparison uses, so a chart and the
109/// comparison it sits beside can never disagree about a commit's value.
110pub 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            // A record with neither metric drawn here — only custom ones, say
129            // — is dropped before counting. Left in, it made its commit use
130            // up one of the `-n` slots while contributing no point, so enough
131            // of them could push every drawable measurement out of the window.
132            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    // The walk is newest first; a series reads oldest to newest.
142    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            // Every record left carries one of the two, so every key has a
151            // value to draw.
152            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
173/// Decides when a newest-first walk has read far enough for [`build`] to
174/// produce the report the whole walk would.
175///
176/// That is one recorded commit past the limit, which is proof that older ones
177/// exist, and every benchmark named with `--bench` seen with something to
178/// draw, so that [`check_benches`] passes on the prefix exactly when it would
179/// on the whole. Until both hold, the walk goes on to the end, and the report
180/// is built from all of it as before.
181///
182/// "Recorded" is [`build`]'s rule, not merely a note being present, or a run of
183/// commits carrying only other benchmarks would end the walk before the
184/// selected one's points were reached.
185pub 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    /// Take in the next commit of the walk; true once nothing older can change
203    /// the report.
204    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
217/// Whether a record carries a metric this report draws.
218fn drawable(r: &Record) -> bool {
219    r.metrics.contains_key(GATED_METRIC) || r.metrics.contains_key(WALL_METRIC)
220}
221
222/// Every benchmark named with `--bench` must have something to draw somewhere
223/// in the walk.
224///
225/// Two separate failures, because they have separate fixes. A name recorded
226/// nowhere is usually a typo. A name recorded only with other metrics is a
227/// benchmark that stopped producing — or never produced — an instruction
228/// count or a wall time, and filtering it would otherwise yield a report that
229/// succeeds, says nothing was recorded, and gets published blank.
230///
231/// The whole walk rather than the `-n` window is the right scope: `-n` counts
232/// only commits with something drawable, so if any exist the window reaches
233/// back to them.
234fn 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
280/// `abcdef0123…` -> `abcdef0`, git's own default abbreviation.
281fn short(sha: &str) -> &str {
282    &sha[..sha.len().min(7)]
283}
284
285/// The calendar date of an ISO 8601 timestamp.
286fn day(date: &str) -> &str {
287    &date[..date.len().min(10)]
288}
289
290/// Subjects longer than this are cut. The subject is the last column precisely
291/// so that it can be ragged, but a 200-character one still wraps every row.
292const 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
303/// A sentence saying what the walk covered, and why it may have covered less
304/// than was asked for. Shared by both renderings so they cannot disagree.
305fn 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        // Only worth saying when the limit was not what stopped the walk.
331        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
339/// The caveat every rendering carries: the numbers beside the gated one are
340/// context, and the wrong one to act on.
341const 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
344/// A markdown table whose columns are padded to line up.
345///
346/// Padded because this is read in a terminal at least as often as rendered,
347/// and padding changes nothing once it is.
348fn 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            // The last column is ragged: trailing spaces on the widest free
360            // text column only lengthen every line.
361            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        // The ragged column's rule matches its header, not its widest cell.
376        let w = if i + 1 == width.len() && !right[i] {
377            header[i].chars().count().max(1)
378        } else {
379            *w
380        };
381        // Two wider than the column, for the spaces either side of a cell.
382        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
396/// Rows for one series, newest first — the order `git log` reads in, and the
397/// one where the most recent number is the first thing seen. Each row comes
398/// with its commit, so a renderer can link the abbreviated SHA it prints.
399fn 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
437/// Render the history as markdown: one table per series.
438///
439/// Markdown for the same reason as [`compare::markdown`] — readable unrendered,
440/// and it drops straight into `$GITHUB_STEP_SUMMARY`.
441pub 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        // A subject is free text; an unescaped pipe in one splits its row.
447        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
467/// Escape text for HTML element content and quoted attribute values alike.
468fn 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("&amp;"),
473            '<' => out.push_str("&lt;"),
474            '>' => out.push_str("&gt;"),
475            '"' => out.push_str("&quot;"),
476            '\'' => out.push_str("&#39;"),
477            c => out.push(c),
478        }
479    }
480    out
481}
482
483/// Chart geometry, in SVG user units. The page scales the drawing to its
484/// column, so these fix proportions and label sizes rather than pixels.
485const WIDTH: f64 = 720.0;
486const LEFT: f64 = 76.0;
487const RIGHT_PAD: f64 = 12.0;
488/// Plot heights. Wall time's is smaller on purpose: it is the context, and
489/// should not take the same space as the number that gates.
490const INS_PLOT: f64 = 150.0;
491const WALL_PLOT: f64 = 56.0;
492/// Room above the plot for the chart's name.
493const TOP: f64 = 24.0;
494/// Room below: enough for commit labels on the chart that carries them, and a
495/// sliver on the one that does not.
496const AXIS_BOTTOM: f64 = 28.0;
497const BARE_BOTTOM: f64 = 8.0;
498
499/// Closer together than this, per-commit dots merge into a smear; the line
500/// alone carries the shape, and the hover columns still identify each commit.
501///
502/// Spacing rather than a count of the series' own points, because every
503/// series shares the page's commit axis: a benchmark added recently has few
504/// points, all of them crowded into the right-hand end.
505const MIN_DOT_SPACING: f64 = 12.0;
506
507/// The smallest vertical span a chart is drawn over, as a fraction of its
508/// values' midpoint.
509///
510/// Scaling each series to its own range is necessary — a 7M-instruction
511/// startup benchmark and a 100M install benchmark share no useful axis — but a
512/// range fitted tightly to a deterministic metric draws its ~0.02% run-to-run
513/// wobble as full-height swings. With a floor of 2%, that wobble stays flat and
514/// a step the size of the default 1% gate still fills half the chart.
515const INS_MIN_SPAN: f64 = 0.02;
516/// The same floor for wall time, wide because the metric is: 4-20% run to run
517/// on a quiet host. A tighter one would draw that noise as a trend.
518const WALL_MIN_SPAN: f64 = 0.25;
519
520/// The y range a series is drawn over: its values, widened to at least
521/// `min_span` of their midpoint, with a margin so no point sits on an edge.
522///
523/// A flat series lands at mid-height, for the reason [`compare::sparkline`]
524/// gives: a deterministic number that never moved is the best outcome, and
525/// drawing it at the floor would make it look like the worst.
526fn 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    // `1.0` keeps an all-zero series from dividing by a zero span.
531    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    // Counts and durations are never negative; an axis that goes below zero
535    // implies they could.
536    if a < 0.0 && lo >= 0.0 {
537        b -= a;
538        a = 0.0;
539    }
540    (a, b)
541}
542
543/// A value to four significant figures with an SI suffix: `29.41M`.
544///
545/// Four because the narrowest chart spans 2% of its midpoint, and three
546/// figures would print the top and bottom labels of such a chart identically.
547fn 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
564/// Horizontal position of a commit. Every chart on the page shares this axis,
565/// so a series that starts later starts further right, and a commit sits in
566/// the same column in every chart.
567fn 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
576/// What a point says on hover: which commit, and everything measured on it.
577fn 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
591/// Where a commit's page is, when the repository lives somewhere that has one.
592fn commit_url(repo: Option<&str>, sha: &str) -> Option<String> {
593    repo.map(|r| format!("https://github.com/{r}/commit/{sha}"))
594}
595
596/// Which metric a chart draws.
597#[derive(Clone, Copy)]
598enum Metric {
599    Instructions,
600    Wall,
601}
602
603/// One chart: a metric over the shared commit axis. `x_axis` labels the first
604/// and last commit beneath it, and is set on whichever chart is drawn last in
605/// a series, so the labels sit once under the pair rather than between them.
606fn 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    // Three hairlines — bottom, middle, top — and their values. Enough to
647    // read a magnitude off; more would compete with the one line that matters.
648    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        // First and last commit only: dates are uneven along a commit axis,
669        // so intermediate ticks would imply a time scale that is not there.
670        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        // Always the latest point, so a long history still shows where it ended.
707        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    // Hover targets: a full-height column per point, wider than the mark, so a
718    // commit can be found without landing on a four-pixel dot. The native
719    // <title> tooltip needs no script, which keeps the page one inert file.
720    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
751/// Theme tokens, light then dark. The dark steps are chosen for the dark
752/// surface rather than inverted from the light ones, and wall time is drawn in
753/// the neutral text tone in both — it is context, not a second series
754/// competing for attention.
755const 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
799/// Render the history as one self-contained HTML page: a chart per series,
800/// instruction counts above and wall time beneath it.
801///
802/// Self-contained — inline SVG and CSS, no script, nothing fetched — so it can
803/// be published to GitHub Pages or opened from disk and look the same, and so
804/// the page cannot break when a CDN moves.
805///
806/// Wall time gets its own smaller chart rather than a second axis on the
807/// first. Two y-scales on one plot invite reading the crossing of two lines as
808/// meaningful, and here one of them is the metric the gate ignores.
809pub 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
937/// Turn the backtick spans [`coverage`] writes for markdown into `<code>`.
938/// Applied after escaping, and backticks are not something escaping touches.
939fn 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    /// Newest first, as `git log` yields it: commit 4 is the tip.
980    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    /// Most trunk commits carry nothing. They count as walked, and take no
1013    /// row and no point.
1014    #[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    /// The same rule as the comparison: a noisy re-run on a commit must not put
1034    /// a spike in the line that the comparison table does not show.
1035    #[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    /// Two runner classes are two series, never one line that jumps where the
1053    /// machine changed.
1054    #[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    /// A benchmark added partway through starts partway through, and its first
1074    /// point has nothing to be a change from.
1075    #[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    /// The limit counts recorded commits, newest first, and says that it left
1102    /// older ones out.
1103    #[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    /// With a filter, a commit carrying only other benchmarks is not a
1119    /// recorded commit — or `-n 5 --bench x` shows fewer than five points.
1120    #[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    /// A typo in a CI step must fail, not publish an empty report forever.
1140    #[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    /// A shallow clone that ran out of commits is not the same as a project
1155    /// that ran out of history, and the report must not read as though it were.
1156    #[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        // When the limit stopped the walk, shallowness is beside the point.
1162        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        // An empty page still has to be a valid page.
1182        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        // Every column but the ragged last one lines up unrendered.
1205        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    /// A subject that escapes its own pipe must not end up with the escape
1221    /// escaped and the pipe bare.
1222    #[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        // Every pipe not preceded by an odd run of backslashes is a cell
1230        // boundary, and six cells have seven.
1231        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    /// Records carrying only metrics this report does not draw must not use up
1242    /// `-n` slots that drawable measurements then lose.
1243    #[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    /// A selected benchmark with nothing drawable must fail, not publish a
1265    /// blank report — and say why, rather than claiming it was never recorded.
1266    #[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    /// Without a filter an empty history is a legitimate state, but one made
1283    /// of undrawable records must not read as though nothing was recorded.
1284    #[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    /// A pipe in a commit subject would otherwise end its table row early.
1296    #[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): &lt;thing&gt;"), "{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        // One chart for instructions, one for wall time.
1334        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    /// Wall-only series — a competitor tool — still get a chart, and say
1351    /// they have no gate-able number rather than drawing an empty one.
1352    #[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    /// A deterministic metric wobbling by 0.02% must not fill the chart. The
1365    /// floor on the span keeps it near the middle.
1366    #[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        // A step the size of a real regression is not clipped.
1371        let (lo, hi) = domain(&[100.0, 150.0], INS_MIN_SPAN);
1372        assert!(lo < 100.0 && hi > 150.0);
1373    }
1374
1375    /// Flat is the best outcome and sits mid-height, not at the floor.
1376    #[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        // All zeros is a range, not a division by zero.
1381        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        // The narrowest chart spans 2%: its top and bottom labels differ.
1392        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}