use anyhow::{Context, Result, bail};
use std::collections::BTreeSet;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;
use crate::compare::Key;
use crate::record::{Record, SCHEMA_VERSION, parse_note};
fn newer_schema(line: &str) -> Option<u64> {
let v = serde_json::from_str::<serde_json::Value>(line)
.ok()?
.get("v")?
.as_u64()?;
(v > u64::from(SCHEMA_VERSION)).then_some(v)
}
fn refuse_newer(name: &str, path: &Path, body: &str) -> Result<()> {
if let Some(v) = body.lines().find_map(newer_schema) {
bail!(
"baseline `{name}` holds records from a newer tak (schema {v}; this tak writes \
{SCHEMA_VERSION}), and saving over it could leave a stale value beside this \
run's. Save under another name, or upgrade tak ({})",
path.display()
);
}
Ok(())
}
const EXT: &str = "jsonl";
#[derive(Debug)]
pub struct Baseline {
pub name: String,
pub path: PathBuf,
pub records: Vec<Record>,
}
#[derive(Debug, Clone)]
pub struct Store {
dir: PathBuf,
}
pub fn validate_name(name: &str) -> Result<()> {
let ok = !name.is_empty()
&& !name.starts_with('.')
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));
if !ok {
bail!(
"invalid baseline name `{name}`: use letters, digits, `-`, `_` and `.`, \
not starting with `.`"
);
}
Ok(())
}
fn key(r: &Record) -> Key {
(r.bench.clone(), r.tool.clone(), r.runner.clone())
}
impl Store {
pub fn locate() -> Result<Self> {
let out = Command::new("git")
.args(["rev-parse", "--git-common-dir"])
.output()
.context("failed to run `git rev-parse --git-common-dir`")?;
if !out.status.success() {
bail!(
"baselines are kept in the repository's git directory, so they need a git \
repository: {}",
String::from_utf8_lossy(&out.stderr).trim()
);
}
let common = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim_end());
let common = std::path::absolute(&common)
.with_context(|| format!("could not resolve {}", common.display()))?;
Ok(Self::at(common.join("tak").join("baselines")))
}
pub fn at(dir: impl Into<PathBuf>) -> Self {
Store { dir: dir.into() }
}
pub fn dir(&self) -> &Path {
&self.dir
}
fn path(&self, name: &str) -> PathBuf {
self.dir.join(format!("{name}.{EXT}"))
}
pub fn list(&self) -> Result<Vec<String>> {
let entries = match std::fs::read_dir(&self.dir) {
Ok(e) => e,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => {
return Err(e).with_context(|| format!("could not read {}", self.dir.display()));
}
};
let mut names = BTreeSet::new();
for entry in entries {
let path = entry?.path();
if path.extension().is_some_and(|e| e == EXT)
&& let Some(stem) = path.file_stem().and_then(|s| s.to_str())
&& validate_name(stem).is_ok()
{
names.insert(stem.to_string());
}
}
Ok(names.into_iter().collect())
}
pub fn load(&self, name: &str) -> Result<Baseline> {
validate_name(name)?;
let path = self.path(name);
let body = match std::fs::read_to_string(&path) {
Ok(b) => b,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
let saved = self.list()?;
if saved.is_empty() {
bail!(
"no baseline `{name}`: none saved yet. Save one first with \
`tak run --save-baseline {name}`"
);
}
bail!("no baseline `{name}` (saved: {})", saved.join(", "));
}
Err(e) => return Err(e).with_context(|| format!("could not read {}", path.display())),
};
let records = parse_note(&body);
if records.is_empty() {
bail!(
"baseline `{name}` holds no measurement this version of tak can read ({})",
path.display()
);
}
Ok(Baseline {
name: name.to_string(),
path,
records,
})
}
pub fn check_saveable(&self, name: &str) -> Result<()> {
validate_name(name)?;
let path = self.path(name);
match std::fs::read_to_string(&path) {
Ok(body) => refuse_newer(name, &path, &body),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e).with_context(|| format!("could not read {}", path.display())),
}
}
pub fn save(&self, name: &str, records: &[Record]) -> Result<PathBuf> {
validate_name(name)?;
std::fs::create_dir_all(&self.dir)
.with_context(|| format!("could not create {}", self.dir.display()))?;
let lock_path = self.dir.join(format!(".{name}.lock"));
let lock = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(&lock_path)
.with_context(|| format!("could not open {}", lock_path.display()))?;
lock.lock()
.with_context(|| format!("could not lock {}", lock_path.display()))?;
let path = self.path(name);
let existing = match std::fs::read_to_string(&path) {
Ok(b) => b,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(e) => return Err(e).with_context(|| format!("could not read {}", path.display())),
};
let replaced: BTreeSet<Key> = records.iter().map(key).collect();
let mut lines = BTreeSet::new();
refuse_newer(name, &path, &existing)?;
for line in existing.lines().filter(|l| !l.trim().is_empty()) {
match Record::from_line(line) {
Ok(Some(r)) if replaced.contains(&key(&r)) => {}
_ => {
lines.insert(line.to_string());
}
}
}
for r in records {
lines.insert(r.to_line()?);
}
let mut temp = tempfile::NamedTempFile::new_in(&self.dir).with_context(|| {
format!(
"could not create a temporary file in {}",
self.dir.display()
)
})?;
for line in &lines {
writeln!(temp, "{line}")?;
}
temp.as_file().sync_all()?;
temp.persist(&path)
.map_err(|e| e.error)
.with_context(|| format!("could not write {}", path.display()))?;
drop(lock);
Ok(path)
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Gap {
CountFailed,
NotCountedHere,
SavedWithoutCount,
OnlyOnOtherRunners(Vec<String>),
NotInBaseline,
UncountedAndOnlyOnOtherRunners(Vec<String>),
}
fn classes(runners: &[String]) -> String {
runners
.iter()
.map(|r| format!("`{r}`"))
.collect::<Vec<_>>()
.join(", ")
}
impl std::fmt::Display for Gap {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Gap::CountFailed => write!(f, "instruction counting failed in this run"),
Gap::NotCountedHere => write!(f, "not counted in this run"),
Gap::SavedWithoutCount => write!(f, "saved without an instruction count"),
Gap::OnlyOnOtherRunners(runners) => {
write!(f, "saved only on runner class {}", classes(runners))
}
Gap::NotInBaseline => write!(f, "not in the baseline"),
Gap::UncountedAndOnlyOnOtherRunners(runners) => write!(
f,
"not counted in this run, and counted in the baseline only on runner class {}",
classes(runners)
),
}
}
}
pub fn gaps(
baseline: &[Record],
current: &[Record],
count_failed: &BTreeSet<Key>,
) -> Vec<(Key, Gap)> {
let counted = |r: &Record| r.metrics.contains_key(crate::compare::GATED_METRIC);
let mut out = Vec::new();
let keys: BTreeSet<Key> = current.iter().map(key).collect();
for k in keys {
let here = current.iter().filter(|r| key(r) == k).any(counted);
if !here && count_failed.contains(&k) {
out.push((k, Gap::CountFailed));
continue;
}
let same: Vec<&Record> = baseline.iter().filter(|r| key(r) == k).collect();
let saved = same.iter().any(|r| counted(r));
let gap = match (here, saved) {
(true, true) => continue,
(false, false) => {
if !same.is_empty() {
continue;
}
let elsewhere = counted_runners(baseline, &k);
if elsewhere.is_empty() {
continue;
}
Gap::UncountedAndOnlyOnOtherRunners(elsewhere)
}
(false, true) => Gap::NotCountedHere,
(true, false) if !same.is_empty() => Gap::SavedWithoutCount,
(true, false) => {
let elsewhere = other_runners(baseline, &k);
if elsewhere.is_empty() {
Gap::NotInBaseline
} else {
Gap::OnlyOnOtherRunners(elsewhere)
}
}
};
out.push((k, gap));
}
out
}
pub fn other_runners(baseline: &[Record], k: &Key) -> Vec<String> {
let runners: BTreeSet<&str> = baseline
.iter()
.filter(|r| r.bench == k.0 && r.tool == k.1 && r.runner != k.2)
.map(|r| r.runner.as_str())
.collect();
runners.into_iter().map(str::to_string).collect()
}
fn counted_runners(baseline: &[Record], k: &Key) -> Vec<String> {
let runners: BTreeSet<&str> = baseline
.iter()
.filter(|r| r.bench == k.0 && r.tool == k.1 && r.runner != k.2)
.filter(|r| r.metrics.contains_key(crate::compare::GATED_METRIC))
.map(|r| r.runner.as_str())
.collect();
runners.into_iter().map(str::to_string).collect()
}
pub fn relevant(baseline: &[Record], current: &[Record]) -> Vec<Record> {
let measured: BTreeSet<Key> = current.iter().map(key).collect();
baseline
.iter()
.filter(|r| measured.contains(&key(r)))
.cloned()
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::record::SCHEMA_VERSION;
use std::collections::BTreeMap;
fn rec(bench: &str, runner: &str, ins: f64) -> Record {
Record {
v: SCHEMA_VERSION,
bench: bench.into(),
tool: "self".into(),
version: None,
runner: runner.into(),
ts: "2026-09-29T00:00:00Z".into(),
metrics: BTreeMap::from([("instructions".to_string(), ins)]),
}
}
fn store() -> (tempfile::TempDir, Store) {
let dir = tempfile::tempdir().unwrap();
let store = Store::at(dir.path().join("baselines"));
(dir, store)
}
fn values(b: &Baseline) -> Vec<(String, String, f64)> {
b.records
.iter()
.map(|r| (r.bench.clone(), r.runner.clone(), r.metrics["instructions"]))
.collect()
}
#[test]
fn names_that_are_not_plain_file_names_are_rejected() {
for bad in ["", ".hidden", "../up", "a/b", "a\\b", "with space", "é"] {
assert!(validate_name(bad).is_err(), "{bad:?} was accepted");
}
for good in ["before", "main-2026.09.29", "v1.2_rc"] {
validate_name(good).unwrap();
}
}
#[test]
fn a_saved_baseline_loads_back() {
let (_tmp, s) = store();
s.save("before", &[rec("a", "r", 10.0)]).unwrap();
let b = s.load("before").unwrap();
assert_eq!(values(&b), vec![("a".into(), "r".into(), 10.0)]);
assert_eq!(s.list().unwrap(), vec!["before".to_string()]);
}
#[test]
fn allocation_metrics_reach_a_baseline_report() {
let with_allocs = |blocks: f64| {
let mut r = rec("a", "r", 10.0);
r.metrics.insert("alloc_blocks".into(), blocks);
r.metrics.insert("alloc_bytes".into(), blocks * 8.0);
r.metrics.insert("alloc_peak_bytes".into(), blocks * 4.0);
r
};
let (_tmp, s) = store();
s.save("before", &[with_allocs(10.0)]).unwrap();
let b = s.load("before").unwrap();
let current = [with_allocs(20.0)];
let c = crate::compare::compare(&relevant(&b.records, ¤t), ¤t);
let gates = crate::compare::Gates::uniform(crate::compare::Gate::new(1.0, 0).unwrap());
let md = crate::compare::markdown(&c, &crate::compare::Trend::new(), &gates, false);
assert!(md.contains("Heap allocations"), "{md}");
assert!(md.contains("| a | 10 → 20 | +100.00% |"), "{md}");
assert!(c.regressions(&gates).is_empty());
}
#[test]
fn saving_replaces_only_the_series_it_measured() {
let (_tmp, s) = store();
s.save("x", &[rec("a", "r", 10.0), rec("b", "r", 20.0)])
.unwrap();
s.save("x", &[rec("a", "r", 11.0)]).unwrap();
let b = s.load("x").unwrap();
assert_eq!(
values(&b),
vec![
("a".into(), "r".into(), 11.0),
("b".into(), "r".into(), 20.0)
]
);
}
#[test]
fn a_save_on_another_runner_keeps_both() {
let (_tmp, s) = store();
s.save("x", &[rec("a", "r1", 10.0)]).unwrap();
s.save("x", &[rec("a", "r2", 99.0)]).unwrap();
assert_eq!(s.load("x").unwrap().records.len(), 2);
}
#[test]
fn a_malformed_line_survives_a_save() {
let (_tmp, s) = store();
std::fs::create_dir_all(s.dir()).unwrap();
std::fs::write(s.path("x"), "not json\n").unwrap();
s.save("x", &[rec("a", "r", 2.0)]).unwrap();
let body = std::fs::read_to_string(s.path("x")).unwrap();
assert!(body.contains("not json"), "{body}");
assert_eq!(s.load("x").unwrap().records.len(), 1);
}
#[test]
fn a_newer_schema_record_refuses_the_save() {
let (_tmp, s) = store();
std::fs::create_dir_all(s.dir()).unwrap();
let mut future = rec("a", "r", 1.0);
future.v = SCHEMA_VERSION + 1;
let body = format!("{}\n", future.to_line().unwrap());
std::fs::write(s.path("x"), &body).unwrap();
let e = s.save("x", &[rec("a", "r", 2.0)]).unwrap_err().to_string();
assert!(e.contains("holds records from a newer tak"), "{e}");
assert!(e.contains("Save under another name"), "{e}");
assert_eq!(std::fs::read_to_string(s.path("x")).unwrap(), body);
s.save("y", &[rec("a", "r", 2.0)]).unwrap();
}
#[test]
fn a_missing_baseline_names_the_saved_ones() {
let (_tmp, s) = store();
let e = s.load("before").unwrap_err().to_string();
assert!(e.contains("none saved yet"), "{e}");
s.save("main", &[rec("a", "r", 1.0)]).unwrap();
s.save("wip", &[rec("a", "r", 1.0)]).unwrap();
let e = s.load("before").unwrap_err().to_string();
assert!(e.contains("saved: main, wip"), "{e}");
}
#[test]
fn a_baseline_with_nothing_readable_is_an_error() {
let (_tmp, s) = store();
std::fs::create_dir_all(s.dir()).unwrap();
std::fs::write(s.path("x"), "not json\n").unwrap();
assert!(s.load("x").is_err());
}
#[test]
fn the_file_does_not_depend_on_save_order() {
let (_tmp, s1) = store();
let (_tmp2, s2) = store();
s1.save("x", &[rec("a", "r", 1.0), rec("b", "r", 2.0)])
.unwrap();
s2.save("x", &[rec("b", "r", 2.0), rec("a", "r", 1.0)])
.unwrap();
assert_eq!(
std::fs::read(s1.path("x")).unwrap(),
std::fs::read(s2.path("x")).unwrap()
);
}
#[test]
fn concurrent_saves_keep_every_series() {
let (_tmp, s) = store();
let threads: Vec<_> = (0..16)
.map(|i| {
let s = s.clone();
std::thread::spawn(move || {
s.save("x", &[rec(&format!("b{i}"), "r", i as f64)])
.unwrap();
})
})
.collect();
for t in threads {
t.join().unwrap();
}
assert_eq!(s.load("x").unwrap().records.len(), 16);
assert_eq!(
s.list().unwrap(),
vec!["x".to_string()],
"the lock file is listed"
);
}
fn gaps(base: &[Record], head: &[Record]) -> Vec<(Key, Gap)> {
super::gaps(base, head, &BTreeSet::new())
}
#[test]
fn a_failed_count_is_a_gap_and_counters_off_is_not() {
let k: Key = ("new".into(), "self".into(), "r".into());
let head = [wall_only("new", "r")];
assert_eq!(
super::gaps(&[], &head, &BTreeSet::from([k.clone()])),
vec![(k.clone(), Gap::CountFailed)]
);
assert_eq!(
super::gaps(
&[wall_only("new", "r")],
&head,
&BTreeSet::from([k.clone()])
),
vec![(k, Gap::CountFailed)]
);
assert_eq!(gaps(&[], &head), vec![]);
}
fn wall_only(bench: &str, runner: &str) -> Record {
let mut r = rec(bench, runner, 0.0);
r.metrics = BTreeMap::from([("wall_min_ms".to_string(), 1.0)]);
r
}
#[test]
fn a_series_this_run_cannot_gate_is_a_gap() {
let base = [
rec("a", "r", 1.0),
rec("b", "r", 1.0),
wall_only("s", "r"),
wall_only("w", "r"),
];
let head = [
rec("a", "r", 1.0),
wall_only("b", "r"),
rec("c", "r", 1.0),
rec("s", "r", 1.0),
wall_only("w", "r"),
];
let got: Vec<(String, Gap)> = gaps(&base, &head)
.into_iter()
.map(|(k, g)| (k.0, g))
.collect();
assert_eq!(
got,
vec![
("b".into(), Gap::NotCountedHere),
("c".into(), Gap::NotInBaseline),
("s".into(), Gap::SavedWithoutCount),
]
);
}
#[test]
fn another_runner_is_ignored_when_this_runner_is_saved() {
let base = [rec("a", "r1", 1.0), rec("a", "r2", 1.0)];
assert_eq!(gaps(&base, &[rec("a", "r1", 1.0)]), vec![]);
assert_eq!(gaps(&base, &[rec("a", "r2", 1.0)]), vec![]);
}
#[test]
fn no_matching_runner_is_a_gap_naming_the_saved_ones() {
let base = [rec("a", "r1", 1.0), rec("a", "r2", 1.0)];
let got = gaps(&base, &[rec("a", "r3", 1.0)]);
assert_eq!(
got[0].1,
Gap::OnlyOnOtherRunners(vec!["r1".into(), "r2".into()])
);
assert_eq!(
got[0].1.to_string(),
"saved only on runner class `r1`, `r2`"
);
}
#[test]
fn uncounted_here_and_counted_only_elsewhere_is_a_gap() {
let base = [rec("a", "r1", 1.0)];
let got = gaps(&base, &[wall_only("a", "r2")]);
assert_eq!(
got[0].1,
Gap::UncountedAndOnlyOnOtherRunners(vec!["r1".into()])
);
assert_eq!(
gaps(&[wall_only("a", "r1")], &[wall_only("a", "r2")]),
vec![]
);
assert_eq!(
gaps(
&[rec("a", "r1", 1.0), wall_only("a", "r2")],
&[wall_only("a", "r2")]
),
vec![]
);
}
#[test]
fn only_this_runs_series_are_compared() {
let baseline = [
rec("a", "r1", 1.0),
rec("a", "r2", 1.0),
rec("b", "r1", 1.0),
];
let kept = relevant(&baseline, &[rec("a", "r1", 2.0)]);
let runners: Vec<_> = kept
.iter()
.map(|r| (r.bench.as_str(), r.runner.as_str()))
.collect();
assert_eq!(runners, vec![("a", "r1")]);
}
}