Files
VoelinClient/crates/voelin-gpui/src/meter.rs
T
faumarayandClaude Sonnet 5.5 3f4dc700af voelin-gpui: the meter's /proc test waits for a CPU tick instead of burning 60 ms
this_process_can_be_read_on_linux burned CPU for 60 ms of wall time and
asserted that some thread group used a tick (10 ms) of it. On a busy machine
this thread gets less than a tick in 60 ms: with 5 busy loops on the test's
core, 39 of 40 runs failed at `!threads.is_empty()`. The test now burns CPU
until a second reading shows the process's tick count above the first and a
thread group above its own (a 30 s deadline only ends a hang, as
docs/testing/load.md asks), then asserts; 40 of 40 pass under the same
recipe (taskset to one core, 5 busy loops, 40 runs).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:19:30 +03:00

304 lines
9.9 KiB
Rust

//! What the app costs, once a second, in the log: the CPU of the process and
//! of each group of threads, the resident memory, and the app's own counters
//! (a development switch, `VOELIN_METER=1`, so that every slice can say what
//! it costs). It is `spike_common::meter` of the GPUI spikes
//! (`spikes/gpui/common/src/meter.rs`, docs/design/gpui-spikes.md) without the
//! measuring run's summary and exit, writing log lines instead of JSON.
//!
//! CPU is in percent of one core (200 means two cores busy). Threads are
//! grouped by name without a trailing number (`llvmpipe-12` becomes
//! `llvmpipe`), which tells the software renderer's share (Mesa's `llvmpipe-*`
//! threads, work a GPU would take over) from GPUI's thread, the engine's
//! runtime and the codecs. The numbers come from `/proc/self`: on other
//! systems the meter says it cannot read them and stops.
use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
/// A number the app counts up (events handled, frames drawn) or sets (open
/// connections); the meter reports counters per second and gauges as they
/// are.
#[derive(Clone, Default, Debug)]
pub struct Counter(Arc<AtomicU64>);
impl Counter {
/// Add one.
pub fn incr(&self) {
self.0.fetch_add(1, Ordering::Relaxed);
}
/// Set (gauges).
pub fn set(&self, value: u64) {
self.0.store(value, Ordering::Relaxed);
}
/// The current value.
pub fn get(&self) -> u64 {
self.0.load(Ordering::Relaxed)
}
}
/// The app's own numbers the meter reports besides the process's.
#[derive(Clone, Default, Debug)]
pub struct Counters {
/// Engine events handled by the root state (per second).
pub engine_events: Counter,
/// One-second ticks of the root state (per second: 1).
pub ticks: Counter,
/// Windows drawn (frames, per second).
pub renders: Counter,
/// Jobs other threads handed to the foreground through
/// [`crate::app::Later`] (per second).
pub later_jobs: Counter,
/// Voice connections that are up (a gauge).
pub connections: Counter,
}
/// CPU ticks of the process and of each thread group, and the resident
/// memory, at one moment.
#[derive(Clone, Debug)]
pub struct Snapshot {
at: Instant,
process: u64,
threads: BTreeMap<String, u64>,
rss_bytes: u64,
}
/// The size of a page of memory, for `statm`'s page counts.
#[cfg(target_os = "linux")]
fn page_size() -> u64 {
rustix::param::page_size() as u64
}
/// The size of a page of memory (Linux only matters: `/proc`).
#[cfg(not(target_os = "linux"))]
fn page_size() -> u64 {
4096
}
/// The unit of the CPU times in `stat`.
#[cfg(target_os = "linux")]
fn clock_ticks_per_second() -> u64 {
rustix::param::clock_ticks_per_second()
}
/// The unit of the CPU times in `stat` (Linux only matters: `/proc`).
#[cfg(not(target_os = "linux"))]
fn clock_ticks_per_second() -> u64 {
100
}
/// `utime + stime` and the name of a `/proc/.../stat` line.
fn ticks_of(stat: &str) -> Option<(String, u64)> {
let open = stat.find('(')?;
let close = stat.rfind(')')?;
let name = stat.get(open + 1..close)?.to_owned();
let fields: Vec<&str> = stat.get(close + 1..)?.split_whitespace().collect();
// Fields 14 and 15 of proc(5); the remainder starts at field 3.
let utime: u64 = fields.get(11)?.parse().ok()?;
let stime: u64 = fields.get(12)?.parse().ok()?;
Some((name, utime + stime))
}
/// A thread's group: its name without a trailing number or separator.
pub fn group_of(name: &str) -> String {
let trimmed = name.trim_end_matches(|c: char| c.is_ascii_digit());
let trimmed = trimmed.trim_end_matches(['-', '_', ':', ' ', '#']);
if trimmed.is_empty() { name.to_owned() } else { trimmed.to_owned() }
}
impl Snapshot {
/// Read `/proc/self` now; `None` where there is none.
pub fn now() -> Option<Self> {
let process = std::fs::read_to_string("/proc/self/stat").ok().and_then(|s| ticks_of(&s))?.1;
let mut threads = BTreeMap::new();
if let Ok(dir) = std::fs::read_dir("/proc/self/task") {
for entry in dir.flatten() {
let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) else { continue };
if let Some((name, ticks)) = ticks_of(&stat) {
*threads.entry(group_of(&name)).or_insert(0) += ticks;
}
}
}
let rss_bytes = std::fs::read_to_string("/proc/self/statm")
.ok()
.and_then(|s| s.split_whitespace().nth(1)?.parse::<u64>().ok())
.map_or(0, |pages| pages * page_size());
Some(Self { at: Instant::now(), process, threads, rss_bytes })
}
/// Resident memory in MiB.
pub fn rss_mib(&self) -> f64 {
self.rss_bytes as f64 / (1024.0 * 1024.0)
}
}
/// CPU in percent of one core between two snapshots: the process's and each
/// thread group's that used any (groups that exited in between count from
/// zero).
pub fn cpu_between(a: &Snapshot, b: &Snapshot) -> (f64, BTreeMap<String, f64>) {
let hz = clock_ticks_per_second() as f64;
let secs = b.at.duration_since(a.at).as_secs_f64().max(1e-6);
let pct = |ticks: u64| ticks as f64 / hz / secs * 100.0;
let process = pct(b.process.saturating_sub(a.process));
let threads = b
.threads
.iter()
.map(|(name, &t)| (name.clone(), pct(t.saturating_sub(*a.threads.get(name).unwrap_or(&0)))))
.filter(|(_, p)| *p > 0.0)
.collect();
(process, threads)
}
/// One second of the meter as a log line: `cpu 42.0% rss 210.4 MiB threads
/// llvmpipe 31.0 main 5.0 | engine_events 0.0/s ... | connections 1`.
pub fn line(
cpu: f64,
rss_mib: f64,
threads: &BTreeMap<String, f64>,
rates: &[(&str, f64)],
gauges: &[(&str, u64)],
) -> String {
let mut text = format!("cpu {cpu:.1}% rss {rss_mib:.1} MiB");
// The busiest groups first; a thread group under 0.5 % is noise.
let mut busy: Vec<(&String, &f64)> = threads.iter().filter(|(_, p)| **p >= 0.5).collect();
busy.sort_by(|a, b| b.1.total_cmp(a.1).then_with(|| a.0.cmp(b.0)));
if !busy.is_empty() {
text.push_str(" | threads");
for (name, pct) in busy {
let _ = write!(text, " {name} {pct:.1}");
}
}
text.push_str(" |");
for (name, rate) in rates {
let _ = write!(text, " {name} {rate:.1}/s");
}
if !gauges.is_empty() {
text.push_str(" |");
for (name, value) in gauges {
let _ = write!(text, " {name} {value}");
}
}
text
}
/// Start the meter on a thread of its own: once a second, a log line (target
/// `voelin_gpui::meter`, level info) with the process's CPU and memory and
/// `counters`' rates. It ends with the process.
pub fn start(counters: Counters) {
let spawned = std::thread::Builder::new().name("voelin-meter".into()).spawn(move || {
let Some(mut last) = Snapshot::now() else {
tracing::warn!(target: "voelin_gpui::meter", "the meter reads /proc/self; there is none here");
return;
};
let rated = [
("engine_events", counters.engine_events.clone()),
("ticks", counters.ticks.clone()),
("renders", counters.renders.clone()),
("later_jobs", counters.later_jobs.clone()),
];
let mut last_counts: Vec<u64> = rated.iter().map(|(_, c)| c.get()).collect();
tracing::info!(target: "voelin_gpui::meter", "meter on: one line a second (VOELIN_METER)");
loop {
std::thread::sleep(Duration::from_secs(1));
let Some(now) = Snapshot::now() else { return };
let secs = now.at.duration_since(last.at).as_secs_f64().max(1e-6);
let (cpu, threads) = cpu_between(&last, &now);
let counts: Vec<u64> = rated.iter().map(|(_, c)| c.get()).collect();
let rates: Vec<(&str, f64)> = rated
.iter()
.zip(counts.iter().zip(&last_counts))
.map(|((name, _), (c, l))| (*name, c.saturating_sub(*l) as f64 / secs))
.collect();
let gauges = [("connections", counters.connections.get())];
tracing::info!(
target: "voelin_gpui::meter",
"{}",
line(cpu, now.rss_mib(), &threads, &rates, &gauges)
);
last = now;
last_counts = counts;
}
});
if let Err(error) = spawned {
tracing::warn!(target: "voelin_gpui::meter", %error, "no meter thread");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn groups_drop_trailing_numbers() {
assert_eq!(group_of("llvmpipe-12"), "llvmpipe");
assert_eq!(group_of("tokio-runtime-w"), "tokio-runtime-w");
assert_eq!(group_of("voelin-meter"), "voelin-meter");
assert_eq!(group_of("1234"), "1234");
}
#[test]
fn stat_lines_parse_with_spaces_in_names() {
let line = "42 (a b) c) S 1 2 3 4 5 6 7 8 9 10 100 23 0 0 20 0 1 0 0";
assert_eq!(ticks_of(line), Some(("a b) c".to_owned(), 123)));
}
#[test]
fn the_line_names_the_busiest_threads_first_and_hides_the_idle_ones() {
let threads = BTreeMap::from([
("main".to_owned(), 5.04),
("llvmpipe".to_owned(), 310.0),
("idle".to_owned(), 0.2),
]);
let text = line(
317.0,
210.44,
&threads,
&[("engine_events", 0.0), ("renders", 59.96)],
&[("connections", 1)],
);
assert_eq!(
text,
"cpu 317.0% rss 210.4 MiB | threads llvmpipe 310.0 main 5.0 | engine_events 0.0/s renders 60.0/s | connections 1"
);
}
#[test]
fn this_process_can_be_read_on_linux() {
if !cfg!(target_os = "linux") {
return;
}
let a = Snapshot::now().expect("/proc/self");
// The kernel counts a process's CPU in ticks of 10 ms, and on a busy
// machine this thread gets a tick's worth of CPU only after a long wall
// time: burn CPU until a second reading shows the process's ticks above
// the first, and in a thread group (the process's total and a thread's
// own are rounded separately). The deadline only ends a hang
// (docs/testing/load.md); it never decides the result.
let deadline = Instant::now() + Duration::from_secs(30);
let (b, cpu) = loop {
let burn = Instant::now();
let mut x = 0u64;
while burn.elapsed() < Duration::from_millis(2) {
x = x.wrapping_mul(31).wrapping_add(7);
}
std::hint::black_box(x);
let b = Snapshot::now().expect("/proc/self");
let (cpu, threads) = cpu_between(&a, &b);
if b.process > a.process && !threads.is_empty() {
break (b, cpu);
}
assert!(
Instant::now() < deadline,
"no CPU tick showed in 30 s: {} -> {}",
a.process,
b.process
);
};
assert!(cpu > 0.0 && b.rss_mib() > 1.0, "{cpu} {}", b.rss_mib());
}
}