diff --git a/crates/server/src/app.rs b/crates/server/src/app.rs index f906a0f..f2f0b5b 100644 --- a/crates/server/src/app.rs +++ b/crates/server/src/app.rs @@ -80,8 +80,10 @@ pub struct State { /// 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 a failure to save has already been reported. + pub warned: bool, + /// How many polls have had their timing reported: the first two. + pub reported: u8, } /// Whether an sccache server is listening. @@ -258,8 +260,8 @@ impl Task { 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; + Err(e) if !state.warned => { + state.warned = true; eprintln!( "sccache-dash: cannot save history to {}: {e}", app.cfg.history.display() @@ -270,12 +272,14 @@ impl Task { } let started = Instant::now(); self.history.take_fetched(); - self.builds.refresh(&self.history); + self.builds.refresh(&self.history, now); 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; + // Reported for the first two polls: the first reads the build observations and draws the + // bootstrap, the second shows what every later poll costs. + if state.reported < 2 { + state.reported += 1; eprintln!( "sccache-dash: {} rows of history in {}; the five views take {:.2} ms and {} rows per poll", self.history.row_count().unwrap_or(0), diff --git a/crates/server/src/history.rs b/crates/server/src/history.rs index ade8c88..60f0802 100644 --- a/crates/server/src/history.rs +++ b/crates/server/src/history.rs @@ -3,7 +3,6 @@ //! 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; @@ -57,16 +56,6 @@ CREATE TABLE IF NOT EXISTS build_obs (t INTEGER NOT NULL, language TEXT NOT NULL 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)] -pub struct BuildObs { - pub t: i64, - pub language: String, - pub compiles: u64, - pub seconds: f64, -} - /// What is remembered between polls, so that differences survive a restart of sccache-dash. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Tracker { @@ -187,6 +176,17 @@ impl History { Ok(()) } + /// Saves a run of readings exactly as the polls would have, in one transaction. + pub fn fill(&self, readings: &[(i64, Counters)]) -> rusqlite::Result<()> { + self.conn.execute_batch("BEGIN")?; + let mut tracker = self.tracker(); + let result = readings + .iter() + .try_for_each(|(t, c)| self.record(&mut tracker, c, *t)); + self.conn.execute_batch("COMMIT")?; + result + } + /// What the previous run of sccache-dash remembered, so that it carries on where it stopped. pub fn tracker(&self) -> Tracker { self.state("tracker").unwrap_or_default() @@ -279,33 +279,6 @@ impl History { }) } - /// 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> { - let sql = format!( - "SELECT t, reset{NAMES}, compilations, hit_read, cache_write, compile FROM readings WHERE t >= ?1 AND t < ?2 ORDER BY t" - ); - let mut stmt = self.conn.prepare(&sql)?; - let rows = stmt.query_map(params![from, to], |row| { - let nanos = |name: &str| -> rusqlite::Result { - Ok((row.get::<_, f64>(name)? * NANOS).round().max(0.0) as u64) - }; - Ok(Row { - t: row.get("t")?, - reset: row.get::<_, i64>("reset")? != 0, - delta: 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() - }, - }) - })?; - let rows = rows.collect::>>()?; - self.count(rows.len()); - Ok(rows) - } - /// 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> { @@ -398,7 +371,7 @@ impl History { }) } - /// The oldest row there is. + /// The oldest row there is: where the `reset` chart starts when no zeroing was ever seen. pub fn first_row(&self) -> rusqlite::Result> { self.count(1); self.conn @@ -454,29 +427,4 @@ impl History { self.count(out.len()); Ok(out) } - - /// The build-time observations, per language and oldest first: the raw data of the histogram. - pub fn build_observations(&self) -> rusqlite::Result>> { - let mut stmt = self - .conn - .prepare("SELECT t, language, compiles, seconds FROM build_obs ORDER BY language, t")?; - let out = stmt.query_map([], |row| { - Ok(BuildObs { - t: row.get(0)?, - language: row.get(1)?, - compiles: row.get::<_, i64>(2)?.max(0) as u64, - seconds: row.get(3)?, - }) - })?; - let mut by_language: BTreeMap> = BTreeMap::new(); - for obs in out { - let obs = obs?; - by_language - .entry(obs.language.clone()) - .or_default() - .push(obs); - } - self.count(by_language.values().map(Vec::len).sum()); - Ok(by_language) - } } diff --git a/crates/server/src/view.rs b/crates/server/src/view.rs index 230882f..694a28a 100644 --- a/crates/server/src/view.rs +++ b/crates/server/src/view.rs @@ -28,6 +28,9 @@ pub mod levels { pub const RUNNING_WINDOW: Duration = Duration::from_secs(5 * 60); /// The chart has at most this many buckets. pub const BUCKETS: i64 = 120; + /// The build-time bootstrap is drawn again at most this often, however many observations + /// a build in flight keeps adding. + pub const BOOTSTRAP_EVERY_SECS: i64 = 60; /// While anything changes a row comes at least this often, so a bucket with no row between /// two rows further apart than this is a gap. pub const GAP_SECS: i64 = 120; @@ -67,6 +70,8 @@ pub struct Builds { draws: Resampled, /// (how many observations there are, when the newest is dated) this was made from. stamp: Option<(i64, i64)>, + /// When the bootstrap was last drawn. + drawn_at: Option, } impl Default for Builds { @@ -85,16 +90,25 @@ impl Builds { means: Vec::new(), draws: Resampled::new(&[]), stamp: None, + drawn_at: None, } } /// Takes in any observations added since the last look, and when there are some works out /// the histograms and draws the bootstrap again: once per change, not once per range. - pub fn refresh(&mut self, h: &History) { + pub fn refresh(&mut self, h: &History, now: i64) { let stamp = soft(h.build_obs_stamp()); if self.stamp == Some(stamp) { return; } + // Observations were added, but the bootstrap was drawn less than a minute ago: they wait + // for that beat, so that a build in flight does not have it redrawn on every poll. + if self + .drawn_at + .is_some_and(|at| now - at < levels::BOOTSTRAP_EVERY_SECS) + { + return; + } let added = match self.stamp { // Rows were only added: read just those. Some((count, newest)) if stamp.0 > count && stamp.1 >= newest => { @@ -133,6 +147,7 @@ impl Builds { self.draws = Resampled::new(&obs); self.times = times; self.stamp = Some(stamp); + self.drawn_at = Some(now); } /// Time saved for one range's hits, from the draws already made. @@ -165,7 +180,9 @@ impl Builds { /// 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 { - Some((self.means[self.languages.iter().position(|l| l == language)?]? - hit_read).max(0.0)) + Some(positive( + self.means[self.languages.iter().position(|l| l == language)?]? - hit_read, + )) } /// How the figure was reached, in plain words with the numbers used. @@ -235,6 +252,15 @@ impl Builds { } } +/// A saving is never negative, and never a negative zero (which JSON would print as `-0.0`). +fn positive(value: f64) -> f64 { + if value > 0.0 { + value + } else { + 0.0 + } +} + /// Whether a language has seen enough usable observations for its saving to be counted. fn counted(obs: &[Observation]) -> bool { obs.iter() @@ -626,9 +652,11 @@ fn compute( 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, + seconds: positive(saved.seconds), hits_left_out: saved.hits_left_out, - interval_90: saved.interval_90, + interval_90: saved + .interval_90 + .map(|(lo, hi)| (positive(lo), positive(hi))), note: builds.note(&counters.langs, hit_read, &saved), }; let mut languages: Vec = counters @@ -706,6 +734,7 @@ mod tests { } const LIVE: &str = include_str!("../../../fixtures/live-0.18.0.json"); + const NOW: i64 = 100_000; /// A reading with these totals, all of it Rust, taking 1 s per hit read, 1 s per cache /// write and 60 s per compile. @@ -766,7 +795,7 @@ mod tests { }); } let mut builds = Builds::new(); - builds.refresh(&history); + builds.refresh(&history, NOW); Scene { history, builds, @@ -1121,7 +1150,7 @@ mod tests { ..State::default() }; let mut builds = Builds::new(); - builds.refresh(&history); + builds.refresh(&history, NOW); let mut scene = Scene { history, builds, @@ -1160,6 +1189,62 @@ mod tests { ); } + #[test] + fn an_empty_range_saves_exactly_zero_never_a_negative_zero() { + let c = |misses: u64| Counters { + totals: Totals { + requests: misses, + misses, + cache_writes: misses, + ..Totals::default() + }, + compilations: misses, + ns: [0, 0, misses * 60_000_000_000], + langs: vec![("Rust".to_owned(), [0, misses, 0])], + ..Counters::default() + }; + // Twelve polls after each of which one Rust build finished: enough to count Rust. Then a + // live reading with no hit anywhere. + let history = History::memory().unwrap(); + let mut tracker = Tracker::default(); + for step in 0..12u64 { + history + .record(&mut tracker, &c(step), (step * 10) as i64) + .unwrap(); + } + let live = Live { + at: 130, + snapshot: stats::Snapshot { + counters: c(11), + ..Default::default() + }, + raw_text: String::new(), + }; + let state = State { + tracker: history.tracker(), + live: Some(live), + ..State::default() + }; + let mut builds = Builds::new(); + builds.refresh(&history, 130); + assert_eq!(builds.times[0].compiles, 11, "Rust is counted"); + + let views = all(&history, &builds, &state, 130); + for (range, v) in Range::ALL.iter().zip(&views) { + let ts = &v.time_saved; + assert_eq!((ts.seconds, ts.hits_left_out), (0.0, 0), "{range:?}"); + assert!(!ts.seconds.is_sign_negative(), "{range:?}: {}", ts.seconds); + let json = serde_json::to_string(ts).unwrap(); + assert!(!json.contains('-'), "{range:?}: no minus sign in {json}"); + assert!( + v.buckets + .iter() + .all(|b| b.saved_seconds == 0.0 && !b.saved_seconds.is_sign_negative()), + "{range:?}" + ); + } + } + #[test] fn time_saved_is_zero_and_explained_when_nothing_is_learned() { let assembler = |hits: u64| Counters { diff --git a/crates/server/tests/http.rs b/crates/server/tests/http.rs index 290d975..cb04c34 100644 --- a/crates/server/tests/http.rs +++ b/crates/server/tests/http.rs @@ -217,14 +217,15 @@ fn zero_from_the_dashboard_zeroes_sccache_and_keeps_the_history() { 1, "the history stays, and the zeroing is one more row" ); - let row = &task.history.rows(0, i64::MAX).unwrap()[0]; - assert!(row.reset, "the zeroing shows in the history as a reset"); + assert!( + task.history.last_reset().unwrap().is_some(), + "the zeroing shows in the history as a reset" + ); assert_eq!( - row.delta, - stats::Counters::default(), + task.history.sums(0, i64::MAX).unwrap(), + Some(stats::Counters::default()), "nothing has been compiled since" ); - assert_eq!(task.history.last_reset().unwrap(), Some(row.t)); let v = app.view(Range::SinceReset); assert_eq!( @@ -331,10 +332,19 @@ fn rows_are_saved_when_counters_change_and_at_most_once_a_minute() { 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) + task.history + .sums(0, i64::MAX) + .unwrap() + .unwrap() + .totals + .requests, + 1 + ); + assert_eq!( + task.history.last_reset().unwrap(), + None, + "a change is not a reset" ); task.poll(&app, NOW + 700); @@ -344,7 +354,7 @@ fn rows_are_saved_when_counters_change_and_at_most_once_a_minute() { "unchanged: nothing more is saved, however long the quiet lasts" ); assert!( - task.history.build_observations().unwrap().is_empty(), + task.history.build_obs_stamp().unwrap() == (0, 0), "and with no misses there is no build observation" ); assert_eq!(app.lock().views.len(), 5, "every poll makes the five views"); @@ -380,9 +390,11 @@ fn the_history_survives_a_restart_in_its_file() { let mut c = b.clone(); c.totals.requests += 5; history.record(&mut tracker, &c, NOW + 70).unwrap(); - let rows = history.rows(0, i64::MAX).unwrap(); - assert_eq!(rows.len(), 1); - assert_eq!((rows[0].t, rows[0].delta.totals.requests), (NOW + 70, 5)); + assert_eq!(history.row_count().unwrap(), 1); + assert_eq!( + history.sums(0, i64::MAX).unwrap().unwrap().totals.requests, + 5 + ); assert_eq!( app.view(Range::Day).range, Some(Range::Day), @@ -418,13 +430,12 @@ fn old_rows_are_deleted_at_startup() { 1, "the one row older than 30 days" ); - let left: Vec = history - .rows(0, i64::MAX) - .unwrap() - .iter() - .map(|r| r.t) - .collect(); - assert_eq!(left, vec![NOW - 30 * day + 3600, NOW - 3600, NOW]); + assert_eq!(history.row_count().unwrap(), 3); + assert_eq!( + history.first_row().unwrap(), + Some(NOW - 30 * day + 3600), + "the oldest row left" + ); assert_eq!(history.prune(NOW).unwrap(), 0, "nothing more to delete"); assert!( fake.history.with_extension("db-wal").exists() @@ -525,3 +536,129 @@ fn a_server_that_will_not_start_is_reported_and_not_retried_for_a_minute() { assert_eq!(app.view(Range::Day).server.status, Status::Running); assert_eq!(app.view(Range::Day).server.error, None); } + +/// The real output with `more` more Rust builds in it: that many more requests, misses and compiles. +fn with_more_rust_builds(more: u64) -> String { + let text = LIVE.replace( + "\"compile_requests\":7351", + &format!("\"compile_requests\":{}", 7351 + more), + ); + let text = text.replace("\"Rust\":3256", &format!("\"Rust\":{}", 3256 + more)); + let text = text.replace("\"rust\":3256", &format!("\"rust\":{}", 3256 + more)); + let text = text.replace( + "\"compilations\":3256", + &format!("\"compilations\":{}", 3256 + more), + ); + let text = text.replace( + "\"cache_writes\":3256", + &format!("\"cache_writes\":{}", 3256 + more), + ); + text.replace( + "\"compiler_write_duration\":{\"secs\":25343", + &format!( + "\"compiler_write_duration\":{{\"secs\":{}", + 25343 + 8 * more + ), + ) +} + +#[test] +fn the_bootstrap_is_not_redrawn_on_every_poll_of_a_build_in_flight() { + let fake = Fake::new(); + let app = App::with_probe(fake.config(), fake.probe()); + let mut task = Task::memory(); + let rust_builds = |app: &App| { + app.view(Range::Day) + .build_times + .first() + .map_or(0, |t| t.compiles) + }; + task.poll(&app, NOW); + assert_eq!(rust_builds(&app), 0, "nothing seen yet"); + + // A build adds one Rust build between every pair of polls. Each is stored at once, but the + // histogram (and with it the bootstrap) waits for the one-minute beat. + for step in 1..6u64 { + fake.answers(&with_more_rust_builds(step)); + task.poll(&app, NOW + (step as i64) * 10); + assert_eq!( + task.history.build_obs_stamp().unwrap().0, + step as i64, + "observation {step} is stored at once" + ); + assert_eq!( + rust_builds(&app), + 0, + "but the bootstrap drawn at the first poll stands (step {step})" + ); + } + fake.answers(&with_more_rust_builds(6)); + task.poll(&app, NOW + 60); + assert_eq!( + rust_builds(&app), + 6, + "a minute after the last draw, everything seen so far is drawn in" + ); + + fake.answers(&with_more_rust_builds(7)); + task.poll(&app, NOW + 70); + assert_eq!( + rust_builds(&app), + 6, + "and it stands again until the next beat" + ); +} + +#[test] +fn a_full_history_costs_few_rows_on_the_second_poll() { + // Thirty days with a row every minute: the most there can ever be. Two languages miss most + // minutes, so only one minute in ten gives a build observation. + let fake = Fake::new(); + let app = App::with_probe(fake.config(), fake.probe()); + let mut task = Task::memory(); + let day = 86_400; + let mut c = stats::Counters::default(); + let mut readings = Vec::new(); + for step in 0..43_200i64 { + let (rust, cxx) = if step % 10 == 0 { (2, 0) } else { (1, 1) }; + c.totals.requests += 10; + c.totals.executed += 8; + c.totals.hits += 6; + c.totals.misses += rust + cxx; + c.totals.not_cacheable += 2; + c.totals.cache_writes += rust + cxx; + c.compilations += rust + cxx; + c.ns = [ + c.ns[0] + 6 * 10_000_000, + c.ns[1] + (rust + cxx) * 1_000_000_000, + c.ns[2] + (rust + cxx) * 8_000_000_000, + ]; + c.langs = vec![ + ("Assembler".to_owned(), [2, 0, 0]), + ("C/C++".to_owned(), [4, cxx, 0]), + ("Rust".to_owned(), [0, rust, 0]), + ]; + readings.push((NOW - 30 * day + step * 60, c.clone())); + } + task.history.fill(&readings).unwrap(); + assert_eq!( + task.history.row_count().unwrap(), + 43_199, + "the first reading is the baseline" + ); + let observations = task.history.build_obs_stamp().unwrap().0; + assert_eq!(observations, 4_319, "one for every tenth minute after the baseline"); + + task.poll(&app, NOW); + let first = app.lock().views_rows; + task.poll(&app, NOW + 10); + let second = app.lock().views_rows; + eprintln!("rows handed out: first poll {first} (reading {observations} build observations once), second poll {second}"); + assert!( + first >= observations as usize, + "the first poll reads every observation once" + ); + assert!(second < 3_000, "the second poll handed out {second} rows"); + let v = app.view(Range::Day); + assert_eq!(v.buckets.len(), 120); +}