Mechanical rustfmt (control-plane, desktop-core and the runtime client had 360 hunks of drift; the CI format steps for control-plane and desktop-core were red), plus, found by running `cargo clippy -D warnings` and the tests on Linux: * control-plane/tests/log_failure_sse.rs `no_panicking_log_macros_in_the_serving_crate` was red on main since the observability merge: two test-only `eprintln!` samples (prometheus.rs, request_log.rs) trip its source scan. They now write to stderr with `write_fmt` and ignore a failed write, which is what the test asks for; the output is the same. * tool_output.rs `is_multiple_of(2)`, an unneeded `mut` in a control-plane test, a collapsible `if` in leleka-inference.rs, `#[allow(dead_code)]` on observer_adaptive_slots (compiled into leleka-inference-evaluation too). * crates/deploy/src/facts.rs: `lab_holder_running` moved above `mod tests` (clippy::items_after_test_module); code moved, not changed. Kept as its own commit so it can be redone with `cargo fmt` if other branches touch these crates first. No behaviour change. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
250 lines
9.2 KiB
Rust
250 lines
9.2 KiB
Rust
//! The hardware half of `GET /metrics`, in the member names of the Python service's Monitor (`hardware`, `hardware_static`,
|
|
//! `history`; `engine/strata/serve/telemetry.py`), built from the engine's telemetry document (`leleka-memory`'s
|
|
//! `telemetry.rs`, copied here by the worker on its health tick).
|
|
//!
|
|
//! Units follow the Python service: memory in bytes, utilisation and CPU in percent, power in watts, temperature in degrees
|
|
//! Celsius, throughput in tokens per second. A figure the engine does not report is absent (never zero).
|
|
|
|
use std::{
|
|
collections::VecDeque,
|
|
sync::Mutex,
|
|
time::{Duration, Instant},
|
|
};
|
|
|
|
use serde_json::{Map, Value, json};
|
|
|
|
/// Samples kept per series. The worker copies the telemetry document on its health tick (2 s by default), so 60 samples are about two
|
|
/// minutes (the Python Monitor samples every second and keeps a minute).
|
|
pub const HISTORY_SAMPLES: usize = 60;
|
|
/// Samples closer than this are the same second.
|
|
const MIN_GAP: Duration = Duration::from_millis(900);
|
|
const MIB: f64 = 1_048_576.0;
|
|
|
|
/// The series the Monitor charts, in the Python service's names.
|
|
pub const SERIES: [&str; 8] = [
|
|
"gpu_util",
|
|
"gpu_mem_used",
|
|
"gpu_temp",
|
|
"gpu_power",
|
|
"cpu",
|
|
"ram_used",
|
|
"tok_s",
|
|
"prefill_tok_s_mean",
|
|
];
|
|
|
|
fn number(value: &Value) -> Option<f64> {
|
|
value.as_f64().filter(|v| v.is_finite())
|
|
}
|
|
|
|
fn bytes(mib: &Value) -> Value {
|
|
number(mib).map_or(Value::Null, |m| json!((m * MIB).round() as u64))
|
|
}
|
|
|
|
/// `hardware`: the latest sample.
|
|
///
|
|
/// * `gpu_*`: from `gpu` (utilisation, memory, temperature, power, SM clock)
|
|
/// * `cpu` is the whole system's busy percentage, `cpu_process_cores` the cores the engine used
|
|
/// * `ram_used` is total minus available, `ram_process_*` the engine's resident and pinned bytes
|
|
/// * `tok_s` is the live decode rate of the request in flight, 0.0 while nothing decodes; `tok_s_mean` and
|
|
/// `prefill_tok_s_mean` are the running averages of the engine's decode and prefill rates (null until measured)
|
|
pub fn hardware_now(document: &Value) -> Value {
|
|
let mut now = Map::new();
|
|
let gpu = &document["gpu"];
|
|
if gpu.is_object() {
|
|
now.insert("gpu_util".into(), gpu["util_pct"].clone());
|
|
now.insert("gpu_mem_util".into(), gpu["mem_util_pct"].clone());
|
|
now.insert("gpu_mem_used".into(), bytes(&gpu["vram_used_mib"]));
|
|
now.insert("gpu_mem_total".into(), bytes(&gpu["vram_total_mib"]));
|
|
now.insert("gpu_temp".into(), gpu["temp_c"].clone());
|
|
now.insert("gpu_power".into(), gpu["power_w"].clone());
|
|
now.insert("gpu_sm_clock_mhz".into(), gpu["sm_clock_mhz"].clone());
|
|
}
|
|
let ram = &document["ram"];
|
|
if ram.is_object() {
|
|
let used = match (number(&ram["total_mib"]), number(&ram["available_mib"])) {
|
|
(Some(total), Some(available)) => {
|
|
json!(((total - available).max(0.0) * MIB).round() as u64)
|
|
}
|
|
_ => Value::Null,
|
|
};
|
|
now.insert("ram_used".into(), used);
|
|
now.insert("ram_total".into(), bytes(&ram["total_mib"]));
|
|
now.insert("ram_process_rss".into(), bytes(&ram["process_rss_mib"]));
|
|
now.insert(
|
|
"ram_process_pinned".into(),
|
|
bytes(&ram["process_pinned_mib"]),
|
|
);
|
|
now.insert("swap_used".into(), bytes(&ram["swap_used_mib"]));
|
|
}
|
|
let cpu = &document["cpu"];
|
|
if cpu.is_object() {
|
|
now.insert("cpu".into(), cpu["system_busy_pct"].clone());
|
|
now.insert(
|
|
"cpu_process_cores".into(),
|
|
cpu["process_busy_cores"].clone(),
|
|
);
|
|
}
|
|
let throughput = &document["throughput"];
|
|
if throughput.is_object() {
|
|
let decoding = document["phase"] == "decode";
|
|
now.insert(
|
|
"tok_s".into(),
|
|
if decoding {
|
|
throughput["decode_tok_s_live"].clone()
|
|
} else {
|
|
json!(0.0)
|
|
},
|
|
);
|
|
now.insert("tok_s_mean".into(), throughput["decode_tok_s_avg"].clone());
|
|
now.insert(
|
|
"prefill_tok_s_mean".into(),
|
|
throughput["prefill_tok_s_avg"].clone(),
|
|
);
|
|
}
|
|
Value::Object(now)
|
|
}
|
|
|
|
/// `hardware_static`: what does not change while the engine runs.
|
|
pub fn hardware_static(document: &Value) -> Value {
|
|
let gpu = &document["gpu"];
|
|
let cores = &document["cpu"]["cores"];
|
|
json!({
|
|
"gpu_name": gpu["name"].clone(),
|
|
"gpu_count": if gpu.is_object() { json!(1) } else { json!(0) },
|
|
"threads": cores.clone(),
|
|
})
|
|
}
|
|
|
|
/// The last [`HISTORY_SAMPLES`] samples of the headline series, oldest first. A sample the engine did not report is `null`.
|
|
#[derive(Default)]
|
|
pub struct Series {
|
|
inner: Mutex<Inner>,
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct Inner {
|
|
last: Option<Instant>,
|
|
rows: std::collections::BTreeMap<&'static str, VecDeque<Value>>,
|
|
}
|
|
|
|
impl Series {
|
|
/// Add the sample `now` (the result of [`hardware_now`]) unless the previous one is less than a second old (a burst of ticks is one sample).
|
|
pub fn push(&self, now: &Value) {
|
|
let Ok(mut inner) = self.inner.lock() else {
|
|
return;
|
|
};
|
|
let at = Instant::now();
|
|
if inner
|
|
.last
|
|
.is_some_and(|last| at.duration_since(last) < MIN_GAP)
|
|
{
|
|
return;
|
|
}
|
|
inner.last = Some(at);
|
|
for key in SERIES {
|
|
let row = inner.rows.entry(key).or_default();
|
|
if row.len() == HISTORY_SAMPLES {
|
|
row.pop_front();
|
|
}
|
|
row.push_back(now.get(key).cloned().unwrap_or(Value::Null));
|
|
}
|
|
}
|
|
|
|
pub fn snapshot(&self) -> Value {
|
|
let Ok(inner) = self.inner.lock() else {
|
|
return json!({});
|
|
};
|
|
let mut out = Map::new();
|
|
for (key, row) in &inner.rows {
|
|
out.insert(
|
|
(*key).to_owned(),
|
|
Value::Array(row.iter().cloned().collect()),
|
|
);
|
|
}
|
|
Value::Object(out)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn document(phase: &str) -> Value {
|
|
json!({
|
|
"version": 1, "phase": phase,
|
|
"gpu": {"index": 0, "util_pct": 91, "mem_util_pct": 40, "vram_used_mib": 30000, "vram_total_mib": 32607,
|
|
"power_w": 480.5, "sm_clock_mhz": 2900, "temp_c": 61, "name": "NVIDIA GeForce RTX 5090"},
|
|
"ram": {"total_mib": 122880, "available_mib": 70000, "process_rss_mib": 55000, "process_pinned_mib": 3000, "swap_used_mib": 0},
|
|
"cpu": {"cores": 32, "process_busy_cores": 7.4, "system_busy_pct": 31.0},
|
|
"throughput": {"decode_tok_s_live": 128.4, "decode_tok_s_avg": 120.0, "prefill_tok_s_avg": 5050.0},
|
|
})
|
|
}
|
|
|
|
#[test]
|
|
fn the_python_names_and_units_are_produced() {
|
|
let now = hardware_now(&document("decode"));
|
|
assert_eq!(now["gpu_util"], 91);
|
|
assert_eq!(now["gpu_mem_used"], 30000u64 * 1_048_576);
|
|
assert_eq!(now["gpu_mem_total"], 32607u64 * 1_048_576);
|
|
assert_eq!(now["gpu_temp"], 61);
|
|
assert_eq!(now["gpu_power"], 480.5);
|
|
assert_eq!(now["cpu"], 31.0);
|
|
assert_eq!(now["ram_used"], (122880u64 - 70000) * 1_048_576);
|
|
assert_eq!(now["ram_total"], 122880u64 * 1_048_576);
|
|
assert_eq!(now["tok_s"], 128.4);
|
|
assert_eq!(now["prefill_tok_s_mean"], 5050.0);
|
|
let fixed = hardware_static(&document("decode"));
|
|
assert_eq!(fixed["gpu_name"], "NVIDIA GeForce RTX 5090");
|
|
assert_eq!(
|
|
(fixed["gpu_count"].clone(), fixed["threads"].clone()),
|
|
(json!(1), json!(32))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn tok_s_is_zero_while_nothing_decodes_and_blocks_are_absent_without_the_device() {
|
|
assert_eq!(hardware_now(&document("idle"))["tok_s"], 0.0);
|
|
assert_eq!(hardware_now(&document("prefill"))["tok_s"], 0.0);
|
|
let mut no_gpu = document("idle");
|
|
no_gpu["gpu"] = Value::Null;
|
|
let now = hardware_now(&no_gpu);
|
|
assert!(now.get("gpu_util").is_none() && now.get("gpu_mem_used").is_none());
|
|
assert_eq!(hardware_static(&no_gpu)["gpu_count"], 0);
|
|
assert_eq!(hardware_now(&Value::Null), json!({}));
|
|
}
|
|
|
|
#[test]
|
|
fn the_series_keeps_the_last_sixty_samples_and_drops_a_burst() {
|
|
let series = Series::default();
|
|
let now = hardware_now(&document("idle"));
|
|
series.push(&now);
|
|
series.push(&now); // within the same second: dropped
|
|
let snapshot = series.snapshot();
|
|
assert_eq!(snapshot["gpu_util"].as_array().unwrap().len(), 1);
|
|
// fill past the bound by rewinding the gate between pushes
|
|
for _ in 0..HISTORY_SAMPLES + 5 {
|
|
series.inner.lock().unwrap().last = None;
|
|
series.push(&now);
|
|
}
|
|
let snapshot = series.snapshot();
|
|
for key in SERIES {
|
|
assert_eq!(
|
|
snapshot[key].as_array().unwrap().len(),
|
|
HISTORY_SAMPLES,
|
|
"{key}"
|
|
);
|
|
}
|
|
// a series the engine did not report is null, not zero
|
|
assert!(
|
|
snapshot["gpu_temp"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.all(|v| v == 61)
|
|
);
|
|
let bare = Series::default();
|
|
bare.push(&json!({}));
|
|
assert!(bare.snapshot()["gpu_util"][0].is_null());
|
|
}
|
|
}
|