1use anyhow::{Context, Result};
16use serde::Serialize;
17use std::collections::BTreeMap;
18use std::path::Path;
19
20#[derive(Debug, Serialize)]
21pub struct Export {
22 #[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 #[serde(serialize_with = "as_string")]
37 pub seed: u64,
38 pub runner: String,
40 pub time: String,
42 pub machine: crate::machine::Machine,
44}
45
46#[derive(Debug, Serialize)]
47pub struct ExportResult {
48 pub command: String,
51 pub bench: String,
52 pub subject: String,
53 #[serde(skip_serializing_if = "Option::is_none")]
57 pub version: Option<Option<String>>,
58 pub mean: f64,
60 pub stddev: Option<f64>,
62 pub median: f64,
63 pub min: f64,
64 pub max: f64,
65 pub times: Vec<f64>,
67 pub exit_codes: Vec<i32>,
72 #[serde(skip_serializing_if = "Option::is_none")]
74 pub checks: Option<Checks>,
75 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
80 pub metrics: BTreeMap<String, Option<f64>>,
81 #[serde(skip_serializing_if = "Option::is_none")]
84 pub allocations: Option<Allocations>,
85}
86
87#[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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
112pub struct Checks {
113 pub passed: usize,
114 pub total: usize,
115 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 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 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 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 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 #[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 #[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 #[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 #[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}