Merge server round 2: SQL bucketing, histogram and interval, starts sccache

This commit is contained in:
swaits committed 2026-11-28 11:57:33 -07:00
commit 7ab1543315
7 files changed
+1523 -473

No files matched your search

Generated
+465
View File
@@ -0,0 +1,465 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "ascii"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "cc"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "chunked_transfer"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901"
[[package]]
name = "dirs"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"
dependencies = [
"dirs-sys",
]
[[package]]
name = "dirs-sys"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys",
]
[[package]]
name = "errno"
version = "0.3.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "fallible-iterator"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
[[package]]
name = "fallible-streaming-iterator"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
[[package]]
name = "fastrand"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "find-msvc-tools"
version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8"
[[package]]
name = "foldhash"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "getrandom"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
"r-efi",
]
[[package]]
name = "hashbrown"
version = "0.15.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
dependencies = [
"foldhash",
]
[[package]]
name = "hashlink"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1"
dependencies = [
"hashbrown",
]
[[package]]
name = "httpdate"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "include_dir"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "923d117408f1e49d914f1a379a309cffe4f18c05cf4e3d12e613a15fc81bd0dd"
dependencies = [
"include_dir_macros",
]
[[package]]
name = "include_dir_macros"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cab85a7ed0bd5f0e76d93846e0147172bed2e2d3f859bcc33a8d9699cad1a75"
dependencies = [
"proc-macro2",
"quote",
]
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "libredox"
version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d"
dependencies = [
"libc",
]
[[package]]
name = "libsqlite3-sys"
version = "0.35.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "133c182a6a2c87864fe97778797e46c7e999672690dc9fa3ee8e241aa4a9c13f"
dependencies = [
"cc",
"pkg-config",
"vcpkg",
]
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "log"
version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "option-ext"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
[[package]]
name = "pkg-config"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "redox_users"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0"
dependencies = [
"libredox",
"thiserror",
]
[[package]]
name = "rusqlite"
version = "0.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "165ca6e57b20e1351573e3729b958bc62f0e48025386970b6e4d29e7a7e71f3f"
dependencies = [
"bitflags",
"fallible-iterator",
"fallible-streaming-iterator",
"hashlink",
"libsqlite3-sys",
"smallvec",
]
[[package]]
name = "rustix"
version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
]
[[package]]
name = "sccache-dash"
version = "0.1.0"
dependencies = [
"dirs",
"include_dir",
"rusqlite",
"sccache-dash-api",
"sccache-dash-stats",
"serde",
"serde_json",
"tempfile",
"tiny_http",
"wait-timeout",
]
[[package]]
name = "sccache-dash-api"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
]
[[package]]
name = "sccache-dash-stats"
version = "0.1.0"
dependencies = [
"sccache-dash-api",
]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "smallvec"
version = "1.16.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59"
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom",
"once_cell",
"rustix",
"windows-sys",
]
[[package]]
name = "thiserror"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tiny_http"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82"
dependencies = [
"ascii",
"chunked_transfer",
"httpdate",
"log",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "wait-timeout"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
dependencies = [
"libc",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+1
View File
@@ -7,6 +7,7 @@ license.workspace = true
[dependencies]
sccache-dash-api = { path = "../api" }
sccache-dash-stats = { path = "../stats" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tiny_http = "0.12"
+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\
+152 -33
View File
@@ -7,10 +7,10 @@ use std::path::PathBuf;
use std::sync::Arc;
use std::thread;
use sccache_dash::app::{unix_now, App, Config};
use sccache_dash::app::{unix_now, App, Config, Probe, Prober, Task};
use sccache_dash::history::History;
use sccache_dash::stats;
use sccache_dash_api::{Range, Status, Totals, View};
use sccache_dash_api::{Range, Severity, Status, Totals, View};
const LIVE: &str = include_str!("../../../fixtures/live-0.18.0.json");
const ZEROED: &str = "{\"stats\":{\"compile_requests\":0,\"cache_hits\":{\"counts\":{},\"adv_counts\":{}},\"cache_misses\":{\"counts\":{},\"adv_counts\":{}},\"cache_errors\":{\"counts\":{},\"adv_counts\":{}}},\"version\":\"0.18.0\"}";
@@ -36,6 +36,7 @@ printf '%s\n' "$*" >> "$0.log"
case "$1" in
--version) echo 'sccache 0.18.0' ;;
--zero-stats) cp "$0.zeroed" "$0.out" ;;
--start-server) if [ -e "$0.no-start" ]; then echo "Server startup failed: Address in use" >&2; exit 1; fi; cp "$0.live" "$0.out"; touch "$0.running"; echo started ;;
*) cat "$0.out" ;;
esac
"#,
@@ -43,6 +44,8 @@ esac
.unwrap();
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::write(dir.path().join("sccache.out"), LIVE).unwrap();
std::fs::write(dir.path().join("sccache.live"), LIVE).unwrap();
std::fs::write(dir.path().join("sccache.running"), "").unwrap();
std::fs::write(dir.path().join("sccache.zeroed"), ZEROED).unwrap();
Fake {
log: dir.path().join("sccache.log"),
@@ -66,6 +69,24 @@ esac
.collect()
}
/// No server running: `--show-stats` then answers with empty counters, as the real one does.
fn down(&self) {
std::fs::remove_file(self.dir.path().join("sccache.running")).unwrap();
self.answers(ZEROED);
}
/// The stand-in for the check on whether sccache's server is listening.
fn probe(&self) -> Prober {
let marker = self.dir.path().join("sccache.running");
Arc::new(move || {
if marker.exists() {
Probe::Running
} else {
Probe::NotRunning
}
})
}
fn config(&self) -> Config {
Config {
sccache: self.script.clone().into(),
@@ -76,15 +97,15 @@ esac
/// A server on a free port next to an empty history, polled once, answering in the background.
/// The test stands in for the polling task: it holds the history and polls by hand.
fn start(fake: &Fake) -> (Arc<App>, History, SocketAddr) {
let app = Arc::new(App::new(fake.config()));
let history = History::memory().unwrap();
app.poll_at(&history, NOW);
fn start(fake: &Fake) -> (Arc<App>, Task, SocketAddr) {
let app = Arc::new(App::with_probe(fake.config(), fake.probe()));
let mut task = Task::memory();
task.poll(&app, NOW);
let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
let addr = server.server_addr().to_ip().unwrap();
let answering = Arc::clone(&app);
thread::spawn(move || sccache_dash::http::answer(server, answering));
(app, history, addr)
(app, task, addr)
}
/// Sends one raw request (`{port}` stands for the server's port) and returns the whole response.
@@ -119,7 +140,7 @@ fn zero(addr: SocketAddr, host: Option<&str>, origin: Option<&str>) -> (u16, Str
#[test]
fn zero_is_refused_for_a_foreign_origin_or_host() {
let fake = Fake::new();
let (app, history, addr) = start(&fake);
let (app, task, addr) = start(&fake);
// A page anywhere else, in any shape: a bare host, another port, or "null".
for origin in [
@@ -154,7 +175,7 @@ fn zero_is_refused_for_a_foreign_origin_or_host() {
fake.calls()
);
assert_eq!(
history.row_count().unwrap(),
task.history.row_count().unwrap(),
0,
"and nothing was written to the history"
);
@@ -167,7 +188,7 @@ fn zero_is_refused_for_a_foreign_origin_or_host() {
#[test]
fn zero_from_the_dashboard_zeroes_sccache_and_keeps_the_history() {
let fake = Fake::new();
let (app, history, addr) = start(&fake);
let (app, mut task, addr) = start(&fake);
let (code, response) = zero(
addr,
@@ -186,24 +207,24 @@ fn zero_from_the_dashboard_zeroes_sccache_and_keeps_the_history() {
);
// What the polling task then does, woken by the request: it reads the counters again.
app.poll_at(&history, unix_now());
task.poll(&app, unix_now());
let calls = fake.calls();
assert_eq!(calls.iter().filter(|c| *c == "--zero-stats").count(), 2);
assert_eq!(calls.last().unwrap(), "--show-stats --stats-format json");
assert_eq!(
history.row_count().unwrap(),
task.history.row_count().unwrap(),
1,
"the history stays, and the zeroing is one more row"
);
let row = &history.rows(0, i64::MAX).unwrap()[0];
let row = &task.history.rows(0, i64::MAX).unwrap()[0];
assert!(row.reset, "the zeroing shows in the history as a reset");
assert_eq!(
row.delta,
stats::Counters::default(),
"nothing has been compiled since"
);
assert_eq!(history.last_reset().unwrap(), Some(row.t));
assert_eq!(task.history.last_reset().unwrap(), Some(row.t));
let v = app.view(Range::SinceReset);
assert_eq!(
@@ -221,7 +242,7 @@ fn zero_from_the_dashboard_zeroes_sccache_and_keeps_the_history() {
#[test]
fn view_export_and_the_page_answer() {
let fake = Fake::new();
let (_app, _history, addr) = start(&fake);
let (_app, _task, addr) = start(&fake);
let response = send(addr, &format!("GET /api/view?range=reset{GET}"));
assert!(
@@ -243,9 +264,7 @@ fn view_export_and_the_page_answer() {
),
(Some("0.18.0"), Some("0.18.0"))
);
assert!(v
.summary_markdown
.starts_with("**sccache, since last reset**\n"));
assert!(v.summary_markdown.starts_with("**sccache, since reset**\n"));
for range in ["1h", "24h", "7d", "30d"] {
let response = send(addr, &format!("GET /api/view?range={range}{GET}"));
let v: View = serde_json::from_str(response.split("\r\n\r\n").nth(1).unwrap()).unwrap();
@@ -287,38 +306,45 @@ fn view_export_and_the_page_answer() {
#[test]
fn rows_are_saved_when_counters_change_and_at_most_once_a_minute() {
let fake = Fake::new();
let app = App::new(fake.config());
let history = History::memory().unwrap();
let rows = || history.row_count().unwrap();
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::memory();
app.poll_at(&history, NOW);
assert_eq!(rows(), 0, "the first reading is a baseline, not a row");
app.poll_at(&history, NOW + 10);
assert_eq!(rows(), 0, "nothing changed");
task.poll(&app, NOW);
assert_eq!(
task.history.row_count().unwrap(),
0,
"the first reading is a baseline, not a row"
);
task.poll(&app, NOW + 10);
assert_eq!(task.history.row_count().unwrap(), 0, "nothing changed");
fake.answers(&LIVE.replace("\"compile_requests\":7351", "\"compile_requests\":7352"));
app.poll_at(&history, NOW + 30);
task.poll(&app, NOW + 30);
assert_eq!(
rows(),
task.history.row_count().unwrap(),
0,
"changed, but less than a minute after the baseline"
);
app.poll_at(&history, NOW + 60);
assert_eq!(rows(), 1, "a minute on, the change is saved");
let row = &history.rows(0, i64::MAX).unwrap()[0];
task.poll(&app, NOW + 60);
assert_eq!(
task.history.row_count().unwrap(),
1,
"a minute on, the change is saved"
);
let row = &task.history.rows(0, i64::MAX).unwrap()[0];
assert_eq!(
(row.t, row.delta.totals.requests, row.reset),
(NOW + 60, 1, false)
);
app.poll_at(&history, NOW + 700);
task.poll(&app, NOW + 700);
assert_eq!(
rows(),
task.history.row_count().unwrap(),
1,
"unchanged: nothing more is saved, however long the quiet lasts"
);
assert!(
history.build_observations().unwrap().is_empty(),
task.history.build_observations().unwrap().is_empty(),
"and with no misses there is no build observation"
);
assert_eq!(app.lock().views.len(), 5, "every poll makes the five views");
@@ -406,3 +432,96 @@ fn old_rows_are_deleted_at_startup() {
"WAL mode is on"
);
}
#[test]
fn a_missing_sccache_server_is_started_once_then_read() {
let fake = Fake::new();
fake.down();
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::memory();
task.poll(&app, NOW);
let calls = fake.calls();
assert_eq!(
calls.iter().filter(|c| *c == "--start-server").count(),
1,
"{calls:?}"
);
assert_eq!(
calls.last().unwrap(),
"--show-stats --stats-format json",
"the counters are read again after starting"
);
let v = app.view(Range::SinceReset);
assert_eq!(v.server.status, Status::Idle, "{:?}", v.server.error);
assert_eq!(
v.totals,
stats::parse(LIVE).unwrap().counters.totals,
"the started server's counters, not the empty ones"
);
task.poll(&app, NOW + 10);
assert_eq!(
fake.calls()
.iter()
.filter(|c| *c == "--start-server")
.count(),
1,
"not started again while it is running"
);
}
#[test]
fn a_server_that_will_not_start_is_reported_and_not_retried_for_a_minute() {
let fake = Fake::new();
fake.down();
std::fs::write(fake.dir.path().join("sccache.no-start"), "").unwrap();
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::memory();
for at in [NOW, NOW + 10, NOW + 50] {
task.poll(&app, at);
let v = app.view(Range::Day);
assert_eq!(v.server.status, Status::NotRunning, "polled at {at}");
assert!(
v.server
.error
.as_deref()
.is_some_and(|e| e.contains("`sccache --start-server` failed")),
"{:?}",
v.server.error
);
assert!(
v.problems
.iter()
.any(|p| p.severity == Severity::Error && p.title == "sccache is not running"),
"{:?}",
v.problems
);
}
assert_eq!(
fake.calls()
.iter()
.filter(|c| *c == "--start-server")
.count(),
1,
"tried once"
);
task.poll(&app, NOW + 60);
assert_eq!(
fake.calls()
.iter()
.filter(|c| *c == "--start-server")
.count(),
2,
"and again a minute later"
);
// Meanwhile the server came up by itself (a compile started it): no more error. Its counters
// differ from the empty ones, so that counts as compiles having arrived.
std::fs::write(fake.dir.path().join("sccache.running"), "").unwrap();
fake.answers(LIVE);
task.poll(&app, NOW + 70);
assert_eq!(app.view(Range::Day).server.status, Status::Running);
assert_eq!(app.view(Range::Day).server.error, None);
}
+166 -74
View File
@@ -140,87 +140,135 @@ pub struct Saved {
/// 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.
///
/// Several sets of hits over the same observations (one per range, say) should
/// go through [`Resampled`] instead: it draws the bootstrap once.
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);
let obs: Vec<&[Observation]> = langs.iter().map(|l| l.obs).collect();
Resampled::new(&obs).time_saved(langs, hit_read_seconds)
}
/// The bootstrap drawn once for a set of languages, so that the time saved for
/// several sets of hits can be worked out from the same draws: the build times
/// seen are the same for every set, only the hits differ.
#[derive(Debug)]
pub struct Resampled {
/// Per replicate, per language: the resampled (compiles, seconds). A language
/// with too little data has zeros there and is left out.
replicates: Vec<Vec<(f64, f64)>>,
/// Whether each language has enough observations to be counted.
counted: Vec<bool>,
}
impl Resampled {
/// Resamples every language that has [`MIN_OBSERVATIONS`] usable observations.
pub fn new(obs_per_language: &[&[Observation]]) -> Resampled {
let data: Vec<Vec<(f64, f64)>> = obs_per_language.iter().map(|obs| points(obs)).collect();
let counted: Vec<bool> = data.iter().map(|d| d.len() >= MIN_OBSERVATIONS).collect();
let mut rng = Rng(SEED);
let mut replicates = Vec::with_capacity(REPLICATES);
for _ in 0..REPLICATES {
replicates.push(data.iter().map(|d| resample(d, &mut rng)).collect());
}
Resampled {
replicates,
counted,
}
}
/// [`time_saved`] for one set of hits, from the draws already made. `langs`
/// must give each language in the order its observations were given to
/// [`new`](Resampled::new); the slices need not be the same ones.
pub fn time_saved(&self, 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 {
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,
0.0
};
}
let mut rng = Rng(SEED);
let mut totals: Vec<f64> = Vec::with_capacity(REPLICATES);
for _ in 0..REPLICATES {
let mut total = 0.0;
for (h, d) in &counted {
if *h == 0.0 {
continue;
let saving = |hits: f64, c: f64, s: f64| hits * (s / c - hit_read).max(0.0);
let counted = |i: usize| langs.get(i).is_some_and(|_| self.counted[i]);
let mut left_out = 0u64;
let seconds: f64 = langs
.iter()
.enumerate()
.filter(|(i, _)| counted(*i))
.map(|(_, l)| {
let d = points(l.obs);
let (c, s) = sums(d.iter());
saving(l.hits as f64, c, s)
})
.sum();
for (i, l) in langs.iter().enumerate() {
if !counted(i) {
left_out = left_out.saturating_add(l.hits);
}
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);
if langs.is_empty() || !self.counted.iter().take(langs.len()).any(|c| *c) {
return Saved {
seconds,
interval_90: None,
hits_left_out: left_out,
};
}
let mut totals: Vec<f64> = self
.replicates
.iter()
.map(|replicate| {
langs
.iter()
.zip(replicate)
.enumerate()
.filter(|(i, _)| counted(*i))
.map(|(_, (l, (c, s)))| saving(l.hits as f64, *c, *s))
.sum()
})
.collect();
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,
}
}
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,
}
/// The usable observations of a language as (compiles, seconds).
fn points(obs: &[Observation]) -> Vec<(f64, f64)> {
obs.iter()
.filter(|o| usable(o))
.map(|o| (o.compiles as f64, o.seconds))
.collect()
}
/// One bootstrap replicate of a language: its observations drawn with replacement, summed.
/// A language with too little data draws nothing.
fn resample(data: &[(f64, f64)], rng: &mut Rng) -> (f64, f64) {
if data.len() < MIN_OBSERVATIONS {
return (0.0, 0.0);
}
let n = data.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| data[((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..data.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 data.len() % 2 == 1 {
let (dc, ds) = pick(rng.next() >> 32);
c += dc;
s += ds;
}
(c + c2, s + s2)
}
fn sums<'a>(it: impl Iterator<Item = &'a (f64, f64)>) -> (f64, f64) {
@@ -466,3 +514,47 @@ mod tests {
assert_eq!(s.interval_90, Some((0.0, 0.0)));
}
}
#[cfg(test)]
mod resampled {
use super::*;
fn o(compiles: u64, seconds: f64) -> Observation {
Observation { compiles, seconds }
}
#[test]
fn several_hit_sets_from_one_draw_each_match_the_one_shot_call() {
let rust: Vec<Observation> = (0..40).map(|i| o(1, 4.0 + (i % 7) as f64)).collect();
let c: Vec<Observation> = (0..30).map(|i| o(1, 0.2 + 0.01 * (i % 5) as f64)).collect();
let tiny: Vec<Observation> = (0..3).map(|_| o(1, 9.0)).collect();
let draws = Resampled::new(&[&rust, &c, &tiny]);
for (rh, ch, th) in [(120, 40, 5), (0, 40, 5), (120, 0, 0), (1, 1, 1)] {
let langs = [
LanguageHits {
hits: rh,
obs: &rust,
},
LanguageHits { hits: ch, obs: &c },
LanguageHits {
hits: th,
obs: &tiny,
},
];
let once = time_saved(&langs, 0.01);
let again = draws.time_saved(&langs, 0.01);
assert_eq!(once.seconds, again.seconds, "{rh}/{ch}/{th}");
assert_eq!(once.hits_left_out, again.hits_left_out, "{rh}/{ch}/{th}");
assert_eq!(
again.hits_left_out, th,
"a language with three observations is left out"
);
let (lo, hi) = again.interval_90.expect("two languages have enough data");
assert!(
lo <= again.seconds && again.seconds <= hi,
"{rh}/{ch}/{th}: {lo} <= {} <= {hi}",
again.seconds
);
}
}
}