use anyhow::{Context, Result};
use serde::Serialize;
use std::collections::BTreeMap;
use std::path::Path;
#[derive(Debug, Serialize)]
pub struct Export {
#[serde(flatten)]
pub meta: Meta,
pub results: Vec<ExportResult>,
}
#[derive(Debug, Clone, Serialize)]
pub struct Meta {
pub tak_version: String,
#[serde(serialize_with = "as_string")]
pub seed: u64,
pub runner: String,
pub time: String,
pub machine: crate::machine::Machine,
}
#[derive(Debug, Serialize)]
pub struct ExportResult {
pub command: String,
pub bench: String,
pub subject: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub version: Option<Option<String>>,
pub mean: f64,
pub stddev: Option<f64>,
pub median: f64,
pub min: f64,
pub max: f64,
pub times: Vec<f64>,
pub exit_codes: Vec<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub checks: Option<Checks>,
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub metrics: BTreeMap<String, Option<f64>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub allocations: Option<Allocations>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct Allocations {
pub blocks: u64,
pub bytes: u64,
pub peak_bytes: u64,
}
impl Allocations {
pub fn from_metrics(metrics: &std::collections::BTreeMap<String, f64>) -> Option<Self> {
let get = |k: &str| metrics.get(k).map(|&v| v as u64);
Some(Allocations {
blocks: get("alloc_blocks")?,
bytes: get("alloc_bytes")?,
peak_bytes: get("alloc_peak_bytes")?,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Checks {
pub passed: usize,
pub total: usize,
pub samples: Vec<bool>,
}
impl Checks {
pub fn new(samples: &[bool]) -> Self {
Checks {
passed: samples.iter().filter(|&&ok| ok).count(),
total: samples.len(),
samples: samples.to_vec(),
}
}
}
impl ExportResult {
pub fn new(bench: &str, subject: &str, command: &str, samples_ms: &[f64]) -> Self {
let times: Vec<f64> = samples_ms.iter().map(|ms| ms / 1000.0).collect();
let mut sorted = times.clone();
sorted.sort_by(f64::total_cmp);
let n = sorted.len();
let mean = sorted.iter().sum::<f64>() / n as f64;
let stddev = (n > 1).then(|| {
(sorted.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64).sqrt()
});
let median = if n.is_multiple_of(2) {
(sorted[n / 2 - 1] + sorted[n / 2]) / 2.0
} else {
sorted[n / 2]
};
ExportResult {
command: command.to_string(),
bench: bench.to_string(),
subject: subject.to_string(),
version: None,
mean,
stddev,
median,
min: sorted[0],
max: sorted[n - 1],
exit_codes: vec![0; n],
times,
checks: None,
allocations: None,
metrics: BTreeMap::new(),
}
}
pub fn with_exit_codes(mut self, codes: &[i32]) -> Self {
debug_assert_eq!(codes.len(), self.times.len());
self.exit_codes = codes.to_vec();
self
}
pub fn with_checks(mut self, samples: &[bool]) -> Self {
debug_assert_eq!(samples.len(), self.times.len());
self.checks = Some(Checks::new(samples));
self
}
}
fn as_string<S: serde::Serializer>(v: &u64, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&v.to_string())
}
pub fn write(path: &Path, meta: Meta, results: Vec<ExportResult>) -> Result<()> {
let json = serde_json::to_string_pretty(&Export { meta, results })?;
std::fs::write(path, json + "\n").with_context(|| format!("could not write {}", path.display()))
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
#[test]
fn times_are_seconds_and_the_median_is_the_true_median() {
let r = ExportResult::new("b", "s", "s", &[4000.0, 1000.0, 3000.0, 2000.0]);
assert_eq!(r.times, [4.0, 1.0, 3.0, 2.0], "kept in the order taken");
assert_eq!((r.min, r.max, r.mean, r.median), (1.0, 4.0, 2.5, 2.5));
assert_eq!(r.exit_codes, [0; 4]);
assert!(r.stddev.unwrap() > 0.0);
}
#[test]
fn checks_are_exported_only_when_there_are_some() {
let plain = serde_json::to_value(ExportResult::new("b", "s", "s", &[1.0, 2.0])).unwrap();
assert!(plain.get("checks").is_none(), "{plain}");
let checked = serde_json::to_value(
ExportResult::new("b", "s", "s", &[1.0, 2.0, 3.0]).with_checks(&[true, false, true]),
)
.unwrap();
assert_eq!(
checked["checks"],
serde_json::json!({"passed": 2, "total": 3, "samples": [true, false, true]})
);
assert_eq!(checked["exit_codes"], serde_json::json!([0, 0, 0]));
}
#[test]
fn a_version_is_absent_unless_asked_for_and_null_when_it_failed() {
let mut r = ExportResult::new("b", "s", "s", &[5.0]);
let json = serde_json::to_value(&r).unwrap();
assert!(json.get("version").is_none());
r.version = Some(None);
assert!(serde_json::to_value(&r).unwrap()["version"].is_null());
r.version = Some(Some("tool 1.2.3".into()));
assert_eq!(serde_json::to_value(&r).unwrap()["version"], "tool 1.2.3");
}
#[test]
fn allocations_are_exported_only_when_counted() {
let mut r = ExportResult::new("b", "s", "s", &[1.0]);
assert!(
serde_json::to_value(&r)
.unwrap()
.get("allocations")
.is_none()
);
let metrics = std::collections::BTreeMap::from([
("alloc_blocks".to_string(), 31.0),
("alloc_bytes".to_string(), 7119.0),
("alloc_peak_bytes".to_string(), 6847.0),
("wall_min_ms".to_string(), 1.0),
]);
r.allocations = Allocations::from_metrics(&metrics);
assert_eq!(
serde_json::to_value(&r).unwrap()["allocations"],
serde_json::json!({"blocks": 31, "bytes": 7119, "peak_bytes": 6847})
);
assert_eq!(
Allocations::from_metrics(&BTreeMap::from([("alloc_blocks".to_string(), 1.0)])),
None
);
}
#[test]
fn metrics_are_exported_only_when_declared() {
let mut r = ExportResult::new("b", "s", "s", &[5.0]);
assert!(serde_json::to_value(&r).unwrap().get("metrics").is_none());
r.metrics = BTreeMap::from([
("binary_bytes".to_string(), Some(1234.0)),
("bundle_kb".to_string(), None),
]);
assert_eq!(
serde_json::to_value(&r).unwrap()["metrics"],
serde_json::json!({"binary_bytes": 1234.0, "bundle_kb": null})
);
}
#[test]
fn a_single_sample_has_no_stddev() {
let r = ExportResult::new("b", "s", "s", &[5.0]);
assert_eq!(r.stddev, None);
let json = serde_json::to_value(&r).unwrap();
assert!(json["stddev"].is_null());
}
#[test]
fn exit_codes_are_what_each_sample_exited_with() {
let r = ExportResult::new("b", "s", "s", &[1.0, 2.0]).with_exit_codes(&[1, 0]);
assert_eq!(r.exit_codes, [1, 0]);
}
}