Files
sccache-dash/crates/server/src/view.rs
T
swaits 693dca6cdf Prove the steady cost by count, redraw the bootstrap once a minute, tidy
A test fills a history with a row a minute for thirty days (43,199 rows,
4,319 build observations) in one transaction, runs two polls and asserts
the second hands out fewer than 3,000 rows; it measures 1,567 (the first
reads every observation once). History::fill saves a run of readings as
the polls would have.

While a build keeps adding observations, they are stored at once but the
bootstrap and the histogram are redrawn at most once a minute.

A saving is never negative or a negative zero.

History::rows and History::build_observations are gone, with the tests
that only used them. History::first_row stays: without it the chart of
the reset range, on a database that never saw a zeroing, would start at
the live reading instead of at the first row.

The timing line is logged for the first two polls.
2026-11-28 12:07:56 -07:00

1595 lines
55 KiB
Rust

//! Turning the saved history into the five `View`s the page draws, one per range. They are made
//! after every poll and kept; a request never waits for the database.
use sccache_dash_api::{
Bucket, BuildTimes, Language, Problem, Range, Server, Severity, Status, TimeSaved, Timing, View,
};
use sccache_dash_stats::{LanguageHits, Observation, Resampled, Saved};
use serde_json::Value;
use crate::app::State;
use crate::history::{BucketLangs, BucketRow, History, Row};
use crate::pretty;
use crate::stats::{self, Counters, CACHE_WRITE, COMPILE, HIT_READ};
/// Where each problem starts, all in one place so they can be turned together.
pub mod levels {
use std::time::Duration;
/// A language is reported when fewer than this many of every hundred compiles hit...
pub const LOW_HIT_RATE_PERCENT: u64 = 40;
/// ...and it has at least this many hits and misses.
pub const LOW_HIT_RATE_COMPILES: u64 = 50;
/// Timeouts are reported when more than this many of every hundred executed compiles timed out.
pub const TIMEOUT_PERCENT: u64 = 1;
/// The cache is reported when it holds this many hundredths of its limit.
pub const CACHE_FULL_PERCENT: u64 = 90;
/// Compiles recorded this recently mean sccache is running.
pub const RUNNING_WINDOW: Duration = Duration::from_secs(5 * 60);
/// The chart has at most this many buckets.
pub const BUCKETS: i64 = 120;
/// The build-time bootstrap is drawn again at most this often, however many observations
/// a build in flight keeps adding.
pub const BOOTSTRAP_EVERY_SECS: i64 = 60;
/// While anything changes a row comes at least this often, so a bucket with no row between
/// two rows further apart than this is a gap.
pub const GAP_SECS: i64 = 120;
}
/// The length of each range, in seconds.
fn length(range: Range) -> i64 {
match range {
Range::Hour => 3600,
Range::Day => 86_400,
Range::Week => 7 * 86_400,
Range::Month | Range::SinceReset => 30 * 86_400,
}
}
/// A query that fails reads as "nothing saved": the reason goes to the log, and the poll goes on.
fn soft<T: Default>(result: rusqlite::Result<T>) -> T {
match result {
Ok(value) => value,
Err(e) => {
eprintln!("sccache-dash: cannot read the history: {e}");
T::default()
}
}
}
/// All that the history says about how long a build of each language takes. The build-time data
/// is the same for every range, so its bootstrap is drawn here, once per change.
pub struct Builds {
/// The languages with observations, in the order their observations were given to the draws.
languages: Vec<String>,
obs: Vec<Vec<Observation>>,
/// Each language's histogram, sorted by compiles seen, largest first.
pub times: Vec<BuildTimes>,
/// Each language's average build time in seconds, when it has seen enough to be counted.
means: Vec<Option<f64>>,
draws: Resampled,
/// (how many observations there are, when the newest is dated) this was made from.
stamp: Option<(i64, i64)>,
/// When the bootstrap was last drawn.
drawn_at: Option<i64>,
}
impl Default for Builds {
fn default() -> Self {
Self::new()
}
}
impl Builds {
/// Nothing learned yet.
pub fn new() -> Builds {
Builds {
languages: Vec::new(),
obs: Vec::new(),
times: Vec::new(),
means: Vec::new(),
draws: Resampled::new(&[]),
stamp: None,
drawn_at: None,
}
}
/// Takes in any observations added since the last look, and when there are some works out
/// the histograms and draws the bootstrap again: once per change, not once per range.
pub fn refresh(&mut self, h: &History, now: i64) {
let stamp = soft(h.build_obs_stamp());
if self.stamp == Some(stamp) {
return;
}
// Observations were added, but the bootstrap was drawn less than a minute ago: they wait
// for that beat, so that a build in flight does not have it redrawn on every poll.
if self
.drawn_at
.is_some_and(|at| now - at < levels::BOOTSTRAP_EVERY_SECS)
{
return;
}
let added = match self.stamp {
// Rows were only added: read just those.
Some((count, newest)) if stamp.0 > count && stamp.1 >= newest => {
soft(h.build_obs_after(newest))
}
_ => {
self.languages.clear();
self.obs.clear();
soft(h.build_obs_after(i64::MIN))
}
};
for (language, observation) in added {
let known = self.languages.iter().position(|l| *l == language);
let i = known.unwrap_or_else(|| {
self.languages.push(language.clone());
self.obs.push(Vec::new());
self.languages.len() - 1
});
self.obs[i].push(observation);
}
let mut times: Vec<BuildTimes> = self
.languages
.iter()
.enumerate()
.map(|(i, l)| sccache_dash_stats::build_times(l, &self.obs[i]))
.collect();
self.means = (0..self.languages.len())
.map(|i| counted(&self.obs[i]).then_some(times[i].mean_ms / 1000.0))
.collect();
times.sort_by(|a, b| {
b.compiles
.cmp(&a.compiles)
.then_with(|| a.language.cmp(&b.language))
});
let obs: Vec<&[Observation]> = self.obs.iter().map(Vec::as_slice).collect();
self.draws = Resampled::new(&obs);
self.times = times;
self.stamp = Some(stamp);
self.drawn_at = Some(now);
}
/// Time saved for one range's hits, from the draws already made.
fn saved(&self, hits: &[(String, [u64; 3])], hit_read: f64) -> Saved {
let mut unknown = 0;
let langs: Vec<LanguageHits<'_>> = self
.languages
.iter()
.enumerate()
.map(|(i, name)| LanguageHits {
hits: hits
.iter()
.find(|(n, _)| n == name)
.map_or(0, |(_, v)| v[0]),
obs: &self.obs[i],
})
.collect();
for (name, v) in hits {
if !self.languages.iter().any(|l| l == name) {
unknown += v[0];
}
}
let saved = self.draws.time_saved(&langs, hit_read);
Saved {
hits_left_out: saved.hits_left_out + unknown,
..saved
}
}
/// What one hit of this language saves on average, for the chart; `None` when the language
/// is left out.
fn saving(&self, language: &str, hit_read: f64) -> Option<f64> {
Some(positive(
self.means[self.languages.iter().position(|l| l == language)?]? - hit_read,
))
}
/// How the figure was reached, in plain words with the numbers used.
fn note(&self, hits: &[(String, [u64; 3])], hit_read: f64, saved: &Saved) -> String {
let counted: Vec<String> = hits
.iter()
.filter(|(name, v)| v[0] > 0 && self.saving(name, 0.0).is_some())
.map(|(name, _)| {
let i = self
.languages
.iter()
.position(|l| l == name)
.expect("a language with hits");
let t = &self
.times
.iter()
.find(|t| t.language == *name)
.expect("its histogram");
format!(
"{} {} (from {} builds)",
name,
pretty::short(self.means[i].unwrap_or(0.0)),
pretty::thousands(t.compiles)
)
})
.collect();
let mut left_out: Vec<(u64, &String)> = hits
.iter()
.filter(|(name, v)| v[0] > 0 && self.saving(name, 0.0).is_none())
.map(|(name, v)| (v[0], name))
.collect::<Vec<_>>();
left_out.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(b.1)));
let left_out: Vec<String> = left_out
.iter()
.map(|(hits, name)| format!("{} {name}", pretty::thousands(*hits)))
.collect();
if hits.iter().all(|(_, v)| v[0] == 0) {
return "There were no hits in this range, so nothing was saved.".to_owned();
}
if counted.is_empty() {
return format!(
"Nothing is counted: no language has {} build times seen yet, each the average over the builds that finished between two polls ten seconds apart. {} hits left out.",
sccache_dash_stats::MIN_OBSERVATIONS,
pretty::thousands(saved.hits_left_out)
);
}
let mut note = format!(
"Learned build times: {}. A hit saves that minus the {} average cache read",
counted.join(", "),
pretty::short(hit_read)
);
if let Some((lo, hi)) = saved.interval_90 {
note.push_str(&format!(
"; in 9 of 10 such draws the total falls between {} and {}",
pretty::hours_and_minutes(lo),
pretty::hours_and_minutes(hi)
));
}
note.push('.');
if !left_out.is_empty() {
note.push_str(&format!(
" Left out: {} hits, too few build times seen to count.",
left_out.join(", ")
));
}
note
}
}
/// A saving is never negative, and never a negative zero (which JSON would print as `-0.0`).
fn positive(value: f64) -> f64 {
if value > 0.0 {
value
} else {
0.0
}
}
/// Whether a language has seen enough usable observations for its saving to be counted.
fn counted(obs: &[Observation]) -> bool {
obs.iter()
.filter(|o| o.compiles > 0 && o.seconds.is_finite() && o.seconds >= 0.0)
.count()
>= sccache_dash_stats::MIN_OBSERVATIONS
}
/// What every range needs the same way, gathered once per poll.
struct Known {
/// What the live reading adds since the last saved row, dated when it was read.
pending: Option<Row>,
server: Server,
}
fn gather(h: &History, st: &State, now: i64) -> Known {
let live = st.live.as_ref();
let pending = live.zip(st.tracker.row_base.as_ref()).map(|(live, base)| {
let (delta, reset) = live.snapshot.counters.since(base);
Row {
t: live.at,
reset,
delta,
}
});
let since = now - levels::RUNNING_WINDOW.as_secs() as i64;
let changed_recently = pending
.as_ref()
.is_some_and(|p| p.delta.totals.requests > 0)
|| soft(h.requests_since(since + 1)) > 0;
Known {
pending,
server: Server {
status: match (live, st.error.as_ref()) {
(None, _) | (_, Some(_)) => Status::NotRunning,
(Some(_), None) if changed_recently => Status::Running,
(Some(_), None) => Status::Idle,
},
version: live.and_then(|l| l.snapshot.version.clone()),
client_version: st.client_version.clone(),
cache_location: live.and_then(|l| l.snapshot.cache_location.clone()),
cache_size: live.and_then(|l| l.snapshot.cache_size),
max_cache_size: live.and_then(|l| l.snapshot.max_cache_size),
error: st.error.clone(),
},
}
}
/// A language's hits and misses go into a bucket's list, and its saving into the bucket's.
fn add_language(
bucket: &mut Bucket,
name: &str,
hits: u64,
misses: u64,
builds: &Builds,
hit_read: f64,
) {
match bucket.languages.iter_mut().find(|(k, _, _)| k == name) {
Some((_, h, m)) => {
*h += hits;
*m += misses;
}
None => bucket.languages.push((name.to_owned(), hits, misses)),
}
bucket.saved_seconds += hits as f64 * builds.saving(name, hit_read).unwrap_or(0.0);
}
/// What the chart of one range is drawn from: the rows and languages SQLite added up per
/// bucket of `chart.len` seconds from `chart.from`, and the live reading.
struct Chart<'a> {
rows: &'a [BucketRow],
langs: &'a [BucketLangs],
pending: Option<&'a Row>,
from: i64,
len: i64,
}
/// The chart: at most [`levels::BUCKETS`] buckets up to and including `now`. `live` says the
/// service is running now, so `now` itself was seen.
fn buckets(chart: Chart<'_>, now: i64, builds: &Builds, hit_read: f64, live: bool) -> Vec<Bucket> {
let count = (((now - chart.from).max(1) + chart.len - 1) / chart.len) as usize;
// The last bucket takes the moment `now` itself, which is always the live reading.
let bucket_of = |t: i64| (((t - chart.from) / chart.len) as usize).min(count - 1);
let mut out: Vec<Bucket> = (0..count as i64)
.map(|i| Bucket {
start: chart.from + i * chart.len,
gap: true,
..Bucket::default()
})
.collect();
let add = |b: &mut Bucket, hits: u64, misses: u64, other: u64, errors: u64, reset: bool| {
b.reset |= reset;
b.hits += hits;
b.misses += misses;
b.other += other;
b.errors += errors;
};
for r in chart.rows {
add(
&mut out[(r.b.max(0) as usize).min(count - 1)],
r.hits,
r.misses,
r.other,
r.errors,
r.reset,
);
}
for l in chart.langs {
add_language(
&mut out[(l.b.max(0) as usize).min(count - 1)],
&l.language,
l.hits,
l.misses,
builds,
hit_read,
);
}
if let Some(p) = chart.pending.filter(|p| p.t >= chart.from && p.t <= now) {
let t = &p.delta.totals;
add(
&mut out[bucket_of(p.t)],
t.hits,
t.misses,
t.not_cacheable + t.unsupported_compiler + t.not_compile,
t.errors(),
p.reset,
);
for (name, v) in &p.delta.langs {
add_language(&mut out[bucket_of(p.t)], name, v[0], v[1], builds, hit_read);
}
}
// A bucket is open when a row falls in it, or when it lies between rows less than two
// minutes apart: rows come every minute while anything changes.
let mut first = vec![None::<i64>; count];
let mut last = vec![None::<i64>; count];
for r in chart.rows {
let i = (r.b.max(0) as usize).min(count - 1);
if first[i].is_none_or(|f| r.first < f) {
first[i] = Some(r.first);
}
if last[i].is_none_or(|l| r.last > l) {
last[i] = Some(r.last);
}
}
let mut previous = None;
for i in 0..count {
if let Some(l) = last[i] {
out[i].gap = false;
previous = Some(l);
continue;
}
let next = (i + 1..count)
.find_map(|j| first[j])
.or_else(|| live.then_some(now));
out[i].gap = !previous
.zip(next)
.is_some_and(|(p, n)| n - p <= levels::GAP_SECS);
}
if live {
out[count - 1].gap = false;
}
for b in &mut out {
b.languages.sort_by(|a, b| a.0.cmp(&b.0));
}
out
}
fn problems(c: &Counters, server: &Server) -> Vec<Problem> {
let t = &c.totals;
let (mut errors, mut warnings) = (Vec::new(), Vec::new());
let problem = |severity, title: String, detail: String| Problem {
severity,
title,
detail,
};
if server.status == Status::NotRunning {
errors.push(problem(
Severity::Error,
"sccache is not running".to_owned(),
format!(
"sccache could not be asked for its counters ({}), so compiles may not be cached at all; check that it is installed and run `sccache --show-stats` yourself to see what it says.",
server.error.as_deref().unwrap_or("no answer")
),
));
}
let n = t.errors();
if n > 0 {
errors.push(problem(
Severity::Error,
format!("{n} cache error{}", if n == 1 { "" } else { "s" }),
format!(
"The cache could not be read or written {n} time{} in this range ({} read, {} write, {} other) and those compiles ran from scratch; check that the disk holding the cache has room and sccache may write to it.",
if n == 1 { "" } else { "s" },
pretty::thousands(t.read_errors),
pretty::thousands(t.write_errors),
pretty::thousands(t.other_errors)
),
));
}
if t.executed > 0
&& u128::from(t.timeouts) * 100
> u128::from(t.executed) * u128::from(levels::TIMEOUT_PERCENT)
{
warnings.push(problem(
Severity::Warning,
format!("Timeouts {}%", pretty::pct(t.timeouts as f64 / t.executed as f64)),
format!(
"The cache took too long to answer on {} of {} compiles, more than {}%, and each was then built from scratch; if the cache is on the network check that connection, or give sccache a longer timeout for it.",
pretty::thousands(t.timeouts),
pretty::thousands(t.executed),
levels::TIMEOUT_PERCENT
),
));
}
let mut low: Vec<(&String, u64, u64)> = c
.langs
.iter()
.filter(|(_, v)| {
let n = v[0] + v[1];
n >= levels::LOW_HIT_RATE_COMPILES
&& u128::from(v[0]) * 100 < u128::from(n) * u128::from(levels::LOW_HIT_RATE_PERCENT)
})
.map(|(name, v)| (name, v[0], v[0] + v[1]))
.collect();
low.sort_by(|a, b| (a.1 * b.2).cmp(&(b.1 * a.2)).then_with(|| a.0.cmp(b.0)));
for (name, hits, n) in low {
warnings.push(problem(
Severity::Warning,
format!("{name} hit rate {}%", pretty::pct(hits as f64 / n as f64)),
format!(
"Only {}% of {} {name} compiles came from the cache, so most were rebuilt; a different toolchain, compiler flags or environment makes sccache miss, so compare those between two builds.",
pretty::pct(hits as f64 / n as f64),
pretty::thousands(n)
),
));
}
if let (Some(size), Some(max)) = (server.cache_size, server.max_cache_size) {
if max > 0
&& u128::from(size) * 100 >= u128::from(max) * u128::from(levels::CACHE_FULL_PERCENT)
{
warnings.push(problem(
Severity::Warning,
format!("Cache {}% full", pretty::pct(size as f64 / max as f64)),
format!(
"The cache holds {}, close to its limit; when it is full sccache deletes its oldest entries to make room, which costs hits, so raise the limit (`SCCACHE_CACHE_SIZE`, for example `50G`) if the disk has room.",
pretty::bytes_of(size, max)
),
));
}
}
if let (Some(running), Some(command)) = (&server.version, &server.client_version) {
if running != command {
warnings.push(problem(
Severity::Warning,
"sccache versions differ".to_owned(),
format!(
"The running sccache server is {running} but the `sccache` command is {command}, which can make compiles fail; run `sccache --stop-server` so the next compile starts the new version."
),
));
}
}
errors.extend(warnings);
errors
}
/// The text "Copy Summary" puts on the clipboard.
pub fn summary(view: &View) -> String {
let t = &view.totals;
let range = view.range.map_or("", Range::label);
let hit_rate = match t.hit_rate() {
Some(r) => format!(
"{}% ({} of {} compiles from cache)",
pretty::pct(r),
pretty::thousands(t.hits),
pretty::thousands(t.hits + t.misses)
),
None => "\u{2014} (no cacheable compiles)".to_owned(),
};
let by_language: Vec<String> = view
.languages
.iter()
.map(|l| {
let n = l.hits + l.misses;
let rate = if n == 0 {
"\u{2014}".to_owned()
} else {
format!("{}%", pretty::pct(l.hits as f64 / n as f64))
};
format!("{} {rate}", l.name)
})
.collect();
let mut s = format!(
"**sccache, {range}**\n\
- Hit rate: {hit_rate}\n\
- By language: {}\n\
- Not cacheable: {} \u{b7} Errors: {} \u{b7} Timeouts: {}\n",
if by_language.is_empty() {
"(none)".to_owned()
} else {
by_language.join(", ")
},
pretty::thousands(t.not_cacheable + t.unsupported_compiler + t.not_compile),
pretty::thousands(t.errors()),
pretty::thousands(t.timeouts),
);
if view.time_saved.seconds > 0.0 {
let interval = match view.time_saved.interval_90 {
Some((lo, hi)) => format!(
"; 90% range {} \u{2013} {}",
pretty::hours_and_minutes(lo),
pretty::hours_and_minutes(hi)
),
None => String::new(),
};
s += &format!(
"- Time saved: ~{} (rough{interval})\n",
pretty::hours_and_minutes(view.time_saved.seconds)
);
}
let kind = view
.server
.cache_location
.as_deref()
.and_then(|l| l.split(':').next())
.map_or_else(|| "unknown location".to_owned(), |k| k.to_lowercase());
let sizes = match (view.server.cache_size, view.server.max_cache_size) {
(Some(size), Some(max)) => pretty::bytes_of(size, max),
_ => "size unknown".to_owned(),
};
s += &format!(
"- Cache: {kind}, {sizes} \u{b7} sccache {}\n",
view.server.version.as_deref().unwrap_or("unknown version")
);
s
}
/// Makes the view for one range.
fn compute(
h: &History,
builds: &Builds,
st: &State,
known: &Known,
range: Range,
now: i64,
) -> View {
let live = st.live.as_ref();
// When the chart starts: a range's length back, or at the last zeroing for `reset`.
let from = match range {
Range::SinceReset => soft(h.last_reset())
.or_else(|| soft(h.first_row()))
.unwrap_or_else(|| live.map_or(now, |l| l.at)),
_ => now - length(range),
};
let to = if range == Range::SinceReset {
i64::MAX
} else {
now + 1
};
let len = ((now - from).max(1) + levels::BUCKETS - 1) / levels::BUCKETS;
let (counters, previous) = match range {
// The counters as they are.
Range::SinceReset => (
live.map_or_else(Counters::default, |l| l.snapshot.counters.clone()),
None,
),
_ => {
let mut counters = soft(h.sums(from, to)).unwrap_or_default();
counters.langs = soft(h.languages(from, to));
counters.not_cached = soft(h.reasons(from, to));
if let Some(pending) = &known.pending {
counters.add(&pending.delta);
}
// The period of the same length just before: one indexed SUM.
(
counters,
soft(h.sums(now - 2 * length(range), from)).map(|p| p.totals),
)
}
};
let t = &counters.totals;
let per = |total_ns: u64, n: u64| (n > 0).then(|| total_ns as f64 / n as f64 / 1e6);
let timing = Timing {
avg_hit_read_ms: per(counters.ns[HIT_READ], t.hits),
avg_cache_write_ms: per(counters.ns[CACHE_WRITE], t.cache_writes),
avg_compile_ms: per(counters.ns[COMPILE], counters.compilations),
};
let hit_read = per(counters.ns[HIT_READ], t.hits).unwrap_or(0.0) / 1e3;
let saved = builds.saved(&counters.langs, hit_read);
let time_saved = TimeSaved {
seconds: positive(saved.seconds),
hits_left_out: saved.hits_left_out,
interval_90: saved
.interval_90
.map(|(lo, hi)| (positive(lo), positive(hi))),
note: builds.note(&counters.langs, hit_read, &saved),
};
let mut languages: Vec<Language> = counters
.langs
.iter()
.map(|(name, v)| Language {
name: name.clone(),
hits: v[0],
misses: v[1],
errors: v[2],
})
.collect();
languages.sort_by(|a, b| {
(b.hits + b.misses)
.cmp(&(a.hits + a.misses))
.then_with(|| a.name.cmp(&b.name))
});
let mut not_cached = counters.not_cached.clone();
not_cached.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
let mut view = View {
range: Some(range),
generated_at: now,
problems: problems(&counters, &known.server),
server: known.server.clone(),
totals: counters.totals,
previous,
timing,
time_saved,
languages,
not_cached,
buckets: buckets(
Chart {
rows: &soft(h.bucket_rows(from, len, to)),
langs: &soft(h.bucket_languages(from, len, to)),
pending: known.pending.as_ref(),
from,
len,
},
now,
builds,
hit_read,
live.is_some(),
),
extras: live.map_or_else(Vec::new, |l| stats::extras(&l.snapshot)),
raw: st.raw.clone().unwrap_or(Value::Null),
summary_markdown: String::new(),
build_times: builds.times.clone(),
};
view.summary_markdown = summary(&view);
view
}
/// The five views, one per range, made after every poll.
pub fn all(h: &History, builds: &Builds, st: &State, now: i64) -> Vec<View> {
let known = gather(h, st, now);
Range::ALL
.iter()
.map(|&range| compute(h, builds, st, &known, range, now))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::app::Live;
use crate::history::{History, Tracker};
use sccache_dash_api::Totals;
/// sccache's counters at one moment, as the tests spell out a history.
#[derive(Clone)]
struct Reading {
t: i64,
c: Counters,
}
const LIVE: &str = include_str!("../../../fixtures/live-0.18.0.json");
const NOW: i64 = 100_000;
/// A reading with these totals, all of it Rust, taking 1 s per hit read, 1 s per cache
/// write and 60 s per compile.
fn reading(t: i64, requests: u64, hits: u64, misses: u64) -> Reading {
Reading {
t,
c: Counters {
totals: Totals {
requests,
hits,
misses,
cache_writes: misses,
..Totals::default()
},
compilations: misses,
ns: [
hits * 1_000_000_000,
misses * 1_000_000_000,
misses * 60_000_000_000,
],
langs: vec![("Rust".to_owned(), [hits, misses, 0])],
..Counters::default()
},
}
}
/// A saved history with a state, as the service has them.
struct Scene {
history: History,
builds: Builds,
state: State,
}
impl Scene {
fn view(&self, range: Range, now: i64) -> View {
all(&self.history, &self.builds, &self.state, now)
[Range::ALL.iter().position(|r| *r == range).unwrap()]
.clone()
}
}
fn state(readings: Vec<Reading>, live: Option<(i64, &str)>) -> Scene {
let history = History::memory().unwrap();
let mut tracker = Tracker::default();
for r in readings {
history.record(&mut tracker, &r.c, r.t).unwrap();
}
let mut state = State {
tracker: history.tracker(),
..State::default()
};
if let Some((at, text)) = live {
state.raw = serde_json::from_str(text).ok();
state.live = Some(Live {
at,
snapshot: stats::parse(text).unwrap(),
raw_text: text.to_owned(),
});
}
let mut builds = Builds::new();
builds.refresh(&history, NOW);
Scene {
history,
builds,
state,
}
}
/// The readings, with a live reading at `at` that saw nothing change since the last of them.
fn quiet_since(readings: Vec<Reading>, at: i64) -> Scene {
let counters = readings
.last()
.map_or_else(Counters::default, |r| r.c.clone());
let snapshot = stats::Snapshot {
counters,
..Default::default()
};
let mut scene = state(readings, None);
scene.state.live = Some(Live {
at,
snapshot,
raw_text: String::new(),
});
scene
}
/// A view of the live output with `edit` applied and sccache's command at `client`. It starts
/// with nothing to report: a cache a tenth of its limit and one language with a perfect rate,
/// so that only what `edit` changes is a problem.
fn seen(edit: impl FnOnce(&mut stats::Snapshot), client: &str) -> View {
let mut snapshot = stats::parse(LIVE).unwrap();
snapshot.cache_size = Some(1024 * 1024 * 1024);
snapshot.counters.langs = vec![("C/C++".to_owned(), [2082, 0, 0])];
edit(&mut snapshot);
let mut scene = state(vec![], None);
scene.state.live = Some(Live {
at: 100,
raw_text: LIVE.to_owned(),
snapshot,
});
scene.state.client_version = Some(client.to_owned());
scene.view(Range::SinceReset, 100)
}
/// No reading at all, only the reason.
fn broken(error: &str) -> Scene {
let mut scene = state(vec![], None);
scene.state.error = Some(error.to_owned());
scene
}
fn titles(view: &View) -> Vec<&str> {
view.problems.iter().map(|p| p.title.as_str()).collect()
}
#[test]
fn totals_are_what_changed_between_the_readings_inside_the_range() {
let st = quiet_since(
vec![
reading(0, 100, 50, 50),
reading(60, 130, 62, 68),
reading(120, 160, 74, 86),
reading(180, 200, 90, 110),
],
200,
);
let v = st.view(Range::Hour, 200);
assert_eq!(
v.totals,
Totals {
requests: 100,
hits: 40,
misses: 60,
cache_writes: 60,
..Totals::default()
}
);
assert_eq!(v.previous, None, "nothing was recorded in the hour before");
assert_eq!(
v.languages,
vec![Language {
name: "Rust".to_owned(),
hits: 40,
misses: 60,
errors: 0
}]
);
assert_eq!(
v.timing,
Timing {
avg_hit_read_ms: Some(1000.0),
avg_cache_write_ms: Some(1000.0),
avg_compile_ms: Some(60000.0)
}
);
assert_eq!(
(
v.buckets.len(),
v.buckets.iter().map(|b| b.hits).sum::<u64>()
),
(120, 40)
);
assert_eq!(v.buckets.iter().map(|b| b.other).sum::<u64>(), 0);
assert_eq!(
(v.server.status, v.range),
(Status::Running, Some(Range::Hour)),
"the last change was 20 s ago"
);
}
#[test]
fn previous_is_the_period_of_the_same_length_before() {
let st = state(
vec![
reading(0, 0, 0, 0),
reading(1000, 5, 0, 5),
reading(2000, 10, 0, 10),
reading(3000, 15, 0, 15),
reading(5000, 17, 0, 17),
reading(6000, 19, 0, 19),
reading(7000, 21, 0, 21),
],
None,
);
let v = st.view(Range::Hour, 8000);
assert_eq!(
v.totals.requests, 6,
"the three intervals ending in the last hour"
);
assert_eq!(
v.previous.map(|p| p.requests),
Some(15),
"the three in the hour before"
);
let v = st.view(Range::Day, 8000);
assert_eq!(v.totals.requests, 21);
assert_eq!(v.previous, None, "nothing was saved before that day");
}
#[test]
fn the_first_reading_ever_counts_for_nothing() {
let st = state(
vec![reading(0, 100, 60, 40), reading(60, 130, 80, 50)],
None,
);
let v = st.view(Range::Week, 100);
assert_eq!(
v.totals.requests, 30,
"only what came after the first reading"
);
assert_eq!((v.totals.hits, v.totals.misses), (20, 10));
let fresh = state(vec![], Some((100, LIVE)));
let v = fresh.view(Range::Week, 100);
assert_eq!(
v.totals,
Totals::default(),
"a first live reading is a baseline too"
);
assert_eq!(v.buckets.iter().map(|b| b.hits).sum::<u64>(), 0);
assert_eq!(v.server.status, Status::Idle);
}
#[test]
fn a_reset_in_the_middle_starts_the_count_again() {
// requests 100 -> 130, then sccache was zeroed and went 10 -> 25
let st = state(
vec![
reading(0, 100, 60, 40),
reading(600, 130, 80, 50),
reading(1200, 10, 3, 7),
reading(1800, 25, 9, 16),
],
None,
);
let v = st.view(Range::Hour, 1900);
assert_eq!(
v.totals.requests, 55,
"30 before the reset, then 10 + 15 from zero"
);
assert_eq!(
(v.totals.hits, v.totals.misses),
(29, 26),
"20 + 3 + 6 hits, 10 + 7 + 9 misses"
);
let flagged: Vec<&Bucket> = v.buckets.iter().filter(|b| b.reset).collect();
assert_eq!(
flagged.len(),
1,
"exactly one bucket is marked reset, not {:?}",
v.buckets
.iter()
.filter(|b| b.reset)
.map(|b| b.start)
.collect::<Vec<_>>()
);
let b = flagged[0];
assert!(
(b.start..b.start + 30).contains(&1200),
"the one holding the reading at 1200"
);
assert!((b.hits, b.misses) == (3, 7));
assert_eq!(
v.buckets.iter().map(|b| b.hits).sum::<u64>(),
29,
"the chart adds up to the totals"
);
}
#[test]
fn the_reset_range_shows_the_live_counters_since_they_were_zeroed() {
let st = state(
vec![
reading(0, 100, 60, 40),
reading(600, 130, 80, 50),
reading(1200, 10, 1, 7),
],
Some((1800, LIVE)),
);
let v = st.view(Range::SinceReset, 1800);
let live = stats::parse(LIVE).unwrap().counters;
assert_eq!(v.totals, live.totals, "as they are, not summed");
assert_eq!(v.previous, None);
assert_eq!(
v.timing.avg_hit_read_ms,
Some(2_190_691_578.0 / 3197.0 / 1e6)
);
let starts: Vec<i64> = v.buckets.iter().map(|b| b.start).collect();
assert_eq!((starts.len(), starts[0], starts[119]), (120, 1200, 1795));
assert!(v.buckets[0].reset, "the chart starts at the reset");
assert_eq!(
(v.buckets[0].hits, v.buckets[119].hits, v.buckets[119].reset),
(1, 3196, false)
);
assert_eq!(
v.buckets.iter().map(|b| b.hits).sum::<u64>(),
live.totals.hits,
"3 at the reset, then the rest at the live reading"
);
assert_eq!(
v.buckets.iter().filter(|b| b.gap).count(),
118,
"a row at the reset, the live reading at the end, nothing in between"
);
assert_eq!(
v.languages[0],
Language {
name: "Rust".to_owned(),
hits: 229,
misses: 3256,
errors: 0
}
);
assert_eq!(
v.not_cached[0],
("crate-type".to_owned(), 621),
"largest reason first"
);
assert_eq!(v.raw, serde_json::from_str::<Value>(LIVE).unwrap());
}
#[test]
fn gaps_show_where_nothing_was_recorded() {
// readings at 0 and 60, then the service was off until 4000
let st = state(
vec![
reading(0, 0, 0, 0),
reading(60, 1, 1, 0),
reading(4000, 2, 1, 1),
reading(4120, 3, 1, 2),
],
None,
);
let v = st.view(Range::Hour, 4200);
assert_eq!(v.totals.requests, 2, "the row at 60 is before the range");
let open: Vec<i64> = v
.buckets
.iter()
.filter(|b| !b.gap)
.map(|b| b.start)
.collect();
assert_eq!(
open,
vec![3990, 4020, 4050, 4080, 4110],
"the buckets with a row, and those between rows two minutes apart"
);
assert_eq!(
(
v.buckets[113].misses,
v.buckets[117].misses,
v.buckets[114].misses
),
(1, 1, 0),
"what changed while the service was off counts when it was noticed"
);
// between readings less than ten minutes apart the service was running, just idle
let rows = (0..=10)
.map(|i| reading(i * 60, i as u64, i as u64, 0))
.collect();
let st = state([vec![reading(-600, 0, 0, 0)], rows].concat(), None);
let v = st.view(Range::Hour, 610);
assert_eq!(
v.buckets.iter().filter(|b| b.gap).count(),
101,
"rows every minute keep the stretch from the first row open"
);
}
/// Four polls, after each of which (from the second on) one Rust miss of 60 s had finished:
/// ten seconds apart, then two minutes, so that two rows are saved and three build
/// observations. Then a live reading with hits in three languages and half a second per hit read.
fn taught() -> Scene {
let taught = |misses: u64| Counters {
totals: Totals {
requests: misses,
misses,
cache_writes: misses,
..Totals::default()
},
compilations: misses,
ns: [0, 0, misses * 60_000_000_000],
langs: vec![("Rust".to_owned(), [0, misses, 0])],
..Counters::default()
};
let history = History::memory().unwrap();
let mut tracker = Tracker::default();
for step in 0..12 {
let (t, misses) = (step * 10, step as u64);
history.record(&mut tracker, &taught(misses), t).unwrap();
}
let mut c = stats::parse(LIVE).unwrap().counters;
c.langs = vec![
("Assembler".to_owned(), [733, 0, 0]),
("C/C++".to_owned(), [2082, 0, 0]),
("Rust".to_owned(), [229, 11, 0]),
];
c.totals = Totals {
requests: 3055,
hits: 3044,
misses: 11,
cache_writes: 11,
..Totals::default()
};
c.compilations = 11;
c.ns = [3_044 * 500_000_000, 11_000_000_000, 11 * 60_000_000_000];
let snapshot = stats::Snapshot {
counters: c,
..stats::parse(LIVE).unwrap()
};
let state = State {
tracker: history.tracker(),
..State::default()
};
let mut builds = Builds::new();
builds.refresh(&history, NOW);
let mut scene = Scene {
history,
builds,
state,
};
scene.state.live = Some(Live {
at: 240,
snapshot,
raw_text: String::new(),
});
scene
}
#[test]
fn time_saved_counts_only_languages_whose_build_time_is_known() {
let v = taught().view(Range::Week, 240);
// Rust hits save 60 s minus the 0.5 s average hit read; C/C++ and Assembler are left out
let ts = &v.time_saved;
assert_eq!(ts.seconds, 229.0 * 59.5);
assert_eq!(ts.hits_left_out, 2082 + 733);
assert_eq!(
ts.note,
"Learned build times: Rust 60 s (from 11 builds). A hit saves that minus the 500 ms average cache read; in 9 of 10 such draws the total falls between 3h 47m and 3h 47m. Left out: 2,082 C/C++, 733 Assembler hits, too few build times seen to count."
);
assert_eq!(v.timing.avg_hit_read_ms, Some(500.0));
assert_eq!(
v.timing.avg_compile_ms,
Some(60000.0),
"three compiles of 60 s"
);
let saved: f64 = v.buckets.iter().map(|b| b.saved_seconds).sum();
assert_eq!(saved, ts.seconds, "the chart adds up to the saving");
assert_eq!(
v.buckets[119].saved_seconds, ts.seconds,
"all of it in the bucket of the live reading"
);
}
#[test]
fn an_empty_range_saves_exactly_zero_never_a_negative_zero() {
let c = |misses: u64| Counters {
totals: Totals {
requests: misses,
misses,
cache_writes: misses,
..Totals::default()
},
compilations: misses,
ns: [0, 0, misses * 60_000_000_000],
langs: vec![("Rust".to_owned(), [0, misses, 0])],
..Counters::default()
};
// Twelve polls after each of which one Rust build finished: enough to count Rust. Then a
// live reading with no hit anywhere.
let history = History::memory().unwrap();
let mut tracker = Tracker::default();
for step in 0..12u64 {
history
.record(&mut tracker, &c(step), (step * 10) as i64)
.unwrap();
}
let live = Live {
at: 130,
snapshot: stats::Snapshot {
counters: c(11),
..Default::default()
},
raw_text: String::new(),
};
let state = State {
tracker: history.tracker(),
live: Some(live),
..State::default()
};
let mut builds = Builds::new();
builds.refresh(&history, 130);
assert_eq!(builds.times[0].compiles, 11, "Rust is counted");
let views = all(&history, &builds, &state, 130);
for (range, v) in Range::ALL.iter().zip(&views) {
let ts = &v.time_saved;
assert_eq!((ts.seconds, ts.hits_left_out), (0.0, 0), "{range:?}");
assert!(!ts.seconds.is_sign_negative(), "{range:?}: {}", ts.seconds);
let json = serde_json::to_string(ts).unwrap();
assert!(!json.contains('-'), "{range:?}: no minus sign in {json}");
assert!(
v.buckets
.iter()
.all(|b| b.saved_seconds == 0.0 && !b.saved_seconds.is_sign_negative()),
"{range:?}"
);
}
}
#[test]
fn time_saved_is_zero_and_explained_when_nothing_is_learned() {
let assembler = |hits: u64| Counters {
totals: Totals {
requests: hits,
hits,
..Totals::default()
},
ns: [hits * 1_000_000_000, 0, 0],
langs: vec![("Assembler".to_owned(), [hits, 0, 0])],
..Counters::default()
};
let snapshot = stats::Snapshot {
counters: assembler(3187),
..stats::Snapshot::default()
};
let mut st = state(
vec![
reading(0, 0, 0, 0),
Reading {
t: 60,
c: assembler(10),
},
],
None,
);
st.state.live = Some(Live {
at: 120,
snapshot,
raw_text: String::new(),
});
let ts = st.view(Range::Day, 120).time_saved;
assert_eq!(
(ts.seconds, ts.hits_left_out),
(0.0, 10 + 3177),
"10 hits in the saved reading, 3,177 more in the live one"
);
assert!(
ts.note
.starts_with("Nothing is counted: no language has 10 build times seen yet"),
"{}",
ts.note
);
assert!(ts.note.ends_with("3,187 hits left out."), "{}", ts.note);
let only_misses = state(vec![reading(0, 0, 0, 5)], None)
.view(Range::Day, 60)
.time_saved;
assert_eq!(
(
only_misses.seconds,
only_misses.hits_left_out,
only_misses.note.as_str()
),
(
0.0,
0,
"There were no hits in this range, so nothing was saved."
)
);
}
#[test]
fn both_hit_rates_and_the_summary_text() {
let v = taught().view(Range::Day, 240);
assert_eq!(
v.totals.hit_rate(),
Some(3044.0 / 3055.0),
"hits out of cacheable compiles"
);
assert_eq!(
v.totals.hit_rate_of_all(),
Some(3044.0 / 3055.0),
"here every request was a cacheable compile"
);
let mixed = Totals {
requests: 100,
executed: 80,
hits: 40,
misses: 40,
not_cacheable: 20,
..Totals::default()
};
assert_eq!(
(mixed.hit_rate(), mixed.hit_rate_of_all()),
(Some(0.5), Some(0.4)),
"the second counts every compiler call"
);
assert_eq!(
v.summary_markdown,
"**sccache, last 24 hours**\n\
- Hit rate: 99.6% (3,044 of 3,055 compiles from cache)\n\
- By language: C/C++ 100%, Assembler 100%, Rust 95.4%\n\
- Not cacheable: 0 \u{b7} Errors: 0 \u{b7} Timeouts: 0\n\
- Time saved: ~3h 47m (rough; 90% range 3h 47m \u{2013} 3h 47m)\n\
- Cache: local disk, 10.0 of 10.0 GB \u{b7} sccache 0.18.0\n"
);
assert!(taught()
.view(Range::Hour, 240)
.summary_markdown
.starts_with("**sccache, last hour**\n"));
assert!(taught()
.view(Range::Week, 240)
.summary_markdown
.starts_with("**sccache, last 7 days**\n"));
assert!(taught()
.view(Range::Month, 240)
.summary_markdown
.starts_with("**sccache, last 30 days**\n"));
let mut plain = state(vec![], Some((100, LIVE)));
plain.state.client_version = Some("0.18.0".to_owned());
assert_eq!(
plain.view(Range::SinceReset, 100).summary_markdown,
"**sccache, since reset**\n\
- Hit rate: 49.5% (3,197 of 6,453 compiles from cache)\n\
- By language: Rust 6.6%, C/C++ 100%, Assembler 100%\n\
- Not cacheable: 856 \u{b7} Errors: 0 \u{b7} Timeouts: 0\n\
- Cache: local disk, 10.0 of 10.0 GB \u{b7} sccache 0.18.0\n",
"nothing is learned, so there is no time-saved line"
);
assert_eq!(
titles(&seen(|_| {}, "0.18.0")),
Vec::<&str>::new(),
"and the untouched starting point has no problems"
);
let empty = broken("").view(Range::Hour, 0);
assert_eq!(
empty.summary_markdown,
"**sccache, last hour**\n\
- Hit rate: \u{2014} (no cacheable compiles)\n\
- By language: (none)\n\
- Not cacheable: 0 \u{b7} Errors: 0 \u{b7} Timeouts: 0\n\
- Cache: unknown location, size unknown \u{b7} sccache unknown version\n"
);
}
#[test]
fn every_problem_and_its_level() {
const GIB: u64 = 1024 * 1024 * 1024;
let v = seen(|s| s.cache_size = Some(9 * GIB), "0.18.0");
assert_eq!(
titles(&v),
["Cache 90% full"],
"exactly 90% of the 10 GiB limit is a problem"
);
assert_eq!(v.problems[0].severity, Severity::Warning);
assert!(v.problems[0]
.detail
.starts_with("The cache holds 9.0 of 10.0 GB, close to its limit;"));
assert!(
seen(|s| s.cache_size = Some(9 * GIB - 1), "0.18.0")
.problems
.is_empty(),
"one byte under is not"
);
assert!(
seen(|s| s.max_cache_size = None, "0.18.0")
.problems
.is_empty(),
"nor is an unknown limit"
);
assert_eq!(
titles(&seen(|s| s.cache_size = Some(10 * GIB), "0.18.0")),
["Cache 100% full"]
);
let over = |timeouts| {
seen(
|s| {
s.counters.totals.executed = 1000;
s.counters.totals.timeouts = timeouts;
},
"0.18.0",
)
};
assert_eq!(
titles(&over(11)),
["Timeouts 1.1%"],
"11 of 1,000 executed compiles"
);
assert!(over(10).problems.is_empty(), "exactly 1% is not over 1%");
assert!(
seen(|s| s.counters.totals.timeouts = 50, "0.18.0")
.problems
.is_empty(),
"50 of 6,495 is not either"
);
let rate = |langs: Vec<(&str, [u64; 3])>| {
seen(
|s| s.counters.langs = langs.into_iter().map(|(n, v)| (n.to_owned(), v)).collect(),
"0.18.0",
)
};
assert_eq!(
titles(&rate(vec![("Rust", [4, 46, 0])])),
["Rust hit rate 8%"]
);
assert!(rate(vec![("Rust", [4, 46, 0])]).problems[0]
.detail
.starts_with("Only 8% of 50 Rust compiles came from the cache, so most were rebuilt;"));
assert!(
rate(vec![("Rust", [19, 30, 0])]).problems.is_empty(),
"49 compiles is too few to say"
);
assert!(
rate(vec![("Rust", [20, 30, 0])]).problems.is_empty(),
"40% is not under 40%"
);
assert!(
rate(vec![("Rust", [49, 1, 0])]).problems.is_empty(),
"a high hit rate is fine"
);
assert_eq!(
titles(&rate(vec![("C", [1, 49, 0]), ("Rust", [4, 46, 0])])),
["C hit rate 2%", "Rust hit rate 8%"],
"worst first"
);
let v = seen(|s| s.counters.totals.read_errors = 1, "0.18.0");
assert_eq!(
(v.problems[0].severity, v.problems[0].title.as_str()),
(Severity::Error, "1 cache error")
);
assert!(v.problems[0].detail.contains(
"1 time in this range (1 read, 0 write, 0 other) and those compiles ran from scratch;"
));
assert_eq!(
titles(&seen(|s| s.counters.totals.write_errors = 2, "0.18.0")),
["2 cache errors"]
);
assert_eq!(
titles(&seen(|s| s.counters.totals.other_errors = 3, "0.18.0")),
["3 cache errors"],
"per-language cache errors count too"
);
let v = seen(|_| {}, "0.19.0");
assert_eq!(
(
v.problems.len(),
v.problems[0].severity,
v.problems[0].title.as_str()
),
(1, Severity::Warning, "sccache versions differ")
);
assert!(v.problems[0]
.detail
.contains("The running sccache server is 0.18.0 but the `sccache` command is 0.19.0"));
let off = broken("`sccache --show-stats --stats-format json`: command not found");
let v = off.view(Range::Hour, 100);
assert_eq!(v.server.status, Status::NotRunning);
assert_eq!(
v.server.error.as_deref(),
Some("`sccache --show-stats --stats-format json`: command not found")
);
assert_eq!(
(
v.problems.len(),
v.problems[0].severity,
v.problems[0].title.as_str()
),
(1, Severity::Error, "sccache is not running")
);
assert!(v.problems[0]
.detail
.contains("run `sccache --show-stats` yourself to see what it says."));
let all = seen(
|s| {
s.cache_size = Some(10 * GIB);
s.counters.totals.timeouts = 300;
s.counters.totals.read_errors = 4;
s.counters.langs = vec![("Rust".to_owned(), [4, 46, 0])];
},
"0.19.1",
);
assert_eq!(
all.problems
.iter()
.map(|p| (p.severity, p.title.as_str()))
.collect::<Vec<_>>(),
vec![
(Severity::Error, "4 cache errors"),
(Severity::Warning, "Timeouts 4.6%"),
(Severity::Warning, "Rust hit rate 8%"),
(Severity::Warning, "Cache 100% full"),
(Severity::Warning, "sccache versions differ"),
],
"most serious first"
);
assert!(
all.problems
.iter()
.all(|p| p.detail.split(". ").count() == 1 && p.detail.ends_with('.')),
"each detail is one sentence: {:?}",
all.problems
);
}
#[test]
fn running_means_compiles_in_the_last_five_minutes() {
let readings = vec![reading(0, 0, 0, 0), reading(1000, 5, 0, 5)];
assert_eq!(
quiet_since(readings.clone(), 1200)
.view(Range::Hour, 1200)
.server
.status,
Status::Running,
"a compile 200 s ago"
);
assert_eq!(
quiet_since(readings, 1300)
.view(Range::Hour, 1300)
.server
.status,
Status::Idle,
"the last compile was 300 s ago"
);
assert_eq!(
state(vec![reading(0, 0, 0, 5)], None)
.view(Range::Hour, 100)
.server
.status,
Status::NotRunning,
"no live reading at all"
);
let c = stats::parse(LIVE).unwrap().counters;
let mut changed = c.clone();
changed.totals.requests -= 3;
let quiet = state(vec![Reading { t: 0, c }], Some((1100, LIVE)));
assert_eq!(
quiet.view(Range::Hour, 1100).server.status,
Status::Idle,
"nothing changed since the last reading"
);
let busy = state(vec![Reading { t: 0, c: changed }], Some((1100, LIVE)));
assert_eq!(
busy.view(Range::Hour, 1100).server.status,
Status::Running,
"the live reading saw three compiles"
);
}
}