1use 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
30fn 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
42fn 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
62const EXT: &str = "jsonl";
65
66#[derive(Debug)]
68pub struct Baseline {
69 pub name: String,
70 pub path: PathBuf,
71 pub records: Vec<Record>,
72}
73
74#[derive(Debug, Clone)]
76pub struct Store {
77 dir: PathBuf,
78}
79
80pub 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 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 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 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 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 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 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 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 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 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 let mut lines = BTreeSet::new();
267 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 drop(lock);
297 Ok(path)
298 }
299}
300
301#[derive(Debug, Clone, PartialEq)]
303pub enum Gap {
304 CountFailed,
307 NotCountedHere,
310 SavedWithoutCount,
313 OnlyOnOtherRunners(Vec<String>),
316 NotInBaseline,
319 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
351pub 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 (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
418pub 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
429fn 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
441pub 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 #[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, ¤t), ¤t);
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 #[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 #[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 #[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 #[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 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 #[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 #[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 fn gaps(base: &[Record], head: &[Record]) -> Vec<(Key, Gap)> {
659 super::gaps(base, head, &BTreeSet::new())
660 }
661
662 #[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 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 #[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 #[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 #[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 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}