Skip to main content

tak_cli/
profile.rs

1//! Per-function instruction profiles, and where a change between two of them
2//! went.
3//!
4//! A failed gate says "+3.2% instructions". That is enough to stop a merge and
5//! not enough to fix anything. cachegrind already knows which functions
6//! retired those instructions — the counting run discarded it to `/dev/null`
7//! — so `tak run --profile-dir` keeps the profile of the run whose count was
8//! reported, and `tak explain` ranks the functions whose counts moved. Timing
9//! tools cannot do this: a sampled profile of a 10ms command is mostly noise,
10//! while these counts are as deterministic as the total they add up to.
11//!
12//! The cachegrind out format is parsed here rather than handed to `cg_diff`
13//! or `cg_annotate`. Both are Python scripts in recent valgrind releases, and
14//! a CI image that installs valgrind for counting need not carry Python.
15//!
16//! Profiles never go into git notes. A profile is hundreds of kilobytes, and a
17//! note is a set of one-line records that concurrent writers deduplicate by
18//! exact bytes — see [`crate::record`].
19
20use anyhow::{Context, Result, bail};
21use std::collections::BTreeMap;
22use std::path::{Path, PathBuf};
23
24/// What a kept profile's file name ends in: `<bench>/<subject>` plus this.
25/// cachegrind's own default is `cachegrind.out.<pid>`; the pid is useless
26/// here and would stop a base and a head from pairing up by name.
27pub const EXTENSION: &str = ".cachegrind.out";
28
29/// Where a profile came from, written into it as `desc: tak <key>: <value>`
30/// lines.
31///
32/// `desc:` is the format's own slot for free-form description, and
33/// `cg_annotate` prints it, so a profile that has been copied out of its
34/// directory still says where it came from.
35#[derive(Debug, Clone, Default, PartialEq)]
36pub struct Origin {
37    /// The runner class. It matters for the same reason the notes are
38    /// partitioned on it: between runner classes a different glibc picks a
39    /// different `memcpy`, and an attribution across them reads as one
40    /// function vanishing and another appearing.
41    pub runner: String,
42    /// The commit measured, when there was one. With the benchmark and
43    /// subject, it lets `tak explain` find what the notes recorded for the
44    /// same series and say when a later run replaced the profile behind it.
45    pub commit: Option<String>,
46    pub bench: String,
47    pub subject: String,
48}
49
50/// Where `tak run --profile-dir DIR` keeps a subject's profile:
51/// `DIR/<bench>/<subject>.cachegrind.out`.
52///
53/// Benchmark and subject names come from `tak.toml` keys, which may be any
54/// string. A name that is not a single, ordinary path component is refused
55/// rather than escaped: `[bench."../x"]` writing outside the directory is
56/// the failure being prevented, and an escaped name would no longer be the
57/// name a reader looks for.
58///
59/// Control characters go through [`crate::record::check_name`], the one
60/// check every recorded name passes; `tak.toml`, `--bench` and `TAK_TOOL`
61/// have normally been through it already. What is added here is only what a
62/// file name needs beyond a recorded one.
63pub fn path_for(dir: &Path, bench: &str, subject: &str) -> Result<PathBuf> {
64    for (what, name) in [("benchmark", bench), ("subject", subject)] {
65        crate::record::check_name(what, name)?;
66        let plain = !name.is_empty() && name != "." && name != ".." && !name.contains(['/', '\\']);
67        if !plain {
68            bail!(
69                "--profile-dir cannot name a file after {what} {name:?}: it is not a plain file name"
70            );
71        }
72    }
73    Ok(dir.join(bench).join(format!("{subject}{EXTENSION}")))
74}
75
76/// Write a profile to `dest`, with where it came from.
77///
78/// Through a temporary file in the same directory and a rename, so an
79/// interrupted run leaves the previous profile or the new one, never half of
80/// one that parses as a function set with most of its functions missing.
81pub fn write(dest: &Path, raw: &[u8], origin: &Origin) -> Result<()> {
82    let parent = dest.parent().context("a profile path has a directory")?;
83    std::fs::create_dir_all(parent)
84        .with_context(|| format!("could not create {}", parent.display()))?;
85    let mut tmp = tempfile::NamedTempFile::new_in(parent)
86        .with_context(|| format!("could not write a profile in {}", parent.display()))?;
87    // `desc:` lines lead the file in the format's grammar, so prepending them
88    // leaves it readable by cachegrind's own tools. One line each, whatever
89    // a value holds.
90    let mut head = String::new();
91    let fields = [
92        ("runner", Some(origin.runner.as_str())),
93        ("commit", origin.commit.as_deref()),
94        ("bench", Some(origin.bench.as_str())),
95        ("subject", Some(origin.subject.as_str())),
96    ];
97    for (key, value) in fields {
98        if let Some(v) = value {
99            let v: String = v
100                .chars()
101                .map(|c| if c.is_control() { ' ' } else { c })
102                .collect();
103            head.push_str(&format!("desc: tak {key}: {v}\n"));
104        }
105    }
106    use std::io::Write;
107    tmp.write_all(head.as_bytes())
108        .and_then(|()| tmp.write_all(raw))
109        .with_context(|| format!("could not write {}", dest.display()))?;
110    tmp.persist(dest)
111        .with_context(|| format!("could not write {}", dest.display()))?;
112    Ok(())
113}
114
115/// One function's self cost, and the source files it was charged under.
116#[derive(Debug, Clone, Default, PartialEq)]
117pub struct Function {
118    /// Instructions retired in the function's own code.
119    pub ir: u64,
120    /// The same, by source file. cachegrind charges a line to the file it
121    /// came from, so a function with a helper inlined into it shows up under
122    /// the helper's header as well as its own source.
123    pub files: BTreeMap<String, u64>,
124}
125
126impl Function {
127    /// The file most of the function's instructions came from — the one a
128    /// reader would open. Ties go to the first name, so the choice is stable.
129    pub fn file(&self) -> &str {
130        self.files
131            .iter()
132            .max_by(|a, b| a.1.cmp(b.1).then_with(|| b.0.cmp(a.0)))
133            .map_or("???", |(f, _)| f.as_str())
134    }
135}
136
137/// A parsed cachegrind out file, reduced to instructions per function.
138#[derive(Debug, Clone, Default, PartialEq)]
139pub struct Profile {
140    /// `desc:` lines, in order.
141    pub desc: Vec<String>,
142    /// The `cmd:` line: what was profiled.
143    pub cmd: Option<String>,
144    /// The `summary:` total, or the sum of the functions when there is none.
145    pub total: u64,
146    /// Keyed on the function's name alone, not on file and name as
147    /// cachegrind does. Its file is wherever the line came from, and two
148    /// builds in different checkouts, or with a helper inlined differently,
149    /// would otherwise disagree about every function in the program.
150    pub functions: BTreeMap<String, Function>,
151}
152
153impl Profile {
154    /// What `tak run --profile-dir` recorded about where this came from, when
155    /// it wrote the file. `None` for a profile from anywhere else.
156    pub fn origin(&self) -> Option<Origin> {
157        let get = |key: &str| {
158            self.desc.iter().find_map(|d| {
159                d.strip_prefix("tak ")?
160                    .strip_prefix(key)?
161                    .strip_prefix(": ")
162                    .map(str::to_string)
163            })
164        };
165        Some(Origin {
166            runner: get("runner")?,
167            commit: get("commit"),
168            bench: get("bench").unwrap_or_default(),
169            subject: get("subject").unwrap_or_default(),
170        })
171    }
172
173    /// The runner class `tak run --profile-dir` recorded, if it wrote this.
174    pub fn runner(&self) -> Option<String> {
175        self.origin().map(|o| o.runner)
176    }
177
178    pub fn load(path: &Path) -> Result<Profile> {
179        let text = std::fs::read_to_string(path)
180            .with_context(|| format!("could not read {}", path.display()))?;
181        parse(&text).with_context(|| format!("could not parse {}", path.display()))
182    }
183}
184
185/// The two name tables of the format's compression: `fl=(3) src/a.rs` defines
186/// 3, and a later `fl=(3)` refers back to it. Files and functions are numbered
187/// separately.
188#[derive(Default)]
189struct Names {
190    files: BTreeMap<String, String>,
191    fns: BTreeMap<String, String>,
192}
193
194/// Resolve a possibly-compressed name.
195///
196/// cachegrind itself writes names in full; callgrind compresses them, and a
197/// profile converted by other tooling may too. `(id)` alone refers to an
198/// earlier definition; `(id) name` defines one.
199fn resolve(table: &mut BTreeMap<String, String>, value: &str) -> Result<String> {
200    let value = value.trim();
201    let Some(rest) = value.strip_prefix('(') else {
202        return Ok(value.to_string());
203    };
204    let Some((id, name)) = rest.split_once(')') else {
205        // `(below main)` is a real function name, not a malformed reference.
206        return Ok(value.to_string());
207    };
208    if !id.chars().all(|c| c.is_ascii_digit()) || id.is_empty() {
209        return Ok(value.to_string());
210    }
211    let name = name.trim();
212    if name.is_empty() {
213        return table
214            .get(id)
215            .cloned()
216            .with_context(|| format!("name ({id}) is used before it is defined"));
217    }
218    table.insert(id.to_string(), name.to_string());
219    Ok(name.to_string())
220}
221
222/// Parse a cachegrind out file.
223///
224/// Only instructions (`Ir`) are kept; tak runs cachegrind with the cache and
225/// branch simulations off, and those are the only events a count gates on.
226///
227/// Tolerant of what it does not need — unknown header and specification
228/// lines are skipped — and strict about what it does: a cost line that will
229/// not parse is an error with its line number, because silently dropping one
230/// understates a function and the ranking built on it would be wrong.
231pub fn parse(text: &str) -> Result<Profile> {
232    let mut p = Profile::default();
233    let mut names = Names::default();
234    // Which cost column is `Ir`, and how many position columns precede the
235    // costs: cachegrind writes one (the line), callgrind may write more.
236    let mut ir_col: Option<usize> = None;
237    let mut positions = 1usize;
238    let mut summary: Option<u64> = None;
239    let mut file = String::from("???");
240    let mut func = String::from("???");
241    // callgrind's `calls=` is followed by the call's *inclusive* cost, which
242    // is already counted in the callee's own lines.
243    let mut skip_cost = false;
244    let mut sum = 0u64;
245
246    for (i, line) in text.lines().enumerate() {
247        let n = i + 1;
248        // Both ends: cachegrind writes no indentation, but a converted or
249        // hand-edited profile may, and an indented cost line skipped as
250        // unrecognised would understate its function while the total stood.
251        let line = line.trim();
252        if line.is_empty() || line.starts_with('#') {
253            continue;
254        }
255        let first = line.as_bytes()[0];
256        if first.is_ascii_digit() || matches!(first, b'+' | b'-' | b'*') {
257            if skip_cost {
258                skip_cost = false;
259                continue;
260            }
261            let col =
262                ir_col.with_context(|| format!("line {n}: a cost before the `events:` line"))?;
263            let fields: Vec<&str> = line.split_whitespace().collect();
264            if fields.len() < positions {
265                bail!("line {n}: expected {positions} position column(s): {line}");
266            }
267            // A trailing zero cost may be left off, so a short line is zero.
268            let ir = match fields.get(positions + col) {
269                Some(v) => v
270                    .parse::<u64>()
271                    .with_context(|| format!("line {n}: not a count: {v}"))?,
272                None => 0,
273            };
274            let f = p.functions.entry(func.clone()).or_default();
275            f.ir += ir;
276            *f.files.entry(file.clone()).or_default() += ir;
277            sum += ir;
278            continue;
279        }
280        if let Some(rest) = line.strip_prefix("desc:") {
281            p.desc.push(rest.trim().to_string());
282        } else if let Some(rest) = line.strip_prefix("cmd:") {
283            p.cmd = Some(rest.trim().to_string());
284        } else if let Some(rest) = line.strip_prefix("events:") {
285            let events: Vec<&str> = rest.split_whitespace().collect();
286            ir_col = Some(
287                events
288                    .iter()
289                    .position(|e| *e == "Ir")
290                    .with_context(|| format!("line {n}: no `Ir` event in `{line}`"))?,
291            );
292        } else if let Some(rest) = line.strip_prefix("positions:") {
293            positions = rest.split_whitespace().count().max(1);
294        } else if let Some(rest) = line
295            .strip_prefix("summary:")
296            .or_else(|| line.strip_prefix("totals:"))
297        {
298            let col = ir_col.with_context(|| format!("line {n}: a total before `events:`"))?;
299            if let Some(v) = rest.split_whitespace().nth(col) {
300                summary = Some(
301                    v.parse()
302                        .with_context(|| format!("line {n}: not a count: {v}"))?,
303                );
304            }
305        } else if let Some((key, value)) = line.split_once('=') {
306            match key {
307                // `fi=`/`fe=` switch file for inlined code within the same
308                // function; `fl=` starts a new function's file.
309                "fl" | "fi" | "fe" => file = resolve(&mut names.files, value)?,
310                "fn" => func = resolve(&mut names.fns, value)?,
311                // Callee names still define compressed ids that a later
312                // `fn=(id)` may refer to.
313                "cfl" | "cfi" => {
314                    resolve(&mut names.files, value)?;
315                }
316                "cfn" => {
317                    resolve(&mut names.fns, value)?;
318                }
319                "calls" => skip_cost = true,
320                _ => {}
321            }
322        }
323        // Anything else — `version:`, `creator:`, `pid:` and the like — says
324        // nothing about where instructions went.
325    }
326    if ir_col.is_none() {
327        bail!("not a cachegrind profile: no `events:` line");
328    }
329    p.total = summary.unwrap_or(sum);
330    Ok(p)
331}
332
333/// One function's count on both sides.
334#[derive(Debug, Clone, PartialEq)]
335pub struct Delta {
336    pub name: String,
337    /// Where it lives, from the head when it exists there.
338    pub file: String,
339    pub base: u64,
340    pub head: u64,
341}
342
343impl Delta {
344    pub fn change(&self) -> i128 {
345        self.head as i128 - self.base as i128
346    }
347}
348
349/// Every function whose count differs, largest change first.
350///
351/// By size of the change in either direction, not by increase alone. A
352/// refactor that moves work shows as one function gaining and another losing,
353/// and a reader seeing only the gain would go looking for new work that is
354/// not there.
355pub fn diff(base: &Profile, head: &Profile) -> Vec<Delta> {
356    let empty = Function::default();
357    let mut out: Vec<Delta> = base
358        .functions
359        .keys()
360        .chain(head.functions.keys())
361        .collect::<std::collections::BTreeSet<_>>()
362        .into_iter()
363        .filter_map(|name| {
364            let b = base.functions.get(name).unwrap_or(&empty);
365            let h = head.functions.get(name).unwrap_or(&empty);
366            (b.ir != h.ir).then(|| Delta {
367                name: name.clone(),
368                file: if h.files.is_empty() { b } else { h }.file().to_string(),
369                base: b.ir,
370                head: h.ir,
371            })
372        })
373        .collect();
374    // Name breaks ties, so the same two profiles always render the same table.
375    out.sort_by(|a, b| {
376        b.change()
377            .unsigned_abs()
378            .cmp(&a.change().unsigned_abs())
379            .then_with(|| a.name.cmp(&b.name))
380    });
381    out
382}
383
384/// A base and a head profile of the same benchmark subject.
385#[derive(Debug, Clone)]
386pub struct Pair {
387    /// How the report names it: `bench`, or `bench (subject)`.
388    pub label: String,
389    pub base: Profile,
390    pub head: Profile,
391}
392
393/// Profiles found on only one side, by their path relative to its directory.
394#[derive(Debug, Clone, Default, PartialEq)]
395pub struct Unpaired {
396    pub base: Vec<String>,
397    pub head: Vec<String>,
398}
399
400/// The profiles `tak run --profile-dir` wrote under `dir`, by relative path.
401fn scan(dir: &Path) -> Result<BTreeMap<String, PathBuf>> {
402    let mut out = BTreeMap::new();
403    let benches =
404        std::fs::read_dir(dir).with_context(|| format!("could not read {}", dir.display()))?;
405    for bench in benches {
406        let bench = bench?;
407        if !bench.file_type()?.is_dir() {
408            continue;
409        }
410        for file in std::fs::read_dir(bench.path())? {
411            let file = file?;
412            let name = file.file_name().to_string_lossy().to_string();
413            if file.file_type()?.is_file() && name.ends_with(EXTENSION) {
414                out.insert(
415                    format!("{}/{name}", bench.file_name().to_string_lossy()),
416                    file.path(),
417                );
418            }
419        }
420    }
421    Ok(out)
422}
423
424/// `bench/subject.cachegrind.out` as the comparison table names it, as
425/// markdown.
426///
427/// Escaped, because names come from `tak.toml` and file names, and in CI the
428/// pull request being reported on controls both. A name must stay a label:
429/// one that could open a heading or a link could write its own claims into
430/// the step summary.
431fn label(rel: &str) -> String {
432    let (bench, file) = rel.split_once('/').unwrap_or(("", rel));
433    let subject = file.strip_suffix(EXTENSION).unwrap_or(file);
434    match bench {
435        "" => text(subject),
436        _ if subject == crate::config::SELF_TOOL => text(bench),
437        _ => format!("{} ({})", text(bench), text(subject)),
438    }
439}
440
441/// Untrusted text as inert markdown, for a heading: control characters as
442/// [`crate::compare::escape_control`] writes them for every report, and
443/// anything markdown could read as syntax backslash-escaped on top. The
444/// shared helpers stop at control characters because their names sit in
445/// table cells and code spans; a heading is neither, and a `[link](…)` or an
446/// `<img>` there would render as one.
447fn text(s: &str) -> String {
448    let s = crate::compare::escape_control(s);
449    let mut out = String::with_capacity(s.len());
450    for c in s.chars() {
451        if "\\`*_[]<>#|!~&".contains(c) {
452            out.push('\\');
453        }
454        out.push(c);
455    }
456    out
457}
458
459/// Pair up what to explain: two directories `tak run --profile-dir` wrote,
460/// matched on `<bench>/<subject>`, or two profile files.
461pub fn load(base: &Path, head: &Path) -> Result<(Vec<Pair>, Unpaired)> {
462    for p in [base, head] {
463        if !p.exists() {
464            bail!("{} does not exist", p.display());
465        }
466    }
467    match (base.is_dir(), head.is_dir()) {
468        (false, false) => {
469            let name = head
470                .file_name()
471                .map(|n| n.to_string_lossy().to_string())
472                .unwrap_or_default();
473            let pair = Pair {
474                label: label(&name),
475                base: Profile::load(base)?,
476                head: Profile::load(head)?,
477            };
478            Ok((vec![pair], Unpaired::default()))
479        }
480        (true, true) => {
481            let (b, h) = (scan(base)?, scan(head)?);
482            let mut pairs = Vec::new();
483            let mut unpaired = Unpaired::default();
484            for (rel, path) in &h {
485                match b.get(rel) {
486                    Some(bpath) => pairs.push(Pair {
487                        label: label(rel),
488                        base: Profile::load(bpath)?,
489                        head: Profile::load(path)?,
490                    }),
491                    None => unpaired.head.push(rel.clone()),
492                }
493            }
494            unpaired.base = b.keys().filter(|k| !h.contains_key(*k)).cloned().collect();
495            Ok((pairs, unpaired))
496        }
497        _ => bail!(
498            "compare a directory with a directory, or a profile with a profile: {} and {}",
499            base.display(),
500            head.display()
501        ),
502    }
503}
504
505/// A name as a code span, fit for a table cell. Rust and C++ names carry `|`
506/// in closures and `<`…`>` in generics; the pipe would end the cell, a
507/// backtick would end the code span, and a newline would end the row.
508///
509/// The shared report helpers: [`crate::compare::code`] fences the span past
510/// any backticks and escapes control characters, and
511/// [`crate::compare::code_cell`] escapes the pipes.
512fn cell(name: &str) -> String {
513    crate::compare::code_cell(&crate::compare::code(name))
514}
515
516/// A warning when a profile is not from the run whose count the notes hold.
517///
518/// Profiles are overwritten by the next run, while `tak compare` takes the
519/// lowest of every count recorded for a commit. Measure twice — a rebuilt
520/// binary on the same commit, or a subject whose work varies — and the
521/// profile left behind can describe a different count from the one the gate
522/// used, which is worth saying rather than explaining the wrong number.
523fn mismatch(side: &str, p: &Profile, recorded: &dyn Fn(&Origin) -> Option<u64>) -> String {
524    let Some(origin) = p.origin() else {
525        return String::new();
526    };
527    match (origin.commit.as_deref(), recorded(&origin)) {
528        (Some(commit), Some(n)) if n != p.total => format!(
529            "\n> [!WARNING]\n> The {side} profile totals {} instructions, but the lowest count \
530             recorded for {} in git notes is {}. The profile is not from the run that count \
531             came from.\n",
532            crate::compare::thousands(p.total as f64),
533            cell(&commit[..commit.len().min(12)]),
534            crate::compare::thousands(n as f64),
535        ),
536        _ => String::new(),
537    }
538}
539
540fn signed(v: i128) -> String {
541    let n = crate::compare::thousands(v.unsigned_abs() as f64);
542    match v.signum() {
543        1 => format!("+{n}"),
544        -1 => format!("-{n}"),
545        _ => n,
546    }
547}
548
549/// Render the attribution as markdown, for a pull request comment or a step
550/// summary beneath `tak compare`'s table.
551///
552/// The rows shown and a final row for the rest add up to the total change,
553/// so a reader can see how much of it the table accounts for.
554///
555/// `recorded` looks up the instruction count git notes hold for a profile's
556/// series, so a profile replaced since that count was recorded is called out.
557/// It is a parameter so this stays free of git.
558pub fn markdown(
559    pairs: &[Pair],
560    unpaired: &Unpaired,
561    top: usize,
562    recorded: &dyn Fn(&Origin) -> Option<u64>,
563) -> String {
564    let mut out = String::from("## Where the instructions went\n");
565    if pairs.is_empty() {
566        out.push_str("\nNo benchmark has a profile on both sides, so nothing was explained.\n");
567    }
568    for pair in pairs {
569        let (base, head) = (pair.base.total, pair.head.total);
570        let change = head as i128 - base as i128;
571        let pct = if base == 0 {
572            String::new()
573        } else {
574            format!(
575                ", **{}{:.2}%**",
576                if change >= 0 { "+" } else { "" },
577                change as f64 / base as f64 * 100.0
578            )
579        };
580        out.push_str(&format!(
581            "\n### {}\n\n{} → {} instructions ({}{pct}).\n",
582            pair.label,
583            crate::compare::thousands(base as f64),
584            crate::compare::thousands(head as f64),
585            signed(change),
586        ));
587        if let (Some(b), Some(h)) = (pair.base.runner(), pair.head.runner())
588            && b != h
589        {
590            out.push_str(&format!(
591                "\n> [!WARNING]\n> Profiled on different runner classes ({} and {}). \
592                 Library code differs between machines, so some of what follows is the \
593                 machine rather than the change.\n",
594                cell(&b),
595                cell(&h)
596            ));
597        }
598        out.push_str(&mismatch("base", &pair.base, recorded));
599        out.push_str(&mismatch("head", &pair.head, recorded));
600        let deltas = diff(&pair.base, &pair.head);
601        if deltas.is_empty() {
602            out.push_str("\nNo function's instruction count changed.\n");
603            continue;
604        }
605        let shown = deltas.len().min(top);
606        if shown < deltas.len() {
607            out.push_str(&format!(
608                "\n{} function(s) changed; the {shown} largest:\n\n",
609                deltas.len()
610            ));
611        } else {
612            out.push_str(&format!("\n{} function(s) changed:\n\n", deltas.len()));
613        }
614        out.push_str("| function | Δ | base | head | file |\n|---|---:|---:|---:|---|\n");
615        for d in &deltas[..shown] {
616            out.push_str(&format!(
617                "| {} | **{}** | {} | {} | {} |\n",
618                cell(&d.name),
619                signed(d.change()),
620                crate::compare::thousands(d.base as f64),
621                crate::compare::thousands(d.head as f64),
622                cell(&d.file),
623            ));
624        }
625        let rest = &deltas[shown..];
626        if !rest.is_empty() {
627            let sum: i128 = rest.iter().map(Delta::change).sum();
628            out.push_str(&format!(
629                "| {} more | {} | | | |\n",
630                rest.len(),
631                signed(sum)
632            ));
633        }
634    }
635    for (side, list) in [("base", &unpaired.base), ("head", &unpaired.head)] {
636        if !list.is_empty() {
637            out.push_str(&format!(
638                "\nOnly in the {side}, so not explained: {}\n",
639                list.iter().map(|p| cell(p)).collect::<Vec<_>>().join(", ")
640            ));
641        }
642    }
643    out.push_str(
644        "\n<sub>Self cost per function: code inlined into a function counts as its own. \
645         Only the benchmarked process is profiled, not programs it starts. \
646         `???` is code without symbols.</sub>\n",
647    );
648    out
649}
650
651#[cfg(test)]
652mod tests {
653    use super::*;
654
655    const BASE: &str = include_str!("../tests/fixtures/profile/base.cachegrind.out");
656    const HEAD: &str = include_str!("../tests/fixtures/profile/head.cachegrind.out");
657
658    #[test]
659    fn a_profile_sums_each_function_across_its_files() {
660        let p = parse(BASE).unwrap();
661        assert_eq!(p.cmd.as_deref(), Some("./mycli --help"));
662        assert_eq!(p.total, 1_500);
663        // `parse_args` has a helper inlined from another file; both count.
664        let f = &p.functions["mycli::parse_args"];
665        assert_eq!(f.ir, 600);
666        assert_eq!(f.files["src/args.rs"], 500);
667        assert_eq!(f.files["src/util.rs"], 100);
668        assert_eq!(f.file(), "src/args.rs");
669        assert_eq!(p.functions.values().map(|f| f.ir).sum::<u64>(), p.total);
670    }
671
672    #[test]
673    fn the_largest_change_comes_first_in_either_direction() {
674        let d = diff(&parse(BASE).unwrap(), &parse(HEAD).unwrap());
675        let got: Vec<(&str, i128)> = d.iter().map(|d| (d.name.as_str(), d.change())).collect();
676        assert_eq!(
677            got,
678            [
679                ("mycli::render", 900),
680                ("mycli::parse_args", -300),
681                ("mycli::new_helper", 50),
682                ("mycli::gone", -40),
683            ]
684        );
685        // A function only on one side is a change from or to zero.
686        let new = d.iter().find(|d| d.name == "mycli::new_helper").unwrap();
687        assert_eq!((new.base, new.head), (0, 50));
688        assert_eq!(new.file, "src/new.rs");
689        let gone = d.iter().find(|d| d.name == "mycli::gone").unwrap();
690        assert_eq!(gone.file, "src/old.rs");
691    }
692
693    #[test]
694    fn identical_profiles_have_no_changes() {
695        let p = parse(BASE).unwrap();
696        assert!(diff(&p, &p).is_empty());
697    }
698
699    #[test]
700    fn a_missing_summary_is_the_sum() {
701        let p = parse("events: Ir\nfl=a.c\nfn=f\n1 5\n2 7\n").unwrap();
702        assert_eq!(p.total, 12);
703    }
704
705    #[test]
706    fn compressed_names_resolve_to_their_definition() {
707        let text = "\
708events: Ir
709fl=(1) src/a.c
710fn=(1) alpha
7111 10
712fn=(2) beta
7132 20
714fl=(1)
715fn=(1)
7163 5
717";
718        let p = parse(text).unwrap();
719        assert_eq!(p.functions["alpha"].ir, 15);
720        assert_eq!(p.functions["beta"].ir, 20);
721        assert_eq!(p.functions["alpha"].files["src/a.c"], 15);
722    }
723
724    /// `(below main)` is how valgrind names the code before `main`, and must
725    /// not be mistaken for a compressed reference.
726    #[test]
727    fn a_parenthesised_name_is_a_name() {
728        let p = parse("events: Ir\nfl=???\nfn=(below main)\n0 9\n").unwrap();
729        assert_eq!(p.functions["(below main)"].ir, 9);
730    }
731
732    #[test]
733    fn a_reference_to_an_undefined_name_is_an_error() {
734        let err = parse("events: Ir\nfn=(7)\n1 1\n").unwrap_err();
735        assert!(format!("{err:#}").contains("(7)"), "{err:#}");
736    }
737
738    /// callgrind's call cost is inclusive and already counted in the callee,
739    /// so adding it would count those instructions twice.
740    #[test]
741    fn the_cost_after_a_call_is_not_self_cost() {
742        let text = "\
743events: Ir
744fl=a.c
745fn=caller
7461 3
747cfn=callee
748calls=1 10
7491 100
7502 4
751fn=callee
75210 100
753";
754        let p = parse(text).unwrap();
755        assert_eq!(p.functions["caller"].ir, 7);
756        assert_eq!(p.functions["callee"].ir, 100);
757    }
758
759    #[test]
760    fn ir_is_found_among_other_events() {
761        let text = "events: Dr Ir Dw\nfl=a.c\nfn=f\n1 100 5 100\n2 100 6\nsummary: 999 11 999\n";
762        let p = parse(text).unwrap();
763        assert_eq!(p.functions["f"].ir, 11);
764        assert_eq!(p.total, 11);
765    }
766
767    #[test]
768    fn a_malformed_cost_names_its_line() {
769        let err = parse("events: Ir\nfn=f\n1 lots\n").unwrap_err();
770        assert!(format!("{err:#}").contains("line 3"), "{err:#}");
771    }
772
773    #[test]
774    fn a_file_without_events_is_not_a_profile() {
775        assert!(parse("hello\n").is_err());
776    }
777
778    fn origin(runner: &str) -> Origin {
779        Origin {
780            runner: runner.into(),
781            commit: Some("0123456789abcdef".into()),
782            bench: "startup".into(),
783            subject: "self".into(),
784        }
785    }
786
787    /// No notes to check against.
788    fn unrecorded(_: &Origin) -> Option<u64> {
789        None
790    }
791
792    #[test]
793    fn the_origin_is_read_back_from_the_description() {
794        let dir = tempfile::tempdir().unwrap();
795        let dest = path_for(dir.path(), "startup", "self").unwrap();
796        write(&dest, BASE.as_bytes(), &origin("gha-linux-x64")).unwrap();
797        let p = Profile::load(&dest).unwrap();
798        assert_eq!(p.origin(), Some(origin("gha-linux-x64")));
799        assert_eq!(p.runner().as_deref(), Some("gha-linux-x64"));
800        // The rest is untouched.
801        assert_eq!(p.total, parse(BASE).unwrap().total);
802        // And a profile tak did not write has none.
803        assert_eq!(parse(BASE).unwrap().origin(), None);
804    }
805
806    /// A value cannot add a `desc:` line of its own, or a cost line.
807    #[test]
808    fn an_origin_stays_on_its_own_lines() {
809        let dir = tempfile::tempdir().unwrap();
810        let dest = dir.path().join("p");
811        let o = Origin {
812            runner: "r\nfl=x\nfn=y\n1 999".into(),
813            ..origin("r")
814        };
815        write(&dest, BASE.as_bytes(), &o).unwrap();
816        let p = Profile::load(&dest).unwrap();
817        assert_eq!(p.total, 1_500);
818        assert!(!p.functions.contains_key("y"));
819    }
820
821    #[test]
822    fn a_name_that_is_not_a_plain_file_name_is_refused() {
823        let dir = Path::new("/p");
824        assert_eq!(
825            path_for(dir, "startup", "self").unwrap(),
826            Path::new("/p/startup/self.cachegrind.out")
827        );
828        for (bench, subject) in [
829            ("..", "x"),
830            ("a/b", "x"),
831            ("a", ""),
832            ("a", "."),
833            ("a", "b\\c"),
834            ("a\nb", "x"),
835            ("a", "x\r"),
836            ("a\0", "x"),
837        ] {
838            assert!(
839                path_for(dir, bench, subject).is_err(),
840                "{bench:?} {subject:?}"
841            );
842        }
843    }
844
845    #[test]
846    fn a_self_subject_is_labelled_by_its_benchmark() {
847        assert_eq!(label("startup/self.cachegrind.out"), "startup");
848        assert_eq!(
849            label("startup/hyperfine.cachegrind.out"),
850            "startup (hyperfine)"
851        );
852        assert_eq!(label("mine.cachegrind.out"), "mine");
853    }
854
855    /// A name from a pull request's `tak.toml` stays a label: it cannot open
856    /// a heading, a link or an HTML tag in the step summary.
857    #[test]
858    fn a_label_cannot_add_markdown() {
859        // The newline is written as `\n`, as every report writes it, and its
860        // backslash escaped so it renders as written.
861        assert_eq!(
862            label("x\n## All clear/[ok](http:\\/e)<b>.cachegrind.out"),
863            "x\\\\n\\#\\# All clear (\\[ok\\](http:\\\\/e)\\<b\\>)"
864        );
865        // Code spans are the shared helper's: fenced past the backtick, the
866        // newline escaped, the pipe kept inside the cell.
867        assert_eq!(cell("a\nb`c|d"), "`` a\\nb`c\\|d ``");
868    }
869
870    #[test]
871    fn directories_pair_on_benchmark_and_subject() {
872        let (b, h) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
873        for (dir, text, subjects) in [
874            (&b, BASE, &["self", "only-base"][..]),
875            (&h, HEAD, &["self", "only-head"][..]),
876        ] {
877            for s in subjects {
878                write(
879                    &path_for(dir.path(), "startup", s).unwrap(),
880                    text.as_bytes(),
881                    &origin("r"),
882                )
883                .unwrap();
884            }
885        }
886        let (pairs, unpaired) = load(b.path(), h.path()).unwrap();
887        assert_eq!(pairs.len(), 1);
888        assert_eq!(pairs[0].label, "startup");
889        assert_eq!(pairs[0].head.total, 2_110);
890        assert_eq!(unpaired.base, ["startup/only-base.cachegrind.out"]);
891        assert_eq!(unpaired.head, ["startup/only-head.cachegrind.out"]);
892        assert!(load(b.path(), &b.path().join("startup/self.cachegrind.out")).is_err());
893    }
894
895    #[test]
896    fn the_report_accounts_for_the_whole_change() {
897        let pair = Pair {
898            label: "startup".into(),
899            base: parse(BASE).unwrap(),
900            head: parse(HEAD).unwrap(),
901        };
902        let md = markdown(&[pair], &Unpaired::default(), 2, &unrecorded);
903        assert!(
904            md.contains("1,500 → 2,110 instructions (+610, **+40.67%**)"),
905            "{md}"
906        );
907        assert!(
908            md.contains("| `mycli::render` | **+900** | 100 | 1,000 | `src/render.rs` |"),
909            "{md}"
910        );
911        assert!(md.contains("| `mycli::parse_args` | **-300** |"), "{md}");
912        // 50 - 40: the two not shown.
913        assert!(md.contains("| 2 more | +10 |"), "{md}");
914        assert!(!md.contains("WARNING"), "{md}");
915    }
916
917    #[test]
918    fn different_runners_are_called_out() {
919        let mut base = parse(BASE).unwrap();
920        let mut head = base.clone();
921        base.desc.push("tak runner: a".into());
922        head.desc.push("tak runner: b".into());
923        let pair = Pair {
924            label: "x".into(),
925            base,
926            head,
927        };
928        let md = markdown(&[pair], &Unpaired::default(), 10, &unrecorded);
929        assert!(
930            md.contains("different runner classes (`a` and `b`)"),
931            "{md}"
932        );
933        assert!(
934            md.contains("No function's instruction count changed."),
935            "{md}"
936        );
937    }
938
939    /// A profile replaced by a later run on the same commit no longer
940    /// describes the count the gate used, and the report says so. One that
941    /// matches, or has nothing recorded, says nothing.
942    #[test]
943    fn a_profile_that_is_not_the_recorded_count_is_called_out() {
944        let with_origin = |text: &str| {
945            let mut p = parse(text).unwrap();
946            p.desc = vec![
947                "tak runner: r".into(),
948                "tak commit: 0123456789abcdef".into(),
949                "tak bench: startup".into(),
950                "tak subject: self".into(),
951            ];
952            p
953        };
954        let pair = Pair {
955            label: "startup".into(),
956            base: with_origin(BASE),
957            head: with_origin(HEAD),
958        };
959        let asked = std::cell::RefCell::new(Vec::new());
960        // The base matches its note; the head's note is lower.
961        let recorded = |o: &Origin| {
962            asked.borrow_mut().push(o.clone());
963            Some(if asked.borrow().len() == 1 {
964                1_500
965            } else {
966                2_000
967            })
968        };
969        let md = markdown(&[pair], &Unpaired::default(), 10, &recorded);
970        assert!(
971            md.contains(
972                "The head profile totals 2,110 instructions, but the lowest count recorded \
973                 for `0123456789ab` in git notes is 2,000."
974            ),
975            "{md}"
976        );
977        assert!(!md.contains("The base profile"), "{md}");
978        assert_eq!(asked.borrow()[0].bench, "startup");
979        assert_eq!(asked.borrow()[0].subject, "self");
980    }
981
982    /// cachegrind writes no indentation, but an indented cost line must not
983    /// be skipped as unrecognised while the total stays as it was.
984    #[test]
985    fn an_indented_line_is_read_like_any_other() {
986        let p = parse("events: Ir\n  fl=a.c\n\tfn=f\n   1 5\n  2 7  \n summary: 12\n").unwrap();
987        assert_eq!(p.functions["f"].ir, 12);
988        assert_eq!(p.functions["f"].files["a.c"], 12);
989    }
990
991    #[test]
992    fn a_pipe_in_a_name_does_not_break_the_table() {
993        assert_eq!(cell("f::{{closure}}|x"), "`f::{{closure}}\\|x`");
994    }
995}