diff --git a/AGENTS.md b/AGENTS.md index 2bf925d..6f136dd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,7 +28,7 @@ CI tests against Go 1.24.x, 1.25.x, 1.26.x and 1.27.x. Go 1.24 tests require `GO Rust workspace with a single crate: `go-runner/` (`codspeed-go-runner`), edition 2024, toolchain 1.90.0. -**Flow:** `main.rs` parses CLI args → `runner::run()` generates overlay + runs `go test` → Go benchmarks write raw JSON results to `$CODSPEED_PROFILE_FOLDER/raw_results/` → `collect_walltime_results()` aggregates into `results/{pid}.json`. +**Flow:** `main.rs` parses CLI args → `runner::run()` generates overlay + runs `go test` → Go benchmarks write raw JSON results to `$CODSPEED_PROFILE_FOLDER/raw_results/` → `collect_walltime_results()` aggregates into `results/{pid}.json` and writes the rounds to `walltime_rounds/{pid}.json.gz`. **Overlay mechanism:** Three files are overlaid into `$GOROOT/src/testing/`: - `benchmark.go` — replaces the standard `testing.B` implementation (version-specific: 1.24, 1.25 or 1.26+) diff --git a/Cargo.lock b/Cargo.lock index 17771dd..ce197f8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -282,6 +282,7 @@ dependencies = [ "codspeed-divan-compat", "env_logger", "flate2", + "getrandom 0.3.3", "glob", "insta", "itertools", diff --git a/go-runner/Cargo.toml b/go-runner/Cargo.toml index 4844963..742dfe7 100644 --- a/go-runner/Cargo.toml +++ b/go-runner/Cargo.toml @@ -11,6 +11,7 @@ env_logger = "0.11" glob = "0.3" log = "0.4" regex = "1.11" +getrandom = "0.3" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" statrs = { version = "0.18", default-features = false } diff --git a/go-runner/src/lib.rs b/go-runner/src/lib.rs index 1b3f2e6..7cd3ea6 100644 --- a/go-runner/src/lib.rs +++ b/go-runner/src/lib.rs @@ -2,7 +2,12 @@ use crate::{ prelude::*, results::{raw_result::RawResult, walltime_results::WalltimeBenchmark}, }; -use std::{collections::HashMap, path::Path}; +use flate2::{Compression, write::GzEncoder}; +use std::{ + collections::HashMap, + io::{BufWriter, IntoInnerError}, + path::Path, +}; pub mod cli; pub mod prelude; @@ -53,11 +58,61 @@ pub fn collect_walltime_results(profile_dir: &Path) -> anyhow::Result<()> { std::fs::create_dir_all(&results_dir)?; let results_file = results_dir.join(format!("{pid}.json")); - let walltime_results = + let mut walltime_results = results::walltime_results::WalltimeResults::new(walltime_benchmarks, creator)?; std::fs::write(&results_file, serde_json::to_string(&walltime_results)?)?; info!("Results written to {results_file:?}"); + + let rounds_dir = profile_dir.join("walltime_rounds"); + std::fs::create_dir_all(&rounds_dir)?; + let rounds_file = std::fs::File::create(rounds_dir.join(format!("{pid}.json.gz")))?; + let mut rounds_writer = BufWriter::new(GzEncoder::new(rounds_file, Compression::fast())); + serde_json::to_writer(&mut rounds_writer, &walltime_results.take_walltime_rounds())?; + rounds_writer + .into_inner() + .map_err(IntoInnerError::into_error)? + .finish()?; } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + use flate2::read::GzDecoder; + + #[test] + fn test_collect_walltime_results_writes_gzipped_rounds() { + let profile_dir = tempfile::TempDir::new().unwrap(); + let raw_results_dir = profile_dir.path().join("raw_results"); + std::fs::create_dir_all(&raw_results_dir).unwrap(); + std::fs::write( + raw_results_dir.join("bench.json"), + serde_json::json!({ + "name": "BenchmarkFoo", + "uri": "pkg/foo_test.go::BenchmarkFoo", + "pid": 42, + "codspeed_time_per_round_ns": [3000, 1000, 2000], + "codspeed_iters_per_round": [3, 1, 2], + }) + .to_string(), + ) + .unwrap(); + + collect_walltime_results(profile_dir.path()).unwrap(); + + let rounds_file = + std::fs::File::open(profile_dir.path().join("walltime_rounds/42.json.gz")).unwrap(); + let rounds: serde_json::Value = + serde_json::from_reader(GzDecoder::new(rounds_file)).unwrap(); + assert_eq!( + rounds, + serde_json::json!({"benchmarks": [{ + "uri": "pkg/foo_test.go::BenchmarkFoo", + "times_per_round_ns": [3000, 1000, 2000], + "iters_per_round": [3, 1, 2], + }]}) + ); + } +} diff --git a/go-runner/src/results/raw_result.rs b/go-runner/src/results/raw_result.rs index ff60ee4..879a6fc 100644 --- a/go-runner/src/results/raw_result.rs +++ b/go-runner/src/results/raw_result.rs @@ -33,8 +33,8 @@ impl RawResult { WalltimeBenchmark::from_runtime_data( json.name, json.uri, - &json.codspeed_iters_per_round, - &json.codspeed_time_per_round_ns, + json.codspeed_iters_per_round, + json.codspeed_time_per_round_ns, None, ), ) diff --git a/go-runner/src/results/walltime_results.rs b/go-runner/src/results/walltime_results.rs index 036a618..e031091 100644 --- a/go-runner/src/results/walltime_results.rs +++ b/go-runner/src/results/walltime_results.rs @@ -1,11 +1,16 @@ // NOTE: This file was taken from `codspeed-rust` and modified a bit to fit this project. +// TODO(COD-4241): call the `codspeed` crate's percentile and round sampling code instead of +// copying it. use anyhow::Result; use serde::{Deserialize, Serialize}; -use statrs::statistics::{Data, Distribution, Max, Min, OrderStatistics}; +use statrs::statistics::{Data, Distribution, Max, Min}; +use std::collections::BTreeSet; const IQR_OUTLIER_FACTOR: f64 = 1.5; const STDEV_OUTLIER_FACTOR: f64 = 3.0; +/// Above this, the rounds file keeps a uniformly random subsample of the rounds, in execution order. +const MAX_WALLTIME_ROUNDS_PER_BENCHMARK: usize = 100_000; #[derive(Debug, Serialize, Deserialize)] pub struct BenchmarkMetadata { @@ -23,6 +28,9 @@ struct BenchmarkStats { q1_ns: f64, median_ns: f64, q3_ns: f64, + /// p1..p99 of the time per iteration: `[24]`, `[49]` and `[74]` equal `q1_ns`, `median_ns` and `q3_ns` + #[serde(default, skip_serializing_if = "Option::is_none")] + percentiles_ns: Option>, rounds: u64, total_time: f64, @@ -40,6 +48,25 @@ struct BenchmarkConfig { max_rounds: Option, } +#[derive(Debug, Serialize, Default)] +struct BenchmarkRounds { + times_per_round_ns: Vec, + iters_per_round: Vec, +} + +#[derive(Debug, Serialize)] +struct UriRounds { + uri: String, + #[serde(flatten)] + rounds: BenchmarkRounds, +} + +/// Content of `walltime_rounds/.json.gz` in the profile folder +#[derive(Debug, Serialize)] +pub struct WalltimeRounds { + benchmarks: Vec, +} + #[derive(Debug, Serialize, Deserialize)] pub struct WalltimeBenchmark { #[serde(flatten)] @@ -47,28 +74,54 @@ pub struct WalltimeBenchmark { config: BenchmarkConfig, stats: BenchmarkStats, + + /// Rounds in execution order, capped at [`MAX_WALLTIME_ROUNDS_PER_BENCHMARK`]: fewer than + /// `stats.rounds` when subsampled + #[serde(skip)] + walltime_rounds: BenchmarkRounds, } impl WalltimeBenchmark { pub fn from_runtime_data( name: String, uri: String, - iters_per_round: &[u64], - times_per_round_ns: &[u64], + iters_per_round: Vec, + times_per_round_ns: Vec, max_time_ns: Option, ) -> Self { let total_time = times_per_round_ns.iter().map(|&t| t as u128).sum::() as f64 / 1_000_000_000.0; - let time_per_iteration_per_round_ns: Vec<_> = times_per_round_ns + let mut time_per_iteration_per_round_ns: Vec<_> = times_per_round_ns .iter() - .zip(iters_per_round) + .zip(&iters_per_round) .map(|(time_per_round, iter_per_round)| { *time_per_round as u128 / *iter_per_round as u128 }) .map(|t| t as f64) .collect::>(); - let mut data = Data::new(time_per_iteration_per_round_ns); + // statrs' `quantile` formula (R-8) on rounds sorted once: statrs itself runs an O(n) selection per call + time_per_iteration_per_round_ns.sort_unstable_by(f64::total_cmp); + let sorted = &time_per_iteration_per_round_ns; + let percentiles_ns: Vec = (1..100) + .map(|p| { + let h = (sorted.len() as f64 + 1.0 / 3.0) * (p as f64 / 100.0) + 1.0 / 3.0; + let hf = h as usize; + if hf == 0 { + return sorted[0]; + } + if hf >= sorted.len() { + return sorted[sorted.len() - 1]; + } + let (a, b) = (sorted[hf - 1], sorted[hf]); + a + (h - hf as f64) * (b - a) + }) + .collect(); + let q1_ns = percentiles_ns[24]; + let median_ns = percentiles_ns[49]; + let q3_ns = percentiles_ns[74]; + + let data = Data::new(time_per_iteration_per_round_ns); let rounds: u64 = data.len() as u64; let mean_ns = data.mean().unwrap(); @@ -81,10 +134,6 @@ impl WalltimeBenchmark { data.std_dev().unwrap() }; - let q1_ns = data.quantile(0.25); - let median_ns = data.median(); - let q3_ns = data.quantile(0.75); - let iqr_ns = q3_ns - q1_ns; let iqr_outlier_rounds = data .iter() @@ -117,6 +166,7 @@ impl WalltimeBenchmark { q1_ns, median_ns, q3_ns, + percentiles_ns: Some(percentiles_ns), rounds, total_time, iqr_outlier_rounds, @@ -125,6 +175,32 @@ impl WalltimeBenchmark { warmup_iters, }; + let walltime_rounds = if times_per_round_ns.len() <= MAX_WALLTIME_ROUNDS_PER_BENCHMARK { + BenchmarkRounds { + times_per_round_ns, + iters_per_round, + } + } else { + // Floyd's sampling of distinct indices; the set iterates them in execution order + let mut random = vec![0u8; 8 * MAX_WALLTIME_ROUNDS_PER_BENCHMARK]; + getrandom::fill(&mut random).expect("Failed to generate random bytes"); + let mut kept_indices = BTreeSet::new(); + let n = times_per_round_ns.len(); + for (j, r) in (n - MAX_WALLTIME_ROUNDS_PER_BENCHMARK..n).zip(random.chunks_exact(8)) { + let t = (u64::from_ne_bytes(r.try_into().unwrap()) % (j as u64 + 1)) as usize; + if !kept_indices.insert(t) { + kept_indices.insert(j); + } + } + BenchmarkRounds { + times_per_round_ns: kept_indices + .iter() + .map(|&i| times_per_round_ns[i]) + .collect(), + iters_per_round: kept_indices.iter().map(|&i| iters_per_round[i]).collect(), + } + }; + WalltimeBenchmark { metadata: BenchmarkMetadata { name, uri }, config: BenchmarkConfig { @@ -132,6 +208,7 @@ impl WalltimeBenchmark { ..Default::default() }, stats, + walltime_rounds, } } } @@ -166,6 +243,19 @@ impl WalltimeResults { benchmarks, }) } + + pub fn take_walltime_rounds(&mut self) -> WalltimeRounds { + WalltimeRounds { + benchmarks: self + .benchmarks + .iter_mut() + .map(|bench| UriRounds { + uri: bench.metadata.uri.clone(), + rounds: std::mem::take(&mut bench.walltime_rounds), + }) + .collect(), + } + } } #[cfg(test)] @@ -180,8 +270,8 @@ mod tests { let benchmark = WalltimeBenchmark::from_runtime_data( NAME.to_string(), URI.to_string(), - &[1], - &[42], + vec![1], + vec![42], None, ); assert_eq!(benchmark.stats.stdev_ns, 0.); @@ -198,8 +288,8 @@ mod tests { let benchmark = WalltimeBenchmark::from_runtime_data( NAME.to_string(), URI.to_string(), - &iters_per_round, - &[42, 42 * 2, 42 * 3, 42 * 4, 42 * 5, 42 * 6], + iters_per_round, + vec![42, 42 * 2, 42 * 3, 42 * 4, 42 * 5, 42 * 6], None, ); @@ -212,4 +302,100 @@ mod tests { 42. * total_rounds / 1_000_000_000.0 ); } + + #[test] + fn test_percentiles_match_statrs() { + for rounds in [1u64, 2, 3, 10, 100] { + // 1..=rounds in a shuffled execution order + let times: Vec = (1..=rounds).map(|i| i * 37 % (rounds + 1)).collect(); + let benchmark = WalltimeBenchmark::from_runtime_data( + NAME.to_string(), + URI.to_string(), + vec![1; times.len()], + times.clone(), + None, + ); + + let percentiles = benchmark.stats.percentiles_ns.unwrap(); + let mut data = Data::new(times.iter().map(|&t| t as f64).collect::>()); + let expected: Vec = (1..100) + .map(|p| statrs::statistics::OrderStatistics::percentile(&mut data, p)) + .collect(); + assert_eq!(percentiles, expected, "{rounds} rounds"); + assert!(percentiles.windows(2).all(|w| w[0] <= w[1])); + assert_eq!(benchmark.stats.q1_ns, percentiles[24]); + assert_eq!(benchmark.stats.median_ns, percentiles[49]); + assert_eq!(benchmark.stats.q3_ns, percentiles[74]); + } + } + + #[test] + fn test_walltime_rounds_capped_in_execution_order() { + let rounds = MAX_WALLTIME_ROUNDS_PER_BENCHMARK + 50_000; + let iters: Vec = (1..=rounds as u64).collect(); + let times: Vec = iters.iter().map(|i| i * 10).collect(); + let benchmark = WalltimeBenchmark::from_runtime_data( + NAME.to_string(), + URI.to_string(), + iters, + times, + None, + ); + + assert_eq!(benchmark.stats.rounds, rounds as u64); + let kept = benchmark.walltime_rounds; + assert_eq!( + kept.times_per_round_ns.len(), + MAX_WALLTIME_ROUNDS_PER_BENCHMARK + ); + assert_eq!( + kept.iters_per_round.len(), + MAX_WALLTIME_ROUNDS_PER_BENCHMARK + ); + // A random subsample, not the first rounds + assert!(*kept.iters_per_round.last().unwrap() > MAX_WALLTIME_ROUNDS_PER_BENCHMARK as u64); + assert!(kept.times_per_round_ns.windows(2).all(|w| w[0] < w[1])); + assert!( + kept.times_per_round_ns + .iter() + .zip(&kept.iters_per_round) + .all(|(&t, &i)| t == i * 10 && (1..=rounds as u64).contains(&i)) + ); + } + + #[test] + fn test_take_walltime_rounds() { + let mut results = WalltimeResults::new( + vec![WalltimeBenchmark::from_runtime_data( + NAME.to_string(), + URI.to_string(), + vec![1, 2], + vec![30, 50], + None, + )], + Creator { + name: "codspeed-go".to_string(), + version: "0.0.0".to_string(), + pid: 1, + }, + ) + .unwrap(); + + let rounds = serde_json::to_value(results.take_walltime_rounds()).unwrap(); + assert_eq!( + rounds, + serde_json::json!({"benchmarks": [ + {"uri": URI, "times_per_round_ns": [30, 50], "iters_per_round": [1, 2]} + ]}) + ); + let results = serde_json::to_value(&results).unwrap(); + assert!(results["benchmarks"][0].get("walltime_rounds").is_none()); + assert_eq!( + results["benchmarks"][0]["stats"]["percentiles_ns"] + .as_array() + .unwrap() + .len(), + 99 + ); + } }