Skip to main content

tak_cli/
baseline.rs

1//! Named local baselines, for the edit-measure loop.
2//!
3//! `tak compare` needs both sides recorded against commits. Someone optimising
4//! a hot path wants to measure, edit, and measure again, and the edited working
5//! tree has no commit to hang a note on. Recording against HEAD anyway would
6//! attach a measurement to a commit whose code it does not describe, and that
7//! note would travel with the next `tak push`. So a baseline is a named file of
8//! records instead, compared with the same [`crate::compare`] the gate uses.
9//!
10//! Files live under the git *common* directory, `<git-common-dir>/tak/baselines`:
11//!
12//! - never committed and never pushed, since nothing under `.git` is;
13//! - outside the working tree, so no `.gitignore` entry is needed and a
14//!   `git clean -fdx` between edits does not delete the baseline;
15//! - shared by every worktree of a clone, so a baseline saved on one branch's
16//!   worktree can be compared from another's.
17//!
18//! One [`Record::to_line`] per line, the same bytes a note would hold, so a
19//! baseline is read by the same parser and skips the same unreadable lines.
20
21use anyhow::{Context, Result, bail};
22use std::collections::BTreeSet;
23use std::io::Write;
24use std::path::{Path, PathBuf};
25use std::process::Command;
26
27use crate::compare::Key;
28use crate::record::{Record, SCHEMA_VERSION, parse_note};
29
30/// The schema version of a line written by a newer tak, if it is one.
31///
32/// Read from the `v` field alone, the one field every schema version keeps,
33/// so it works whatever else a newer record changed.
34fn newer_schema(line: &str) -> Option<u64> {
35    let v = serde_json::from_str::<serde_json::Value>(line)
36        .ok()?
37        .get("v")?
38        .as_u64()?;
39    (v > u64::from(SCHEMA_VERSION)).then_some(v)
40}
41
42/// Refuse to save over a baseline that holds a record from a newer schema.
43///
44/// Refused rather than kept or dropped. Kept, the newer line sits beside this
45/// run's line for the same series, and once tak is upgraded again the reader
46/// folds both to their minimum, so a stale value can win. Dropped, an older
47/// tak destroys what a newer one saved. And this version cannot tell which
48/// series the line belongs to: a newer schema may spell its key differently.
49/// A downgrade is rare, and another name costs nothing.
50fn refuse_newer(name: &str, path: &Path, body: &str) -> Result<()> {
51    if let Some(v) = body.lines().find_map(newer_schema) {
52        bail!(
53            "baseline `{name}` holds records from a newer tak (schema {v}; this tak writes \
54             {SCHEMA_VERSION}), and saving over it could leave a stale value beside this \
55             run's. Save under another name, or upgrade tak ({})",
56            path.display()
57        );
58    }
59    Ok(())
60}
61
62/// Extension of a baseline file. Listing only these keeps the temporary file
63/// an interrupted save leaves behind out of "saved baselines".
64const EXT: &str = "jsonl";
65
66/// A saved baseline, loaded.
67#[derive(Debug)]
68pub struct Baseline {
69    pub name: String,
70    pub path: PathBuf,
71    pub records: Vec<Record>,
72}
73
74/// The directory baselines are kept in.
75#[derive(Debug, Clone)]
76pub struct Store {
77    dir: PathBuf,
78}
79
80/// Reject a name that is not a plain file name.
81///
82/// The name becomes a path component, so `../x` or `a/b` would write outside
83/// the store, and a leading `.` would hide the file from the listing a missing
84/// baseline's error prints. A narrow character set is easier to hold than a
85/// list of what to escape on every platform.
86pub fn validate_name(name: &str) -> Result<()> {
87    let ok = !name.is_empty()
88        && !name.starts_with('.')
89        && name
90            .chars()
91            .all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));
92    if !ok {
93        bail!(
94            "invalid baseline name `{name}`: use letters, digits, `-`, `_` and `.`, \
95             not starting with `.`"
96        );
97    }
98    Ok(())
99}
100
101fn key(r: &Record) -> Key {
102    (r.bench.clone(), r.tool.clone(), r.runner.clone())
103}
104
105impl Store {
106    /// The store for the repository the current directory is in.
107    ///
108    /// No fallback outside a repository. Anywhere else — a per-user data
109    /// directory, the current directory — is either shared between unrelated
110    /// projects, where one project's `before` silently answers for another's,
111    /// or inside a tree that may be committed.
112    pub fn locate() -> Result<Self> {
113        let out = Command::new("git")
114            .args(["rev-parse", "--git-common-dir"])
115            .output()
116            .context("failed to run `git rev-parse --git-common-dir`")?;
117        if !out.status.success() {
118            bail!(
119                "baselines are kept in the repository's git directory, so they need a git \
120                 repository: {}",
121                String::from_utf8_lossy(&out.stderr).trim()
122            );
123        }
124        let common = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim_end());
125        // Relative to the current directory when git prints it that way
126        // (`.git` at the top of a checkout), absolute from inside a worktree.
127        // Anchored here so every path printed later is one the user can open.
128        let common = std::path::absolute(&common)
129            .with_context(|| format!("could not resolve {}", common.display()))?;
130        Ok(Self::at(common.join("tak").join("baselines")))
131    }
132
133    /// A store rooted at `dir`, which need not exist yet.
134    pub fn at(dir: impl Into<PathBuf>) -> Self {
135        Store { dir: dir.into() }
136    }
137
138    pub fn dir(&self) -> &Path {
139        &self.dir
140    }
141
142    fn path(&self, name: &str) -> PathBuf {
143        self.dir.join(format!("{name}.{EXT}"))
144    }
145
146    /// Names of the saved baselines, sorted.
147    pub fn list(&self) -> Result<Vec<String>> {
148        let entries = match std::fs::read_dir(&self.dir) {
149            Ok(e) => e,
150            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
151            Err(e) => {
152                return Err(e).with_context(|| format!("could not read {}", self.dir.display()));
153            }
154        };
155        let mut names = BTreeSet::new();
156        for entry in entries {
157            let path = entry?.path();
158            if path.extension().is_some_and(|e| e == EXT)
159                && let Some(stem) = path.file_stem().and_then(|s| s.to_str())
160                && validate_name(stem).is_ok()
161            {
162                names.insert(stem.to_string());
163            }
164        }
165        Ok(names.into_iter().collect())
166    }
167
168    /// Load a baseline, failing when it does not exist or holds nothing.
169    ///
170    /// Called before anything is measured: a mistyped name should cost a
171    /// second, not a full run followed by an error.
172    pub fn load(&self, name: &str) -> Result<Baseline> {
173        validate_name(name)?;
174        let path = self.path(name);
175        let body = match std::fs::read_to_string(&path) {
176            Ok(b) => b,
177            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
178                let saved = self.list()?;
179                if saved.is_empty() {
180                    bail!(
181                        "no baseline `{name}`: none saved yet. Save one first with \
182                         `tak run --save-baseline {name}`"
183                    );
184                }
185                bail!("no baseline `{name}` (saved: {})", saved.join(", "));
186            }
187            Err(e) => return Err(e).with_context(|| format!("could not read {}", path.display())),
188        };
189        let records = parse_note(&body);
190        // Empty is an error rather than an empty comparison: the user named
191        // this baseline to compare against, and a report that compared nothing
192        // is easy to misread as one that found nothing.
193        if records.is_empty() {
194            bail!(
195                "baseline `{name}` holds no measurement this version of tak can read ({})",
196                path.display()
197            );
198        }
199        Ok(Baseline {
200            name: name.to_string(),
201            path,
202            records,
203        })
204    }
205
206    /// Fail now if saving under `name` would be refused later, so a run
207    /// that cannot be saved is not measured first.
208    pub fn check_saveable(&self, name: &str) -> Result<()> {
209        validate_name(name)?;
210        let path = self.path(name);
211        match std::fs::read_to_string(&path) {
212            Ok(body) => refuse_newer(name, &path, &body),
213            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
214            Err(e) => Err(e).with_context(|| format!("could not read {}", path.display())),
215        }
216    }
217
218    /// Save `records` under `name`, returning the file written.
219    ///
220    /// Replaces what the baseline held for each series in `records` and keeps
221    /// every other series, so `tak run --bench a --save-baseline x` updates `a`
222    /// without discarding the `b` a full run saved earlier. The same series key
223    /// `compare` uses, runner included: a baseline saved with `--runner` on two
224    /// classes keeps one series for each.
225    ///
226    /// A line that does not parse at all — a hand edit — is kept as it is:
227    /// readers skip it, and dropping it would destroy something someone wrote.
228    /// A record from a newer schema refuses the save instead; see the comment
229    /// where it is found.
230    ///
231    /// Written to a temporary file and renamed into place, so an interrupted
232    /// save leaves the previous baseline whole rather than half of either.
233    ///
234    /// The read-modify-write holds an exclusive lock on a sibling lock file.
235    /// Every worktree of a clone shares this directory, so two runs saving
236    /// different benchmarks to one name at once is ordinary. Without the
237    /// lock both would read the old file, and whichever renamed last would
238    /// silently drop the other's series while both reported success. An OS
239    /// lock rather than an exclusively created marker file, because the OS
240    /// releases it when a process dies; a marker left by a killed run would
241    /// block every save after it until someone deleted it by hand.
242    pub fn save(&self, name: &str, records: &[Record]) -> Result<PathBuf> {
243        validate_name(name)?;
244        std::fs::create_dir_all(&self.dir)
245            .with_context(|| format!("could not create {}", self.dir.display()))?;
246        // Hidden and without the baseline extension, so `list` never shows it.
247        let lock_path = self.dir.join(format!(".{name}.lock"));
248        let lock = std::fs::OpenOptions::new()
249            .create(true)
250            .truncate(false)
251            .write(true)
252            .open(&lock_path)
253            .with_context(|| format!("could not open {}", lock_path.display()))?;
254        lock.lock()
255            .with_context(|| format!("could not lock {}", lock_path.display()))?;
256
257        let path = self.path(name);
258        let existing = match std::fs::read_to_string(&path) {
259            Ok(b) => b,
260            Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
261            Err(e) => return Err(e).with_context(|| format!("could not read {}", path.display())),
262        };
263        let replaced: BTreeSet<Key> = records.iter().map(key).collect();
264        // Sorted and deduplicated, as a note is, so the file's bytes depend
265        // only on what it holds and not on the order runs were saved in.
266        let mut lines = BTreeSet::new();
267        // Checked again under the lock: `check_saveable` ran before measuring,
268        // and a newer tak in another worktree may have saved since.
269        refuse_newer(name, &path, &existing)?;
270        for line in existing.lines().filter(|l| !l.trim().is_empty()) {
271            match Record::from_line(line) {
272                Ok(Some(r)) if replaced.contains(&key(&r)) => {}
273                _ => {
274                    lines.insert(line.to_string());
275                }
276            }
277        }
278        for r in records {
279            lines.insert(r.to_line()?);
280        }
281
282        let mut temp = tempfile::NamedTempFile::new_in(&self.dir).with_context(|| {
283            format!(
284                "could not create a temporary file in {}",
285                self.dir.display()
286            )
287        })?;
288        for line in &lines {
289            writeln!(temp, "{line}")?;
290        }
291        temp.as_file().sync_all()?;
292        temp.persist(&path)
293            .map_err(|e| e.error)
294            .with_context(|| format!("could not write {}", path.display()))?;
295        // Only now: the next writer must read the file this one renamed in.
296        drop(lock);
297        Ok(path)
298    }
299}
300
301/// Why a series this run measured cannot be gated against the baseline.
302#[derive(Debug, Clone, PartialEq)]
303pub enum Gap {
304    /// This run asked for a count, valgrind was present, and counting
305    /// failed. Whatever the baseline holds, nothing here can be compared.
306    CountFailed,
307    /// The baseline counted it on this runner class and this run did not:
308    /// valgrind missing, counting failed, or counters turned off.
309    NotCountedHere,
310    /// This run counted it and the baseline holds it on this runner class
311    /// without a count.
312    SavedWithoutCount,
313    /// This run counted it and the baseline holds it only on these other
314    /// runner classes, which are never compared with this one.
315    OnlyOnOtherRunners(Vec<String>),
316    /// This run counted it and the baseline has never seen it: new since the
317    /// baseline was saved.
318    NotInBaseline,
319    /// This run did not count it, and the baseline counted it only on these
320    /// other runner classes.
321    UncountedAndOnlyOnOtherRunners(Vec<String>),
322}
323
324fn classes(runners: &[String]) -> String {
325    runners
326        .iter()
327        .map(|r| format!("`{r}`"))
328        .collect::<Vec<_>>()
329        .join(", ")
330}
331
332impl std::fmt::Display for Gap {
333    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
334        match self {
335            Gap::CountFailed => write!(f, "instruction counting failed in this run"),
336            Gap::NotCountedHere => write!(f, "not counted in this run"),
337            Gap::SavedWithoutCount => write!(f, "saved without an instruction count"),
338            Gap::OnlyOnOtherRunners(runners) => {
339                write!(f, "saved only on runner class {}", classes(runners))
340            }
341            Gap::NotInBaseline => write!(f, "not in the baseline"),
342            Gap::UncountedAndOnlyOnOtherRunners(runners) => write!(
343                f,
344                "not counted in this run, and counted in the baseline only on runner class {}",
345                classes(runners)
346            ),
347        }
348    }
349}
350
351/// The series this run measured that `--gate` cannot check, and why.
352///
353/// A benchmark whose count this run failed to take, one added since the
354/// baseline was saved, or one the baseline holds only for another runner
355/// class would otherwise pass a gate that checked only its neighbours.
356///
357/// Judged per series of *this run*, so on this run's runner class only. A
358/// baseline saved on two classes holds a series for each, and the one for the
359/// other class is not missing from this run — it was never going to be
360/// compared with it. Counting it as a gap failed every gate on both classes.
361///
362/// A series with no count on either side is left out: a subject with
363/// `counters = false` is wall-clock only by design and never gates. That rule
364/// cannot tell design from accident by the records alone, which look the same
365/// either way, so `count_failed` names the series whose count this run asked
366/// for, with valgrind present, and did not get. Those are always a gap: a new
367/// benchmark whose count failed has nothing in the baseline either, and was
368/// otherwise skipped while `--gate` passed on its neighbours.
369pub fn gaps(
370    baseline: &[Record],
371    current: &[Record],
372    count_failed: &BTreeSet<Key>,
373) -> Vec<(Key, Gap)> {
374    let counted = |r: &Record| r.metrics.contains_key(crate::compare::GATED_METRIC);
375    let mut out = Vec::new();
376    let keys: BTreeSet<Key> = current.iter().map(key).collect();
377    for k in keys {
378        let here = current.iter().filter(|r| key(r) == k).any(counted);
379        if !here && count_failed.contains(&k) {
380            out.push((k, Gap::CountFailed));
381            continue;
382        }
383        let same: Vec<&Record> = baseline.iter().filter(|r| key(r) == k).collect();
384        let saved = same.iter().any(|r| counted(r));
385        let gap = match (here, saved) {
386            (true, true) => continue,
387            // Uncounted on both sides of this class: wall-clock only by
388            // design, unless this class is absent and another class counted
389            // it. Then the benchmark is one the project gates, and this run
390            // neither counted it nor has anything to hold it to. Skipping it
391            // let `--gate` pass on the strength of the other benchmarks.
392            (false, false) => {
393                if !same.is_empty() {
394                    continue;
395                }
396                let elsewhere = counted_runners(baseline, &k);
397                if elsewhere.is_empty() {
398                    continue;
399                }
400                Gap::UncountedAndOnlyOnOtherRunners(elsewhere)
401            }
402            (false, true) => Gap::NotCountedHere,
403            (true, false) if !same.is_empty() => Gap::SavedWithoutCount,
404            (true, false) => {
405                let elsewhere = other_runners(baseline, &k);
406                if elsewhere.is_empty() {
407                    Gap::NotInBaseline
408                } else {
409                    Gap::OnlyOnOtherRunners(elsewhere)
410                }
411            }
412        };
413        out.push((k, gap));
414    }
415    out
416}
417
418/// Runner classes other than `k`'s that the baseline holds `k`'s benchmark
419/// and tool on, sorted.
420pub fn other_runners(baseline: &[Record], k: &Key) -> Vec<String> {
421    let runners: BTreeSet<&str> = baseline
422        .iter()
423        .filter(|r| r.bench == k.0 && r.tool == k.1 && r.runner != k.2)
424        .map(|r| r.runner.as_str())
425        .collect();
426    runners.into_iter().map(str::to_string).collect()
427}
428
429/// Like [`other_runners`], but only the classes that saved an instruction
430/// count for it.
431fn counted_runners(baseline: &[Record], k: &Key) -> Vec<String> {
432    let runners: BTreeSet<&str> = baseline
433        .iter()
434        .filter(|r| r.bench == k.0 && r.tool == k.1 && r.runner != k.2)
435        .filter(|r| r.metrics.contains_key(crate::compare::GATED_METRIC))
436        .map(|r| r.runner.as_str())
437        .collect();
438    runners.into_iter().map(str::to_string).collect()
439}
440
441/// The part of a baseline this run is compared against: the series this run
442/// measured, on this run's runner class.
443///
444/// A baseline outlives the run that saved it, so `tak run --bench a` against
445/// one saved by a full run would otherwise list every other benchmark as
446/// "measured on the base but not here". That warning exists for a CI job that
447/// silently stopped running something; here it would only be noise. The same
448/// goes for the series a baseline holds for other runner classes: they are
449/// not comparable, and not missing either. When one of them is all the
450/// baseline has for a benchmark, [`other_runners`] names it in a warning and
451/// [`gaps`] keeps `--gate` from passing over it.
452pub fn relevant(baseline: &[Record], current: &[Record]) -> Vec<Record> {
453    let measured: BTreeSet<Key> = current.iter().map(key).collect();
454    baseline
455        .iter()
456        .filter(|r| measured.contains(&key(r)))
457        .cloned()
458        .collect()
459}
460
461#[cfg(test)]
462mod tests {
463    use super::*;
464    use crate::record::SCHEMA_VERSION;
465    use std::collections::BTreeMap;
466
467    fn rec(bench: &str, runner: &str, ins: f64) -> Record {
468        Record {
469            v: SCHEMA_VERSION,
470            bench: bench.into(),
471            tool: "self".into(),
472            version: None,
473            runner: runner.into(),
474            ts: "2026-09-29T00:00:00Z".into(),
475            metrics: BTreeMap::from([("instructions".to_string(), ins)]),
476        }
477    }
478
479    fn store() -> (tempfile::TempDir, Store) {
480        let dir = tempfile::tempdir().unwrap();
481        let store = Store::at(dir.path().join("baselines"));
482        (dir, store)
483    }
484
485    fn values(b: &Baseline) -> Vec<(String, String, f64)> {
486        b.records
487            .iter()
488            .map(|r| (r.bench.clone(), r.runner.clone(), r.metrics["instructions"]))
489            .collect()
490    }
491
492    #[test]
493    fn names_that_are_not_plain_file_names_are_rejected() {
494        for bad in ["", ".hidden", "../up", "a/b", "a\\b", "with space", "é"] {
495            assert!(validate_name(bad).is_err(), "{bad:?} was accepted");
496        }
497        for good in ["before", "main-2026.09.29", "v1.2_rc"] {
498            validate_name(good).unwrap();
499        }
500    }
501
502    #[test]
503    fn a_saved_baseline_loads_back() {
504        let (_tmp, s) = store();
505        s.save("before", &[rec("a", "r", 10.0)]).unwrap();
506        let b = s.load("before").unwrap();
507        assert_eq!(values(&b), vec![("a".into(), "r".into(), 10.0)]);
508        assert_eq!(s.list().unwrap(), vec!["before".to_string()]);
509    }
510
511    /// Heap-allocation metrics survive a save and load, and a `--baseline`
512    /// report renders them through the same allocation table as `tak
513    /// compare`, still without gating on them.
514    #[test]
515    fn allocation_metrics_reach_a_baseline_report() {
516        let with_allocs = |blocks: f64| {
517            let mut r = rec("a", "r", 10.0);
518            r.metrics.insert("alloc_blocks".into(), blocks);
519            r.metrics.insert("alloc_bytes".into(), blocks * 8.0);
520            r.metrics.insert("alloc_peak_bytes".into(), blocks * 4.0);
521            r
522        };
523        let (_tmp, s) = store();
524        s.save("before", &[with_allocs(10.0)]).unwrap();
525        let b = s.load("before").unwrap();
526        let current = [with_allocs(20.0)];
527        let c = crate::compare::compare(&relevant(&b.records, &current), &current);
528        let gates = crate::compare::Gates::uniform(crate::compare::Gate::new(1.0, 0).unwrap());
529        let md = crate::compare::markdown(&c, &crate::compare::Trend::new(), &gates, false);
530        assert!(md.contains("Heap allocations"), "{md}");
531        assert!(md.contains("| a | 10 → 20 | +100.00% |"), "{md}");
532        assert!(c.regressions(&gates).is_empty());
533    }
534
535    /// Saving a subset updates that subset and keeps the rest, the way a
536    /// criterion baseline does per benchmark.
537    #[test]
538    fn saving_replaces_only_the_series_it_measured() {
539        let (_tmp, s) = store();
540        s.save("x", &[rec("a", "r", 10.0), rec("b", "r", 20.0)])
541            .unwrap();
542        s.save("x", &[rec("a", "r", 11.0)]).unwrap();
543        let b = s.load("x").unwrap();
544        assert_eq!(
545            values(&b),
546            vec![
547                ("a".into(), "r".into(), 11.0),
548                ("b".into(), "r".into(), 20.0)
549            ]
550        );
551    }
552
553    /// Runner is part of the series, so saving on one class leaves the
554    /// other's numbers alone.
555    #[test]
556    fn a_save_on_another_runner_keeps_both() {
557        let (_tmp, s) = store();
558        s.save("x", &[rec("a", "r1", 10.0)]).unwrap();
559        s.save("x", &[rec("a", "r2", 99.0)]).unwrap();
560        assert_eq!(s.load("x").unwrap().records.len(), 2);
561    }
562
563    /// A line that is not a record at all — a hand edit — survives a save.
564    #[test]
565    fn a_malformed_line_survives_a_save() {
566        let (_tmp, s) = store();
567        std::fs::create_dir_all(s.dir()).unwrap();
568        std::fs::write(s.path("x"), "not json\n").unwrap();
569        s.save("x", &[rec("a", "r", 2.0)]).unwrap();
570        let body = std::fs::read_to_string(s.path("x")).unwrap();
571        assert!(body.contains("not json"), "{body}");
572        assert_eq!(s.load("x").unwrap().records.len(), 1);
573    }
574
575    /// An older tak neither deletes a newer one's record nor writes beside
576    /// it: kept next to this run's line for the same series, the stale newer
577    /// value would win the minimum once tak is upgraded again. So the save is
578    /// refused, and the file is left exactly as it was.
579    #[test]
580    fn a_newer_schema_record_refuses_the_save() {
581        let (_tmp, s) = store();
582        std::fs::create_dir_all(s.dir()).unwrap();
583        let mut future = rec("a", "r", 1.0);
584        future.v = SCHEMA_VERSION + 1;
585        let body = format!("{}\n", future.to_line().unwrap());
586        std::fs::write(s.path("x"), &body).unwrap();
587        let e = s.save("x", &[rec("a", "r", 2.0)]).unwrap_err().to_string();
588        assert!(e.contains("holds records from a newer tak"), "{e}");
589        assert!(e.contains("Save under another name"), "{e}");
590        assert_eq!(std::fs::read_to_string(s.path("x")).unwrap(), body);
591        // Another name is unaffected.
592        s.save("y", &[rec("a", "r", 2.0)]).unwrap();
593    }
594
595    #[test]
596    fn a_missing_baseline_names_the_saved_ones() {
597        let (_tmp, s) = store();
598        let e = s.load("before").unwrap_err().to_string();
599        assert!(e.contains("none saved yet"), "{e}");
600        s.save("main", &[rec("a", "r", 1.0)]).unwrap();
601        s.save("wip", &[rec("a", "r", 1.0)]).unwrap();
602        let e = s.load("before").unwrap_err().to_string();
603        assert!(e.contains("saved: main, wip"), "{e}");
604    }
605
606    #[test]
607    fn a_baseline_with_nothing_readable_is_an_error() {
608        let (_tmp, s) = store();
609        std::fs::create_dir_all(s.dir()).unwrap();
610        std::fs::write(s.path("x"), "not json\n").unwrap();
611        assert!(s.load("x").is_err());
612    }
613
614    /// Two saves of the same records in a different order write the same
615    /// bytes, so the file never changes for a reason that is not the data.
616    #[test]
617    fn the_file_does_not_depend_on_save_order() {
618        let (_tmp, s1) = store();
619        let (_tmp2, s2) = store();
620        s1.save("x", &[rec("a", "r", 1.0), rec("b", "r", 2.0)])
621            .unwrap();
622        s2.save("x", &[rec("b", "r", 2.0), rec("a", "r", 1.0)])
623            .unwrap();
624        assert_eq!(
625            std::fs::read(s1.path("x")).unwrap(),
626            std::fs::read(s2.path("x")).unwrap()
627        );
628    }
629
630    /// Concurrent saves of different benchmarks to one name, as two
631    /// worktrees would do, must all survive. Threads rather than processes:
632    /// the lock is on an open file description, so two opens in one process
633    /// contend exactly as two processes would.
634    #[test]
635    fn concurrent_saves_keep_every_series() {
636        let (_tmp, s) = store();
637        let threads: Vec<_> = (0..16)
638            .map(|i| {
639                let s = s.clone();
640                std::thread::spawn(move || {
641                    s.save("x", &[rec(&format!("b{i}"), "r", i as f64)])
642                        .unwrap();
643                })
644            })
645            .collect();
646        for t in threads {
647            t.join().unwrap();
648        }
649        assert_eq!(s.load("x").unwrap().records.len(), 16);
650        assert_eq!(
651            s.list().unwrap(),
652            vec!["x".to_string()],
653            "the lock file is listed"
654        );
655    }
656
657    /// The gaps of a run in which no count failed.
658    fn gaps(base: &[Record], head: &[Record]) -> Vec<(Key, Gap)> {
659        super::gaps(base, head, &BTreeSet::new())
660    }
661
662    /// A count that was asked for, with valgrind present, and failed is a
663    /// gap whatever the baseline holds — including nothing at all, for a
664    /// benchmark added since it was saved. Counters off by design is not.
665    #[test]
666    fn a_failed_count_is_a_gap_and_counters_off_is_not() {
667        let k: Key = ("new".into(), "self".into(), "r".into());
668        let head = [wall_only("new", "r")];
669        assert_eq!(
670            super::gaps(&[], &head, &BTreeSet::from([k.clone()])),
671            vec![(k.clone(), Gap::CountFailed)]
672        );
673        assert_eq!(
674            super::gaps(
675                &[wall_only("new", "r")],
676                &head,
677                &BTreeSet::from([k.clone()])
678            ),
679            vec![(k, Gap::CountFailed)]
680        );
681        assert_eq!(gaps(&[], &head), vec![]);
682    }
683
684    fn wall_only(bench: &str, runner: &str) -> Record {
685        let mut r = rec(bench, runner, 0.0);
686        r.metrics = BTreeMap::from([("wall_min_ms".to_string(), 1.0)]);
687        r
688    }
689
690    #[test]
691    fn a_series_this_run_cannot_gate_is_a_gap() {
692        let base = [
693            rec("a", "r", 1.0),
694            rec("b", "r", 1.0),
695            wall_only("s", "r"),
696            wall_only("w", "r"),
697        ];
698        // `b` lost its count this run; `c` is new; `s` was saved uncounted;
699        // `w` never had a count on either side and is wall-clock only.
700        let head = [
701            rec("a", "r", 1.0),
702            wall_only("b", "r"),
703            rec("c", "r", 1.0),
704            rec("s", "r", 1.0),
705            wall_only("w", "r"),
706        ];
707        let got: Vec<(String, Gap)> = gaps(&base, &head)
708            .into_iter()
709            .map(|(k, g)| (k.0, g))
710            .collect();
711        assert_eq!(
712            got,
713            vec![
714                ("b".into(), Gap::NotCountedHere),
715                ("c".into(), Gap::NotInBaseline),
716                ("s".into(), Gap::SavedWithoutCount),
717            ]
718        );
719    }
720
721    /// A baseline saved on two runner classes holds a series for each. The
722    /// other class's is not this run's, so it is not a gap: counting it as
723    /// one failed every gate on both classes.
724    #[test]
725    fn another_runner_is_ignored_when_this_runner_is_saved() {
726        let base = [rec("a", "r1", 1.0), rec("a", "r2", 1.0)];
727        assert_eq!(gaps(&base, &[rec("a", "r1", 1.0)]), vec![]);
728        assert_eq!(gaps(&base, &[rec("a", "r2", 1.0)]), vec![]);
729    }
730
731    /// When no saved class matches, the gap names the classes there are, so
732    /// the message cannot suggest saving on one that is already present.
733    #[test]
734    fn no_matching_runner_is_a_gap_naming_the_saved_ones() {
735        let base = [rec("a", "r1", 1.0), rec("a", "r2", 1.0)];
736        let got = gaps(&base, &[rec("a", "r3", 1.0)]);
737        assert_eq!(
738            got[0].1,
739            Gap::OnlyOnOtherRunners(vec!["r1".into(), "r2".into()])
740        );
741        assert_eq!(
742            got[0].1.to_string(),
743            "saved only on runner class `r1`, `r2`"
744        );
745    }
746
747    /// Uncounted here and counted only on another class: a gated benchmark
748    /// this run neither counted nor can compare, which a gate must not skip.
749    /// Uncounted on this class on both sides stays wall-clock only.
750    #[test]
751    fn uncounted_here_and_counted_only_elsewhere_is_a_gap() {
752        let base = [rec("a", "r1", 1.0)];
753        let got = gaps(&base, &[wall_only("a", "r2")]);
754        assert_eq!(
755            got[0].1,
756            Gap::UncountedAndOnlyOnOtherRunners(vec!["r1".into()])
757        );
758        assert_eq!(
759            gaps(&[wall_only("a", "r1")], &[wall_only("a", "r2")]),
760            vec![]
761        );
762        assert_eq!(
763            gaps(
764                &[rec("a", "r1", 1.0), wall_only("a", "r2")],
765                &[wall_only("a", "r2")]
766            ),
767            vec![]
768        );
769    }
770
771    #[test]
772    fn only_this_runs_series_are_compared() {
773        let baseline = [
774            rec("a", "r1", 1.0),
775            rec("a", "r2", 1.0),
776            rec("b", "r1", 1.0),
777        ];
778        let kept = relevant(&baseline, &[rec("a", "r1", 2.0)]);
779        // `b` was not run, and `a` on `r2` is another class's series.
780        let runners: Vec<_> = kept
781            .iter()
782            .map(|r| (r.bench.as_str(), r.runner.as_str()))
783            .collect();
784        assert_eq!(runners, vec![("a", "r1")]);
785    }
786}