Skip to main content

tak_cli/
record.rs

1//! The on-disk record format.
2//!
3//! One JSON object per line, keys sorted, stored as a git note on the commit the
4//! measurement describes. Line-oriented and order-independent so that git's
5//! `cat_sort_uniq` notes merge strategy resolves concurrent CI writers without
6//! conflicts — see [`crate::notes`].
7//!
8//! Serialisation goes through [`Record::to_line`] rather than plain
9//! `serde_json::to_string` because `cat_sort_uniq` dedupes on exact bytes: two
10//! writers emitting the same measurement must produce byte-identical lines.
11
12use serde::{Deserialize, Serialize};
13use std::collections::BTreeMap;
14
15/// Bumped when the record shape changes incompatibly. Readers skip lines whose
16/// version they do not understand rather than failing the whole history.
17pub const SCHEMA_VERSION: u32 = 1;
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct Record {
21    /// Schema version. Serialised first-by-name (`v`) purely by BTreeMap ordering.
22    pub v: u32,
23
24    /// Benchmark name, from `bench.toml`.
25    pub bench: String,
26
27    /// Which program produced this measurement. Defaults to the project itself;
28    /// set to `pnpm`, `npm`, … for competitive comparisons, which are wall-clock
29    /// only — instruction counts across different programs are not comparable.
30    pub tool: String,
31
32    /// Version of `tool`, when meaningful (release backfills, competitors).
33    #[serde(skip_serializing_if = "Option::is_none")]
34    pub version: Option<String>,
35
36    /// Runner class. Series MUST be partitioned on this: moving between runner
37    /// types shifts absolute numbers enough to look like a regression.
38    pub runner: String,
39
40    /// RFC 3339, second resolution.
41    pub ts: String,
42
43    /// Metric name -> value. Deterministic metrics (`instructions`) are integers;
44    /// timings are milliseconds. A BTreeMap so key order is stable across writers.
45    pub metrics: BTreeMap<String, f64>,
46}
47
48impl Record {
49    /// Serialise to a single line, with map keys sorted.
50    ///
51    /// Stability matters: `cat_sort_uniq` dedupes byte-identical lines, so an
52    /// identical measurement written twice must collapse to one entry.
53    pub fn to_line(&self) -> anyhow::Result<String> {
54        Ok(serde_json::to_string(self)?)
55    }
56
57    /// Parse one line. Returns `Ok(None)` for blank lines and for records from a
58    /// future schema version, so that a newer writer cannot break an older reader.
59    pub fn from_line(line: &str) -> anyhow::Result<Option<Self>> {
60        let line = line.trim();
61        if line.is_empty() {
62            return Ok(None);
63        }
64        let rec: Record = serde_json::from_str(line)?;
65        if rec.v > SCHEMA_VERSION {
66            return Ok(None);
67        }
68        Ok(Some(rec))
69    }
70}
71
72/// Whether tak itself writes metric `name`: the instruction count, or one of
73/// the wall-clock statistics.
74///
75/// Everything else in [`Record::metrics`] was declared by a project in a
76/// `[bench.B.metric.NAME]` table. The line is drawn here, beside the format,
77/// because two things depend on it staying the same: `tak.toml` refuses a
78/// declared metric that would overwrite a built-in one in the same record, and
79/// `compare` reports the rest in a table of their own. `wall_` is reserved as
80/// a whole prefix rather than name by name, so a timing statistic added later
81/// cannot land on a name some project already records something else under.
82/// `alloc_` likewise, for the heap-allocation counts DHAT records.
83pub fn is_builtin_metric(name: &str) -> bool {
84    name == "instructions" || name.starts_with("wall_") || name.starts_with("alloc_")
85}
86
87/// Reject a name that will be recorded — benchmark, subject or tool, runner
88/// class — if it holds a control character.
89///
90/// Reports are read line by line: tak's own workflows decide a check by what
91/// a line starts with, and a name holding a newline could put a forged verdict
92/// such as `**Nothing was compared` at the start of one. `tak.toml`, `--bench`
93/// and `TAK_TOOL` all come from the change under test, so this is checked where
94/// a name enters, before anything is measured. Nothing legitimate needs a
95/// control character in a name. Report rendering escapes them as well, for
96/// notes that older tak versions wrote before this check existed.
97pub fn check_name(what: &str, name: &str) -> anyhow::Result<()> {
98    if let Some(c) = name.chars().find(|c| c.is_control()) {
99        anyhow::bail!(
100            "{what} {name:?} contains the control character {c:?}. Names appear in reports \
101             that are read line by line, so they may not contain control characters, \
102             newlines included"
103        );
104    }
105    Ok(())
106}
107
108/// Parse a whole note body, skipping lines that fail to parse.
109///
110/// A single malformed line — hand-edited, or written by a broken tool — must not
111/// render an entire commit's history unreadable.
112pub fn parse_note(body: &str) -> Vec<Record> {
113    body.lines()
114        .filter_map(|l| Record::from_line(l).ok().flatten())
115        .collect()
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    fn rec() -> Record {
123        Record {
124            v: SCHEMA_VERSION,
125            bench: "hook-env".into(),
126            tool: "mise".into(),
127            version: None,
128            runner: "linux-amd64".into(),
129            ts: "2026-07-24T09:00:00Z".into(),
130            metrics: BTreeMap::from([
131                ("instructions".to_string(), 29_413_235.0),
132                ("wall_min_ms".to_string(), 11.28),
133            ]),
134        }
135    }
136
137    #[test]
138    fn line_roundtrips() {
139        let line = rec().to_line().unwrap();
140        let back = Record::from_line(&line).unwrap().unwrap();
141        assert_eq!(back.bench, "hook-env");
142        assert_eq!(back.metrics["instructions"], 29_413_235.0);
143    }
144
145    #[test]
146    fn serialisation_is_byte_stable() {
147        // cat_sort_uniq dedupes on exact bytes; two writers must agree.
148        assert_eq!(rec().to_line().unwrap(), rec().to_line().unwrap());
149    }
150
151    #[test]
152    fn blank_lines_are_skipped_not_errors() {
153        assert!(Record::from_line("   ").unwrap().is_none());
154    }
155
156    #[test]
157    fn future_schema_versions_are_skipped() {
158        let mut r = rec();
159        r.v = SCHEMA_VERSION + 1;
160        let line = r.to_line().unwrap();
161        assert!(Record::from_line(&line).unwrap().is_none());
162    }
163
164    #[test]
165    fn one_bad_line_does_not_poison_the_note() {
166        let body = format!(
167            "{}\nnot json at all\n{}",
168            rec().to_line().unwrap(),
169            rec().to_line().unwrap()
170        );
171        assert_eq!(parse_note(&body).len(), 2);
172    }
173}