diff --git a/crates/stats/Cargo.toml b/crates/stats/Cargo.toml new file mode 100644 index 0000000..92b7e9c --- /dev/null +++ b/crates/stats/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "sccache-dash-stats" +description = "Build-time histograms and a bootstrapped time-saved interval for sccache-dash" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +sccache-dash-api = { path = "../api" } diff --git a/crates/stats/src/lib.rs b/crates/stats/src/lib.rs new file mode 100644 index 0000000..94cb653 --- /dev/null +++ b/crates/stats/src/lib.rs @@ -0,0 +1,468 @@ +//! Build-time statistics from sccache's running totals. +//! +//! sccache reports only totals. The server reads them every 10 seconds, so one +//! data point is an [`Observation`]: between two readings, `compiles` builds of +//! one language finished, taking `seconds` in total. This crate turns such +//! points into a per-language histogram ([`build_times`]) and a time-saved +//! figure with a 90% interval ([`time_saved`]). +//! +//! Pure arithmetic: no clock, no OS randomness, no threads. The same input +//! always gives the same output, on any target including wasm. + +use sccache_dash_api::{Bin, BuildTimes}; + +/// One gap between two readings: `compiles` builds finished, `seconds` in total. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Observation { + pub compiles: u64, + pub seconds: f64, +} + +/// Fewer usable observations than this and a language is left out of the +/// time-saved figure: too little data to claim a saving or an interval. +pub const MIN_OBSERVATIONS: usize = 10; + +/// Bootstrap replicates used for the interval. +const REPLICATES: usize = 2000; +/// Fixed seed so results are reproducible. +const SEED: u64 = 0x5CCA_C4E5_7A75_0001; +/// Bins: 4 per decade over 1 ms .. 1000 s (6 decades). +const BINS: usize = 24; + +fn usable(o: &Observation) -> bool { + o.compiles > 0 && o.seconds.is_finite() && o.seconds >= 0.0 +} + +/// Nominal bin edge `k` (0..=BINS) in milliseconds: 10^(k/4). +fn edge_ms(k: usize) -> f64 { + 10f64.powf(k as f64 / 4.0) +} + +/// Histogram and summary of build times for one language. +/// +/// Each usable observation contributes its per-build average +/// (`seconds / compiles`) with weight `compiles`. Bin edges are evenly spaced +/// on a log scale, 4 per decade, from 1 ms to 1000 s; the ends are open +/// (anything shorter lands in the first bin, anything longer in the last), +/// though `from_ms`/`to_ms` report the nominal edges. Only the span from the +/// first to the last non-empty bin is returned, empty bins between included. +/// `mean_ms` is total seconds / total compiles; `median_ms` and `p90_ms` are +/// weighted by compiles. Observations with zero compiles or negative or +/// non-finite seconds are ignored. No usable data gives zero compiles, no bins. +pub fn build_times(language: &str, obs: &[Observation]) -> BuildTimes { + let mut pts: Vec<(f64, u64)> = obs + .iter() + .filter(|o| usable(o)) + .map(|o| (o.seconds / o.compiles as f64, o.compiles)) + .collect(); + let mut out = BuildTimes { + language: language.to_string(), + ..BuildTimes::default() + }; + if pts.is_empty() { + return out; + } + let total: u64 = pts.iter().map(|p| p.1).sum(); + let secs: f64 = obs.iter().filter(|o| usable(o)).map(|o| o.seconds).sum(); + out.compiles = total; + out.mean_ms = secs / total as f64 * 1000.0; + + pts.sort_unstable_by(|a, b| a.0.total_cmp(&b.0)); + out.median_ms = weighted_quantile(&pts, total, 1, 2) * 1000.0; + out.p90_ms = weighted_quantile(&pts, total, 9, 10) * 1000.0; + + let edges: Vec = (0..=BINS).map(edge_ms).collect(); + let mut counts = [0u64; BINS]; + for &(avg_s, w) in &pts { + let ms = avg_s * 1000.0; + // Interior edges only, so the two end bins are open. + let i = edges[1..BINS].partition_point(|e| *e <= ms); + counts[i] += w; + } + let first = counts.iter().position(|c| *c > 0).unwrap_or(0); + let last = counts.iter().rposition(|c| *c > 0).unwrap_or(0); + out.bins = (first..=last) + .map(|i| Bin { + from_ms: edges[i], + to_ms: edges[i + 1], + compiles: counts[i], + }) + .collect(); + out +} + +/// Smallest value whose cumulative weight reaches `num/den` of the total. +/// `pts` must be sorted ascending and non-empty. +fn weighted_quantile(pts: &[(f64, u64)], total: u64, num: u128, den: u128) -> f64 { + let mut cum: u128 = 0; + for &(v, w) in pts { + cum += w as u128; + if cum * den >= total as u128 * num { + return v; + } + } + pts[pts.len() - 1].0 +} + +/// A language's cache hits and the build times seen for it. +#[derive(Clone, Copy, Debug)] +pub struct LanguageHits<'a> { + pub hits: u64, + pub obs: &'a [Observation], +} + +/// Time saved by the cache. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Saved { + pub seconds: f64, + /// 5th and 95th percentile of the bootstrap; `None` when no language had + /// enough data. + pub interval_90: Option<(f64, f64)>, + /// Hits in languages with too few observations, not counted in `seconds`. + pub hits_left_out: u64, +} + +/// Time saved by cache hits: for each language, +/// `hits * max(0, mean build time - hit_read_seconds)`, summed. +/// +/// `hit_read_seconds` is the average time a hit costs. A language with fewer +/// than [`MIN_OBSERVATIONS`] usable observations is left out entirely and its +/// hits go to `hits_left_out`. +/// +/// The interval is a bootstrap (2000 replicates, fixed seed): each replicate +/// resamples every counted language's observations with replacement, recomputes +/// its mean build time, and totals the saving; the interval is the 5th to 95th +/// percentile of the totals (widened if needed to include the point estimate). +/// +/// What it covers: uncertainty in each language's average build time, given +/// the data seen. What it does not cover: it assumes the compiles that hit the +/// cache would have taken as long as the ones that were actually built, which +/// may not hold (cached compiles may be larger or smaller than the typical +/// miss); nor does it cover errors in `hits` or `hit_read_seconds`, or any +/// drift in build times over time. +pub fn time_saved(langs: &[LanguageHits], hit_read_seconds: f64) -> Saved { + let hit_read = if hit_read_seconds.is_finite() && hit_read_seconds > 0.0 { + hit_read_seconds + } else { + 0.0 + }; + let mut left_out = 0u64; + // (hits, (compiles, seconds) pairs) for counted languages. + let mut counted: Vec<(f64, Vec<(f64, f64)>)> = Vec::new(); + for l in langs { + let data: Vec<(f64, f64)> = l + .obs + .iter() + .filter(|o| usable(o)) + .map(|o| (o.compiles as f64, o.seconds)) + .collect(); + if data.len() < MIN_OBSERVATIONS { + left_out = left_out.saturating_add(l.hits); + } else { + counted.push((l.hits as f64, data)); + } + } + + let saving = |hits: f64, c: f64, s: f64| hits * (s / c - hit_read).max(0.0); + let seconds: f64 = counted + .iter() + .map(|(h, d)| { + let (c, s) = sums(d.iter()); + saving(*h, c, s) + }) + .sum(); + + if counted.is_empty() { + return Saved { + seconds, + interval_90: None, + hits_left_out: left_out, + }; + } + + let mut rng = Rng(SEED); + let mut totals: Vec = Vec::with_capacity(REPLICATES); + for _ in 0..REPLICATES { + let mut total = 0.0; + for (h, d) in &counted { + if *h == 0.0 { + continue; + } + let n = d.len() as u64; + // Two 32-bit draws per 64-bit output; (r * n) >> 32 is in 0..n. + // Two independent accumulator pairs keep the adds from chaining. + let pick = |r: u64| d[((r * n) >> 32) as usize]; + let (mut c, mut s) = (0.0, 0.0); + let (mut c2, mut s2) = (0.0, 0.0); + for _ in 0..d.len() / 2 { + let x = rng.next(); + let (dc, ds) = pick(x >> 32); + let (ec, es) = pick(x & 0xFFFF_FFFF); + c += dc; + s += ds; + c2 += ec; + s2 += es; + } + if d.len() % 2 == 1 { + let (dc, ds) = pick(rng.next() >> 32); + c += dc; + s += ds; + } + let (c, s) = (c + c2, s + s2); + total += saving(*h, c, s); + } + totals.push(total); + } + totals.sort_unstable_by(|a, b| a.total_cmp(b)); + let lo = totals[REPLICATES / 20].min(seconds); + let hi = totals[REPLICATES - REPLICATES / 20 - 1].max(seconds); + Saved { + seconds, + interval_90: Some((lo, hi)), + hits_left_out: left_out, + } +} + +fn sums<'a>(it: impl Iterator) -> (f64, f64) { + it.fold((0.0, 0.0), |(c, s), (dc, ds)| (c + dc, s + ds)) +} + +/// wyrand: a tiny generator, one multiply per output. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0xA076_1D64_78BD_642F); + let m = u128::from(self.0) * u128::from(self.0 ^ 0xE703_7ED1_A0B4_28DB); + (m as u64) ^ ((m >> 64) as u64) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn o(compiles: u64, seconds: f64) -> Observation { + Observation { compiles, seconds } + } + + fn close(a: f64, b: f64) -> bool { + (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1.0) + } + + #[test] + fn empty_and_garbage_give_nothing() { + let t = build_times("Rust", &[]); + assert_eq!(t.language, "Rust"); + assert_eq!(t.compiles, 0); + assert!(t.bins.is_empty()); + let t = build_times( + "Rust", + &[o(0, 1.0), o(1, f64::NAN), o(1, -1.0), o(2, f64::INFINITY)], + ); + assert_eq!(t.compiles, 0); + assert!(t.bins.is_empty()); + } + + #[test] + fn garbage_is_ignored() { + let good = [o(1, 1.0), o(2, 6.0)]; + let mut mixed = good.to_vec(); + mixed.extend([ + o(0, 5.0), + o(3, f64::NAN), + o(1, -2.0), + o(1, f64::NEG_INFINITY), + ]); + assert_eq!(build_times("C", &good), build_times("C", &mixed)); + } + + #[test] + fn bins_cover_edges_and_open_ends() { + // 1 s is exactly edge 12 (1000 ms): lands in the bin starting there. + let t = build_times("C", &[o(1, 1.0)]); + assert_eq!(t.bins.len(), 1); + assert!(close(t.bins[0].from_ms, 1000.0)); + assert!(close(t.bins[0].to_ms, 10f64.powf(3.25))); + assert_eq!(t.bins[0].compiles, 1); + // Just under 1 s goes in the bin below. + let t = build_times("C", &[o(1, 0.9999)]); + assert!(close(t.bins[0].to_ms, 1000.0)); + // Below 1 ms, and zero seconds: first bin, open below. + let t = build_times("C", &[o(1, 0.0001), o(1, 0.0)]); + assert_eq!(t.bins.len(), 1); + assert!(close(t.bins[0].from_ms, 1.0)); + assert!(close(t.bins[0].to_ms, 10f64.powf(0.25))); + assert_eq!(t.bins[0].compiles, 2); + // Above 1000 s: last bin, open above. + let t = build_times("C", &[o(1, 5000.0)]); + assert_eq!(t.bins.len(), 1); + assert!(close(t.bins[0].from_ms, 10f64.powf(5.75))); + assert!(close(t.bins[0].to_ms, 1e6)); + // Exactly 1 ms is in the first bin; exactly 1000 s is in the last. + assert!(close(build_times("C", &[o(1, 0.001)]).bins[0].from_ms, 1.0)); + assert!(close( + build_times("C", &[o(1, 1000.0)]).bins[0].from_ms, + 10f64.powf(5.75) + )); + } + + #[test] + fn bins_span_first_to_last_with_gaps_and_weights() { + // 1 ms (bin 0), 1 s (bin 12). Weight is compiles; avg of (3, 3 s) is 1 s. + let t = build_times("C", &[o(1, 0.001), o(3, 3.0)]); + assert_eq!(t.bins.len(), 13); + assert_eq!(t.bins[0].compiles, 1); + assert_eq!(t.bins[12].compiles, 3); + assert!(t.bins[1..12].iter().all(|b| b.compiles == 0)); + assert_eq!(t.bins.iter().map(|b| b.compiles).sum::(), t.compiles); + // Contiguous edges. + for w in t.bins.windows(2) { + assert!(close(w[0].to_ms, w[1].from_ms)); + } + } + + #[test] + fn weighted_summary_hand_worked() { + // Per-build averages: 1 s (w1), 2 s (w1), 3 s (w2: 6 s over 2 builds). + // Total 4 builds, 9 s: mean 2.25 s. Cumulative weights 1, 2, 4. + // Median: first cumulative >= 2 is 2 s. p90: first >= 3.6 is 3 s. + let t = build_times("Rust", &[o(2, 6.0), o(1, 1.0), o(1, 2.0)]); + assert_eq!(t.compiles, 4); + assert!(close(t.mean_ms, 2250.0)); + assert!(close(t.median_ms, 2000.0)); + assert!(close(t.p90_ms, 3000.0)); + } + + #[test] + fn same_input_same_output() { + let data: Vec = (1..40).map(|i| o(1 + i % 3, 0.5 * i as f64)).collect(); + assert_eq!(build_times("C", &data), build_times("C", &data)); + let l = [LanguageHits { + hits: 300, + obs: &data, + }]; + assert_eq!(time_saved(&l, 0.01), time_saved(&l, 0.01)); + } + + #[test] + fn identical_observations_give_zero_width_interval() { + let data = vec![o(1, 4.0); 20]; + let s = time_saved( + &[LanguageHits { + hits: 100, + obs: &data, + }], + 0.5, + ); + assert!(close(s.seconds, 350.0)); + let (lo, hi) = s.interval_90.unwrap(); + assert_eq!(lo, hi); + assert!(close(lo, s.seconds)); + assert_eq!(s.hits_left_out, 0); + } + + fn spread(amp: f64) -> Vec { + (0..40) + .map(|i| { + o( + 1, + 2.0 + if i % 2 == 0 { amp } else { -amp } * (1.0 + (i % 5) as f64 / 5.0), + ) + }) + .collect() + } + + #[test] + fn wider_spread_wider_interval_and_contains_point() { + let narrow = spread(0.1); + let wide = spread(1.0); + let n = time_saved( + &[LanguageHits { + hits: 1000, + obs: &narrow, + }], + 0.0, + ); + let w = time_saved( + &[LanguageHits { + hits: 1000, + obs: &wide, + }], + 0.0, + ); + let (nl, nh) = n.interval_90.unwrap(); + let (wl, wh) = w.interval_90.unwrap(); + assert!(wh - wl > 3.0 * (nh - nl), "{} vs {}", wh - wl, nh - nl); + assert!(nh - nl > 0.0); + assert!(nl <= n.seconds && n.seconds <= nh); + assert!(wl <= w.seconds && w.seconds <= wh); + } + + #[test] + fn skewed_data_interval_still_contains_point() { + let mut data = vec![o(1, 1.0); 10]; + data.push(o(1, 500.0)); + let s = time_saved( + &[LanguageHits { + hits: 50, + obs: &data, + }], + 0.0, + ); + let (lo, hi) = s.interval_90.unwrap(); + assert!(lo <= s.seconds && s.seconds <= hi); + } + + #[test] + fn small_language_left_out_and_counted() { + let big = vec![o(1, 2.0); MIN_OBSERVATIONS]; + let small = vec![o(1, 100.0); MIN_OBSERVATIONS - 1]; + let mut padded = small.clone(); + padded.extend([o(0, 1.0), o(1, f64::NAN)]); // garbage does not count + let s = time_saved( + &[ + LanguageHits { + hits: 10, + obs: &big, + }, + LanguageHits { + hits: 7, + obs: &small, + }, + LanguageHits { + hits: 5, + obs: &padded, + }, + ], + 0.0, + ); + assert_eq!(s.hits_left_out, 12); + assert!(close(s.seconds, 20.0)); + let only_small = time_saved( + &[LanguageHits { + hits: 7, + obs: &small, + }], + 0.0, + ); + assert_eq!(only_small.interval_90, None); + assert_eq!(only_small.seconds, 0.0); + assert_eq!(only_small.hits_left_out, 7); + assert_eq!(time_saved(&[], 1.0).interval_90, None); + } + + #[test] + fn hit_cost_never_makes_negative_saving() { + let data = vec![o(1, 0.1); 12]; + let s = time_saved( + &[LanguageHits { + hits: 100, + obs: &data, + }], + 5.0, + ); + assert_eq!(s.seconds, 0.0); + assert_eq!(s.interval_90, Some((0.0, 0.0))); + } +}