Skip to main content

tak_cli/
export.rs

1//! Results in hyperfine's `--export-json` shape.
2//!
3//! Projects moving from hyperfine already have scripts that read that file
4//! (aube's `generate-results.js` reads `mean`, `stddev`, `min` and `max`).
5//! Writing the same shape lets them switch the measuring tool without
6//! rewriting what consumes it. `bench` and `subject` are extra keys, which
7//! hyperfine consumers ignore; they are what tell entries apart once one file
8//! holds several benchmarks. `user` and `system` are omitted because tak does
9//! not measure CPU time. Everything tak adds is an extra key, and none of
10//! hyperfine's changes meaning: `checks` is present only for a subject with a
11//! `check`, `version` only for one with a `version_cmd`, `allocations` only
12//! for one whose heap allocations were counted, and `metrics` only for one
13//! with custom metrics.
14
15use anyhow::{Context, Result};
16use serde::Serialize;
17use std::collections::BTreeMap;
18use std::path::Path;
19
20#[derive(Debug, Serialize)]
21pub struct Export {
22    /// How the run was made, so a surprising result can be traced and its
23    /// sample order repeated. Extra top-level keys; hyperfine has none.
24    #[serde(flatten)]
25    pub meta: Meta,
26    pub results: Vec<ExportResult>,
27}
28
29#[derive(Debug, Clone, Serialize)]
30pub struct Meta {
31    pub tak_version: String,
32    /// The run's seed: `tak run --seed` with it repeats the sample order, as
33    /// long as `runs = "auto"` settles on the same counts. A string, because
34    /// a seed given with `--seed` can exceed 2^53, and a JSON number that
35    /// large is rounded by JavaScript and jq — silently naming another order.
36    #[serde(serialize_with = "as_string")]
37    pub seed: u64,
38    /// The runner class the run would be recorded under.
39    pub runner: String,
40    /// When the run finished, RFC 3339.
41    pub time: String,
42    /// What the run was measured on, for a results page to state.
43    pub machine: crate::machine::Machine,
44}
45
46#[derive(Debug, Serialize)]
47pub struct ExportResult {
48    /// hyperfine's display name: the subject, or the benchmark for a
49    /// single-command one.
50    pub command: String,
51    pub bench: String,
52    pub subject: String,
53    /// What the subject's `version_cmd` printed. Absent when it has none,
54    /// `null` when it failed — a subject is still measured and exported
55    /// without its version.
56    #[serde(skip_serializing_if = "Option::is_none")]
57    pub version: Option<Option<String>>,
58    /// Seconds, like hyperfine, not the milliseconds tak records.
59    pub mean: f64,
60    /// `null` for a single sample, as hyperfine writes it.
61    pub stddev: Option<f64>,
62    pub median: f64,
63    pub min: f64,
64    pub max: f64,
65    /// Every timed sample in seconds, in the order taken.
66    pub times: Vec<f64>,
67    /// What each sample exited with, aligned with `times`. Always one of the
68    /// subject's `ok_exit_codes` (0 unless it says otherwise): a sample that
69    /// exits with anything else drops its subject rather than being kept. A
70    /// failed `check` is not a failed run, and is reported in `checks`.
71    pub exit_codes: Vec<i32>,
72    /// The outcome of the subject's `check`, when it has one.
73    #[serde(skip_serializing_if = "Option::is_none")]
74    pub checks: Option<Checks>,
75    /// The subject's custom metrics by name, each `null` when it could not
76    /// be taken. Absent for a subject that declares none, so the hyperfine
77    /// shape is unchanged for everyone else. A BTreeMap so the keys come
78    /// out in the same order every run.
79    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
80    pub metrics: BTreeMap<String, Option<f64>>,
81    /// Heap allocations DHAT counted, when the subject asked for them and
82    /// valgrind was there to count them.
83    #[serde(skip_serializing_if = "Option::is_none")]
84    pub allocations: Option<Allocations>,
85}
86
87/// The minimum of each allocation metric over the DHAT runs, as recorded.
88/// Counts, so integers rather than the floats the metrics map holds.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
90pub struct Allocations {
91    pub blocks: u64,
92    pub bytes: u64,
93    pub peak_bytes: u64,
94}
95
96impl Allocations {
97    /// From a record's metrics: all three, or none. A partial set cannot
98    /// happen, since they are measured together, and an export should not
99    /// invent the missing ones.
100    pub fn from_metrics(metrics: &std::collections::BTreeMap<String, f64>) -> Option<Self> {
101        let get = |k: &str| metrics.get(k).map(|&v| v as u64);
102        Some(Allocations {
103            blocks: get("alloc_blocks")?,
104            bytes: get("alloc_bytes")?,
105            peak_bytes: get("alloc_peak_bytes")?,
106        })
107    }
108}
109
110/// How a subject's timed samples fared against its `check`.
111#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
112pub struct Checks {
113    pub passed: usize,
114    pub total: usize,
115    /// Whether each sample passed, aligned with `times`, so a failure can be
116    /// matched to the time it produced.
117    pub samples: Vec<bool>,
118}
119
120impl Checks {
121    pub fn new(samples: &[bool]) -> Self {
122        Checks {
123            passed: samples.iter().filter(|&&ok| ok).count(),
124            total: samples.len(),
125            samples: samples.to_vec(),
126        }
127    }
128}
129
130impl ExportResult {
131    /// A result whose samples all exited 0; see [`Self::with_exit_codes`].
132    pub fn new(bench: &str, subject: &str, command: &str, samples_ms: &[f64]) -> Self {
133        let times: Vec<f64> = samples_ms.iter().map(|ms| ms / 1000.0).collect();
134        let mut sorted = times.clone();
135        sorted.sort_by(f64::total_cmp);
136        let n = sorted.len();
137        let mean = sorted.iter().sum::<f64>() / n as f64;
138        let stddev = (n > 1).then(|| {
139            (sorted.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64).sqrt()
140        });
141        // The true median, as hyperfine reports it, rather than tak's p50
142        // (the upper middle sample).
143        let median = if n.is_multiple_of(2) {
144            (sorted[n / 2 - 1] + sorted[n / 2]) / 2.0
145        } else {
146            sorted[n / 2]
147        };
148        ExportResult {
149            command: command.to_string(),
150            bench: bench.to_string(),
151            subject: subject.to_string(),
152            version: None,
153            mean,
154            stddev,
155            median,
156            min: sorted[0],
157            max: sorted[n - 1],
158            exit_codes: vec![0; n],
159            times,
160            checks: None,
161            allocations: None,
162            metrics: BTreeMap::new(),
163        }
164    }
165
166    /// Record what each sample actually exited with, one per sample.
167    pub fn with_exit_codes(mut self, codes: &[i32]) -> Self {
168        debug_assert_eq!(codes.len(), self.times.len());
169        self.exit_codes = codes.to_vec();
170        self
171    }
172
173    /// Attach a subject's check outcomes, one per sample.
174    pub fn with_checks(mut self, samples: &[bool]) -> Self {
175        debug_assert_eq!(samples.len(), self.times.len());
176        self.checks = Some(Checks::new(samples));
177        self
178    }
179}
180
181fn as_string<S: serde::Serializer>(v: &u64, s: S) -> Result<S::Ok, S::Error> {
182    s.serialize_str(&v.to_string())
183}
184
185pub fn write(path: &Path, meta: Meta, results: Vec<ExportResult>) -> Result<()> {
186    let json = serde_json::to_string_pretty(&Export { meta, results })?;
187    std::fs::write(path, json + "\n").with_context(|| format!("could not write {}", path.display()))
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193    use std::collections::BTreeMap;
194
195    #[test]
196    fn times_are_seconds_and_the_median_is_the_true_median() {
197        let r = ExportResult::new("b", "s", "s", &[4000.0, 1000.0, 3000.0, 2000.0]);
198        assert_eq!(r.times, [4.0, 1.0, 3.0, 2.0], "kept in the order taken");
199        assert_eq!((r.min, r.max, r.mean, r.median), (1.0, 4.0, 2.5, 2.5));
200        assert_eq!(r.exit_codes, [0; 4]);
201        assert!(r.stddev.unwrap() > 0.0);
202    }
203
204    /// `checks` is absent without a check, so a subject that has none
205    /// exports exactly the hyperfine shape it did before.
206    #[test]
207    fn checks_are_exported_only_when_there_are_some() {
208        let plain = serde_json::to_value(ExportResult::new("b", "s", "s", &[1.0, 2.0])).unwrap();
209        assert!(plain.get("checks").is_none(), "{plain}");
210
211        let checked = serde_json::to_value(
212            ExportResult::new("b", "s", "s", &[1.0, 2.0, 3.0]).with_checks(&[true, false, true]),
213        )
214        .unwrap();
215        assert_eq!(
216            checked["checks"],
217            serde_json::json!({"passed": 2, "total": 3, "samples": [true, false, true]})
218        );
219        assert_eq!(checked["exit_codes"], serde_json::json!([0, 0, 0]));
220    }
221
222    #[test]
223    fn a_version_is_absent_unless_asked_for_and_null_when_it_failed() {
224        let mut r = ExportResult::new("b", "s", "s", &[5.0]);
225        let json = serde_json::to_value(&r).unwrap();
226        assert!(json.get("version").is_none());
227        r.version = Some(None);
228        assert!(serde_json::to_value(&r).unwrap()["version"].is_null());
229        r.version = Some(Some("tool 1.2.3".into()));
230        assert_eq!(serde_json::to_value(&r).unwrap()["version"], "tool 1.2.3");
231    }
232
233    /// Absent unless counted, like `checks`, so a subject that did not ask
234    /// exports the same shape as before.
235    #[test]
236    fn allocations_are_exported_only_when_counted() {
237        let mut r = ExportResult::new("b", "s", "s", &[1.0]);
238        assert!(
239            serde_json::to_value(&r)
240                .unwrap()
241                .get("allocations")
242                .is_none()
243        );
244
245        let metrics = std::collections::BTreeMap::from([
246            ("alloc_blocks".to_string(), 31.0),
247            ("alloc_bytes".to_string(), 7119.0),
248            ("alloc_peak_bytes".to_string(), 6847.0),
249            ("wall_min_ms".to_string(), 1.0),
250        ]);
251        r.allocations = Allocations::from_metrics(&metrics);
252        assert_eq!(
253            serde_json::to_value(&r).unwrap()["allocations"],
254            serde_json::json!({"blocks": 31, "bytes": 7119, "peak_bytes": 6847})
255        );
256        assert_eq!(
257            Allocations::from_metrics(&BTreeMap::from([("alloc_blocks".to_string(), 1.0)])),
258            None
259        );
260    }
261
262    /// Custom metrics appear only for a subject that declares some, and a
263    /// failed one is `null` rather than missing, so a reader can tell "not
264    /// declared" from "declared and broken".
265    #[test]
266    fn metrics_are_exported_only_when_declared() {
267        let mut r = ExportResult::new("b", "s", "s", &[5.0]);
268        assert!(serde_json::to_value(&r).unwrap().get("metrics").is_none());
269        r.metrics = BTreeMap::from([
270            ("binary_bytes".to_string(), Some(1234.0)),
271            ("bundle_kb".to_string(), None),
272        ]);
273        assert_eq!(
274            serde_json::to_value(&r).unwrap()["metrics"],
275            serde_json::json!({"binary_bytes": 1234.0, "bundle_kb": null})
276        );
277    }
278
279    #[test]
280    fn a_single_sample_has_no_stddev() {
281        let r = ExportResult::new("b", "s", "s", &[5.0]);
282        assert_eq!(r.stddev, None);
283        let json = serde_json::to_value(&r).unwrap();
284        assert!(json["stddev"].is_null());
285    }
286
287    /// Each sample's real exit code is kept, in the order taken, rather than
288    /// assumed to be 0.
289    #[test]
290    fn exit_codes_are_what_each_sample_exited_with() {
291        let r = ExportResult::new("b", "s", "s", &[1.0, 2.0]).with_exit_codes(&[1, 0]);
292        assert_eq!(r.exit_codes, [1, 0]);
293    }
294}