runtime telemetry: GPU load/VRAM (NVML), RAM, CPU cores, prefill/decode tok/s, cache hits, context
leleka-memory::telemetry (sampler + per-request records) -> Backend::telemetry_report -> Snapshot.telemetry_json (gRPC) -> control plane /v1/status machine -> leleka status. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
b726c4615b
commit
08e2c78761
@@ -379,6 +379,8 @@ async fn refresh_prefix_view(engine: &Engine, config: &BackendWorkerConfig) {
|
||||
if let Some(view) = &config.memory_view {
|
||||
let report = on_engine(engine, |backend| backend.memory_report()).await.ok().flatten();
|
||||
view.set(report);
|
||||
let telemetry = on_engine(engine, |backend| backend.telemetry_report()).await.ok().flatten();
|
||||
view.set_telemetry(telemetry);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -32,6 +32,8 @@ pub struct Closed {
|
||||
#[derive(Default)]
|
||||
pub struct MemoryView {
|
||||
latest: RwLock<Option<(Value, Instant)>>,
|
||||
/// The engine's telemetry document (`Backend::telemetry_report`) and when it was copied.
|
||||
telemetry: RwLock<Option<(Value, Instant)>>,
|
||||
gated: AtomicU64,
|
||||
}
|
||||
|
||||
@@ -44,6 +46,27 @@ impl MemoryView {
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace the stored telemetry document (`None`: the engine reports none, or is unreachable).
|
||||
pub fn set_telemetry(&self, document: Option<String>) {
|
||||
let value = document.and_then(|text| serde_json::from_str::<Value>(&text).ok()).filter(Value::is_object);
|
||||
if let Ok(mut latest) = self.telemetry.write() {
|
||||
*latest = value.map(|value| (value, Instant::now()));
|
||||
}
|
||||
}
|
||||
|
||||
/// For `GET /v1/status` `machine`: the engine's telemetry with its age; a document older than [`FRESH_FOR`] is `null`.
|
||||
pub fn telemetry_status(&self) -> Value {
|
||||
let Ok(latest) = self.telemetry.read() else { return Value::Null };
|
||||
match latest.as_ref() {
|
||||
Some((value, at)) if at.elapsed() <= FRESH_FOR => {
|
||||
let mut value = value.clone();
|
||||
value["age_ms"] = json!(at.elapsed().as_millis() as u64);
|
||||
value
|
||||
}
|
||||
_ => Value::Null,
|
||||
}
|
||||
}
|
||||
|
||||
/// For `GET /v1/status`: the report with its age and this process's gate counter; `null` when there is none.
|
||||
pub fn status(&self) -> Value {
|
||||
let Ok(latest) = self.latest.read() else { return Value::Null };
|
||||
|
||||
@@ -341,7 +341,7 @@ async fn status_value(state: &AppState) -> Value {
|
||||
"activity": {"requests": worker.metrics.started, "in_flight": usize::from(busy) + queued,
|
||||
"last_request_at": last_at},
|
||||
"last_timings": timings,
|
||||
"machine": {"at": now_s(), "gpu": null, "ram": null},
|
||||
"machine": machine_view(&state.memory),
|
||||
"memory": state.memory.status(),
|
||||
});
|
||||
// Present only when a prefix cache exists: the Python server's status has no such key (golden http_surface).
|
||||
@@ -570,3 +570,14 @@ pub async fn mcp_status(State(state): State<AppState>) -> Response {
|
||||
};
|
||||
reply(StatusCode::OK, body)
|
||||
}
|
||||
|
||||
/// `machine` of `GET /v1/status`: the engine's telemetry (GPU load and VRAM, RAM, CPU cores, throughput, cache hits, context)
|
||||
/// when it reports any; the legacy `{at, gpu, ram}` shape with nulls otherwise.
|
||||
fn machine_view(memory: &crate::memory_view::MemoryView) -> Value {
|
||||
let mut view = memory.telemetry_status();
|
||||
if !view.is_object() {
|
||||
return json!({"at": now_s(), "gpu": null, "ram": null});
|
||||
}
|
||||
view["at"] = json!(now_s());
|
||||
view
|
||||
}
|
||||
|
||||
@@ -276,6 +276,12 @@ pub trait Backend: Send {
|
||||
fn memory_report(&self) -> Option<String> {
|
||||
None
|
||||
}
|
||||
/// JSON telemetry of the backend for the operator (`leleka status`): GPU load and VRAM, host RAM, CPU cores in use, prefill and
|
||||
/// decode tokens per second, prefix-cache hits and the context in use. `None`: this backend reports none (the default).
|
||||
/// Cheap and non-blocking by contract (the text was rendered by the backend's sampler thread).
|
||||
fn telemetry_report(&self) -> Option<String> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
|
||||
+3420
-3419
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,167 @@
|
||||
//! GPU load for the operator (`leleka status`): utilisation, VRAM, power and clock through NVML, loaded with `dlopen`
|
||||
//! so a host without the library simply reports nothing. Read-only queries; nothing here touches a CUDA context.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct NvmlSample {
|
||||
pub index: u32,
|
||||
pub util_pct: u32,
|
||||
pub mem_util_pct: u32,
|
||||
pub vram_used_mib: u64,
|
||||
pub vram_total_mib: u64,
|
||||
pub power_w: Option<f64>,
|
||||
pub sm_clock_mhz: Option<u32>,
|
||||
}
|
||||
|
||||
/// A reusable handle to NVML's device `index`; `None` when the library, the symbols or the device are missing.
|
||||
pub struct Nvml(imp::Handle);
|
||||
|
||||
impl Nvml {
|
||||
pub fn open(index: u32) -> Option<Nvml> {
|
||||
imp::Handle::open(index).map(Nvml)
|
||||
}
|
||||
pub fn sample(&self) -> Option<NvmlSample> {
|
||||
self.0.sample()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
#[allow(unsafe_code)]
|
||||
mod imp {
|
||||
use super::NvmlSample;
|
||||
use libc::{c_int, c_uint, c_void};
|
||||
|
||||
type Init = unsafe extern "C" fn() -> c_int;
|
||||
type GetHandle = unsafe extern "C" fn(c_uint, *mut *mut c_void) -> c_int;
|
||||
#[repr(C)]
|
||||
#[derive(Default)]
|
||||
struct Utilization {
|
||||
gpu: c_uint,
|
||||
memory: c_uint,
|
||||
}
|
||||
#[repr(C)]
|
||||
#[derive(Default)]
|
||||
struct MemoryInfo {
|
||||
total: u64,
|
||||
free: u64,
|
||||
used: u64,
|
||||
}
|
||||
type GetUtilization = unsafe extern "C" fn(*mut c_void, *mut Utilization) -> c_int;
|
||||
type GetMemory = unsafe extern "C" fn(*mut c_void, *mut MemoryInfo) -> c_int;
|
||||
type GetPower = unsafe extern "C" fn(*mut c_void, *mut c_uint) -> c_int;
|
||||
type GetClock = unsafe extern "C" fn(*mut c_void, c_uint, *mut c_uint) -> c_int;
|
||||
const NVML_CLOCK_SM: c_uint = 1;
|
||||
|
||||
pub(super) struct Handle {
|
||||
library: *mut c_void,
|
||||
device: *mut c_void,
|
||||
index: u32,
|
||||
utilization: GetUtilization,
|
||||
memory: GetMemory,
|
||||
power: Option<GetPower>,
|
||||
clock: Option<GetClock>,
|
||||
}
|
||||
|
||||
// SAFETY: NVML's query functions are thread-safe after nvmlInit; the handle is plain data and the library stays loaded.
|
||||
unsafe impl Send for Handle {}
|
||||
unsafe impl Sync for Handle {}
|
||||
|
||||
fn symbol(library: *mut c_void, name: &std::ffi::CStr) -> Option<*mut c_void> {
|
||||
// SAFETY: a live dlopen handle and a static C name.
|
||||
let address = unsafe { libc::dlsym(library, name.as_ptr()) };
|
||||
(!address.is_null()).then_some(address)
|
||||
}
|
||||
|
||||
impl Handle {
|
||||
pub(super) fn open(index: u32) -> Option<Handle> {
|
||||
// SAFETY: fixed library names and flags.
|
||||
let library = unsafe {
|
||||
let first = libc::dlopen(c"libnvidia-ml.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL);
|
||||
if first.is_null() {
|
||||
libc::dlopen(c"libnvidia-ml.so".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL)
|
||||
} else {
|
||||
first
|
||||
}
|
||||
};
|
||||
if library.is_null() {
|
||||
return None;
|
||||
}
|
||||
let built = (|| {
|
||||
// SAFETY: each transmute names the documented NVML C signature of the symbol it loads.
|
||||
unsafe {
|
||||
let init: Init = std::mem::transmute(symbol(library, c"nvmlInit_v2")?);
|
||||
let get_handle: GetHandle = std::mem::transmute(symbol(library, c"nvmlDeviceGetHandleByIndex_v2")?);
|
||||
let utilization: GetUtilization = std::mem::transmute(symbol(library, c"nvmlDeviceGetUtilizationRates")?);
|
||||
let memory: GetMemory = std::mem::transmute(symbol(library, c"nvmlDeviceGetMemoryInfo")?);
|
||||
let power = symbol(library, c"nvmlDeviceGetPowerUsage").map(|p| std::mem::transmute::<*mut c_void, GetPower>(p));
|
||||
let clock = symbol(library, c"nvmlDeviceGetClockInfo").map(|p| std::mem::transmute::<*mut c_void, GetClock>(p));
|
||||
if init() != 0 {
|
||||
return None;
|
||||
}
|
||||
let mut device: *mut c_void = std::ptr::null_mut();
|
||||
if get_handle(index, &mut device) != 0 || device.is_null() {
|
||||
return None;
|
||||
}
|
||||
Some(Handle { library, device, index, utilization, memory, power, clock })
|
||||
}
|
||||
})();
|
||||
if built.is_none() {
|
||||
// SAFETY: the reference this call opened.
|
||||
unsafe {
|
||||
libc::dlclose(library);
|
||||
}
|
||||
}
|
||||
built
|
||||
}
|
||||
|
||||
pub(super) fn sample(&self) -> Option<NvmlSample> {
|
||||
let mut utilization = Utilization::default();
|
||||
let mut memory = MemoryInfo::default();
|
||||
// SAFETY: valid device handle, correctly sized out-parameters.
|
||||
let (ok_util, ok_mem) = unsafe { ((self.utilization)(self.device, &mut utilization) == 0, (self.memory)(self.device, &mut memory) == 0) };
|
||||
if !ok_util && !ok_mem {
|
||||
return None;
|
||||
}
|
||||
let power_w = self.power.and_then(|f| {
|
||||
let mut milliwatts: c_uint = 0;
|
||||
// SAFETY: as above.
|
||||
(unsafe { f(self.device, &mut milliwatts) } == 0).then(|| f64::from(milliwatts) / 1000.0)
|
||||
});
|
||||
let sm_clock_mhz = self.clock.and_then(|f| {
|
||||
let mut mhz: c_uint = 0;
|
||||
// SAFETY: as above.
|
||||
(unsafe { f(self.device, NVML_CLOCK_SM, &mut mhz) } == 0).then_some(mhz)
|
||||
});
|
||||
Some(NvmlSample {
|
||||
index: self.index,
|
||||
util_pct: utilization.gpu,
|
||||
mem_util_pct: utilization.memory,
|
||||
vram_used_mib: memory.used >> 20,
|
||||
vram_total_mib: memory.total >> 20,
|
||||
power_w,
|
||||
sm_clock_mhz,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Handle {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the reference `open` took; NVML stays initialised for the process, which is harmless.
|
||||
unsafe {
|
||||
libc::dlclose(self.library);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(all(target_os = "linux", target_pointer_width = "64")))]
|
||||
mod imp {
|
||||
use super::NvmlSample;
|
||||
pub(super) struct Handle;
|
||||
impl Handle {
|
||||
pub(super) fn open(_index: u32) -> Option<Handle> {
|
||||
None
|
||||
}
|
||||
pub(super) fn sample(&self) -> Option<NvmlSample> {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
+639
-545
File diff suppressed because it is too large
Load Diff
@@ -273,6 +273,17 @@ pub async fn probe_ready_at(paths: &Paths, api: &str) -> bool {
|
||||
matches!(http::get(address, "/ready", Some(key.trim_end()), Duration::from_secs(3)).await, Ok(r) if r.status == 200)
|
||||
}
|
||||
|
||||
/// `GET /v1/status` with the key of `paths`: the gateway's status document (`machine` carries the engine telemetry).
|
||||
pub async fn fetch_status(paths: &Paths, api: &str) -> Option<serde_json::Value> {
|
||||
let key = std::fs::read_to_string(paths.api_key()).ok()?;
|
||||
let address = crate::config::probe_address(api)?;
|
||||
let response = http::get(address, "/v1/status", Some(key.trim_end()), Duration::from_secs(3)).await.ok()?;
|
||||
if response.status != 200 {
|
||||
return None;
|
||||
}
|
||||
serde_json::from_str(&response.body).ok()
|
||||
}
|
||||
|
||||
pub fn unit_text(ctx: &Context, scope: UnitScopeTag) -> Result<(PathBuf, String), String> {
|
||||
let home = std::env::var_os("HOME").map(PathBuf::from);
|
||||
let text = units::render(
|
||||
|
||||
@@ -1,23 +1,24 @@
|
||||
//! Memory safety for the Leleka runtime: an allocation inventory, a startup budget that refuses what cannot fit and
|
||||
//! sizes the caches from what is left, a runtime pressure monitor that sheds load in a fixed order instead of letting the
|
||||
//! OOM killer or a swap storm decide, a residency guard for the sealed KAR memfd, and the census used by the soak tests.
|
||||
//!
|
||||
//! Model-free and CUDA-free by design: the runtime feeds it numbers (what it will allocate, what the device reports) and
|
||||
//! acts on its decisions (evict, refuse, lock). See `docs/memory-safety.md`.
|
||||
|
||||
pub mod census;
|
||||
pub mod governor;
|
||||
pub mod heap;
|
||||
pub mod host;
|
||||
pub mod inventory;
|
||||
pub mod ledger;
|
||||
pub mod lock;
|
||||
pub mod plan;
|
||||
pub mod pressure;
|
||||
pub mod procfs;
|
||||
|
||||
pub use governor::{Admission, Governor, GovernorConfig, LockReport, Refuse, RequestShape, SamplerGuard, ShedDirective, published_report};
|
||||
pub use host::{FakeProc, HostFacts, ProcSource, RealProc};
|
||||
pub use inventory::{Entry, Inventory, Space, When};
|
||||
pub use plan::{CacheWish, FixedItem, GIB, KarForm, MIB, Plan, PlanInput, Policy, Refusal, VramFacts, VramPlan, check_vram};
|
||||
pub use pressure::Level;
|
||||
//! Memory safety for the Leleka runtime: an allocation inventory, a startup budget that refuses what cannot fit and
|
||||
//! sizes the caches from what is left, a runtime pressure monitor that sheds load in a fixed order instead of letting the
|
||||
//! OOM killer or a swap storm decide, a residency guard for the sealed KAR memfd, and the census used by the soak tests.
|
||||
//!
|
||||
//! Model-free and CUDA-free by design: the runtime feeds it numbers (what it will allocate, what the device reports) and
|
||||
//! acts on its decisions (evict, refuse, lock). See `docs/memory-safety.md`.
|
||||
|
||||
pub mod census;
|
||||
pub mod governor;
|
||||
pub mod heap;
|
||||
pub mod host;
|
||||
pub mod inventory;
|
||||
pub mod ledger;
|
||||
pub mod lock;
|
||||
pub mod plan;
|
||||
pub mod pressure;
|
||||
pub mod procfs;
|
||||
pub mod telemetry;
|
||||
|
||||
pub use governor::{Admission, Governor, GovernorConfig, LockReport, Refuse, RequestShape, SamplerGuard, ShedDirective, published_report};
|
||||
pub use host::{FakeProc, HostFacts, ProcSource, RealProc};
|
||||
pub use inventory::{Entry, Inventory, Space, When};
|
||||
pub use plan::{CacheWish, FixedItem, GIB, KarForm, MIB, Plan, PlanInput, Policy, Refusal, VramFacts, VramPlan, check_vram};
|
||||
pub use pressure::Level;
|
||||
|
||||
@@ -0,0 +1,498 @@
|
||||
//! Runtime telemetry: what the operator watches while the engine serves. GPU load and VRAM (through a probe the
|
||||
//! runtime supplies), host RAM and the process footprint, CPU cores in use, prefill and decode throughput, prefix-cache
|
||||
//! hits and the context in use. Rendered as one JSON document (`published_telemetry`) that rides the runtime snapshot
|
||||
//! (`Snapshot.telemetry_json`) to the gateway, `/v1/status` and `leleka status`.
|
||||
//!
|
||||
//! The serve loop calls the `record_*` functions (a mutex-guarded struct, no allocation); one sampler thread reads
|
||||
//! `/proc` once a second and publishes. Everything that parses or computes is a pure function over fixtures.
|
||||
use crate::{
|
||||
host::{ProcSource, RealProc},
|
||||
procfs,
|
||||
};
|
||||
use serde::Serialize;
|
||||
use std::{
|
||||
sync::{
|
||||
Arc, Mutex, MutexGuard,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
/// Linux reports process CPU time in clock ticks of `USER_HZ`, which is 100 on every supported architecture.
|
||||
const USER_HZ: f64 = 100.0;
|
||||
/// Weight of the newest request in the running average of the throughput.
|
||||
const EMA_ALPHA: f64 = 0.3;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
|
||||
pub struct GpuSample {
|
||||
pub index: u32,
|
||||
/// Percent of the last sample period in which any kernel ran (NVML `utilization.gpu`).
|
||||
pub util_pct: u32,
|
||||
/// Percent of the period the memory interface was reading or writing (NVML `utilization.memory`).
|
||||
pub mem_util_pct: u32,
|
||||
pub vram_used_mib: u64,
|
||||
pub vram_total_mib: u64,
|
||||
pub power_w: Option<f64>,
|
||||
pub sm_clock_mhz: Option<u32>,
|
||||
}
|
||||
|
||||
type GpuProbe = Box<dyn Fn() -> Option<GpuSample> + Send + Sync>;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Phase {
|
||||
#[default]
|
||||
Idle,
|
||||
Prefill,
|
||||
Decode,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct State {
|
||||
phase: Phase,
|
||||
started: Option<Instant>,
|
||||
first_token: Option<Instant>,
|
||||
produced_now: u64,
|
||||
/// Lifetime counters.
|
||||
requests: u64,
|
||||
cache_hit_requests: u64,
|
||||
prompt_tokens: u64,
|
||||
reused_tokens: u64,
|
||||
produced_tokens: u64,
|
||||
prefill_tokens: u64,
|
||||
prefill_ms: f64,
|
||||
decode_tokens: u64,
|
||||
decode_ms: f64,
|
||||
/// Last finished request.
|
||||
last_prompt_tokens: u64,
|
||||
last_reused_tokens: u64,
|
||||
last_prefill_tok_s: Option<f64>,
|
||||
last_decode_tok_s: Option<f64>,
|
||||
prefill_ema: Option<f64>,
|
||||
decode_ema: Option<f64>,
|
||||
context_live: u64,
|
||||
context_max: u64,
|
||||
}
|
||||
|
||||
static STATE: Mutex<Option<State>> = Mutex::new(None);
|
||||
static PUBLISHED: Mutex<Option<String>> = Mutex::new(None);
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(|p| p.into_inner())
|
||||
}
|
||||
|
||||
fn with_state(f: impl FnOnce(&mut State)) {
|
||||
f(lock(&STATE).get_or_insert_with(State::default));
|
||||
}
|
||||
|
||||
/// The last document the sampler published (JSON text).
|
||||
pub fn published_telemetry() -> Option<String> {
|
||||
lock(&PUBLISHED).clone()
|
||||
}
|
||||
|
||||
/// The context window the engine serves (tokens); constant for a loaded model.
|
||||
pub fn set_context_max(tokens: u64) {
|
||||
with_state(|s| s.context_max = tokens);
|
||||
}
|
||||
|
||||
/// A request entered the engine: `prompt_tokens` to prefill, of which the cache supplies `reused_tokens`.
|
||||
pub fn request_started(prompt_tokens: u64, reused_tokens: u64) {
|
||||
with_state(|s| {
|
||||
s.phase = Phase::Prefill;
|
||||
s.started = Some(Instant::now());
|
||||
s.first_token = None;
|
||||
s.produced_now = 0;
|
||||
s.context_live = prompt_tokens;
|
||||
s.last_prompt_tokens = prompt_tokens;
|
||||
s.last_reused_tokens = reused_tokens;
|
||||
});
|
||||
}
|
||||
|
||||
/// Tokens were delivered: the first delivery ends the prefill phase.
|
||||
pub fn tokens_delivered(count: u64) {
|
||||
with_state(|s| {
|
||||
if s.first_token.is_none() {
|
||||
s.first_token = Some(Instant::now());
|
||||
s.phase = Phase::Decode;
|
||||
}
|
||||
s.produced_now += count;
|
||||
s.context_live += count;
|
||||
});
|
||||
}
|
||||
|
||||
/// A request ended without numbers worth folding in (cancelled or failed): the engine is idle again.
|
||||
pub fn request_aborted() {
|
||||
with_state(|s| {
|
||||
s.phase = Phase::Idle;
|
||||
s.started = None;
|
||||
s.first_token = None;
|
||||
});
|
||||
}
|
||||
|
||||
/// A request finished (any outcome that produced numbers): fold it into the lifetime figures.
|
||||
pub fn request_finished(prompt_tokens: u64, reused_tokens: u64, produced: u64, prompt_ms: f64, decode_ms: f64) {
|
||||
with_state(|s| {
|
||||
s.phase = Phase::Idle;
|
||||
s.started = None;
|
||||
s.first_token = None;
|
||||
s.requests += 1;
|
||||
s.prompt_tokens += prompt_tokens;
|
||||
s.reused_tokens += reused_tokens;
|
||||
s.produced_tokens += produced;
|
||||
if reused_tokens > 0 {
|
||||
s.cache_hit_requests += 1;
|
||||
}
|
||||
s.last_prompt_tokens = prompt_tokens;
|
||||
s.last_reused_tokens = reused_tokens;
|
||||
s.context_live = prompt_tokens + produced;
|
||||
let prefilled = prompt_tokens.saturating_sub(reused_tokens);
|
||||
if prefilled > 0 && prompt_ms > 0.0 {
|
||||
let rate = prefilled as f64 * 1e3 / prompt_ms;
|
||||
s.prefill_tokens += prefilled;
|
||||
s.prefill_ms += prompt_ms;
|
||||
s.last_prefill_tok_s = Some(rate);
|
||||
s.prefill_ema = Some(ema(s.prefill_ema, rate));
|
||||
}
|
||||
if produced > 0 && decode_ms > 0.0 {
|
||||
let rate = produced as f64 * 1e3 / decode_ms;
|
||||
s.decode_tokens += produced;
|
||||
s.decode_ms += decode_ms;
|
||||
s.last_decode_tok_s = Some(rate);
|
||||
s.decode_ema = Some(ema(s.decode_ema, rate));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn ema(previous: Option<f64>, value: f64) -> f64 {
|
||||
previous.map_or(value, |p| p + EMA_ALPHA * (value - p))
|
||||
}
|
||||
|
||||
fn round1(value: f64) -> f64 {
|
||||
(value * 10.0).round() / 10.0
|
||||
}
|
||||
|
||||
/// Process and system CPU time read at one instant.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct CpuReading {
|
||||
/// utime + stime of this process, in clock ticks.
|
||||
pub process_ticks: u64,
|
||||
/// Sum of all non-idle and all system ticks (`/proc/stat` first line).
|
||||
pub system_busy: u64,
|
||||
pub system_total: u64,
|
||||
}
|
||||
|
||||
/// `/proc/self/stat`: utime and stime are fields 14 and 15 (counted after the parenthesised command name).
|
||||
pub fn parse_self_stat_ticks(text: &str) -> Option<u64> {
|
||||
let rest = text.rsplit_once(')')?.1;
|
||||
let fields: Vec<&str> = rest.split_ascii_whitespace().collect();
|
||||
// after ")" the fields start at 3 (state); utime is 14, stime 15
|
||||
let utime: u64 = fields.get(11)?.parse().ok()?;
|
||||
let stime: u64 = fields.get(12)?.parse().ok()?;
|
||||
Some(utime + stime)
|
||||
}
|
||||
|
||||
/// `/proc/stat` first line: (busy, total) ticks over all CPUs.
|
||||
pub fn parse_stat_cpu(text: &str) -> Option<(u64, u64)> {
|
||||
let line = text.lines().next()?;
|
||||
let mut parts = line.split_ascii_whitespace();
|
||||
if parts.next()? != "cpu" {
|
||||
return None;
|
||||
}
|
||||
let values: Vec<u64> = parts.filter_map(|v| v.parse().ok()).collect();
|
||||
if values.len() < 4 {
|
||||
return None;
|
||||
}
|
||||
let idle = values[3] + values.get(4).copied().unwrap_or(0);
|
||||
let total: u64 = values.iter().take(8).sum();
|
||||
Some((total.saturating_sub(idle), total))
|
||||
}
|
||||
|
||||
pub fn read_cpu(src: &dyn ProcSource) -> Option<CpuReading> {
|
||||
let process_ticks = parse_self_stat_ticks(&src.read("/proc/self/stat").ok()?)?;
|
||||
let (system_busy, system_total) = parse_stat_cpu(&src.read("/proc/stat").ok()?)?;
|
||||
Some(CpuReading { process_ticks, system_busy, system_total })
|
||||
}
|
||||
|
||||
/// Cores worth of CPU this process used between two readings, and the whole system's busy percentage.
|
||||
pub fn cpu_usage(before: &CpuReading, after: &CpuReading, wall: Duration) -> (f64, f64) {
|
||||
let seconds = wall.as_secs_f64().max(1e-6);
|
||||
let process = after.process_ticks.saturating_sub(before.process_ticks) as f64 / USER_HZ / seconds;
|
||||
let total = after.system_total.saturating_sub(before.system_total);
|
||||
let busy = after.system_busy.saturating_sub(before.system_busy);
|
||||
let system = if total == 0 { 0.0 } else { 100.0 * busy as f64 / total as f64 };
|
||||
(process, system)
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct Ram {
|
||||
total_mib: u64,
|
||||
available_mib: u64,
|
||||
process_rss_mib: u64,
|
||||
process_pinned_mib: u64,
|
||||
swap_used_mib: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct Cpu {
|
||||
cores: u32,
|
||||
process_busy_cores: f64,
|
||||
system_busy_pct: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct Rates {
|
||||
prefill_tok_s_last: Option<f64>,
|
||||
prefill_tok_s_avg: Option<f64>,
|
||||
prefill_tok_s_lifetime: Option<f64>,
|
||||
decode_tok_s_last: Option<f64>,
|
||||
decode_tok_s_avg: Option<f64>,
|
||||
decode_tok_s_lifetime: Option<f64>,
|
||||
/// While a request is decoding: tokens delivered so far over the time since its first token.
|
||||
decode_tok_s_live: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct Cache {
|
||||
requests: u64,
|
||||
hit_requests: u64,
|
||||
hit_ratio: Option<f64>,
|
||||
prompt_tokens: u64,
|
||||
reused_tokens: u64,
|
||||
token_hit_ratio: Option<f64>,
|
||||
last_prompt_tokens: u64,
|
||||
last_reused_tokens: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct Context {
|
||||
live_tokens: u64,
|
||||
max_tokens: u64,
|
||||
used_pct: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct Document {
|
||||
version: u32,
|
||||
ts_ms: u64,
|
||||
uptime_s: u64,
|
||||
phase: Phase,
|
||||
gpu: Option<GpuSample>,
|
||||
ram: Option<Ram>,
|
||||
cpu: Option<Cpu>,
|
||||
throughput: Rates,
|
||||
cache: Cache,
|
||||
context: Context,
|
||||
}
|
||||
|
||||
fn ratio(part: u64, whole: u64) -> Option<f64> {
|
||||
(whole > 0).then(|| (part as f64 / whole as f64 * 1e4).round() / 1e4)
|
||||
}
|
||||
|
||||
fn lifetime_rate(tokens: u64, ms: f64) -> Option<f64> {
|
||||
(ms > 0.0).then(|| round1(tokens as f64 * 1e3 / ms))
|
||||
}
|
||||
|
||||
/// Everything the sampler measured this tick.
|
||||
pub struct Measured {
|
||||
pub now_ms: u64,
|
||||
pub uptime_s: u64,
|
||||
pub gpu: Option<GpuSample>,
|
||||
pub meminfo: procfs::MemInfo,
|
||||
pub status: procfs::ProcStatus,
|
||||
pub cores: u32,
|
||||
pub cpu: Option<(f64, f64)>,
|
||||
}
|
||||
|
||||
fn render(state: &State, measured: &Measured) -> String {
|
||||
let mib = |bytes: Option<u64>| bytes.map_or(0, |b| b >> 20);
|
||||
let ram = measured.meminfo.mem_total.map(|total| Ram {
|
||||
total_mib: total >> 20,
|
||||
available_mib: mib(measured.meminfo.mem_available),
|
||||
process_rss_mib: mib(measured.status.vm_rss),
|
||||
process_pinned_mib: mib(measured.status.vm_pin),
|
||||
swap_used_mib: measured.meminfo.swap_total.unwrap_or(0).saturating_sub(measured.meminfo.swap_free.unwrap_or(0)) >> 20,
|
||||
});
|
||||
let live_rate = match (state.phase, state.first_token) {
|
||||
(Phase::Decode, Some(first)) if state.produced_now > 1 => {
|
||||
let secs = first.elapsed().as_secs_f64();
|
||||
(secs > 0.05).then(|| round1(state.produced_now as f64 / secs))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let document = Document {
|
||||
version: 1,
|
||||
ts_ms: measured.now_ms,
|
||||
uptime_s: measured.uptime_s,
|
||||
phase: state.phase,
|
||||
gpu: measured.gpu,
|
||||
ram,
|
||||
cpu: measured.cpu.map(|(process, system)| Cpu {
|
||||
cores: measured.cores,
|
||||
process_busy_cores: round1(process),
|
||||
system_busy_pct: round1(system),
|
||||
}),
|
||||
throughput: Rates {
|
||||
prefill_tok_s_last: state.last_prefill_tok_s.map(round1),
|
||||
prefill_tok_s_avg: state.prefill_ema.map(round1),
|
||||
prefill_tok_s_lifetime: lifetime_rate(state.prefill_tokens, state.prefill_ms),
|
||||
decode_tok_s_last: state.last_decode_tok_s.map(round1),
|
||||
decode_tok_s_avg: state.decode_ema.map(round1),
|
||||
decode_tok_s_lifetime: lifetime_rate(state.decode_tokens, state.decode_ms),
|
||||
decode_tok_s_live: live_rate,
|
||||
},
|
||||
cache: Cache {
|
||||
requests: state.requests,
|
||||
hit_requests: state.cache_hit_requests,
|
||||
hit_ratio: ratio(state.cache_hit_requests, state.requests),
|
||||
prompt_tokens: state.prompt_tokens,
|
||||
reused_tokens: state.reused_tokens,
|
||||
token_hit_ratio: ratio(state.reused_tokens, state.prompt_tokens),
|
||||
last_prompt_tokens: state.last_prompt_tokens,
|
||||
last_reused_tokens: state.last_reused_tokens,
|
||||
},
|
||||
context: Context {
|
||||
live_tokens: state.context_live,
|
||||
max_tokens: state.context_max,
|
||||
used_pct: ratio(state.context_live, state.context_max).map(|r| (r * 1e4).round() / 1e2),
|
||||
},
|
||||
};
|
||||
serde_json::to_string(&document).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Render the current document from the recorded state and one measurement (public for tests and for a one-shot read).
|
||||
pub fn render_now(measured: &Measured) -> String {
|
||||
let guard = lock(&STATE);
|
||||
match guard.as_ref() {
|
||||
Some(state) => render(state, measured),
|
||||
None => render(&State::default(), measured),
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Sampler {
|
||||
stop: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl Sampler {
|
||||
pub fn stop(&self) {
|
||||
self.stop.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Sampler {
|
||||
fn drop(&mut self) {
|
||||
self.stop();
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the once-a-second sampler over the real `/proc`. `gpu_probe` reads the device (NVML); `None` reports no GPU block.
|
||||
pub fn start(gpu_probe: Option<GpuProbe>, period: Duration) -> Sampler {
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let flag = stop.clone();
|
||||
let spawned = std::thread::Builder::new().name("leleka-telemetry".into()).spawn(move || {
|
||||
let src = RealProc;
|
||||
let began = Instant::now();
|
||||
let cores = std::thread::available_parallelism().map_or(0, |n| n.get() as u32);
|
||||
let mut previous = read_cpu(&src).map(|reading| (reading, Instant::now()));
|
||||
while !flag.load(Ordering::Acquire) {
|
||||
std::thread::sleep(period);
|
||||
let now = Instant::now();
|
||||
let reading = read_cpu(&src);
|
||||
let cpu = match (&previous, &reading) {
|
||||
(Some((before, at)), Some(after)) => Some(cpu_usage(before, after, now.duration_since(*at))),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(reading) = reading {
|
||||
previous = Some((reading, now));
|
||||
}
|
||||
let measured = Measured {
|
||||
now_ms: SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64),
|
||||
uptime_s: began.elapsed().as_secs(),
|
||||
gpu: gpu_probe.as_ref().and_then(|probe| probe()),
|
||||
meminfo: procfs::parse_meminfo(&src.read("/proc/meminfo").unwrap_or_default()),
|
||||
status: procfs::parse_status(&src.read("/proc/self/status").unwrap_or_default()),
|
||||
cores,
|
||||
cpu,
|
||||
};
|
||||
let text = render_now(&measured);
|
||||
*lock(&PUBLISHED) = Some(text);
|
||||
}
|
||||
});
|
||||
if spawned.is_err() {
|
||||
stop.store(true, Ordering::Release);
|
||||
}
|
||||
Sampler { stop }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
static SERIAL: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn measured() -> Measured {
|
||||
Measured {
|
||||
now_ms: 1,
|
||||
uptime_s: 5,
|
||||
gpu: Some(GpuSample { index: 0, util_pct: 91, mem_util_pct: 40, vram_used_mib: 30000, vram_total_mib: 32607, power_w: Some(480.0), sm_clock_mhz: Some(2900) }),
|
||||
meminfo: procfs::parse_meminfo("MemTotal: 125829120 kB\nMemAvailable: 70000000 kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n"),
|
||||
status: procfs::parse_status("VmRSS:\t55000000 kB\nVmPin:\t3000000 kB\n"),
|
||||
cores: 32,
|
||||
cpu: Some((7.4, 31.0)),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn self_stat_survives_a_command_name_with_spaces_and_parentheses() {
|
||||
let line = "123 (a b) c) S 1 2 3 4 5 6 7 8 9 10 250 50 0 0 20 0 1 0";
|
||||
assert_eq!(parse_self_stat_ticks(line), Some(300));
|
||||
assert_eq!(parse_self_stat_ticks("garbage"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_cpu_counts_idle_and_iowait_as_not_busy() {
|
||||
let (busy, total) = parse_stat_cpu("cpu 100 0 50 800 50 0 0 0 0 0\ncpu0 1 2 3 4\n").unwrap();
|
||||
assert_eq!((busy, total), (150, 1000));
|
||||
let before = CpuReading { process_ticks: 1000, system_busy: 0, system_total: 0 };
|
||||
let after = CpuReading { process_ticks: 1740, system_busy: 150, system_total: 1000 };
|
||||
let (process, system) = cpu_usage(&before, &after, Duration::from_secs(1));
|
||||
assert!((process - 7.4).abs() < 1e-9 && (system - 15.0).abs() < 1e-9, "{process} {system}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requests_fold_into_rates_cache_and_context() {
|
||||
let _serial = lock(&SERIAL);
|
||||
*lock(&STATE) = None;
|
||||
set_context_max(262_144);
|
||||
request_started(100_000, 80_000);
|
||||
tokens_delivered(4);
|
||||
request_finished(100_000, 80_000, 400, 4_000.0, 4_000.0);
|
||||
request_started(101_000, 0);
|
||||
request_finished(101_000, 0, 200, 20_000.0, 2_000.0);
|
||||
let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap();
|
||||
assert_eq!(doc["phase"], "idle");
|
||||
assert_eq!(doc["cache"]["requests"], 2);
|
||||
assert_eq!(doc["cache"]["hit_requests"], 1);
|
||||
assert_eq!(doc["cache"]["hit_ratio"], 0.5);
|
||||
// 100000+101000 prompt tokens, 80000 reused
|
||||
assert_eq!(doc["cache"]["token_hit_ratio"], 0.398);
|
||||
// prefill: 20000 tokens in 4000 ms = 5000/s, then 101000 in 20000 ms = 5050/s
|
||||
assert_eq!(doc["throughput"]["prefill_tok_s_last"], 5050.0);
|
||||
assert_eq!(doc["throughput"]["decode_tok_s_last"], 100.0);
|
||||
assert_eq!(doc["throughput"]["decode_tok_s_lifetime"], 100.0);
|
||||
assert_eq!(doc["context"]["live_tokens"], 101_200);
|
||||
assert_eq!(doc["context"]["max_tokens"], 262_144);
|
||||
assert_eq!(doc["gpu"]["util_pct"], 91);
|
||||
assert_eq!(doc["ram"]["total_mib"], 122_880);
|
||||
assert_eq!(doc["cpu"]["process_busy_cores"], 7.4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_state_renders_nulls_not_zeros_for_unmeasured_rates() {
|
||||
let _serial = lock(&SERIAL);
|
||||
*lock(&STATE) = None;
|
||||
let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap();
|
||||
assert!(doc["throughput"]["decode_tok_s_last"].is_null());
|
||||
assert!(doc["cache"]["hit_ratio"].is_null());
|
||||
assert!(doc["context"]["used_pct"].is_null());
|
||||
}
|
||||
}
|
||||
@@ -845,6 +845,12 @@ impl Backend for Proxy {
|
||||
}
|
||||
leleka_memory::published_report()
|
||||
}
|
||||
fn telemetry_report(&self) -> Option<String> {
|
||||
if self.shared.shutdown.load(Ordering::Acquire) {
|
||||
return None;
|
||||
}
|
||||
leleka_memory::telemetry::published_telemetry()
|
||||
}
|
||||
fn load(
|
||||
&mut self,
|
||||
model: ModelDescriptor,
|
||||
@@ -1435,6 +1441,7 @@ fn serve_load(
|
||||
}
|
||||
let driver = Driver::load()
|
||||
.map_err(|_| load_failure(LoadPhase::Driver, unavailable("CUDA driver unavailable")))?;
|
||||
GPU_ORDINAL.store(config.gpu_device_ordinal, Ordering::Relaxed);
|
||||
let device = driver
|
||||
.device(config.gpu_device_ordinal as i32)
|
||||
.map_err(|_| load_failure(LoadPhase::Device, unavailable("CUDA device unavailable")))?;
|
||||
@@ -2500,6 +2507,9 @@ fn validate_request(request: &GenerationRequest) -> Result<(), BackendError> {
|
||||
/// Validated sampling plan of a request: `None` keeps the ordinary greedy path
|
||||
/// (temperature 0 and no penalty), `Some` carries the Original `SamplerParams` for
|
||||
/// the host sampler. `entropy` seeds requests that carry no seed (Original `seed = 0`).
|
||||
/// The CUDA ordinal of the loaded device, for the telemetry sampler (NVML indexes the same physical order).
|
||||
pub(crate) static GPU_ORDINAL: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
|
||||
fn request_sampler(
|
||||
request: &GenerationRequest,
|
||||
entropy: u64,
|
||||
|
||||
@@ -461,9 +461,11 @@ mod runner {
|
||||
let mut captured: Option<GenerationFailure> = None;
|
||||
let mut timed_out = false;
|
||||
let mut generated_ids: Vec<i32> = Vec::new();
|
||||
leleka_memory::telemetry::request_started(prompt.len() as u64, 0);
|
||||
let result = {
|
||||
let mut emit = |tokens: &[i32]| -> Result<(), ForwardError> {
|
||||
generated_ids.extend_from_slice(tokens);
|
||||
leleka_memory::telemetry::tokens_delivered(tokens.len() as u64);
|
||||
let mut deliver = |token: i32| -> Result<(), GenerationFailure> {
|
||||
count += 1;
|
||||
if stop_tokens.contains(&token) {
|
||||
@@ -496,21 +498,31 @@ mod runner {
|
||||
stack.serve(&serve_request, &mut emit, &mut cancel_probe)
|
||||
};
|
||||
if let Some(failure) = captured.take() {
|
||||
leleka_memory::telemetry::request_aborted();
|
||||
return Err(failure);
|
||||
}
|
||||
if timed_out {
|
||||
leleka_memory::telemetry::request_aborted();
|
||||
return Err(unavailable("generation deadline exceeded").into());
|
||||
}
|
||||
let outcome = match result {
|
||||
Ok(outcome) => outcome,
|
||||
Err(ServeError::Cancelled) => return Err(GenerationFailure::Cancelled),
|
||||
Err(ServeError::Refused(admission)) => return Err(admission_error(admission).into()),
|
||||
Err(ServeError::Cancelled) => {
|
||||
leleka_memory::telemetry::request_aborted();
|
||||
return Err(GenerationFailure::Cancelled);
|
||||
}
|
||||
Err(ServeError::Refused(admission)) => {
|
||||
leleka_memory::telemetry::request_aborted();
|
||||
return Err(admission_error(admission).into());
|
||||
}
|
||||
Err(ServeError::Failed(error)) => {
|
||||
leleka_memory::telemetry::request_aborted();
|
||||
use std::io::Write;
|
||||
let _ = writeln!(std::io::stderr().lock(), "leleka-serve request failed: class={error:?}");
|
||||
return Err(unavailable("Original serve request failed").into());
|
||||
}
|
||||
Err(ServeError::Broken(error)) => {
|
||||
leleka_memory::telemetry::request_aborted();
|
||||
use std::io::Write;
|
||||
let _ = writeln!(std::io::stderr().lock(), "leleka-serve stack lost an owner: class={error:?}");
|
||||
return Err(unavailable("Original serve stack lost a physical owner").into());
|
||||
@@ -533,6 +545,8 @@ mod runner {
|
||||
output_tokens: count,
|
||||
reused_input_tokens: stack.reused_tokens() as u64,
|
||||
};
|
||||
let (prompt_ms, decode_ms) = stack.last_timing();
|
||||
leleka_memory::telemetry::request_finished(usage.input_tokens, usage.reused_input_tokens, usage.output_tokens, prompt_ms, decode_ms);
|
||||
emit_event(sink, &cancelled, GenerationEvent::Usage(usage.clone()))?;
|
||||
{
|
||||
use std::io::Write;
|
||||
@@ -597,6 +611,24 @@ mod runner {
|
||||
})?;
|
||||
publish_prefix_summary(&stack, shared);
|
||||
crate::load_clock::lap("serve_stack_open_total");
|
||||
// operator telemetry: GPU/RAM/CPU once a second, throughput and cache hits recorded per request
|
||||
leleka_memory::telemetry::set_context_max(u64::from(context_tokens));
|
||||
let _telemetry = leleka_memory::telemetry::start(
|
||||
leleka_cuda_driver::nvml::Nvml::open(crate::backend::GPU_ORDINAL.load(Ordering::Relaxed)).map(|nvml| {
|
||||
Box::new(move || {
|
||||
nvml.sample().map(|s| leleka_memory::telemetry::GpuSample {
|
||||
index: s.index,
|
||||
util_pct: s.util_pct,
|
||||
mem_util_pct: s.mem_util_pct,
|
||||
vram_used_mib: s.vram_used_mib,
|
||||
vram_total_mib: s.vram_total_mib,
|
||||
power_w: s.power_w,
|
||||
sm_clock_mhz: s.sm_clock_mhz,
|
||||
})
|
||||
}) as Box<dyn Fn() -> Option<leleka_memory::telemetry::GpuSample> + Send + Sync>
|
||||
}),
|
||||
Duration::from_secs(1),
|
||||
);
|
||||
let mut stack = Some(stack);
|
||||
if shared.shutdown.load(Ordering::Acquire) {
|
||||
if let Some(stack) = stack.take() {
|
||||
|
||||
@@ -59,6 +59,8 @@ message Snapshot {
|
||||
string prefix_cache_json = 11;
|
||||
// JSON report of the runtime's memory governor (docs/memory-safety.md): pressure level, Retry-After, plan, inventory, counters. Empty when it has none.
|
||||
string memory_json = 12;
|
||||
// JSON telemetry of the runtime for the operator (leleka-memory telemetry): GPU load and VRAM, host RAM, CPU cores in use, prefill and decode tokens/s, prefix-cache hits, context in use. Empty when it has none.
|
||||
string telemetry_json = 13;
|
||||
}
|
||||
message LoadRequest { string operation_id = 1; string expected_epoch = 2; ModelDescriptor model = 3; LoadConfig config = 4; }
|
||||
message UnloadRequest { string operation_id = 1; string expected_epoch = 2; string handle = 3; }
|
||||
|
||||
@@ -38,6 +38,8 @@ pub struct GrpcBackend {
|
||||
prefix_summary: Mutex<Option<String>>,
|
||||
/// The runtime's memory-governor report from the last probe (`Backend::memory_report`).
|
||||
memory_report: Mutex<Option<String>>,
|
||||
/// The runtime's telemetry document from the last probe (`Backend::telemetry_report`).
|
||||
telemetry_report: Mutex<Option<String>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -96,6 +98,7 @@ impl GrpcBackend {
|
||||
active: Arc::new(Mutex::new(None)),
|
||||
prefix_summary: Mutex::new(None),
|
||||
memory_report: Mutex::new(None),
|
||||
telemetry_report: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,6 +152,9 @@ impl api::Backend for GrpcBackend {
|
||||
// memory pressure matters before and without a loaded model: no epoch/ready condition, only a non-empty report
|
||||
*cell = probe.as_ref().filter(|snapshot| !snapshot.memory_json.is_empty()).map(|snapshot| snapshot.memory_json.clone());
|
||||
}
|
||||
if let Ok(mut cell) = self.telemetry_report.lock() {
|
||||
*cell = probe.as_ref().filter(|snapshot| !snapshot.telemetry_json.is_empty()).map(|snapshot| snapshot.telemetry_json.clone());
|
||||
}
|
||||
if let Ok(mut cell) = self.prefix_summary.lock() {
|
||||
*cell = probe
|
||||
.as_ref()
|
||||
@@ -189,6 +195,11 @@ impl api::Backend for GrpcBackend {
|
||||
self.memory_report.lock().ok().and_then(|cell| cell.clone())
|
||||
}
|
||||
|
||||
/// The runtime's telemetry document as of the last `capabilities` probe; `None` when unreachable or it has none.
|
||||
fn telemetry_report(&self) -> Option<String> {
|
||||
self.telemetry_report.lock().ok().and_then(|cell| cell.clone())
|
||||
}
|
||||
|
||||
fn load(
|
||||
&mut self,
|
||||
model: api::ModelDescriptor,
|
||||
|
||||
@@ -348,6 +348,7 @@ mod tests {
|
||||
active_request_id: String::new(),
|
||||
prefix_cache_json: String::new(),
|
||||
memory_json: String::new(),
|
||||
telemetry_json: String::new(),
|
||||
};
|
||||
assert!(validate_snapshot(&snapshot).is_ok());
|
||||
snapshot
|
||||
@@ -387,6 +388,7 @@ mod tests {
|
||||
active_request_id: String::new(),
|
||||
prefix_cache_json: String::new(),
|
||||
memory_json: String::new(),
|
||||
telemetry_json: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,6 +117,7 @@ impl Fake {
|
||||
active_request_id: String::new(),
|
||||
prefix_cache_json: String::new(),
|
||||
memory_json: String::new(),
|
||||
telemetry_json: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -57,6 +57,8 @@ struct State {
|
||||
prefix_cache_json: String,
|
||||
/// The backend's memory-governor report as of the last observation (`Backend::memory_report`).
|
||||
memory_json: String,
|
||||
/// The backend's telemetry document as of the last observation (`Backend::telemetry_report`).
|
||||
telemetry_json: String,
|
||||
}
|
||||
struct Operation {
|
||||
digest: [u8; 32],
|
||||
@@ -137,6 +139,7 @@ fn snapshot(state: &State) -> proto::Snapshot {
|
||||
active_request_id: state.active.clone().unwrap_or_default(),
|
||||
prefix_cache_json: if state.stopping { String::new() } else { state.prefix_cache_json.clone() },
|
||||
memory_json: if state.stopping { String::new() } else { state.memory_json.clone() },
|
||||
telemetry_json: if state.stopping { String::new() } else { state.telemetry_json.clone() },
|
||||
}
|
||||
}
|
||||
fn publish(inner: &Inner, state: &mut State) {
|
||||
@@ -175,6 +178,7 @@ impl RuntimeServer {
|
||||
stopping: false,
|
||||
prefix_cache_json: String::new(),
|
||||
memory_json: String::new(),
|
||||
telemetry_json: String::new(),
|
||||
}),
|
||||
changes,
|
||||
controls: Arc::new(Semaphore::new(16)),
|
||||
@@ -746,15 +750,16 @@ fn close_admission(inner: &Inner) {
|
||||
}
|
||||
fn refresh_capabilities(inner: &Inner) {
|
||||
// Observations must not wait behind a load/acceptance acknowledgement.
|
||||
let (capabilities, summary, memory) = match inner.backend.try_lock() {
|
||||
Ok(backend) => (backend.capabilities(), backend.prefix_cache_summary(), backend.memory_report()),
|
||||
let (capabilities, summary, memory, telemetry) = match inner.backend.try_lock() {
|
||||
Ok(backend) => (backend.capabilities(), backend.prefix_cache_summary(), backend.memory_report(), backend.telemetry_report()),
|
||||
Err(std::sync::TryLockError::WouldBlock) => return,
|
||||
Err(std::sync::TryLockError::Poisoned(_)) => (api::BackendCapabilities::default(), None, None),
|
||||
Err(std::sync::TryLockError::Poisoned(_)) => (api::BackendCapabilities::default(), None, None, None),
|
||||
};
|
||||
if let Ok(mut state) = inner.state.lock() {
|
||||
// the summary changes with every request; watchers are told about it only through a snapshot they ask for
|
||||
state.prefix_cache_json = summary.unwrap_or_default();
|
||||
state.memory_json = memory.unwrap_or_default();
|
||||
state.telemetry_json = telemetry.unwrap_or_default();
|
||||
let capabilities = if state.loaded.is_some() {
|
||||
capabilities
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user