Bucket in SQLite, draw the build-time bootstrap once, start sccache's server

Speed: the chart's counts come from GROUP BY over the bucket number, so
about 120 rows per table per range reach Rust instead of every saved row;
a range total is one indexed SUM. History counts the rows it hands out.

Build times: crates/stats gains Resampled, which draws the bootstrap once
for a set of languages and applies it to any number of hit sets; the
server keeps it and redraws only when an observation was added. The
views fill build_times, time saved and the 90% interval from the stats
crate, and the time-saved arithmetic of the server is gone.

Starting sccache: when nothing listens where the client looks
(SCCACHE_SERVER_UDS, or 127.0.0.1 at SCCACHE_SERVER_PORT), sccache
--start-server is run once and the counters read again; a failure is
reported as NotRunning and not retried for a minute.

Uses the api's Range::ALL, parse and label.
This commit is contained in:
swaits committed 2026-11-28 11:57:10 -07:00
1 parent 90a6302149
commit 16ba94517b
7 files changed
+1523 -473

No files matched your search

+192 -97
View File
@@ -1,8 +1,10 @@
//! What the service knows right now, and how it is kept up to date.
//! What the service knows right now, and how it is kept up to date. One task polls sccache, and
//! it alone holds the history and makes the views; requests only read what it made.
use std::ffi::{OsStr, OsString};
use std::io::{ErrorKind, Read};
use std::path::PathBuf;
use std::net::{SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
@@ -14,22 +16,18 @@ use serde_json::Value;
use wait_timeout::ChildExt;
use crate::history::{History, Tracker};
use crate::stats::{self, Snapshot};
use crate::view;
use crate::stats::Snapshot;
use crate::view::{self, Builds};
/// How often sccache is asked for its counters.
pub const POLL: Duration = Duration::from_secs(10);
/// A sccache command that takes longer than this counts as failed.
const COMMAND_TIMEOUT: Duration = Duration::from_secs(20);
const PRUNE_EVERY: Duration = Duration::from_secs(86_400);
/// The ranges a view is kept for, in the order they are cached.
pub const RANGES: [Range; 5] = [
Range::Hour,
Range::Day,
Range::Week,
Range::Month,
Range::SinceReset,
];
/// When starting sccache's server fails, it is not tried again sooner than this.
pub const START_EVERY: i64 = 60;
/// The port sccache's server listens on when `SCCACHE_SERVER_PORT` does not say.
const SCCACHE_PORT: u16 = 4226;
pub struct Config {
/// The sccache command the service runs.
@@ -72,32 +70,52 @@ pub struct State {
/// sccache's output of the last good reading, as JSON.
pub raw: Option<Value>,
pub client_version: Option<String>,
/// Why there is no live reading.
/// Why sccache counts as not running.
pub error: Option<String>,
/// What the previous poll and the last saved row saw.
pub tracker: Tracker,
/// One view per range of [`RANGES`], made after every poll.
/// One view per range of [`Range::ALL`], made after every poll.
pub views: Vec<View>,
/// How long making those views took at the last poll.
/// How long making those views took at the last poll, and how many rows the database
/// handed out for it: a count of the work, which does not depend on how busy the machine is.
pub views_took: Duration,
pub views_rows: usize,
/// Whether a failure to save, and the first timing, have already been reported.
pub reported: bool,
}
/// Whether an sccache server is listening.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Probe {
Running,
NotRunning,
/// It could not be told; nothing is started then.
Unknown,
}
pub type Prober = Arc<dyn Fn() -> Probe + Send + Sync>;
pub struct App {
pub cfg: Config,
state: Mutex<State>,
/// Wakes the polling task, as `/api/zero` needs: only that task holds the database.
wake: (Sender<()>, Mutex<Option<Receiver<()>>>),
probe: Prober,
}
impl App {
pub fn new(cfg: Config) -> App {
App::with_probe(cfg, Arc::new(server_listening))
}
/// With a stand-in for the check on sccache's server, as tests need.
pub fn with_probe(cfg: Config, probe: Prober) -> App {
let (send, receive) = channel();
App {
cfg,
state: Mutex::new(State::default()),
wake: (send, Mutex::new(Some(receive))),
probe,
}
}
@@ -108,7 +126,8 @@ impl App {
/// The view made for `range` at the last poll. A request never touches the database.
pub fn view(&self, range: Range) -> View {
let state = self.lock();
match state.views.get(index(range)) {
let index = Range::ALL.iter().position(|r| *r == range).unwrap_or(1);
match state.views.get(index) {
Some(view) => view.clone(),
None => View {
range: Some(range),
@@ -117,80 +136,6 @@ impl App {
}
}
/// Opens the history for the polling task: what is too old is deleted, and what the
/// previous run remembered is taken over.
pub fn open_history(&self, now: i64) -> Result<History, String> {
let file = self.cfg.history.display().to_string();
let history =
History::open(&self.cfg.history).map_err(|e| format!("cannot open {file}: {e}"))?;
history
.prune(now)
.map_err(|e| format!("cannot prune {file}: {e}"))?;
self.lock().tracker = history.tracker();
Ok(history)
}
pub fn poll(&self, history: &History) {
self.poll_at(history, unix_now());
}
/// Asks sccache for its counters and version, records what changed, and makes the views.
pub fn poll_at(&self, history: &History, now: i64) {
let version = run(&self.cfg.sccache, &["--version"])
.ok()
.and_then(|text| {
text.split_whitespace()
.find(|w| w.starts_with(|c: char| c.is_ascii_digit()))
.map(str::to_owned)
});
let read = run(
&self.cfg.sccache,
&["--show-stats", "--stats-format", "json"],
)
.and_then(|text| stats::parse(&text).map(|snapshot| (text, snapshot)));
let mut state = self.lock();
state.client_version = version;
match read {
Ok((text, snapshot)) => {
state.error = None;
state.raw = serde_json::from_str(&text).ok();
state.live = Some(Live {
at: now,
snapshot,
raw_text: text,
});
}
Err(e) => {
state.error = Some(e);
state.live = None;
state.raw = None;
}
}
let file = self.cfg.history.display().to_string();
if let Some(counters) = state.live.as_ref().map(|l| l.snapshot.counters.clone()) {
match history.record(&mut state.tracker, &counters, now) {
Ok(()) => {}
Err(e) if !state.reported => {
state.reported = true;
eprintln!("sccache-dash: cannot save history to {file}: {e}");
}
Err(_) => {}
}
}
let started = Instant::now();
state.views = view::all(history, &state, now);
state.views_took = started.elapsed();
if !state.reported {
state.reported = true;
eprintln!(
"sccache-dash: {} rows of history in {}; the five views take {:.2} ms per poll",
history.row_count().unwrap_or(0),
file,
state.views_took.as_secs_f64() * 1e3
);
}
}
/// Runs `sccache --zero-stats`; the saved history stays as it is.
pub fn zero(&self) -> Result<(), String> {
run(&self.cfg.sccache, &["--zero-stats"])?;
@@ -203,8 +148,8 @@ impl App {
/// until the process ends. This task alone holds the database.
pub fn keep_updated(self: Arc<Self>) {
thread::spawn(move || {
let history = match self.open_history(unix_now()) {
Ok(history) => history,
let mut task = match Task::open(&self.cfg.history, unix_now()) {
Ok(task) => task,
Err(e) => {
eprintln!("sccache-dash: {e}");
std::process::exit(1);
@@ -218,10 +163,10 @@ impl App {
.take();
let mut pruned = Instant::now();
loop {
self.poll(&history);
task.poll(&self, unix_now());
if pruned.elapsed() >= PRUNE_EVERY {
pruned = Instant::now();
if let Err(e) = history.prune(unix_now()) {
if let Err(e) = task.history.prune(unix_now()) {
eprintln!(
"sccache-dash: cannot prune {}: {e}",
self.cfg.history.display()
@@ -239,9 +184,159 @@ impl App {
}
}
/// Where a range's view is kept.
fn index(range: Range) -> usize {
RANGES.iter().position(|r| *r == range).unwrap_or(1)
/// The polling task's own things: the history, whose connection is not shared, and what it has
/// learned of build times.
pub struct Task {
pub history: History,
builds: Builds,
/// When sccache's server was last tried to start, and why it is still not running.
started_at: Option<i64>,
start_error: Option<String>,
}
impl Task {
/// Opens the history file, deleting what is too old.
pub fn open(path: &Path, now: i64) -> Result<Task, String> {
let history = History::open(path)?;
history
.prune(now)
.map_err(|e| format!("cannot prune {}: {e}", path.display()))?;
Ok(Task::with(history))
}
/// An empty history that is never written to disk, for tests.
pub fn memory() -> Task {
Task::with(History::memory().expect("an in-memory database"))
}
fn with(history: History) -> Task {
Task {
history,
builds: Builds::new(),
started_at: None,
start_error: None,
}
}
/// Asks sccache for its counters and version, starting its server if none is listening,
/// records what changed, and makes the views.
pub fn poll(&mut self, app: &App, now: i64) {
let version = run(&app.cfg.sccache, &["--version"]).ok().and_then(|text| {
text.split_whitespace()
.find(|w| w.starts_with(|c: char| c.is_ascii_digit()))
.map(str::to_owned)
});
let mut read = read_stats(&app.cfg.sccache);
// Without a server, `--show-stats` answers with empty counters rather than starting one.
let probe = (app.probe)();
match (probe, read.is_ok()) {
(Probe::NotRunning, true) => match self.start_server(app, now) {
Ok(()) => read = read_stats(&app.cfg.sccache),
Err(e) => self.start_error = Some(e),
},
(Probe::Running | Probe::Unknown, _) => self.start_error = None,
(Probe::NotRunning, false) => {}
}
let mut state = app.lock();
state.client_version = version;
match read {
Ok((text, snapshot)) => {
state.error = self.start_error.clone();
state.raw = serde_json::from_str(&text).ok();
state.live = Some(Live {
at: now,
snapshot,
raw_text: text,
});
}
Err(e) => {
state.error = Some(e);
state.live = None;
state.raw = None;
}
}
if let Some(counters) = state.live.as_ref().map(|l| l.snapshot.counters.clone()) {
match self.history.record(&mut state.tracker, &counters, now) {
Ok(()) => {}
Err(e) if !state.reported => {
state.reported = true;
eprintln!(
"sccache-dash: cannot save history to {}: {e}",
app.cfg.history.display()
);
}
Err(_) => {}
}
}
let started = Instant::now();
self.history.take_fetched();
self.builds.refresh(&self.history);
state.views = view::all(&self.history, &self.builds, &state, now);
state.views_took = started.elapsed();
state.views_rows = self.history.take_fetched();
if !state.reported {
state.reported = true;
eprintln!(
"sccache-dash: {} rows of history in {}; the five views take {:.2} ms and {} rows per poll",
self.history.row_count().unwrap_or(0),
app.cfg.history.display(),
state.views_took.as_secs_f64() * 1e3,
state.views_rows
);
}
}
/// Starts sccache's server when none is listening, at most once a minute. `Err` says why
/// there is none, including when an earlier attempt is still being waited out.
fn start_server(&mut self, app: &App, now: i64) -> Result<(), String> {
if let Some(when) = self.started_at {
if now - when < START_EVERY {
return Err(self
.start_error
.clone()
.unwrap_or_else(|| "no sccache server is running".to_owned()));
}
}
self.started_at = Some(now);
run(&app.cfg.sccache, &["--start-server"])
.map(|_| ())
.map_err(|e| {
format!("no sccache server is running and `sccache --start-server` failed: {e}")
})
}
}
fn read_stats(sccache: &OsStr) -> Result<(String, Snapshot), String> {
run(sccache, &["--show-stats", "--stats-format", "json"])
.and_then(|text| crate::stats::parse(&text).map(|snapshot| (text, snapshot)))
}
/// Whether an sccache server is listening, found the way its client finds it (`get_addr` in
/// sccache 0.18): `SCCACHE_SERVER_UDS` names its socket, otherwise it is on 127.0.0.1 at the
/// port `SCCACHE_SERVER_PORT` gives, 4226 by default. Only a connection is made and closed
/// again: no request is sent, so nothing is started, read or reset.
pub fn server_listening() -> Probe {
if let Some(path) = std::env::var_os("SCCACHE_SERVER_UDS").filter(|p| !p.is_empty()) {
return match std::os::unix::net::UnixStream::connect(path) {
Ok(_) => Probe::Running,
Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::ConnectionRefused) => {
Probe::NotRunning
}
Err(_) => Probe::Unknown,
};
}
let port = std::env::var("SCCACHE_SERVER_PORT")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(SCCACHE_PORT);
match TcpStream::connect_timeout(
&SocketAddr::from(([127, 0, 0, 1], port)),
Duration::from_millis(500),
) {
Ok(_) => Probe::Running,
Err(e) if e.kind() == ErrorKind::ConnectionRefused => Probe::NotRunning,
Err(_) => Probe::Unknown,
}
}
/// Runs sccache and returns what it printed; `Err` says why when it is missing, fails or hangs.
+179 -68
View File
@@ -1,14 +1,17 @@
//! The saved history in one SQLite file. Each row holds what changed since the row before it,
//! so that a range total is one indexed `SELECT SUM(...)`. Rows come at most one a minute and
//! only when sccache's counters changed; a stretch without rows is a gap.
//! so that a range total is one indexed `SELECT SUM(...)` and the chart one `GROUP BY`. Rows come
//! at most one a minute and only when sccache's counters changed; a stretch without rows is a gap.
use std::cell::Cell;
use std::collections::BTreeMap;
use std::path::Path;
use std::time::Duration;
use rusqlite::{params, params_from_iter, Connection, OptionalExtension};
use sccache_dash_api::Totals;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use sccache_dash_stats::Observation;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use crate::stats::{Counters, COMPILE};
@@ -46,6 +49,14 @@ macro_rules! push {
const NAMES: &str = each!(names!());
const DEFS: &str = each!(defs!());
const SUMS: &str = each!(sums!());
const OTHER_TABLES: &str = "
CREATE TABLE IF NOT EXISTS reading_languages (t INTEGER NOT NULL, language TEXT NOT NULL, hits INTEGER NOT NULL, misses INTEGER NOT NULL, errors INTEGER NOT NULL, PRIMARY KEY (t, language)) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS not_cached (t INTEGER NOT NULL, reason TEXT NOT NULL, count INTEGER NOT NULL, PRIMARY KEY (t, reason)) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS build_obs (t INTEGER NOT NULL, language TEXT NOT NULL, compiles INTEGER NOT NULL, seconds REAL NOT NULL, PRIMARY KEY (t, language)) WITHOUT ROWID;
CREATE INDEX IF NOT EXISTS build_obs_language ON build_obs (language);
CREATE TABLE IF NOT EXISTS state (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID;";
/// One point of the histogram of build times: the builds of one language that finished between
/// two polls ten seconds apart.
#[derive(Clone, Debug, PartialEq)]
@@ -67,7 +78,7 @@ pub struct Tracker {
pub row_at: i64,
}
/// One saved row: when it was written, and what had changed since the row before.
/// What the live reading adds since the last saved row.
#[derive(Clone, Debug, PartialEq)]
pub struct Row {
pub t: i64,
@@ -76,8 +87,33 @@ pub struct Row {
pub delta: Counters,
}
/// One bucket of the chart as SQLite adds it up; `b` is the bucket's number.
#[derive(Clone, Debug, PartialEq)]
pub struct BucketRow {
pub b: i64,
pub reset: bool,
/// When the first and the last row in the bucket are dated.
pub first: i64,
pub last: i64,
pub hits: u64,
pub misses: u64,
pub other: u64,
pub errors: u64,
}
/// One language's hits and misses in one bucket of the chart.
#[derive(Clone, Debug, PartialEq)]
pub struct BucketLangs {
pub b: i64,
pub language: String,
pub hits: u64,
pub misses: u64,
}
pub struct History {
conn: Connection,
/// How many rows queries have handed out since the last look: a count of the work done.
fetched: Cell<usize>,
}
impl History {
@@ -103,7 +139,19 @@ impl History {
compilations INTEGER NOT NULL DEFAULT 0, hit_read REAL NOT NULL DEFAULT 0, \
cache_write REAL NOT NULL DEFAULT 0, compile REAL NOT NULL DEFAULT 0);\n{OTHER_TABLES}"
))?;
Ok(History { conn })
Ok(History {
conn,
fetched: Cell::new(0),
})
}
/// How many rows queries handed out since the last look.
pub fn take_fetched(&self) -> usize {
self.fetched.replace(0)
}
fn count(&self, rows: usize) {
self.fetched.set(self.fetched.get() + rows);
}
/// Deletes the rows older than [`KEEP_DAYS`], and says how many went.
@@ -151,10 +199,9 @@ impl History {
if let Some(previous) = &tracker.last_poll {
let (since, _) = c.since(previous);
if let Some((language, _)) = since.one_missed_language() {
let seconds = since.ns[COMPILE] as f64 / NANOS;
self.conn.execute(
"INSERT OR REPLACE INTO build_obs (t, language, compiles, seconds) VALUES (?1, ?2, ?3, ?4)",
params![now, language, since.compilations as i64, seconds],
params![now, language, since.compilations as i64, since.ns[COMPILE] as f64 / NANOS],
)?;
}
}
@@ -166,8 +213,7 @@ impl History {
}
Some(base) => {
let (diff, reset) = c.since(base);
let changed = diff != Counters::default() || reset;
if changed && now - tracker.row_at >= MIN_ROW_SECS {
if (diff != Counters::default() || reset) && now - tracker.row_at >= MIN_ROW_SECS {
self.save(now, &diff, reset)?;
tracker.row_base = Some(c.clone());
tracker.row_at = now;
@@ -192,9 +238,9 @@ impl History {
);
self.conn
.execute(&sql, params_from_iter(values.iter().map(|v| v.as_ref())))?;
let mut langs = self.conn.prepare(
"INSERT INTO reading_languages (t, language, hits, misses, errors) VALUES (?1, ?2, ?3, ?4, ?5)",
)?;
let mut langs = self
.conn
.prepare("INSERT INTO reading_languages (t, language, hits, misses, errors) VALUES (?1, ?2, ?3, ?4, ?5)")?;
for (name, v) in &diff.langs {
langs.execute(params![t, name, v[0] as i64, v[1] as i64, v[2] as i64])?;
}
@@ -207,21 +253,34 @@ impl History {
Ok(())
}
/// The totals of the rows from `from` (inclusive) to `to` (exclusive): one indexed query.
/// `None` when there is no row in that time.
pub fn sums(&self, from: i64, to: i64) -> rusqlite::Result<Option<Totals>> {
let sql = format!("SELECT COUNT(*){SUMS} FROM readings WHERE t >= ?1 AND t < ?2");
/// The counters summed over the rows from `from` (inclusive) to `to` (exclusive): one indexed
/// query. `None` when there is no row in that time. Languages and reasons are not part of it.
pub fn sums(&self, from: i64, to: i64) -> rusqlite::Result<Option<Counters>> {
let sql = format!(
"SELECT COUNT(*){SUMS}, SUM(compilations) AS compilations, SUM(hit_read) AS hit_read, \
SUM(cache_write) AS cache_write, SUM(compile) AS compile FROM readings WHERE t >= ?1 AND t < ?2"
);
self.count(1);
self.conn.query_row(&sql, params![from, to], |row| {
let rows: i64 = row.get(0)?;
let nanos = |name: &str| -> rusqlite::Result<u64> {
Ok((row.get::<_, f64>(name)? * NANOS).round().max(0.0) as u64)
};
Ok(if rows > 0 {
Some(each!(totals_of!(row)))
Some(Counters {
totals: each!(totals_of!(row)),
compilations: row.get::<_, i64>("compilations")?.max(0) as u64,
ns: [nanos("hit_read")?, nanos("cache_write")?, nanos("compile")?],
..Counters::default()
})
} else {
None
})
})
}
/// The rows from `from` (inclusive) to `to` (exclusive), oldest first.
/// The rows from `from` (inclusive) to `to` (exclusive), oldest first, each with what had
/// changed since the row before.
pub fn rows(&self, from: i64, to: i64) -> rusqlite::Result<Vec<Row>> {
let sql = format!(
"SELECT t, reset{NAMES}, compilations, hit_read, cache_write, compile FROM readings WHERE t >= ?1 AND t < ?2 ORDER BY t"
@@ -242,10 +301,62 @@ impl History {
},
})
})?;
rows.collect()
let rows = rows.collect::<rusqlite::Result<Vec<_>>>()?;
self.count(rows.len());
Ok(rows)
}
/// (language, hits, misses, errors) summed over the rows from `from` to `to`.
/// The chart's counts, one row per bucket: bucket `b` holds the rows dated from
/// `from + b * len` on, for `t` below `to`.
pub fn bucket_rows(&self, from: i64, len: i64, to: i64) -> rusqlite::Result<Vec<BucketRow>> {
let sql = "SELECT (t - ?1) / ?2 AS b, MAX(reset) != 0 AS reset, MIN(t) AS first, MAX(t) AS last, \
SUM(hits) AS hits, SUM(misses) AS misses, \
SUM(not_cacheable) + SUM(unsupported_compiler) + SUM(not_compile) AS other, \
SUM(read_errors) + SUM(write_errors) + SUM(other_errors) AS errors \
FROM readings WHERE t >= ?1 AND t < ?3 GROUP BY b";
let mut stmt = self.conn.prepare(sql)?;
let rows = stmt.query_map(params![from, len, to], |row| {
Ok(BucketRow {
b: row.get("b")?,
reset: row.get::<_, i64>("reset")? != 0,
first: row.get("first")?,
last: row.get("last")?,
hits: row.get::<_, i64>("hits")?.max(0) as u64,
misses: row.get::<_, i64>("misses")?.max(0) as u64,
other: row.get::<_, i64>("other")?.max(0) as u64,
errors: row.get::<_, i64>("errors")?.max(0) as u64,
})
})?;
let rows = rows.collect::<rusqlite::Result<Vec<_>>>()?;
self.count(rows.len());
Ok(rows)
}
/// Each language's hits and misses per bucket of the chart.
pub fn bucket_languages(
&self,
from: i64,
len: i64,
to: i64,
) -> rusqlite::Result<Vec<BucketLangs>> {
let mut stmt = self.conn.prepare(
"SELECT (t - ?1) / ?2 AS b, language, SUM(hits) AS hits, SUM(misses) AS misses \
FROM reading_languages WHERE t >= ?1 AND t < ?3 GROUP BY b, language",
)?;
let rows = stmt.query_map(params![from, len, to], |row| {
Ok(BucketLangs {
b: row.get("b")?,
language: row.get(1)?,
hits: row.get::<_, i64>(2)?.max(0) as u64,
misses: row.get::<_, i64>(3)?.max(0) as u64,
})
})?;
let rows = rows.collect::<rusqlite::Result<Vec<_>>>()?;
self.count(rows.len());
Ok(rows)
}
/// (language, [hits, misses, errors]) summed over the rows from `from` to `to`.
pub fn languages(&self, from: i64, to: i64) -> rusqlite::Result<Vec<(String, [u64; 3])>> {
let mut stmt = self.conn.prepare(
"SELECT language, SUM(hits), SUM(misses), SUM(errors) FROM reading_languages WHERE t >= ?1 AND t < ?2 GROUP BY language ORDER BY language",
@@ -260,27 +371,9 @@ impl History {
],
))
})?;
out.collect()
}
/// (t, language, hits, misses) of the rows from `from` to `to`, for the chart.
pub fn language_rows(
&self,
from: i64,
to: i64,
) -> rusqlite::Result<Vec<(i64, String, u64, u64)>> {
let mut stmt = self.conn.prepare(
"SELECT t, language, hits, misses FROM reading_languages WHERE t >= ?1 AND t < ?2 ORDER BY t",
)?;
let out = stmt.query_map(params![from, to], |row| {
Ok((
row.get(0)?,
row.get(1)?,
row.get::<_, i64>(2)?.max(0) as u64,
row.get::<_, i64>(3)?.max(0) as u64,
))
})?;
out.collect()
let out = out.collect::<rusqlite::Result<Vec<_>>>()?;
self.count(out.len());
Ok(out)
}
/// (reason, count) summed over the rows from `from` to `to`.
@@ -291,21 +384,14 @@ impl History {
let out = stmt.query_map(params![from, to], |row| {
Ok((row.get(0)?, row.get::<_, i64>(1)?.max(0) as u64))
})?;
out.collect()
}
/// `requests` summed over the rows from `from` on.
pub fn requests_since(&self, from: i64) -> rusqlite::Result<u64> {
let sum: i64 = self.conn.query_row(
"SELECT COALESCE(SUM(requests), 0) FROM readings WHERE t >= ?1",
[from],
|row| row.get(0),
)?;
Ok(sum.max(0) as u64)
let out = out.collect::<rusqlite::Result<Vec<_>>>()?;
self.count(out.len());
Ok(out)
}
/// When the counters were last seen to be zeroed; `None` when they never were.
pub fn last_reset(&self) -> rusqlite::Result<Option<i64>> {
self.count(1);
self.conn
.query_row("SELECT MAX(t) FROM readings WHERE reset != 0", [], |row| {
row.get(0)
@@ -314,28 +400,59 @@ impl History {
/// The oldest row there is.
pub fn first_row(&self) -> rusqlite::Result<Option<i64>> {
self.count(1);
self.conn
.query_row("SELECT MIN(t) FROM readings", [], |row| row.get(0))
}
/// How many rows there are, all told.
pub fn row_count(&self) -> rusqlite::Result<usize> {
self.conn
.query_row("SELECT COUNT(*) FROM readings", [], |row| row.get(0))
Ok(self
.conn
.query_row("SELECT COUNT(*) FROM readings", [], |row| {
row.get::<_, i64>(0)
})? as usize)
}
/// (seconds spent compiling, compiles) seen for each language, from the build observations.
pub fn build_time_totals(&self) -> rusqlite::Result<BTreeMap<String, (f64, u64)>> {
let mut stmt = self.conn.prepare(
"SELECT language, SUM(seconds), SUM(compiles) FROM build_obs GROUP BY language",
/// `requests` summed over the rows from `from` on.
pub fn requests_since(&self, from: i64) -> rusqlite::Result<u64> {
self.count(1);
let sum: i64 = self.conn.query_row(
"SELECT COALESCE(SUM(requests), 0) FROM readings WHERE t >= ?1",
[from],
|row| row.get(0),
)?;
let out = stmt.query_map([], |row| {
Ok(sum.max(0) as u64)
}
/// How many build observations there are and when the newest one is dated: one row, to tell
/// whether they changed.
pub fn build_obs_stamp(&self) -> rusqlite::Result<(i64, i64)> {
self.count(1);
self.conn.query_row(
"SELECT COUNT(*), COALESCE(MAX(t), 0) FROM build_obs",
[],
|row| Ok((row.get(0)?, row.get(1)?)),
)
}
/// The build observations dated after `after`: (language, what was seen).
pub fn build_obs_after(&self, after: i64) -> rusqlite::Result<Vec<(String, Observation)>> {
let mut stmt = self
.conn
.prepare("SELECT language, compiles, seconds FROM build_obs WHERE t > ?1 ORDER BY t")?;
let out = stmt.query_map([after], |row| {
Ok((
row.get(0)?,
(row.get::<_, f64>(1)?, row.get::<_, i64>(2)?.max(0) as u64),
Observation {
compiles: row.get::<_, i64>(1)?.max(0) as u64,
seconds: row.get(2)?,
},
))
})?;
out.collect()
let out = out.collect::<rusqlite::Result<Vec<_>>>()?;
self.count(out.len());
Ok(out)
}
/// The build-time observations, per language and oldest first: the raw data of the histogram.
@@ -359,13 +476,7 @@ impl History {
.or_default()
.push(obs);
}
self.count(by_language.values().map(Vec::len).sum());
Ok(by_language)
}
}
const OTHER_TABLES: &str = "
CREATE TABLE IF NOT EXISTS reading_languages (t INTEGER NOT NULL, language TEXT NOT NULL, hits INTEGER NOT NULL, misses INTEGER NOT NULL, errors INTEGER NOT NULL, PRIMARY KEY (t, language)) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS not_cached (t INTEGER NOT NULL, reason TEXT NOT NULL, count INTEGER NOT NULL, PRIMARY KEY (t, reason)) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS build_obs (t INTEGER NOT NULL, language TEXT NOT NULL, compiles INTEGER NOT NULL, seconds REAL NOT NULL, PRIMARY KEY (t, language)) WITHOUT ROWID;
CREATE INDEX IF NOT EXISTS build_obs_language ON build_obs (language);
CREATE TABLE IF NOT EXISTS state (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID;";
+368 -201
View File
@@ -1,15 +1,14 @@
//! 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 std::collections::BTreeMap;
use sccache_dash_api::{
Bucket, Language, Problem, Range, Server, Severity, Status, TimeSaved, Timing, View,
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, RANGES};
use crate::history::{History, Row};
use crate::app::State;
use crate::history::{BucketLangs, BucketRow, History, Row};
use crate::pretty;
use crate::stats::{self, Counters, CACHE_WRITE, COMPILE, HIT_READ};
@@ -55,22 +54,197 @@ fn soft<T: Default>(result: rusqlite::Result<T>) -> T {
}
}
/// What a compile of each language takes, from the build observations: the polls after which
/// every build that had finished was of that one language.
#[derive(Default)]
struct Learned(BTreeMap<String, (f64, u64)>);
/// 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)>,
}
impl Learned {
/// (average build time in seconds, compiles it was learned from).
fn build_time(&self, lang: &str) -> Option<(f64, u64)> {
let (seconds, n) = self.0.get(lang).filter(|(_, n)| *n > 0)?;
Some((*seconds / *n as f64, *n))
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,
}
}
/// 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) {
let stamp = soft(h.build_obs_stamp());
if self.stamp == Some(stamp) {
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);
}
/// 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((self.means[self.languages.iter().position(|l| l == language)?]? - hit_read).max(0.0))
}
/// 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
}
}
/// 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 {
learned: Learned,
/// What the live reading adds since the last saved row, dated when it was read.
pending: Option<Row>,
server: Server,
@@ -92,13 +266,12 @@ fn gather(h: &History, st: &State, now: i64) -> Known {
.is_some_and(|p| p.delta.totals.requests > 0)
|| soft(h.requests_since(since + 1)) > 0;
Known {
learned: Learned(soft(h.build_time_totals())),
pending,
server: Server {
status: match live {
None => Status::NotRunning,
Some(_) if changed_recently => Status::Running,
Some(_) => Status::Idle,
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(),
@@ -110,146 +283,119 @@ fn gather(h: &History, st: &State, now: i64) -> Known {
}
}
/// The rough, deliberately low saving: a hit counts only when the build time of its language
/// is known. Also returns the average time a hit took to read, which the chart needs.
fn time_saved(c: &Counters, learned: &Learned) -> (TimeSaved, f64) {
let t = &c.totals;
let hit_read = if t.hits > 0 {
c.ns[HIT_READ] as f64 / t.hits as f64 / 1e9
} else {
0.0
};
let (mut seconds, mut left_out, mut used, mut unknown) = (0.0, 0, Vec::new(), Vec::new());
for (name, v) in &c.langs {
if v[0] == 0 {
continue;
}
match learned.build_time(name) {
Some((build, compiles)) => {
seconds += v[0] as f64 * (build - hit_read).max(0.0);
used.push(format!(
"{} {} (from {} compiles)",
name,
pretty::short(build),
pretty::thousands(compiles)
));
}
None => {
left_out += v[0];
unknown.push((v[0], name));
}
/// 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)),
}
let note = if t.hits == 0 {
"There were no hits in this range, so nothing was saved.".to_owned()
} else if used.is_empty() {
format!(
"Nothing is counted: no build time has been learned yet, which takes polls after which every build that finished was of one language. {} hits left out.",
pretty::thousands(left_out)
)
} else {
let mut note = format!(
"Learned build times: {}. A hit saves that minus the {} average cache read.",
used.join(", "),
pretty::short(hit_read)
);
if left_out > 0 {
unknown.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(b.1)));
let names: Vec<String> = unknown
.iter()
.map(|(hits, name)| format!("{} {name}", pretty::thousands(*hits)))
.collect();
note.push_str(&format!(
" Left out: {} hits ({}), no build time learned for them yet.",
pretty::thousands(left_out),
names.join(", ")
));
}
note
};
(
TimeSaved {
seconds,
hits_left_out: left_out,
note,
interval_90: None,
},
hit_read,
)
bucket.saved_seconds += hits as f64 * builds.saving(name, hit_read).unwrap_or(0.0);
}
/// The chart: at most [`levels::BUCKETS`] buckets from `from` up to and including `to`, each
/// holding the rows dated in it. `live` says the service is running now, so `to` itself was seen.
fn buckets(
rows: &[&Row],
langs: &[(i64, String, u64, u64)],
/// 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,
to: i64,
learned: &Learned,
hit_read: f64,
live: bool,
) -> Vec<Bucket> {
let span = (to - from).max(1);
let len = (span + levels::BUCKETS - 1) / levels::BUCKETS;
let count = ((span + len - 1) / len) as usize;
// The last bucket takes the moment `to` itself, which is always the live reading.
let bucket_of = |t: i64| (((t - from) / len) as usize).min(count - 1);
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: from + i * len,
start: chart.from + i * chart.len,
gap: true,
..Bucket::default()
})
.collect();
for row in rows {
if row.t < from || row.t > to {
continue;
}
let b = &mut out[bucket_of(row.t)];
let t = &row.delta.totals;
b.reset |= row.reset;
b.hits += t.hits;
b.misses += t.misses;
b.other += t.not_cacheable + t.unsupported_compiler + t.not_compile;
b.errors += t.errors();
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 (t, name, hits, misses) in langs {
if *t < from || *t > to {
continue;
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);
}
let b = &mut out[bucket_of(*t)];
match b.languages.iter_mut().find(|(k, _, _)| k == name) {
Some((_, h, m)) => {
*h += hits;
*m += misses;
}
None => b.languages.push((name.clone(), *hits, *misses)),
}
b.saved_seconds += *hits as f64
* learned
.build_time(name)
.map_or(0.0, |(build, _)| (build - hit_read).max(0.0));
}
// 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 times: Vec<i64> = rows
.iter()
.map(|r| r.t)
.filter(|&t| t >= from && t <= to)
.collect();
if live {
times.push(to);
}
for &t in &times {
out[bucket_of(t)].gap = false;
}
for w in times.windows(2) {
if w[1] - w[0] <= levels::GAP_SECS {
for b in &mut out[bucket_of(w[0])..bucket_of(w[1])] {
b.gap = false;
}
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));
@@ -359,13 +505,7 @@ fn problems(c: &Counters, server: &Server) -> Vec<Problem> {
/// The text "Copy Summary" puts on the clipboard.
pub fn summary(view: &View) -> String {
let t = &view.totals;
let range = match view.range {
Some(Range::Hour) => "last hour",
Some(Range::Day) => "last 24 hours",
Some(Range::Week) => "last 7 days",
Some(Range::Month) => "last 30 days",
_ => "since last reset",
};
let range = view.range.map_or("", Range::label);
let hit_rate = match t.hit_rate() {
Some(r) => format!(
"{}% ({} of {} compiles from cache)",
@@ -403,8 +543,16 @@ pub fn summary(view: &View) -> String {
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)\n",
"- Time saved: ~{} (rough{interval})\n",
pretty::hours_and_minutes(view.time_saved.seconds)
);
}
@@ -426,9 +574,16 @@ pub fn summary(view: &View) -> String {
}
/// Makes the view for one range.
fn compute(h: &History, known: &Known, st: &State, range: Range, now: i64) -> View {
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: at the last zeroing for `reset`, a range's length back otherwise.
// 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()))
@@ -440,8 +595,7 @@ fn compute(h: &History, known: &Known, st: &State, range: Range, now: i64) -> Vi
} else {
now + 1
};
// The saved rows are read once: they make the totals and the chart, so the two always agree.
let saved = soft(h.rows(from, to));
let len = ((now - from).max(1) + levels::BUCKETS - 1) / levels::BUCKETS;
let (counters, previous) = match range {
// The counters as they are.
Range::SinceReset => (
@@ -449,32 +603,19 @@ fn compute(h: &History, known: &Known, st: &State, range: Range, now: i64) -> Vi
None,
),
_ => {
let mut counters = Counters::default();
for row in &saved {
counters.add(&row.delta);
}
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)))
(
counters,
soft(h.sums(now - 2 * length(range), from)).map(|p| p.totals),
)
}
};
let mut chart: Vec<&Row> = saved.iter().collect();
let mut langs = soft(h.language_rows(from, to));
if let Some(pending) = &known.pending {
chart.push(pending);
langs.extend(
pending
.delta
.langs
.iter()
.map(|(name, v)| (pending.t, name.clone(), v[0], v[1])),
);
}
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 {
@@ -482,7 +623,14 @@ fn compute(h: &History, known: &Known, st: &State, range: Range, now: i64) -> Vi
avg_cache_write_ms: per(counters.ns[CACHE_WRITE], t.cache_writes),
avg_compile_ms: per(counters.ns[COMPILE], counters.compilations),
};
let (time_saved, hit_read) = time_saved(&counters, &known.learned);
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: saved.seconds,
hits_left_out: saved.hits_left_out,
interval_90: saved.interval_90,
note: builds.note(&counters.langs, hit_read, &saved),
};
let mut languages: Vec<Language> = counters
.langs
.iter()
@@ -513,29 +661,33 @@ fn compute(h: &History, known: &Known, st: &State, range: Range, now: i64) -> Vi
languages,
not_cached,
buckets: buckets(
&chart,
&langs,
from,
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,
&known.learned,
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: Vec::new(),
build_times: builds.times.clone(),
};
view.summary_markdown = summary(&view);
view
}
/// The five views, one per range of [`RANGES`], made after every poll.
pub fn all(h: &History, st: &State, now: i64) -> Vec<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);
RANGES
Range::ALL
.iter()
.map(|&range| compute(h, &known, st, range, now))
.map(|&range| compute(h, builds, st, &known, range, now))
.collect()
}
@@ -583,13 +735,15 @@ mod tests {
/// 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.state, now)[RANGES.iter().position(|r| *r == range).unwrap()]
.clone()
all(&self.history, &self.builds, &self.state, now)
[Range::ALL.iter().position(|r| *r == range).unwrap()]
.clone()
}
}
@@ -611,7 +765,13 @@ mod tests {
raw_text: text.to_owned(),
});
}
Scene { history, state }
let mut builds = Builds::new();
builds.refresh(&history);
Scene {
history,
builds,
state,
}
}
/// The readings, with a live reading at `at` that saw nothing change since the last of them.
@@ -933,24 +1093,25 @@ mod tests {
};
let history = History::memory().unwrap();
let mut tracker = Tracker::default();
for (t, misses) in [(0, 0), (10, 1), (70, 2), (130, 3)] {
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, 3, 0]),
("Rust".to_owned(), [229, 11, 0]),
];
c.totals = Totals {
requests: 3047,
requests: 3055,
hits: 3044,
misses: 3,
cache_writes: 3,
misses: 11,
cache_writes: 11,
..Totals::default()
};
c.compilations = 3;
c.ns = [3_044 * 500_000_000, 3_000_000_000, 3 * 60_000_000_000];
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()
@@ -959,7 +1120,13 @@ mod tests {
tracker: history.tracker(),
..State::default()
};
let mut scene = Scene { history, state };
let mut builds = Builds::new();
builds.refresh(&history);
let mut scene = Scene {
history,
builds,
state,
};
scene.state.live = Some(Live {
at: 240,
snapshot,
@@ -977,7 +1144,7 @@ mod tests {
assert_eq!(ts.hits_left_out, 2082 + 733);
assert_eq!(
ts.note,
"Learned build times: Rust 60 s (from 3 compiles). A hit saves that minus the 500 ms average cache read. Left out: 2,815 hits (2,082 C/C++, 733 Assembler), no build time learned for them yet."
"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!(
@@ -1032,7 +1199,7 @@ mod tests {
);
assert!(
ts.note
.starts_with("Nothing is counted: no build time has been learned yet"),
.starts_with("Nothing is counted: no language has 10 build times seen yet"),
"{}",
ts.note
);
@@ -1060,12 +1227,12 @@ mod tests {
let v = taught().view(Range::Day, 240);
assert_eq!(
v.totals.hit_rate(),
Some(3044.0 / 3047.0),
Some(3044.0 / 3055.0),
"hits out of cacheable compiles"
);
assert_eq!(
v.totals.hit_rate_of_all(),
Some(3044.0 / 3047.0),
Some(3044.0 / 3055.0),
"here every request was a cacheable compile"
);
let mixed = Totals {
@@ -1084,10 +1251,10 @@ mod tests {
assert_eq!(
v.summary_markdown,
"**sccache, last 24 hours**\n\
- Hit rate: 99.9% (3,044 of 3,047 compiles from cache)\n\
- By language: C/C++ 100%, Assembler 100%, Rust 98.7%\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)\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()
@@ -1107,7 +1274,7 @@ mod tests {
plain.state.client_version = Some("0.18.0".to_owned());
assert_eq!(
plain.view(Range::SinceReset, 100).summary_markdown,
"**sccache, since last reset**\n\
"**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\