Merge branch 'claude/platform' into claude/port-gpu-bringup
# Conflicts: # crates/deploy/src/app.rs # crates/deploy/src/cli.rs
This commit is contained in:
+109
-17
@@ -2,7 +2,7 @@ use std::sync::Arc;
|
|||||||
|
|
||||||
use axum::{
|
use axum::{
|
||||||
Json, Router,
|
Json, Router,
|
||||||
extract::{DefaultBodyLimit, State},
|
extract::{DefaultBodyLimit, RawQuery, State},
|
||||||
http::{HeaderMap, StatusCode},
|
http::{HeaderMap, StatusCode},
|
||||||
middleware,
|
middleware,
|
||||||
response::{IntoResponse, Response},
|
response::{IntoResponse, Response},
|
||||||
@@ -47,6 +47,8 @@ pub struct AppState {
|
|||||||
pub prefix_cache: Arc<crate::prefix_view::PrefixView>,
|
pub prefix_cache: Arc<crate::prefix_view::PrefixView>,
|
||||||
/// The engine's memory-governor report: the pressure gate and the numbers behind `GET /v1/status` `memory` (`docs/memory-safety.md`).
|
/// The engine's memory-governor report: the pressure gate and the numbers behind `GET /v1/status` `memory` (`docs/memory-safety.md`).
|
||||||
pub memory: Arc<crate::memory_view::MemoryView>,
|
pub memory: Arc<crate::memory_view::MemoryView>,
|
||||||
|
/// The API request monitor (`api_monitor` in the config; off by default): `GET /api/requests`.
|
||||||
|
pub monitor: Arc<crate::request_monitor::RequestMonitor>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for AppState {
|
impl Default for AppState {
|
||||||
@@ -71,6 +73,7 @@ impl Default for AppState {
|
|||||||
vision: None,
|
vision: None,
|
||||||
prefix_cache: Arc::new(Default::default()),
|
prefix_cache: Arc::new(Default::default()),
|
||||||
memory: Arc::new(Default::default()),
|
memory: Arc::new(Default::default()),
|
||||||
|
monitor: Arc::new(Default::default()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -117,9 +120,14 @@ pub fn router(state: AppState) -> Router {
|
|||||||
.route("/v1/models/{id}", get(crate::models_api::retrieve))
|
.route("/v1/models/{id}", get(crate::models_api::retrieve))
|
||||||
.route(
|
.route(
|
||||||
"/v1/responses",
|
"/v1/responses",
|
||||||
post(responses::create_route).layer(middleware::from_fn_with_state(
|
post(responses::create_route)
|
||||||
state.lifecycle.clone(),
|
.layer(middleware::from_fn_with_state(
|
||||||
crate::lifecycle::admit,
|
state.lifecycle.clone(),
|
||||||
|
crate::lifecycle::admit,
|
||||||
|
))
|
||||||
|
.layer(middleware::from_fn_with_state(
|
||||||
|
state.monitor.clone(),
|
||||||
|
crate::request_monitor::capture,
|
||||||
)),
|
)),
|
||||||
)
|
)
|
||||||
.route(
|
.route(
|
||||||
@@ -131,9 +139,14 @@ pub fn router(state: AppState) -> Router {
|
|||||||
)
|
)
|
||||||
.route(
|
.route(
|
||||||
"/v1/chat/completions",
|
"/v1/chat/completions",
|
||||||
post(crate::chat::create).layer(middleware::from_fn_with_state(
|
post(crate::chat::create)
|
||||||
state.lifecycle.clone(),
|
.layer(middleware::from_fn_with_state(
|
||||||
crate::lifecycle::admit,
|
state.lifecycle.clone(),
|
||||||
|
crate::lifecycle::admit,
|
||||||
|
))
|
||||||
|
.layer(middleware::from_fn_with_state(
|
||||||
|
state.monitor.clone(),
|
||||||
|
crate::request_monitor::capture,
|
||||||
)),
|
)),
|
||||||
)
|
)
|
||||||
.route(
|
.route(
|
||||||
@@ -152,8 +165,13 @@ pub fn router(state: AppState) -> Router {
|
|||||||
state.lifecycle.clone(),
|
state.lifecycle.clone(),
|
||||||
crate::lifecycle::admit,
|
crate::lifecycle::admit,
|
||||||
))
|
))
|
||||||
.layer(middleware::from_fn(crate::messages::protocol)),
|
.layer(middleware::from_fn(crate::messages::protocol))
|
||||||
|
.layer(middleware::from_fn_with_state(
|
||||||
|
state.monitor.clone(),
|
||||||
|
crate::request_monitor::capture,
|
||||||
|
)),
|
||||||
)
|
)
|
||||||
|
.route("/api/requests", get(crate::server_api::api_requests))
|
||||||
.route("/admin/lifecycle", get(lifecycle_status))
|
.route("/admin/lifecycle", get(lifecycle_status))
|
||||||
.route(
|
.route(
|
||||||
"/v1/responses/{id}",
|
"/v1/responses/{id}",
|
||||||
@@ -239,31 +257,105 @@ async fn resume(State(state): State<AppState>, headers: HeaderMap) -> Response {
|
|||||||
lifecycle_status(State(state)).await.into_response()
|
lifecycle_status(State(state)).await.into_response()
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn metrics(State(state): State<AppState>) -> Json<serde_json::Value> {
|
/// `GET /metrics`: the native JSON document, or its Prometheus text exposition (`?format=prometheus`, or an `Accept` that asks
|
||||||
|
/// for `text/plain` / OpenMetrics, as a Prometheus scraper sends). `?requests=all` lists every kept generation, not the last 12.
|
||||||
|
async fn metrics(State(state): State<AppState>, RawQuery(query): RawQuery, headers: HeaderMap) -> Response {
|
||||||
|
let accept = headers.get(axum::http::header::ACCEPT).and_then(|v| v.to_str().ok());
|
||||||
|
let all = query.as_deref().is_some_and(|q| q.split('&').any(|pair| pair == "requests=all"));
|
||||||
|
let document = metrics_document(&state, all).await;
|
||||||
|
if crate::prometheus::wanted(query.as_deref(), accept) {
|
||||||
|
let mut response = crate::prometheus::render(&document).into_response();
|
||||||
|
response.headers_mut().insert(
|
||||||
|
axum::http::header::CONTENT_TYPE,
|
||||||
|
axum::http::HeaderValue::from_static(crate::prometheus::CONTENT_TYPE),
|
||||||
|
);
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
Json(document).into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The generations shown by default in `requests` (the Python Monitor shows twelve).
|
||||||
|
const RECENT_REQUESTS: usize = 12;
|
||||||
|
|
||||||
|
/// The `/metrics` document. `schema_version` stays 1: the members below `generation` are the Python Monitor's
|
||||||
|
/// (`engine`, `live`, `requests`, `requests_kept`, `totals`, `hardware`, `hardware_static`, `history`, `time`) and were added
|
||||||
|
/// beside the native ones, which are unchanged.
|
||||||
|
pub async fn metrics_document(state: &AppState, all_requests: bool) -> serde_json::Value {
|
||||||
let worker = *state.worker.read().await;
|
let worker = *state.worker.read().await;
|
||||||
let generation = worker.metrics;
|
let generation = worker.metrics;
|
||||||
|
let lifecycle = state.lifecycle.snapshot();
|
||||||
let queue_capacity = state.generation.as_ref().map(mpsc::Sender::max_capacity);
|
let queue_capacity = state.generation.as_ref().map(mpsc::Sender::max_capacity);
|
||||||
let queue_used = state
|
let queue_used = state
|
||||||
.generation
|
.generation
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|sender| sender.max_capacity() - sender.capacity());
|
.map(|sender| sender.max_capacity() - sender.capacity());
|
||||||
Json(serde_json::json!({
|
let memory = state.memory.status();
|
||||||
|
let (hardware, hardware_static, telemetry, history) = state.memory.hardware();
|
||||||
|
let busy = generation.active_since.is_some();
|
||||||
|
let phase = telemetry["phase"].as_str();
|
||||||
|
let engine_state = if worker.state != WorkerState::Ready {
|
||||||
|
serde_json::to_value(worker.state).unwrap_or(serde_json::Value::Null)
|
||||||
|
} else if busy {
|
||||||
|
serde_json::json!(if phase == Some("prefill") { "reading" } else { "generating" })
|
||||||
|
} else {
|
||||||
|
serde_json::json!("idle")
|
||||||
|
};
|
||||||
|
let elapsed_ms = generation.active_since.map(|start| start.elapsed().as_millis().min(u64::MAX as u128) as u64);
|
||||||
|
let live = serde_json::json!({
|
||||||
|
"state": engine_state,
|
||||||
|
"active": busy,
|
||||||
|
"queued": lifecycle.generation_jobs.saturating_sub(usize::from(busy)),
|
||||||
|
"phase": if busy { phase.map_or(serde_json::Value::Null, |p| serde_json::json!(p)) } else { serde_json::Value::Null },
|
||||||
|
"prompt_tokens": if busy { telemetry["request"]["prompt_tokens"].clone() } else { serde_json::Value::Null },
|
||||||
|
"generated": if busy { telemetry["request"]["generated_tokens"].clone() } else { serde_json::Value::Null },
|
||||||
|
"elapsed_s": elapsed_ms.map(|ms| (ms as f64 / 100.0).round() / 10.0),
|
||||||
|
"tok_s": if busy { hardware["tok_s"].clone() } else { serde_json::Value::Null },
|
||||||
|
"tok_s_mean": if busy { hardware["tok_s_mean"].clone() } else { serde_json::Value::Null },
|
||||||
|
"prefill_tok_s_mean": if busy { hardware["prefill_tok_s_mean"].clone() } else { serde_json::Value::Null },
|
||||||
|
"prompt_read": null, "prompt_total": null, "max_tokens": null, "tok_s_window_s": null,
|
||||||
|
});
|
||||||
|
let engine = serde_json::json!({
|
||||||
|
"model": state.model, "max_context": worker.max_context.or(worker.known_max_context),
|
||||||
|
"images": state.vision.is_some(), "version": env!("CARGO_PKG_VERSION"),
|
||||||
|
"api_monitor": state.monitor.enabled(),
|
||||||
|
"settings": telemetry["settings"].clone(),
|
||||||
|
});
|
||||||
|
let (requests, requests_kept, totals) = match generation.history {
|
||||||
|
Some(history) => (
|
||||||
|
history.requests((!all_requests).then_some(RECENT_REQUESTS)),
|
||||||
|
history.kept(),
|
||||||
|
history.totals(),
|
||||||
|
),
|
||||||
|
None => (Vec::new(), 0, serde_json::Value::Null),
|
||||||
|
};
|
||||||
|
serde_json::json!({
|
||||||
"schema_version": 1,
|
"schema_version": 1,
|
||||||
"scope": "control_plane_process",
|
"scope": "control_plane_process",
|
||||||
"model": state.model,
|
"model": state.model,
|
||||||
"worker": worker.state,
|
"worker": worker.state,
|
||||||
"active": generation.active_since.is_some(),
|
"up": worker.state == WorkerState::Ready,
|
||||||
"active_elapsed_ms": generation.active_since.map(|start| start.elapsed().as_millis().min(u64::MAX as u128) as u64),
|
"active": busy,
|
||||||
|
"active_elapsed_ms": elapsed_ms,
|
||||||
"queue_capacity": queue_capacity,
|
"queue_capacity": queue_capacity,
|
||||||
"queue_used": queue_used,
|
"queue_used": queue_used,
|
||||||
"memory": {
|
"memory": {
|
||||||
"level": state.memory.status()["gate"]["level"].clone(),
|
"level": memory["gate"]["level"].clone(),
|
||||||
"gate_rejections": state.memory.gate_rejections(),
|
"gate_rejections": state.memory.gate_rejections(),
|
||||||
"available_bytes": state.memory.status()["gate"]["available_bytes"].clone(),
|
"available_bytes": memory["gate"]["available_bytes"].clone(),
|
||||||
},
|
},
|
||||||
"generation": generation,
|
"generation": generation,
|
||||||
"done_decode_tokens_per_second": crate::metrics::token_rate(generation.done_generated_tokens, generation.done_decode_ms),
|
"done_decode_tokens_per_second": crate::metrics::token_rate(generation.done_generated_tokens, generation.done_decode_ms),
|
||||||
}))
|
"engine": engine,
|
||||||
|
"live": live,
|
||||||
|
"requests": requests,
|
||||||
|
"requests_kept": requests_kept,
|
||||||
|
"totals": totals,
|
||||||
|
"hardware": hardware,
|
||||||
|
"hardware_static": hardware_static,
|
||||||
|
"history": history,
|
||||||
|
"telemetry": telemetry,
|
||||||
|
"time": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64()),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn ready(State(state): State<AppState>) -> (StatusCode, Json<StatusResponse>) {
|
async fn ready(State(state): State<AppState>) -> (StatusCode, Json<StatusResponse>) {
|
||||||
@@ -430,7 +522,7 @@ mod tests {
|
|||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
let initial_status = serde_json::to_value(status(State(state.clone())).await.0).unwrap();
|
let initial_status = serde_json::to_value(status(State(state.clone())).await.0).unwrap();
|
||||||
let initial_metrics = metrics(State(state.clone())).await.0;
|
let initial_metrics = metrics_document(&state, false).await;
|
||||||
assert_eq!(initial_metrics["active"], false);
|
assert_eq!(initial_metrics["active"], false);
|
||||||
assert!(initial_metrics["done_decode_tokens_per_second"].is_null());
|
assert!(initial_metrics["done_decode_tokens_per_second"].is_null());
|
||||||
let (result, _rx) = tokio::sync::oneshot::channel();
|
let (result, _rx) = tokio::sync::oneshot::channel();
|
||||||
@@ -468,7 +560,7 @@ mod tests {
|
|||||||
initial_status
|
initial_status
|
||||||
);
|
);
|
||||||
receiver.recv().await.unwrap();
|
receiver.recv().await.unwrap();
|
||||||
assert_eq!(metrics(State(state)).await.0["queue_used"], 0);
|
assert_eq!(metrics_document(&state, false).await["queue_used"], 0);
|
||||||
server.abort();
|
server.abort();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -182,6 +182,7 @@ mod tests {
|
|||||||
for path in [
|
for path in [
|
||||||
"/status",
|
"/status",
|
||||||
"/metrics",
|
"/metrics",
|
||||||
|
"/api/requests",
|
||||||
"/ready",
|
"/ready",
|
||||||
"/v1/responses",
|
"/v1/responses",
|
||||||
"/admin/drain",
|
"/admin/drain",
|
||||||
|
|||||||
@@ -36,6 +36,8 @@ pub struct Config {
|
|||||||
pub cors_origins: Vec<String>,
|
pub cors_origins: Vec<String>,
|
||||||
/// Origins that count as this server's own page (`trusted_origins`; no wildcard).
|
/// Origins that count as this server's own page (`trusted_origins`; no wildcard).
|
||||||
pub trusted_origins: Vec<String>,
|
pub trusted_origins: Vec<String>,
|
||||||
|
/// `api_monitor`: keep the last requests' prompts and answers in memory for `GET /api/requests` (off by default).
|
||||||
|
pub api_monitor: bool,
|
||||||
/// The `sampling` block: defaults for what a request leaves out.
|
/// The `sampling` block: defaults for what a request leaves out.
|
||||||
pub sampling: leleka_serving_policy::shared::ConfigSampling,
|
pub sampling: leleka_serving_policy::shared::ConfigSampling,
|
||||||
/// `reasoning_budget_tokens`: the default thinking budget (0: none).
|
/// `reasoning_budget_tokens`: the default thinking budget (0: none).
|
||||||
@@ -75,6 +77,7 @@ struct FileConfig {
|
|||||||
aliases: Option<serde_json::Value>,
|
aliases: Option<serde_json::Value>,
|
||||||
cors_origins: Option<serde_json::Value>,
|
cors_origins: Option<serde_json::Value>,
|
||||||
trusted_origins: Option<serde_json::Value>,
|
trusted_origins: Option<serde_json::Value>,
|
||||||
|
api_monitor: Option<bool>,
|
||||||
sampling: Option<serde_json::Value>,
|
sampling: Option<serde_json::Value>,
|
||||||
reasoning_budget_tokens: Option<serde_json::Value>,
|
reasoning_budget_tokens: Option<serde_json::Value>,
|
||||||
shared_settings_file: Option<PathBuf>,
|
shared_settings_file: Option<PathBuf>,
|
||||||
@@ -561,6 +564,7 @@ impl Config {
|
|||||||
aliases,
|
aliases,
|
||||||
cors_origins,
|
cors_origins,
|
||||||
trusted_origins,
|
trusted_origins,
|
||||||
|
api_monitor: file.api_monitor == Some(true),
|
||||||
sampling,
|
sampling,
|
||||||
reasoning_budget_tokens: file.reasoning_budget_tokens,
|
reasoning_budget_tokens: file.reasoning_budget_tokens,
|
||||||
shared_settings_file,
|
shared_settings_file,
|
||||||
@@ -750,6 +754,7 @@ mod tests {
|
|||||||
assert_eq!(config.aliases, vec!["gpt-local"]);
|
assert_eq!(config.aliases, vec!["gpt-local"]);
|
||||||
assert_eq!(config.cors_origins, vec!["https://chat.example.com", "*"]);
|
assert_eq!(config.cors_origins, vec!["https://chat.example.com", "*"]);
|
||||||
assert_eq!(config.trusted_origins, vec!["https://strata.example.com"]);
|
assert_eq!(config.trusted_origins, vec!["https://strata.example.com"]);
|
||||||
|
assert!(!config.api_monitor, "the request monitor is opt-in");
|
||||||
assert_eq!(config.sampling.sampling.top_k, Some(30));
|
assert_eq!(config.sampling.sampling.top_k, Some(30));
|
||||||
assert_eq!(config.sampling.ignored, vec!["nonsense"]);
|
assert_eq!(config.sampling.ignored, vec!["nonsense"]);
|
||||||
assert_eq!(config.idle_unload, Some(Duration::from_secs(90)));
|
assert_eq!(config.idle_unload, Some(Duration::from_secs(90)));
|
||||||
@@ -768,6 +773,15 @@ mod tests {
|
|||||||
let _ = fs::remove_dir_all(dir);
|
let _ = fs::remove_dir_all(dir);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_request_monitor_is_enabled_only_by_a_true_boolean() {
|
||||||
|
let dir = temp("api-monitor");
|
||||||
|
assert!(load(&dir, json!({"model": "m", "api_monitor": true})).unwrap().api_monitor);
|
||||||
|
assert!(!load(&dir, json!({"model": "m", "api_monitor": false})).unwrap().api_monitor);
|
||||||
|
assert!(load(&dir, json!({"model": "m", "api_monitor": "yes"})).is_err());
|
||||||
|
let _ = fs::remove_dir_all(dir);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn bad_serving_settings_stop_the_start() {
|
fn bad_serving_settings_stop_the_start() {
|
||||||
let dir = temp("serving-bad");
|
let dir = temp("serving-bad");
|
||||||
|
|||||||
@@ -0,0 +1,195 @@
|
|||||||
|
//! 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -44,7 +44,10 @@ pub mod kar_stream_encode;
|
|||||||
pub mod kar_writer;
|
pub mod kar_writer;
|
||||||
pub mod key_init;
|
pub mod key_init;
|
||||||
pub mod lifecycle;
|
pub mod lifecycle;
|
||||||
|
pub mod hardware_view;
|
||||||
pub mod metrics;
|
pub mod metrics;
|
||||||
|
pub mod prometheus;
|
||||||
|
pub mod request_monitor;
|
||||||
pub mod model;
|
pub mod model;
|
||||||
pub mod model_pipeline;
|
pub mod model_pipeline;
|
||||||
pub mod models_api;
|
pub mod models_api;
|
||||||
|
|||||||
@@ -926,6 +926,7 @@ async fn serve(config_path: Option<&Path>) -> Result<(), Box<dyn std::error::Err
|
|||||||
config.cors_origins.clone(),
|
config.cors_origins.clone(),
|
||||||
)),
|
)),
|
||||||
trusted_origins: Arc::new(config.trusted_origins.clone()),
|
trusted_origins: Arc::new(config.trusted_origins.clone()),
|
||||||
|
monitor: Arc::new(strata_control::request_monitor::RequestMonitor::new(config.api_monitor)),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
if !config.mcp_servers.is_empty() {
|
if !config.mcp_servers.is_empty() {
|
||||||
|
|||||||
@@ -34,6 +34,8 @@ pub struct MemoryView {
|
|||||||
latest: RwLock<Option<(Value, Instant)>>,
|
latest: RwLock<Option<(Value, Instant)>>,
|
||||||
/// The engine's telemetry document (`Backend::telemetry_report`) and when it was copied.
|
/// The engine's telemetry document (`Backend::telemetry_report`) and when it was copied.
|
||||||
telemetry: RwLock<Option<(Value, Instant)>>,
|
telemetry: RwLock<Option<(Value, Instant)>>,
|
||||||
|
/// A minute of the headline telemetry series (`GET /metrics` `history`).
|
||||||
|
series: crate::hardware_view::Series,
|
||||||
gated: AtomicU64,
|
gated: AtomicU64,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,11 +51,29 @@ impl MemoryView {
|
|||||||
/// Replace the stored telemetry document (`None`: the engine reports none, or is unreachable).
|
/// Replace the stored telemetry document (`None`: the engine reports none, or is unreachable).
|
||||||
pub fn set_telemetry(&self, document: Option<String>) {
|
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);
|
let value = document.and_then(|text| serde_json::from_str::<Value>(&text).ok()).filter(Value::is_object);
|
||||||
|
if let Some(value) = &value {
|
||||||
|
self.series.push(&crate::hardware_view::hardware_now(value));
|
||||||
|
}
|
||||||
if let Ok(mut latest) = self.telemetry.write() {
|
if let Ok(mut latest) = self.telemetry.write() {
|
||||||
*latest = value.map(|value| (value, Instant::now()));
|
*latest = value.map(|value| (value, Instant::now()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// For `GET /metrics`: the fresh telemetry document (or `null`), the Python-named `hardware` and `hardware_static`
|
||||||
|
/// blocks derived from it, and the series history.
|
||||||
|
pub fn hardware(&self) -> (Value, Value, Value, Value) {
|
||||||
|
let document = self.telemetry_status();
|
||||||
|
if document.is_null() {
|
||||||
|
return (json!({}), json!({}), Value::Null, self.series.snapshot());
|
||||||
|
}
|
||||||
|
(
|
||||||
|
crate::hardware_view::hardware_now(&document),
|
||||||
|
crate::hardware_view::hardware_static(&document),
|
||||||
|
document,
|
||||||
|
self.series.snapshot(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/// For `GET /v1/status` `machine`: the engine's telemetry with its age; a document older than [`FRESH_FOR`] is `null`.
|
/// 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 {
|
pub fn telemetry_status(&self) -> Value {
|
||||||
let Ok(latest) = self.telemetry.read() else { return Value::Null };
|
let Ok(latest) = self.telemetry.read() else { return Value::Null };
|
||||||
|
|||||||
@@ -1,12 +1,149 @@
|
|||||||
//! Payload-free engine telemetry, scoped to one control-plane process.
|
//! Payload-free engine telemetry, scoped to one control-plane process.
|
||||||
use std::time::Instant;
|
use std::{
|
||||||
|
collections::VecDeque,
|
||||||
|
sync::Mutex,
|
||||||
|
time::{Instant, SystemTime, UNIX_EPOCH},
|
||||||
|
};
|
||||||
|
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
use crate::wire::{Done, Finish};
|
use crate::wire::{Done, Finish};
|
||||||
|
|
||||||
|
/// How many finished generations `GET /metrics` keeps (the Python service keeps 500 too).
|
||||||
|
pub const HISTORY_KEPT: usize = 500;
|
||||||
|
|
||||||
|
/// One settled generation, as the Python service's `Service.history` entry (`GET /metrics` `requests`).
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
struct Finished {
|
||||||
|
/// Start, seconds since the epoch.
|
||||||
|
time: f64,
|
||||||
|
duration_s: f64,
|
||||||
|
/// `stop`, `length`, `cancel`, `disconnect` or `error` (the attempt ended without a DONE).
|
||||||
|
finish: &'static str,
|
||||||
|
prompt_tokens: Option<u64>,
|
||||||
|
reused: Option<u64>,
|
||||||
|
output_tokens: Option<u64>,
|
||||||
|
prompt_ms: Option<f64>,
|
||||||
|
decode_ms: Option<f64>,
|
||||||
|
expert_hits: Option<u64>,
|
||||||
|
expert_lookups: Option<u64>,
|
||||||
|
drafts_offered: Option<u64>,
|
||||||
|
drafts_accepted: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||||
|
struct Totals {
|
||||||
|
requests: u64,
|
||||||
|
prompt_tokens: u64,
|
||||||
|
reused: u64,
|
||||||
|
output_tokens: u64,
|
||||||
|
prompt_ms: f64,
|
||||||
|
decode_ms: f64,
|
||||||
|
drafts_offered: u64,
|
||||||
|
drafts_accepted: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Inner {
|
||||||
|
kept: VecDeque<Finished>,
|
||||||
|
totals: Totals,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The last finished generations and the totals since the process started: the `requests`, `requests_kept` and `totals` of
|
||||||
|
/// `GET /metrics`. Payload-free (counts and timings only). One per process: the worker status is `Copy`, so it holds a
|
||||||
|
/// `&'static` handle, leaked once by [`History::leak`].
|
||||||
|
pub struct History {
|
||||||
|
since: SystemTime,
|
||||||
|
inner: Mutex<Inner>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unix_seconds(at: SystemTime) -> f64 {
|
||||||
|
at.duration_since(UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn round(value: f64, digits: i32) -> f64 {
|
||||||
|
let scale = 10f64.powi(digits);
|
||||||
|
(value * scale).round() / scale
|
||||||
|
}
|
||||||
|
|
||||||
|
impl History {
|
||||||
|
pub fn leak() -> &'static History {
|
||||||
|
Box::leak(Box::new(History {
|
||||||
|
since: SystemTime::now(),
|
||||||
|
inner: Mutex::new(Inner { kept: VecDeque::new(), totals: Totals::default() }),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn record(&self, entry: Finished) {
|
||||||
|
let Ok(mut inner) = self.inner.lock() else { return };
|
||||||
|
let totals = &mut inner.totals;
|
||||||
|
totals.requests = totals.requests.saturating_add(1);
|
||||||
|
totals.prompt_tokens = totals.prompt_tokens.saturating_add(entry.prompt_tokens.unwrap_or(0));
|
||||||
|
totals.reused = totals.reused.saturating_add(entry.reused.unwrap_or(0));
|
||||||
|
totals.output_tokens = totals.output_tokens.saturating_add(entry.output_tokens.unwrap_or(0));
|
||||||
|
totals.prompt_ms = (totals.prompt_ms + entry.prompt_ms.unwrap_or(0.0)).min(f64::MAX);
|
||||||
|
totals.decode_ms = (totals.decode_ms + entry.decode_ms.unwrap_or(0.0)).min(f64::MAX);
|
||||||
|
totals.drafts_offered = totals.drafts_offered.saturating_add(entry.drafts_offered.unwrap_or(0));
|
||||||
|
totals.drafts_accepted = totals.drafts_accepted.saturating_add(entry.drafts_accepted.unwrap_or(0));
|
||||||
|
if inner.kept.len() == HISTORY_KEPT {
|
||||||
|
inner.kept.pop_front();
|
||||||
|
}
|
||||||
|
inner.kept.push_back(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Number of generations kept.
|
||||||
|
pub fn kept(&self) -> usize {
|
||||||
|
self.inner.lock().map_or(0, |inner| inner.kept.len())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Newest first, at most `limit` (`None`: all). The members are the Python service's, with `null` where the engine did
|
||||||
|
/// not say (`reused`, `hit_rate`, the draft counters, the timings of a failed attempt).
|
||||||
|
pub fn requests(&self, limit: Option<usize>) -> Vec<Value> {
|
||||||
|
let Ok(inner) = self.inner.lock() else { return Vec::new() };
|
||||||
|
inner
|
||||||
|
.kept
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.take(limit.unwrap_or(usize::MAX))
|
||||||
|
.map(|entry| {
|
||||||
|
let rate = match (entry.output_tokens, entry.decode_ms) {
|
||||||
|
(Some(tokens), Some(ms)) if tokens > 0 && ms > 0.0 => token_rate(tokens, ms).map(|r| round(r, 1)),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
let hit_rate = match (entry.expert_hits, entry.expert_lookups) {
|
||||||
|
(Some(hits), Some(lookups)) if lookups > 0 => Some(round(hits as f64 / lookups as f64, 3)),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
json!({
|
||||||
|
"time": round(entry.time, 3), "duration_s": round(entry.duration_s, 1), "finish": entry.finish,
|
||||||
|
"prompt_tokens": entry.prompt_tokens, "reused": entry.reused, "output_tokens": entry.output_tokens,
|
||||||
|
"engine_generated": entry.output_tokens, "prompt_ms": entry.prompt_ms, "decode_ms": entry.decode_ms,
|
||||||
|
"decode_tok_s": rate, "hit_rate": hit_rate,
|
||||||
|
"drafts_offered": entry.drafts_offered, "drafts_accepted": entry.drafts_accepted,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The Python service's `totals`: since the process started, summed over every settled generation.
|
||||||
|
pub fn totals(&self) -> Value {
|
||||||
|
let totals = self.inner.lock().map(|inner| inner.totals).unwrap_or_default();
|
||||||
|
json!({
|
||||||
|
"since": round(unix_seconds(self.since), 3), "requests": totals.requests, "prompt_tokens": totals.prompt_tokens,
|
||||||
|
"reused": totals.reused, "output_tokens": totals.output_tokens,
|
||||||
|
"prompt_ms": round(totals.prompt_ms, 1), "decode_ms": round(totals.decode_ms, 1),
|
||||||
|
"drafts_offered": totals.drafts_offered, "drafts_accepted": totals.drafts_accepted,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, Default, Serialize)]
|
#[derive(Clone, Copy, Default, Serialize)]
|
||||||
pub struct GenerationMetrics {
|
pub struct GenerationMetrics {
|
||||||
|
/// Where settled generations are listed for `GET /metrics`; `None` in a bare status (nothing is listed then).
|
||||||
|
#[serde(skip)]
|
||||||
|
pub history: Option<&'static History>,
|
||||||
|
#[serde(skip)]
|
||||||
|
started_wall: Option<SystemTime>,
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
pub active_since: Option<Instant>,
|
pub active_since: Option<Instant>,
|
||||||
pub started: u64,
|
pub started: u64,
|
||||||
@@ -41,19 +178,58 @@ pub fn token_rate(tokens: u64, milliseconds: f64) -> Option<f64> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl GenerationMetrics {
|
impl GenerationMetrics {
|
||||||
|
/// Metrics that also list settled generations in a process-wide [`History`].
|
||||||
|
pub fn with_history() -> Self {
|
||||||
|
Self { history: Some(History::leak()), ..Self::default() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn settle(&mut self, finish: &'static str, done: Option<&Done>) {
|
||||||
|
let started = self.started_wall.take();
|
||||||
|
let Some(history) = self.history else { return };
|
||||||
|
let (now, started) = (SystemTime::now(), started.unwrap_or_else(SystemTime::now));
|
||||||
|
history.record(Finished {
|
||||||
|
time: unix_seconds(started),
|
||||||
|
duration_s: now.duration_since(started).map_or(0.0, |d| d.as_secs_f64()),
|
||||||
|
finish,
|
||||||
|
prompt_tokens: done.map(|d| d.prompt_tokens),
|
||||||
|
reused: done.and_then(|d| d.reused),
|
||||||
|
output_tokens: done.map(|d| d.generated),
|
||||||
|
prompt_ms: done.map(|d| d.prompt_ms),
|
||||||
|
decode_ms: done.map(|d| d.decode_ms),
|
||||||
|
expert_hits: done.and_then(|d| d.expert_hits),
|
||||||
|
expert_lookups: done.and_then(|d| d.expert_lookups),
|
||||||
|
drafts_offered: done.and_then(|d| d.drafts_offered),
|
||||||
|
drafts_accepted: done.and_then(|d| d.drafts_accepted),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
pub fn start(&mut self) {
|
pub fn start(&mut self) {
|
||||||
self.started = self.started.saturating_add(1);
|
self.started = self.started.saturating_add(1);
|
||||||
self.active_since = Some(Instant::now());
|
self.active_since = Some(Instant::now());
|
||||||
|
self.started_wall = Some(SystemTime::now());
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn fail(&mut self) {
|
pub fn fail(&mut self) {
|
||||||
if self.active_since.take().is_some() {
|
if self.active_since.take().is_some() {
|
||||||
self.failed_or_interrupted = self.failed_or_interrupted.saturating_add(1);
|
self.failed_or_interrupted = self.failed_or_interrupted.saturating_add(1);
|
||||||
|
self.settle("error", None);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn finish(&mut self, done: &Done, disconnected: bool) {
|
pub fn finish(&mut self, done: &Done, disconnected: bool) {
|
||||||
self.active_since = None;
|
self.active_since = None;
|
||||||
|
self.settle(
|
||||||
|
if disconnected {
|
||||||
|
"disconnect"
|
||||||
|
} else {
|
||||||
|
match done.finish {
|
||||||
|
Finish::Stop => "stop",
|
||||||
|
Finish::Length => "length",
|
||||||
|
Finish::Cancel => "cancel",
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Some(done),
|
||||||
|
);
|
||||||
if disconnected || done.finish == Finish::Cancel {
|
if disconnected || done.finish == Finish::Cancel {
|
||||||
self.cancelled = self.cancelled.saturating_add(1);
|
self.cancelled = self.cancelled.saturating_add(1);
|
||||||
} else {
|
} else {
|
||||||
@@ -88,17 +264,19 @@ impl GenerationMetrics {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
fn done(line: &str) -> Done {
|
||||||
|
let crate::wire::Event::Done(done) = crate::wire::parse_line(line).unwrap().unwrap() else {
|
||||||
|
panic!()
|
||||||
|
};
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn unavailable_rates_are_null_and_disconnected_done_is_cancelled() {
|
fn unavailable_rates_are_null_and_disconnected_done_is_cancelled() {
|
||||||
assert_eq!(token_rate(10, 0.0), None);
|
assert_eq!(token_rate(10, 0.0), None);
|
||||||
assert_eq!(token_rate(10, f64::MIN_POSITIVE), None);
|
assert_eq!(token_rate(10, f64::MIN_POSITIVE), None);
|
||||||
assert_eq!(token_rate(10, 20.0), Some(500.0));
|
assert_eq!(token_rate(10, 20.0), Some(500.0));
|
||||||
let crate::wire::Event::Done(done) = crate::wire::parse_line("DONE 2 3 1.0 4.0 stop")
|
let done = done("DONE 2 3 1.0 4.0 stop");
|
||||||
.unwrap()
|
|
||||||
.unwrap()
|
|
||||||
else {
|
|
||||||
panic!()
|
|
||||||
};
|
|
||||||
let mut metrics = GenerationMetrics::default();
|
let mut metrics = GenerationMetrics::default();
|
||||||
metrics.start();
|
metrics.start();
|
||||||
metrics.finish(&done, true);
|
metrics.finish(&done, true);
|
||||||
@@ -117,4 +295,59 @@ mod tests {
|
|||||||
Some(500.0)
|
Some(500.0)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn settled_generations_are_listed_newest_first_with_totals() {
|
||||||
|
let mut metrics = GenerationMetrics::with_history();
|
||||||
|
let history = metrics.history.unwrap();
|
||||||
|
assert_eq!(history.kept(), 0);
|
||||||
|
metrics.start();
|
||||||
|
metrics.finish(&done("DONE 20 100 250.0 1000.0 length"), false);
|
||||||
|
metrics.start();
|
||||||
|
metrics.finish(&done("DONE 4 50 10.0 40.0 stop"), true);
|
||||||
|
metrics.start();
|
||||||
|
metrics.fail();
|
||||||
|
// an attempt that was never started has nothing to settle
|
||||||
|
metrics.fail();
|
||||||
|
assert_eq!(history.kept(), 3);
|
||||||
|
let listed = history.requests(Some(2));
|
||||||
|
assert_eq!(listed.len(), 2);
|
||||||
|
assert_eq!(listed[0]["finish"], "error");
|
||||||
|
assert!(listed[0]["prompt_tokens"].is_null() && listed[0]["decode_tok_s"].is_null());
|
||||||
|
assert_eq!(listed[1]["finish"], "disconnect");
|
||||||
|
let all = history.requests(None);
|
||||||
|
assert_eq!(all[2]["finish"], "length");
|
||||||
|
assert_eq!(all[2]["prompt_tokens"], 100);
|
||||||
|
assert_eq!(all[2]["output_tokens"], 20);
|
||||||
|
assert_eq!(all[2]["decode_tok_s"], 20.0);
|
||||||
|
assert!(all[2]["hit_rate"].is_null());
|
||||||
|
let totals = history.totals();
|
||||||
|
assert_eq!(totals["requests"], 3);
|
||||||
|
assert_eq!(totals["prompt_tokens"], 150);
|
||||||
|
assert_eq!(totals["output_tokens"], 24);
|
||||||
|
assert_eq!(totals["decode_ms"], 1040.0);
|
||||||
|
assert!(totals["since"].as_f64().unwrap() > 1.0e9);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_history_is_bounded() {
|
||||||
|
let mut metrics = GenerationMetrics::with_history();
|
||||||
|
for _ in 0..HISTORY_KEPT + 7 {
|
||||||
|
metrics.start();
|
||||||
|
metrics.finish(&done("DONE 1 1 1.0 1.0 stop"), false);
|
||||||
|
}
|
||||||
|
let history = metrics.history.unwrap();
|
||||||
|
assert_eq!(history.kept(), HISTORY_KEPT);
|
||||||
|
// the totals still count every request
|
||||||
|
assert_eq!(history.totals()["requests"], HISTORY_KEPT as u64 + 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_bare_metrics_value_lists_nothing_and_does_not_fail() {
|
||||||
|
let mut metrics = GenerationMetrics::default();
|
||||||
|
metrics.start();
|
||||||
|
metrics.fail();
|
||||||
|
assert!(metrics.history.is_none());
|
||||||
|
assert_eq!(metrics.failed_or_interrupted, 1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,237 @@
|
|||||||
|
//! `GET /metrics?format=prometheus` (or an `Accept` that asks for `text/plain` / OpenMetrics): the same document as the JSON
|
||||||
|
//! `/metrics`, as Prometheus text exposition. A figure the document leaves `null` or does not have is not exposed (Prometheus
|
||||||
|
//! has no null; a missing series is the honest answer for "not measured"). Counters carry the `_total` suffix and
|
||||||
|
//! count since the control plane started; everything else is a gauge sampled when the endpoint is read.
|
||||||
|
//!
|
||||||
|
//! The table below is the contract: metric name, type, help, where it comes from in the JSON document, and a scale.
|
||||||
|
|
||||||
|
use std::fmt::Write;
|
||||||
|
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
pub const CONTENT_TYPE: &str = "text/plain; version=0.0.4; charset=utf-8";
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum Kind {
|
||||||
|
Counter,
|
||||||
|
Gauge,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Series {
|
||||||
|
name: &'static str,
|
||||||
|
kind: Kind,
|
||||||
|
help: &'static str,
|
||||||
|
/// JSON pointer into the `/metrics` document.
|
||||||
|
from: &'static str,
|
||||||
|
scale: f64,
|
||||||
|
/// A fixed label, `name="value"` (several series of one metric differ only by it).
|
||||||
|
label: Option<(&'static str, &'static str)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn counter(name: &'static str, help: &'static str, from: &'static str, scale: f64) -> Series {
|
||||||
|
Series { name, kind: Kind::Counter, help, from, scale, label: None }
|
||||||
|
}
|
||||||
|
const fn gauge(name: &'static str, help: &'static str, from: &'static str, scale: f64) -> Series {
|
||||||
|
Series { name, kind: Kind::Gauge, help, from, scale, label: None }
|
||||||
|
}
|
||||||
|
const fn labelled(name: &'static str, help: &'static str, from: &'static str, label: (&'static str, &'static str)) -> Series {
|
||||||
|
Series { name, kind: Kind::Gauge, help, from, scale: 1.0, label: Some(label) }
|
||||||
|
}
|
||||||
|
|
||||||
|
const SERIES: &[Series] = &[
|
||||||
|
counter("leleka_generations_started_total", "Generations admitted to the engine.", "/generation/started", 1.0),
|
||||||
|
counter("leleka_generations_completed_total", "Generations that ended with a DONE other than cancel.", "/generation/completed", 1.0),
|
||||||
|
counter("leleka_generations_cancelled_total", "Generations cancelled or abandoned by the client.", "/generation/cancelled", 1.0),
|
||||||
|
counter("leleka_generations_failed_total", "Admitted generations that ended without a DONE.", "/generation/failed_or_interrupted", 1.0),
|
||||||
|
counter("leleka_prompt_tokens_total", "Prompt tokens of settled generations.", "/totals/prompt_tokens", 1.0),
|
||||||
|
counter("leleka_prompt_tokens_reused_total", "Prompt tokens served from a cache.", "/totals/reused", 1.0),
|
||||||
|
counter("leleka_generated_tokens_total", "Tokens generated by settled generations.", "/totals/output_tokens", 1.0),
|
||||||
|
counter("leleka_prefill_seconds_total", "Engine time spent reading prompts.", "/totals/prompt_ms", 1e-3),
|
||||||
|
counter("leleka_decode_seconds_total", "Engine time spent generating tokens.", "/totals/decode_ms", 1e-3),
|
||||||
|
counter("leleka_draft_tokens_offered_total", "Speculative draft tokens offered.", "/totals/drafts_offered", 1.0),
|
||||||
|
counter("leleka_draft_tokens_accepted_total", "Speculative draft tokens accepted.", "/totals/drafts_accepted", 1.0),
|
||||||
|
counter("leleka_memory_gate_rejections_total", "Requests refused up front for host memory pressure.", "/memory/gate_rejections", 1.0),
|
||||||
|
gauge("leleka_up", "1 when the engine is loaded and accepting generations.", "/up", 1.0),
|
||||||
|
gauge("leleka_generation_active", "1 while a generation runs.", "/live/active", 1.0),
|
||||||
|
gauge("leleka_generation_elapsed_seconds", "Seconds the running generation has been active.", "/live/elapsed_s", 1.0),
|
||||||
|
gauge("leleka_requests_queued", "Generations waiting for the engine.", "/live/queued", 1.0),
|
||||||
|
gauge("leleka_queue_used", "Commands in the bounded generation channel.", "/queue_used", 1.0),
|
||||||
|
gauge("leleka_queue_capacity", "Capacity of the generation channel.", "/queue_capacity", 1.0),
|
||||||
|
gauge("leleka_context_max_tokens", "Context window the engine serves, in tokens.", "/engine/max_context", 1.0),
|
||||||
|
gauge("leleka_context_live_tokens", "Tokens in the session context (prompt plus output).", "/telemetry/context/live_tokens", 1.0),
|
||||||
|
gauge("leleka_context_used_percent", "Share of the context window in use.", "/telemetry/context/used_pct", 1.0),
|
||||||
|
gauge("leleka_gpu_utilization_percent", "Share of the last sample period in which a kernel ran.", "/hardware/gpu_util", 1.0),
|
||||||
|
gauge("leleka_gpu_memory_utilization_percent", "Share of the period the memory interface was busy.", "/hardware/gpu_mem_util", 1.0),
|
||||||
|
gauge("leleka_gpu_memory_used_bytes", "Device memory in use.", "/hardware/gpu_mem_used", 1.0),
|
||||||
|
gauge("leleka_gpu_memory_total_bytes", "Device memory installed.", "/hardware/gpu_mem_total", 1.0),
|
||||||
|
gauge("leleka_gpu_temperature_celsius", "GPU core temperature.", "/hardware/gpu_temp", 1.0),
|
||||||
|
gauge("leleka_gpu_power_watts", "GPU board power draw.", "/hardware/gpu_power", 1.0),
|
||||||
|
gauge("leleka_gpu_sm_clock_megahertz", "GPU SM clock.", "/hardware/gpu_sm_clock_mhz", 1.0),
|
||||||
|
gauge("leleka_host_memory_used_bytes", "Host RAM in use (total minus available).", "/hardware/ram_used", 1.0),
|
||||||
|
gauge("leleka_host_memory_total_bytes", "Host RAM installed.", "/hardware/ram_total", 1.0),
|
||||||
|
gauge("leleka_host_swap_used_bytes", "Swap in use.", "/hardware/swap_used", 1.0),
|
||||||
|
gauge("leleka_engine_resident_bytes", "Resident set of the engine process.", "/hardware/ram_process_rss", 1.0),
|
||||||
|
gauge("leleka_engine_pinned_bytes", "Page-locked memory of the engine process.", "/hardware/ram_process_pinned", 1.0),
|
||||||
|
gauge("leleka_host_cpu_busy_percent", "Busy share of all CPUs.", "/hardware/cpu", 1.0),
|
||||||
|
gauge("leleka_engine_cpu_busy_cores", "CPU cores worth of time the engine used.", "/hardware/cpu_process_cores", 1.0),
|
||||||
|
labelled("leleka_decode_tokens_per_second", "Decode throughput.", "/hardware/tok_s", ("window", "live")),
|
||||||
|
labelled("leleka_decode_tokens_per_second", "Decode throughput.", "/telemetry/throughput/decode_tok_s_last", ("window", "last")),
|
||||||
|
labelled("leleka_decode_tokens_per_second", "Decode throughput.", "/hardware/tok_s_mean", ("window", "average")),
|
||||||
|
labelled("leleka_decode_tokens_per_second", "Decode throughput.", "/telemetry/throughput/decode_tok_s_lifetime", ("window", "lifetime")),
|
||||||
|
labelled("leleka_prefill_tokens_per_second", "Prefill throughput over newly read tokens.", "/telemetry/throughput/prefill_tok_s_last", ("window", "last")),
|
||||||
|
labelled("leleka_prefill_tokens_per_second", "Prefill throughput over newly read tokens.", "/hardware/prefill_tok_s_mean", ("window", "average")),
|
||||||
|
labelled("leleka_prefill_tokens_per_second", "Prefill throughput over newly read tokens.", "/telemetry/throughput/prefill_tok_s_lifetime", ("window", "lifetime")),
|
||||||
|
gauge("leleka_prefix_cache_requests", "Requests the prefix cache has seen.", "/telemetry/cache/requests", 1.0),
|
||||||
|
gauge("leleka_prefix_cache_hit_requests", "Requests that reused a checkpoint.", "/telemetry/cache/hit_requests", 1.0),
|
||||||
|
gauge("leleka_prefix_cache_hit_ratio", "Share of requests that reused a checkpoint.", "/telemetry/cache/hit_ratio", 1.0),
|
||||||
|
gauge("leleka_prefix_cache_token_hit_ratio", "Share of prompt tokens served from a checkpoint.", "/telemetry/cache/token_hit_ratio", 1.0),
|
||||||
|
gauge("leleka_prefix_cache_reused_tokens", "Prompt tokens reused since the engine started.", "/telemetry/cache/reused_tokens", 1.0),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// The phase the engine reports, as a one-hot gauge (`idle`, `prefill`, `decode`).
|
||||||
|
const PHASES: [&str; 3] = ["idle", "prefill", "decode"];
|
||||||
|
|
||||||
|
fn escape(text: &str) -> String {
|
||||||
|
text.replace('\\', "\\\\").replace('\n', "\\n").replace('"', "\\\"")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn format_value(value: f64) -> String {
|
||||||
|
if value.fract() == 0.0 && value.abs() < 1e15 {
|
||||||
|
format!("{}", value as i64)
|
||||||
|
} else {
|
||||||
|
format!("{value}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Render the `/metrics` document. `model` (when the document has one) labels `leleka_info`.
|
||||||
|
pub fn render(document: &Value) -> String {
|
||||||
|
let mut out = String::new();
|
||||||
|
let mut described: Vec<&str> = Vec::new();
|
||||||
|
for series in SERIES {
|
||||||
|
let Some(raw) = document.pointer(series.from) else { continue };
|
||||||
|
let value = match raw {
|
||||||
|
Value::Bool(flag) => f64::from(u8::from(*flag)),
|
||||||
|
other => match other.as_f64() {
|
||||||
|
Some(number) if number.is_finite() => number * series.scale,
|
||||||
|
_ => continue,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
if !described.contains(&series.name) {
|
||||||
|
described.push(series.name);
|
||||||
|
let kind = if series.kind == Kind::Counter { "counter" } else { "gauge" };
|
||||||
|
let _ = writeln!(out, "# HELP {} {}", series.name, series.help);
|
||||||
|
let _ = writeln!(out, "# TYPE {} {kind}", series.name);
|
||||||
|
}
|
||||||
|
match series.label {
|
||||||
|
Some((name, label)) => {
|
||||||
|
let _ = writeln!(out, "{}{{{name}=\"{label}\"}} {}", series.name, format_value(value));
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
let _ = writeln!(out, "{} {}", series.name, format_value(value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(phase) = document.pointer("/telemetry/phase").and_then(Value::as_str) {
|
||||||
|
let _ = writeln!(out, "# HELP leleka_engine_phase 1 for the phase the engine is in.");
|
||||||
|
let _ = writeln!(out, "# TYPE leleka_engine_phase gauge");
|
||||||
|
for candidate in PHASES {
|
||||||
|
let _ = writeln!(out, "leleka_engine_phase{{phase=\"{candidate}\"}} {}", u8::from(candidate == phase));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = writeln!(out, "# HELP leleka_info The served model.");
|
||||||
|
let _ = writeln!(out, "# TYPE leleka_info gauge");
|
||||||
|
let model = document.get("model").and_then(Value::as_str).unwrap_or("");
|
||||||
|
let _ = writeln!(out, "leleka_info{{model=\"{}\"}} 1", escape(model));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a request asks for the text exposition: `?format=prometheus` (or `openmetrics`/`text`), or an `Accept` that lists
|
||||||
|
/// `text/plain` or OpenMetrics (what a Prometheus scraper sends) and does not ask for JSON first.
|
||||||
|
pub fn wanted(query: Option<&str>, accept: Option<&str>) -> bool {
|
||||||
|
if let Some(query) = query {
|
||||||
|
for pair in query.split('&') {
|
||||||
|
if let Some(("format", value)) = pair.split_once('=') {
|
||||||
|
return matches!(value, "prometheus" | "openmetrics" | "text");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let Some(accept) = accept else { return false };
|
||||||
|
let accept = accept.to_ascii_lowercase();
|
||||||
|
let text = accept.find("text/plain").or_else(|| accept.find("openmetrics-text"));
|
||||||
|
let json = accept.find("application/json");
|
||||||
|
match (text, json) {
|
||||||
|
(Some(text), Some(json)) => text < json,
|
||||||
|
(Some(_), None) => true,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
fn document() -> Value {
|
||||||
|
json!({
|
||||||
|
"model": "qwen \"3.8\"", "up": true, "queue_used": 1, "queue_capacity": 64,
|
||||||
|
"generation": {"started": 5, "completed": 3, "cancelled": 1, "failed_or_interrupted": 1},
|
||||||
|
"totals": {"prompt_tokens": 1000, "reused": 400, "output_tokens": 250, "prompt_ms": 2500.0, "decode_ms": 1250.0, "drafts_offered": 90, "drafts_accepted": 60},
|
||||||
|
"memory": {"gate_rejections": 2},
|
||||||
|
"live": {"active": true, "elapsed_s": 3.5, "queued": 0},
|
||||||
|
"engine": {"max_context": 262144},
|
||||||
|
"hardware": {"gpu_util": 91, "gpu_mem_used": 31457280000u64, "gpu_temp": 61, "gpu_power": 480.5, "cpu": 31.0, "tok_s": 128.4, "tok_s_mean": 120.0, "prefill_tok_s_mean": 5050.0, "ram_used": 5.0e10},
|
||||||
|
"telemetry": {"phase": "decode", "context": {"live_tokens": 101200, "used_pct": 38.6},
|
||||||
|
"throughput": {"decode_tok_s_last": 100.0, "decode_tok_s_lifetime": null},
|
||||||
|
"cache": {"requests": 2, "hit_ratio": 0.5}},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn counters_gauges_and_labels_render_in_the_text_format() {
|
||||||
|
let text = render(&document());
|
||||||
|
assert!(text.contains("# TYPE leleka_generations_started_total counter\nleleka_generations_started_total 5\n"));
|
||||||
|
assert!(text.contains("leleka_prefill_seconds_total 2.5\n"));
|
||||||
|
assert!(text.contains("leleka_decode_seconds_total 1.25\n"));
|
||||||
|
assert!(text.contains("leleka_up 1\n") && text.contains("leleka_generation_active 1\n"));
|
||||||
|
assert!(text.contains("# TYPE leleka_gpu_memory_used_bytes gauge\nleleka_gpu_memory_used_bytes 31457280000\n"));
|
||||||
|
assert!(text.contains("leleka_gpu_power_watts 480.5\n"));
|
||||||
|
assert!(text.contains("leleka_context_live_tokens 101200\n"));
|
||||||
|
// one HELP/TYPE per metric, a series per label value
|
||||||
|
assert_eq!(text.matches("# TYPE leleka_decode_tokens_per_second").count(), 1);
|
||||||
|
assert!(text.contains("leleka_decode_tokens_per_second{window=\"live\"} 128.4\n"));
|
||||||
|
assert!(text.contains("leleka_decode_tokens_per_second{window=\"last\"} 100\n"));
|
||||||
|
assert!(text.contains("leleka_decode_tokens_per_second{window=\"average\"} 120\n"));
|
||||||
|
assert!(text.contains("leleka_engine_phase{phase=\"decode\"} 1\n") && text.contains("leleka_engine_phase{phase=\"idle\"} 0\n"));
|
||||||
|
assert!(text.contains("leleka_info{model=\"qwen \\\"3.8\\\"\"} 1\n"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unmeasured_figures_are_not_exposed() {
|
||||||
|
let text = render(&document());
|
||||||
|
// null in the document: no lifetime decode rate, no GPU clock, no swap
|
||||||
|
assert!(!text.contains("window=\"lifetime\""));
|
||||||
|
assert!(!text.contains("leleka_gpu_sm_clock_megahertz"));
|
||||||
|
let bare = render(&json!({"model": "m", "up": false}));
|
||||||
|
assert!(bare.contains("leleka_up 0\n"));
|
||||||
|
assert!(!bare.contains("leleka_gpu_") && !bare.contains("leleka_engine_phase"));
|
||||||
|
// every line is HELP, TYPE or a sample
|
||||||
|
for line in text.lines() {
|
||||||
|
assert!(line.starts_with("# HELP ") || line.starts_with("# TYPE ") || line.starts_with("leleka_"), "{line}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_format_is_chosen_by_query_or_accept() {
|
||||||
|
assert!(wanted(Some("format=prometheus"), None));
|
||||||
|
assert!(wanted(Some("requests=all&format=openmetrics"), None));
|
||||||
|
assert!(!wanted(Some("format=json"), Some("text/plain")));
|
||||||
|
assert!(!wanted(None, None));
|
||||||
|
assert!(!wanted(None, Some("*/*")));
|
||||||
|
assert!(!wanted(None, Some("application/json")));
|
||||||
|
// what a Prometheus server sends
|
||||||
|
assert!(wanted(None, Some("application/openmetrics-text;version=1.0.0,text/plain;version=0.0.4;q=0.5,*/*;q=0.1")));
|
||||||
|
assert!(wanted(None, Some("text/plain")));
|
||||||
|
// a browser or SDK that prefers JSON keeps the JSON document
|
||||||
|
assert!(!wanted(None, Some("application/json, text/plain, */*")));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,617 @@
|
|||||||
|
//! The API request monitor: `GET /api/requests`, the opt-in inspection of the last requests' prompts and answers of the Python
|
||||||
|
//! service (`api_monitor` in its config; `engine/strata/serve/server.py` `begin_request` / `request_records`, tests in
|
||||||
|
//! `serve/test_monitor.py`).
|
||||||
|
//!
|
||||||
|
//! It keeps the last [`RETENTION`] requests of the three generation dialects (`/v1/chat/completions`, `/v1/messages`,
|
||||||
|
//! `/v1/responses`) in memory: the request body as pretty JSON, the generated text and reasoning, the usage, the error, the
|
||||||
|
//! HTTP status and the wall-clock timings. It is off unless the config sets `"api_monitor": true`, because it holds prompts
|
||||||
|
//! and answers in memory; nothing is written to disk and request headers (credentials) are never captured. Every captured
|
||||||
|
//! text is bounded to [`CAP`] bytes and says so (`*_truncated`).
|
||||||
|
//!
|
||||||
|
//! The capture is a middleware around the three routes: it reads the request body once (bounded by the 16 MiB route limit),
|
||||||
|
//! hands the same bytes on, and either collects a JSON response or taps an event stream chunk by chunk without delaying it.
|
||||||
|
//! A stream whose consumer goes away before it ends is recorded as `disconnected`.
|
||||||
|
//!
|
||||||
|
//! Differences from the Python monitor, all deliberate: `/v1/responses` is monitored too; `queue_s` and `load_s` are `null`
|
||||||
|
//! (a request's wait for the engine is not attributed per request here: see `/metrics` `live.queued`); the state is `queued`
|
||||||
|
//! until the first generated text, then `generating`, then `completed`, `error` or `disconnected`; there is no HTML page.
|
||||||
|
use std::{
|
||||||
|
collections::VecDeque,
|
||||||
|
pin::Pin,
|
||||||
|
sync::{Arc, Mutex},
|
||||||
|
task::{Context, Poll},
|
||||||
|
time::{Instant, SystemTime, UNIX_EPOCH},
|
||||||
|
};
|
||||||
|
|
||||||
|
use axum::{
|
||||||
|
body::{Body, Bytes},
|
||||||
|
extract::{Request, State},
|
||||||
|
http::{HeaderValue, StatusCode, header},
|
||||||
|
middleware::Next,
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
};
|
||||||
|
use futures_core::Stream;
|
||||||
|
use serde_json::{Map, Value, json};
|
||||||
|
|
||||||
|
/// Requests kept.
|
||||||
|
pub const RETENTION: usize = 100;
|
||||||
|
/// Bytes kept of each captured text (the request, the output, the reasoning, the response).
|
||||||
|
pub const CAP: usize = 262_144;
|
||||||
|
/// Body limit of the generation routes.
|
||||||
|
const BODY_LIMIT: usize = 16 * 1024 * 1024;
|
||||||
|
/// A response collected whole (not an event stream) is read up to this size for capture.
|
||||||
|
const RESPONSE_LIMIT: usize = 64 * 1024 * 1024;
|
||||||
|
/// A single event line longer than this is dropped from the capture (the stream itself is untouched).
|
||||||
|
const LINE_LIMIT: usize = 1 << 20;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Record {
|
||||||
|
id: String,
|
||||||
|
path: String,
|
||||||
|
model: Value,
|
||||||
|
started_at: f64,
|
||||||
|
state: &'static str,
|
||||||
|
outcome: Option<&'static str>,
|
||||||
|
stream: bool,
|
||||||
|
response_format: Value,
|
||||||
|
input: String,
|
||||||
|
input_truncated: bool,
|
||||||
|
output: String,
|
||||||
|
output_truncated: bool,
|
||||||
|
reasoning: String,
|
||||||
|
reasoning_truncated: bool,
|
||||||
|
first_token_s: Option<f64>,
|
||||||
|
usage: Option<Value>,
|
||||||
|
error: Option<Value>,
|
||||||
|
http_status: Option<u16>,
|
||||||
|
response: Option<String>,
|
||||||
|
response_truncated: bool,
|
||||||
|
wallclock_s: Option<f64>,
|
||||||
|
finished_at: Option<f64>,
|
||||||
|
clock: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn now_unix() -> f64 {
|
||||||
|
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn seconds(since: Instant) -> f64 {
|
||||||
|
(since.elapsed().as_secs_f64() * 1000.0).round() / 1000.0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Append `add` to `target` without exceeding [`CAP`] bytes (cut at a character boundary); true when something was left out.
|
||||||
|
fn append_clipped(target: &mut String, flag: &mut bool, add: &str) {
|
||||||
|
let room = CAP.saturating_sub(target.len());
|
||||||
|
if add.len() <= room {
|
||||||
|
target.push_str(add);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let mut end = room;
|
||||||
|
while end > 0 && !add.is_char_boundary(end) {
|
||||||
|
end -= 1;
|
||||||
|
}
|
||||||
|
target.push_str(&add[..end]);
|
||||||
|
*flag = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clipped(text: &str) -> (String, bool) {
|
||||||
|
let mut out = String::new();
|
||||||
|
let mut flag = false;
|
||||||
|
append_clipped(&mut out, &mut flag, text);
|
||||||
|
(out, flag)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Record {
|
||||||
|
fn first_text(&mut self) {
|
||||||
|
if self.first_token_s.is_none() {
|
||||||
|
self.first_token_s = Some(seconds(self.clock));
|
||||||
|
self.state = "generating";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_output(&mut self, text: Option<&str>) {
|
||||||
|
if let Some(text) = text.filter(|t| !t.is_empty()) {
|
||||||
|
self.first_text();
|
||||||
|
append_clipped(&mut self.output, &mut self.output_truncated, text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_reasoning(&mut self, text: Option<&str>) {
|
||||||
|
if let Some(text) = text.filter(|t| !t.is_empty()) {
|
||||||
|
self.first_text();
|
||||||
|
append_clipped(&mut self.reasoning, &mut self.reasoning_truncated, text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One server-sent event (`data:` payload) of any of the three dialects.
|
||||||
|
fn absorb_event(&mut self, event: &Value) {
|
||||||
|
if let Some(choices) = event.get("choices").and_then(Value::as_array) {
|
||||||
|
if let Some(delta) = choices.first().and_then(|choice| choice.get("delta")) {
|
||||||
|
self.add_output(delta.get("content").and_then(Value::as_str));
|
||||||
|
self.add_reasoning(delta.get("reasoning_content").or_else(|| delta.get("reasoning")).and_then(Value::as_str));
|
||||||
|
}
|
||||||
|
if let Some(usage) = event.get("usage").filter(|u| u.is_object()) {
|
||||||
|
self.usage = Some(usage.clone());
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
match event.get("type").and_then(Value::as_str) {
|
||||||
|
Some("content_block_delta") => {
|
||||||
|
let delta = &event["delta"];
|
||||||
|
self.add_output(delta.get("text").and_then(Value::as_str));
|
||||||
|
self.add_reasoning(delta.get("thinking").and_then(Value::as_str));
|
||||||
|
}
|
||||||
|
Some("message_start") => {
|
||||||
|
if let Some(usage) = event.pointer("/message/usage").filter(|u| u.is_object()) {
|
||||||
|
self.usage = Some(usage.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some("message_delta") => {
|
||||||
|
if let Some(update) = event.get("usage").and_then(Value::as_object) {
|
||||||
|
let mut merged = self.usage.as_ref().and_then(Value::as_object).cloned().unwrap_or_default();
|
||||||
|
merged.extend(update.clone());
|
||||||
|
self.usage = Some(Value::Object(merged));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some("response.output_text.delta") => self.add_output(event.get("delta").and_then(Value::as_str)),
|
||||||
|
Some("response.reasoning_text.delta" | "response.reasoning_summary_text.delta") => {
|
||||||
|
self.add_reasoning(event.get("delta").and_then(Value::as_str));
|
||||||
|
}
|
||||||
|
Some("response.completed" | "response.incomplete") => {
|
||||||
|
if let Some(usage) = event.pointer("/response/usage").filter(|u| u.is_object()) {
|
||||||
|
self.usage = Some(usage.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some("response.failed") => {
|
||||||
|
self.error = Some(event.pointer("/response/error").cloned().unwrap_or_else(|| event.clone()));
|
||||||
|
}
|
||||||
|
Some("error") => self.error = Some(event.get("error").cloned().unwrap_or_else(|| event.clone())),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A response that was sent whole (any dialect).
|
||||||
|
fn absorb_response(&mut self, body: &Value) {
|
||||||
|
if let Some(error) = body.get("error").filter(|e| !e.is_null()) {
|
||||||
|
self.error = Some(error.clone());
|
||||||
|
}
|
||||||
|
if let Some(usage) = body.get("usage").filter(|u| u.is_object()) {
|
||||||
|
self.usage = Some(usage.clone());
|
||||||
|
}
|
||||||
|
// Chat Completions
|
||||||
|
if let Some(message) = body.pointer("/choices/0/message") {
|
||||||
|
self.add_output(message.get("content").and_then(Value::as_str));
|
||||||
|
self.add_reasoning(message.get("reasoning_content").or_else(|| message.get("reasoning")).and_then(Value::as_str));
|
||||||
|
}
|
||||||
|
// Messages
|
||||||
|
if let Some(blocks) = body.get("content").and_then(Value::as_array) {
|
||||||
|
for block in blocks {
|
||||||
|
match block.get("type").and_then(Value::as_str) {
|
||||||
|
Some("text") => self.add_output(block.get("text").and_then(Value::as_str)),
|
||||||
|
Some("thinking") => self.add_reasoning(block.get("thinking").and_then(Value::as_str)),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Responses
|
||||||
|
if let Some(items) = body.get("output").and_then(Value::as_array) {
|
||||||
|
for item in items {
|
||||||
|
let parts = item.get("content").and_then(Value::as_array).into_iter().flatten();
|
||||||
|
match item.get("type").and_then(Value::as_str) {
|
||||||
|
Some("message") => {
|
||||||
|
for part in parts {
|
||||||
|
if part.get("type").and_then(Value::as_str) == Some("output_text") {
|
||||||
|
self.add_output(part.get("text").and_then(Value::as_str));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some("reasoning") => {
|
||||||
|
for part in parts.chain(item.get("summary").and_then(Value::as_array).into_iter().flatten()) {
|
||||||
|
self.add_reasoning(part.get("text").and_then(Value::as_str));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Ok(pretty) = serde_json::to_string_pretty(body) {
|
||||||
|
let (text, truncated) = clipped(&pretty);
|
||||||
|
self.response = Some(text);
|
||||||
|
self.response_truncated = truncated;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn settle(&mut self, outcome: Option<&'static str>) {
|
||||||
|
if self.finished_at.is_some() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.wallclock_s = Some(seconds(self.clock));
|
||||||
|
self.finished_at = Some(now_unix());
|
||||||
|
if let Some(outcome) = outcome {
|
||||||
|
self.outcome = Some(outcome);
|
||||||
|
}
|
||||||
|
let failed = self.error.is_some() || self.http_status.is_some_and(|status| status >= 400);
|
||||||
|
self.state = if failed {
|
||||||
|
"error"
|
||||||
|
} else if self.outcome == Some("disconnected") {
|
||||||
|
"disconnected"
|
||||||
|
} else {
|
||||||
|
"completed"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The summary row (no prompts or answers) or the whole record.
|
||||||
|
fn render(&self, detail: bool) -> Value {
|
||||||
|
let mut out = Map::new();
|
||||||
|
let mut put = |key: &str, value: Value| {
|
||||||
|
out.insert(key.to_owned(), value);
|
||||||
|
};
|
||||||
|
put("id", json!(self.id));
|
||||||
|
put("path", json!(self.path));
|
||||||
|
put("model", self.model.clone());
|
||||||
|
put("started_at", json!(self.started_at));
|
||||||
|
put("state", json!(self.state));
|
||||||
|
put("stream", json!(self.stream));
|
||||||
|
put("response_format", self.response_format.clone());
|
||||||
|
put("input_truncated", json!(self.input_truncated));
|
||||||
|
put("output_truncated", json!(self.output_truncated));
|
||||||
|
put("reasoning_truncated", json!(self.reasoning_truncated));
|
||||||
|
put("queue_s", Value::Null);
|
||||||
|
put("load_s", Value::Null);
|
||||||
|
put("first_token_s", json!(self.first_token_s));
|
||||||
|
put("wallclock_s", json!(self.wallclock_s.unwrap_or_else(|| seconds(self.clock))));
|
||||||
|
if let Some(status) = self.http_status {
|
||||||
|
put("http_status", json!(status));
|
||||||
|
}
|
||||||
|
if let Some(at) = self.finished_at {
|
||||||
|
put("finished_at", json!(at));
|
||||||
|
}
|
||||||
|
if let Some(outcome) = self.outcome {
|
||||||
|
put("outcome", json!(outcome));
|
||||||
|
}
|
||||||
|
if let Some(usage) = &self.usage {
|
||||||
|
put("usage", usage.clone());
|
||||||
|
}
|
||||||
|
if let Some(error) = &self.error {
|
||||||
|
put("error", error.clone());
|
||||||
|
}
|
||||||
|
if self.response.is_some() {
|
||||||
|
put("response_truncated", json!(self.response_truncated));
|
||||||
|
}
|
||||||
|
if detail {
|
||||||
|
put("input", json!(self.input));
|
||||||
|
put("output", json!(self.output));
|
||||||
|
put("reasoning", json!(self.reasoning));
|
||||||
|
if let Some(response) = &self.response {
|
||||||
|
put("response", json!(response));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Value::Object(out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Shared = Arc<Mutex<Record>>;
|
||||||
|
|
||||||
|
/// The monitor: disabled (nothing is kept) or a bounded list of request records.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct RequestMonitor {
|
||||||
|
enabled: bool,
|
||||||
|
records: Mutex<VecDeque<Shared>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RequestMonitor {
|
||||||
|
pub fn new(enabled: bool) -> Self {
|
||||||
|
Self { enabled, records: Mutex::new(VecDeque::new()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn enabled(&self) -> bool {
|
||||||
|
self.enabled
|
||||||
|
}
|
||||||
|
|
||||||
|
fn begin(&self, path: &str, body: &[u8]) -> Shared {
|
||||||
|
let request: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
|
||||||
|
let raw = if request.is_null() {
|
||||||
|
String::from_utf8_lossy(body).into_owned()
|
||||||
|
} else {
|
||||||
|
serde_json::to_string_pretty(&request).unwrap_or_default()
|
||||||
|
};
|
||||||
|
let (input, input_truncated) = clipped(&raw);
|
||||||
|
let record = Arc::new(Mutex::new(Record {
|
||||||
|
id: uuid::Uuid::new_v4().simple().to_string()[..12].to_owned(),
|
||||||
|
path: path.to_owned(),
|
||||||
|
model: request.get("model").filter(|m| m.is_string()).cloned().unwrap_or(Value::Null),
|
||||||
|
started_at: now_unix(),
|
||||||
|
state: "queued",
|
||||||
|
outcome: None,
|
||||||
|
stream: request.get("stream") == Some(&json!(true)),
|
||||||
|
response_format: request
|
||||||
|
.get("response_format")
|
||||||
|
.and_then(|f| f.get("type"))
|
||||||
|
.or_else(|| request.pointer("/text/format/type"))
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or(Value::Null),
|
||||||
|
input,
|
||||||
|
input_truncated,
|
||||||
|
output: String::new(),
|
||||||
|
output_truncated: false,
|
||||||
|
reasoning: String::new(),
|
||||||
|
reasoning_truncated: false,
|
||||||
|
first_token_s: None,
|
||||||
|
usage: None,
|
||||||
|
error: None,
|
||||||
|
http_status: None,
|
||||||
|
response: None,
|
||||||
|
response_truncated: false,
|
||||||
|
wallclock_s: None,
|
||||||
|
finished_at: None,
|
||||||
|
clock: Instant::now(),
|
||||||
|
}));
|
||||||
|
if let Ok(mut records) = self.records.lock() {
|
||||||
|
if records.len() == RETENTION {
|
||||||
|
records.pop_front();
|
||||||
|
}
|
||||||
|
records.push_back(record.clone());
|
||||||
|
}
|
||||||
|
record
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Newest first, without prompts and answers.
|
||||||
|
pub fn summaries(&self) -> Vec<Value> {
|
||||||
|
let records: Vec<Shared> = self.records.lock().map(|r| r.iter().rev().cloned().collect()).unwrap_or_default();
|
||||||
|
records.iter().filter_map(|record| record.lock().ok().map(|r| r.render(false))).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One whole record, `None` once it was evicted (or never existed).
|
||||||
|
pub fn detail(&self, id: &str) -> Option<Value> {
|
||||||
|
let record = self.records.lock().ok()?.iter().find(|r| r.lock().is_ok_and(|r| r.id == id))?.clone();
|
||||||
|
let rendered = record.lock().ok()?.render(true);
|
||||||
|
Some(rendered)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An event stream passed through unchanged while its events are read into the record.
|
||||||
|
struct Tap {
|
||||||
|
inner: axum::body::BodyDataStream,
|
||||||
|
record: Shared,
|
||||||
|
pending: Vec<u8>,
|
||||||
|
done: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Tap {
|
||||||
|
fn absorb(&mut self, chunk: &[u8]) {
|
||||||
|
self.pending.extend_from_slice(chunk);
|
||||||
|
let Ok(mut record) = self.record.lock() else { return };
|
||||||
|
while let Some(newline) = self.pending.iter().position(|b| *b == b'\n') {
|
||||||
|
let line: Vec<u8> = self.pending.drain(..=newline).collect();
|
||||||
|
let line = String::from_utf8_lossy(&line);
|
||||||
|
let Some(data) = line.trim_end_matches(['\r', '\n']).strip_prefix("data:") else { continue };
|
||||||
|
let data = data.trim();
|
||||||
|
if data.is_empty() || data == "[DONE]" || data.len() > LINE_LIMIT {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Ok(event) = serde_json::from_str::<Value>(data) {
|
||||||
|
record.absorb_event(&event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.pending.len() > LINE_LIMIT {
|
||||||
|
self.pending.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn settle(&mut self, outcome: Option<&'static str>) {
|
||||||
|
self.done = true;
|
||||||
|
if let Ok(mut record) = self.record.lock() {
|
||||||
|
record.settle(outcome);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Stream for Tap {
|
||||||
|
type Item = Result<Bytes, axum::Error>;
|
||||||
|
|
||||||
|
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||||
|
match Pin::new(&mut self.inner).poll_next(cx) {
|
||||||
|
Poll::Ready(Some(Ok(chunk))) => {
|
||||||
|
self.absorb(&chunk);
|
||||||
|
Poll::Ready(Some(Ok(chunk)))
|
||||||
|
}
|
||||||
|
Poll::Ready(Some(Err(error))) => {
|
||||||
|
self.settle(Some("disconnected"));
|
||||||
|
Poll::Ready(Some(Err(error)))
|
||||||
|
}
|
||||||
|
Poll::Ready(None) => {
|
||||||
|
self.settle(None);
|
||||||
|
Poll::Ready(None)
|
||||||
|
}
|
||||||
|
Poll::Pending => Poll::Pending,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Tap {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if !self.done {
|
||||||
|
// the consumer went away before the stream ended
|
||||||
|
self.settle(Some("disconnected"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn too_large() -> Response {
|
||||||
|
let body = json!({"error": {"message": "request body too large", "type": "invalid_request_error"}});
|
||||||
|
(StatusCode::PAYLOAD_TOO_LARGE, axum::Json(body)).into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Middleware for the generation routes: record the request and its answer when the monitor is on; a no-op otherwise.
|
||||||
|
pub async fn capture(State(monitor): State<Arc<RequestMonitor>>, request: Request, next: Next) -> Response {
|
||||||
|
if !monitor.enabled {
|
||||||
|
return next.run(request).await;
|
||||||
|
}
|
||||||
|
let path = request.uri().path().to_owned();
|
||||||
|
let (parts, body) = request.into_parts();
|
||||||
|
let Ok(bytes) = axum::body::to_bytes(body, BODY_LIMIT).await else {
|
||||||
|
return too_large();
|
||||||
|
};
|
||||||
|
let record = monitor.begin(&path, &bytes);
|
||||||
|
let response = next.run(Request::from_parts(parts, Body::from(bytes))).await;
|
||||||
|
let (mut parts, body) = response.into_parts();
|
||||||
|
if let Ok(mut r) = record.lock() {
|
||||||
|
r.http_status = Some(parts.status.as_u16());
|
||||||
|
}
|
||||||
|
let streaming = parts
|
||||||
|
.headers
|
||||||
|
.get(header::CONTENT_TYPE)
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.is_some_and(|v| v.starts_with("text/event-stream"));
|
||||||
|
if streaming {
|
||||||
|
let tap = Tap { inner: body.into_data_stream(), record, pending: Vec::new(), done: false };
|
||||||
|
return Response::from_parts(parts, Body::from_stream(tap));
|
||||||
|
}
|
||||||
|
match axum::body::to_bytes(body, RESPONSE_LIMIT).await {
|
||||||
|
Ok(bytes) => {
|
||||||
|
if let Ok(mut r) = record.lock() {
|
||||||
|
if let Ok(value) = serde_json::from_slice::<Value>(&bytes) {
|
||||||
|
r.absorb_response(&value);
|
||||||
|
}
|
||||||
|
r.settle(None);
|
||||||
|
}
|
||||||
|
if let Ok(length) = HeaderValue::from_str(&bytes.len().to_string()) {
|
||||||
|
parts.headers.insert(header::CONTENT_LENGTH, length);
|
||||||
|
}
|
||||||
|
Response::from_parts(parts, Body::from(bytes))
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
if let Ok(mut r) = record.lock() {
|
||||||
|
r.settle(Some("disconnected"));
|
||||||
|
}
|
||||||
|
crate::elog!("request monitor: could not read a response body: {error}");
|
||||||
|
(StatusCode::INTERNAL_SERVER_ERROR, "response body unavailable").into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn record() -> Shared {
|
||||||
|
RequestMonitor::new(true).begin("/v1/chat/completions", br#"{"model":"m","stream":true,"messages":[{"role":"user","content":"hi"}]}"#)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_request_is_captured_as_pretty_json_with_its_model_and_stream_flag() {
|
||||||
|
let monitor = RequestMonitor::new(true);
|
||||||
|
let shared = monitor.begin("/v1/responses", br#"{"model":"qwen","stream":false,"text":{"format":{"type":"json_object"}},"input":"hi"}"#);
|
||||||
|
let r = shared.lock().unwrap();
|
||||||
|
assert_eq!((r.model.clone(), r.stream, r.state), (json!("qwen"), false, "queued"));
|
||||||
|
assert_eq!(r.response_format, json!("json_object"));
|
||||||
|
assert!(r.input.contains("\"input\": \"hi\""), "{}", r.input);
|
||||||
|
assert_eq!(r.id.len(), 12);
|
||||||
|
// a body that is not JSON is kept as text
|
||||||
|
let other = monitor.begin("/v1/responses", b"not json");
|
||||||
|
assert_eq!(other.lock().unwrap().input, "not json");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chat_anthropic_and_responses_streams_are_read() {
|
||||||
|
let shared = record();
|
||||||
|
let mut r = shared.lock().unwrap();
|
||||||
|
r.absorb_event(&json!({"choices": [{"delta": {"content": "Hel"}}]}));
|
||||||
|
assert_eq!(r.state, "generating");
|
||||||
|
assert!(r.first_token_s.is_some());
|
||||||
|
r.absorb_event(&json!({"choices": [{"delta": {"content": "lo", "reasoning_content": "think"}}], "usage": {"completion_tokens": 2}}));
|
||||||
|
r.absorb_event(&json!({"type": "content_block_delta", "delta": {"type": "text_delta", "text": "!"}}));
|
||||||
|
r.absorb_event(&json!({"type": "content_block_delta", "delta": {"type": "thinking_delta", "thinking": "+"}}));
|
||||||
|
r.absorb_event(&json!({"type": "response.output_text.delta", "delta": "?"}));
|
||||||
|
r.absorb_event(&json!({"type": "response.reasoning_text.delta", "delta": "-"}));
|
||||||
|
assert_eq!((r.output.as_str(), r.reasoning.as_str()), ("Hello!?", "think+-"));
|
||||||
|
assert_eq!(r.usage, Some(json!({"completion_tokens": 2})));
|
||||||
|
r.absorb_event(&json!({"type": "message_start", "message": {"usage": {"input_tokens": 9, "output_tokens": 1}}}));
|
||||||
|
r.absorb_event(&json!({"type": "message_delta", "usage": {"output_tokens": 7}}));
|
||||||
|
assert_eq!(r.usage, Some(json!({"input_tokens": 9, "output_tokens": 7})));
|
||||||
|
r.absorb_event(&json!({"type": "response.completed", "response": {"usage": {"input_tokens": 3, "output_tokens": 4, "total_tokens": 7}}}));
|
||||||
|
assert_eq!(r.usage.as_ref().unwrap()["total_tokens"], 7);
|
||||||
|
r.absorb_event(&json!({"type": "response.failed", "response": {"error": {"message": "boom"}}}));
|
||||||
|
assert_eq!(r.error, Some(json!({"message": "boom"})));
|
||||||
|
r.settle(None);
|
||||||
|
assert_eq!(r.state, "error");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn whole_responses_of_the_three_dialects_are_read() {
|
||||||
|
let chat = json!({"choices": [{"message": {"content": "A", "reasoning_content": "r"}}], "usage": {"completion_tokens": 1}});
|
||||||
|
let messages = json!({"type": "message", "content": [{"type": "thinking", "thinking": "t"}, {"type": "text", "text": "B"}], "usage": {"output_tokens": 1}});
|
||||||
|
let responses = json!({"object": "response", "output": [
|
||||||
|
{"type": "reasoning", "content": [{"type": "reasoning_text", "text": "x"}], "summary": [{"text": "y"}]},
|
||||||
|
{"type": "message", "content": [{"type": "output_text", "text": "C"}]}], "usage": {"output_tokens": 3}});
|
||||||
|
for (body, output, reasoning) in [(chat, "A", "r"), (messages, "B", "t"), (responses, "C", "xy")] {
|
||||||
|
let shared = record();
|
||||||
|
let mut r = shared.lock().unwrap();
|
||||||
|
r.absorb_response(&body);
|
||||||
|
r.settle(None);
|
||||||
|
assert_eq!((r.output.as_str(), r.reasoning.as_str(), r.state), (output, reasoning, "completed"));
|
||||||
|
assert_eq!(serde_json::from_str::<Value>(r.response.as_ref().unwrap()).unwrap(), body);
|
||||||
|
assert!(r.usage.is_some());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_http_error_or_a_dropped_stream_is_not_a_success() {
|
||||||
|
let shared = record();
|
||||||
|
let mut r = shared.lock().unwrap();
|
||||||
|
r.http_status = Some(429);
|
||||||
|
r.settle(None);
|
||||||
|
assert_eq!(r.state, "error");
|
||||||
|
let shared = record();
|
||||||
|
let mut r = shared.lock().unwrap();
|
||||||
|
r.http_status = Some(200);
|
||||||
|
r.settle(Some("disconnected"));
|
||||||
|
assert_eq!((r.state, r.outcome), ("disconnected", Some("disconnected")));
|
||||||
|
// settling twice keeps the first verdict
|
||||||
|
r.settle(None);
|
||||||
|
assert_eq!(r.state, "disconnected");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn captured_text_is_bounded_and_flagged_at_a_character_boundary() {
|
||||||
|
let shared = record();
|
||||||
|
let mut r = shared.lock().unwrap();
|
||||||
|
let big = "é".repeat(CAP);
|
||||||
|
r.add_output(Some(&big));
|
||||||
|
r.add_output(Some("more"));
|
||||||
|
assert!(r.output.len() <= CAP && r.output_truncated);
|
||||||
|
assert!(r.output.chars().all(|c| c == 'é'));
|
||||||
|
let monitor = RequestMonitor::new(true);
|
||||||
|
let body = format!("{{\"input\":\"{}\"}}", "x".repeat(CAP + 100));
|
||||||
|
let huge = monitor.begin("/v1/responses", body.as_bytes());
|
||||||
|
let huge = huge.lock().unwrap();
|
||||||
|
assert_eq!(huge.input.len(), CAP);
|
||||||
|
assert!(huge.input_truncated);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn retention_evicts_the_oldest_and_summaries_leave_the_payload_out() {
|
||||||
|
let monitor = RequestMonitor::new(true);
|
||||||
|
let first = monitor.begin("/v1/messages", br#"{"messages":[]}"#);
|
||||||
|
let first_id = first.lock().unwrap().id.clone();
|
||||||
|
for _ in 0..RETENTION {
|
||||||
|
monitor.begin("/v1/messages", br#"{"messages":[]}"#);
|
||||||
|
}
|
||||||
|
assert_eq!(monitor.summaries().len(), RETENTION);
|
||||||
|
assert!(monitor.detail(&first_id).is_none());
|
||||||
|
let newest = monitor.summaries().remove(0);
|
||||||
|
for payload in ["input", "output", "reasoning", "response"] {
|
||||||
|
assert!(newest.get(payload).is_none(), "{payload}");
|
||||||
|
}
|
||||||
|
let detail = monitor.detail(newest["id"].as_str().unwrap()).unwrap();
|
||||||
|
assert!(detail.get("input").is_some() && detail.get("output").is_some());
|
||||||
|
assert!(newest["queue_s"].is_null() && newest["load_s"].is_null());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_disabled_monitor_keeps_nothing() {
|
||||||
|
let monitor = RequestMonitor::default();
|
||||||
|
assert!(!monitor.enabled());
|
||||||
|
assert!(monitor.summaries().is_empty());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,7 +14,7 @@ use std::{
|
|||||||
use axum::{
|
use axum::{
|
||||||
Json,
|
Json,
|
||||||
body::Bytes,
|
body::Bytes,
|
||||||
extract::{Request, State},
|
extract::{RawQuery, Request, State},
|
||||||
http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header},
|
http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header},
|
||||||
middleware::Next,
|
middleware::Next,
|
||||||
response::{IntoResponse, Response},
|
response::{IntoResponse, Response},
|
||||||
@@ -560,6 +560,29 @@ pub async fn v1_reconfigure(State(state): State<AppState>, headers: HeaderMap, b
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `GET /api/requests`: the request monitor (`api_monitor` in the config; 404 while it is off, as in the Original). Without
|
||||||
|
/// `id` the retained requests, newest first, without prompts and answers; with `?id=` one whole record, or 404 once evicted.
|
||||||
|
pub async fn api_requests(State(state): State<AppState>, RawQuery(query): RawQuery) -> Response {
|
||||||
|
if !state.monitor.enabled() {
|
||||||
|
return not_found().await;
|
||||||
|
}
|
||||||
|
let id = query.as_deref().and_then(|query| {
|
||||||
|
query.split('&').find_map(|pair| pair.strip_prefix("id=").map(|id| id.to_owned()))
|
||||||
|
});
|
||||||
|
if let Some(id) = id {
|
||||||
|
return match state.monitor.detail(&id) {
|
||||||
|
Some(record) => reply(StatusCode::OK, record),
|
||||||
|
None => reply(StatusCode::NOT_FOUND, error_body(None, "request no longer retained")),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let worker = *state.worker.read().await;
|
||||||
|
reply(
|
||||||
|
StatusCode::OK,
|
||||||
|
json!({"requests": state.monitor.summaries(), "retention": crate::request_monitor::RETENTION, "persistent": false,
|
||||||
|
"loaded": is_loaded(&worker), "auto_load": state.control.is_some()}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/// Unknown paths: a JSON error, like the Original's `{"error": {"message": "not found"}}`.
|
/// Unknown paths: a JSON error, like the Original's `{"error": {"message": "not found"}}`.
|
||||||
pub async fn not_found() -> Response {
|
pub async fn not_found() -> Response {
|
||||||
reply(StatusCode::NOT_FOUND, error_body(None, "not found"))
|
reply(StatusCode::NOT_FOUND, error_body(None, "not found"))
|
||||||
|
|||||||
@@ -94,7 +94,7 @@ impl Default for WorkerStatus {
|
|||||||
max_context: None,
|
max_context: None,
|
||||||
known_max_context: None,
|
known_max_context: None,
|
||||||
last_activity: None,
|
last_activity: None,
|
||||||
metrics: Default::default(),
|
metrics: crate::metrics::GenerationMetrics::with_history(),
|
||||||
output_cap: None,
|
output_cap: None,
|
||||||
text_level_engine: false,
|
text_level_engine: false,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -111,6 +111,15 @@ impl Stack {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn start_with(name: &str, tune: impl FnOnce(&mut BackendWorkerConfig)) -> Self {
|
async fn start_with(name: &str, tune: impl FnOnce(&mut BackendWorkerConfig)) -> Self {
|
||||||
|
Self::start_full(name, tune, false).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The same stack with the API request monitor (`api_monitor`) on.
|
||||||
|
async fn start_monitored(name: &str) -> Self {
|
||||||
|
Self::start_full(name, |_| {}, true).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn start_full(name: &str, tune: impl FnOnce(&mut BackendWorkerConfig), monitor: bool) -> Self {
|
||||||
let dir = common::scratch(name);
|
let dir = common::scratch(name);
|
||||||
let tokenizer = merging_tokenizer(&dir);
|
let tokenizer = merging_tokenizer(&dir);
|
||||||
let (engine, handle) = ScriptedEngine::new(ScriptedEngine::fixture_descriptor());
|
let (engine, handle) = ScriptedEngine::new(ScriptedEngine::fixture_descriptor());
|
||||||
@@ -147,6 +156,7 @@ impl Stack {
|
|||||||
tokenizer: Some(tokenizer.clone()),
|
tokenizer: Some(tokenizer.clone()),
|
||||||
generation: Some(requests),
|
generation: Some(requests),
|
||||||
control: Some(control),
|
control: Some(control),
|
||||||
|
monitor: Arc::new(strata_control::request_monitor::RequestMonitor::new(monitor)),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
@@ -1502,3 +1512,166 @@ async fn a_known_prompt_text_is_sent_only_when_the_ids_decode_to_it() {
|
|||||||
);
|
);
|
||||||
stack.finish().await;
|
stack.finish().await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The telemetry document an engine publishes (`leleka-memory`'s `telemetry.rs`), as the worker copies it into the view.
|
||||||
|
fn engine_telemetry() -> String {
|
||||||
|
json!({
|
||||||
|
"version": 1, "phase": "idle", "request": null,
|
||||||
|
"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_last": 100.0, "decode_tok_s_avg": 100.0, "decode_tok_s_lifetime": 100.0, "decode_tok_s_live": null,
|
||||||
|
"prefill_tok_s_last": 5050.0, "prefill_tok_s_avg": 5050.0, "prefill_tok_s_lifetime": 5000.0},
|
||||||
|
"cache": {"requests": 2, "hit_requests": 1, "hit_ratio": 0.5, "prompt_tokens": 201000, "reused_tokens": 80000, "token_hit_ratio": 0.398, "last_prompt_tokens": 101000, "last_reused_tokens": 0},
|
||||||
|
"context": {"live_tokens": 101200, "max_tokens": 262144, "used_pct": 38.6},
|
||||||
|
"settings": {"context_tokens": 262144},
|
||||||
|
})
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_request_monitor_records_prompts_answers_and_usage_in_the_three_dialects() {
|
||||||
|
let stack = Stack::start_monitored("bw-monitor").await;
|
||||||
|
let parse = |body: &str| -> Value { serde_json::from_str(body).unwrap() };
|
||||||
|
assert_eq!(parse(&stack.get("/api/requests").await.1)["requests"].as_array().unwrap().len(), 0);
|
||||||
|
|
||||||
|
stack.engine.push(Script::stop_with(&["hel", "lo"], usage(7, 2, 0)));
|
||||||
|
let chat = json!({"model": "fixture", "messages": [{"role": "user", "content": "say <b>hi</b>"}]});
|
||||||
|
assert_eq!(stack.post("/v1/chat/completions", &chat).await.0, 200);
|
||||||
|
stack.engine.push(Script::stop_with(&["str", "eam"], usage(7, 2, 0)));
|
||||||
|
let streamed = json!({"model": "fixture", "stream": true, "stream_options": {"include_usage": true}, "messages": [{"role": "user", "content": "go"}]});
|
||||||
|
assert_eq!(stack.post("/v1/chat/completions", &streamed).await.0, 200);
|
||||||
|
stack.engine.push(Script::stop_with(&["res", "p"], usage(4, 2, 1)));
|
||||||
|
assert_eq!(stack.post("/v1/responses", &body(json!({"stream": true}))).await.0, 200);
|
||||||
|
stack.engine.push(Script::stop_with(&["whole"], usage(4, 1, 0)));
|
||||||
|
assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200);
|
||||||
|
// a refused request is recorded as an error with its status, not as a success
|
||||||
|
let (status, _) = stack.post("/v1/responses", &json!({"model": "fixture", "input": "x", "bogus": 1})).await;
|
||||||
|
assert!(status >= 400);
|
||||||
|
|
||||||
|
let listed = parse(&stack.get("/api/requests").await.1);
|
||||||
|
assert_eq!(listed["retention"], 100);
|
||||||
|
assert_eq!(listed["persistent"], false);
|
||||||
|
assert_eq!(listed["loaded"], true);
|
||||||
|
let rows = listed["requests"].as_array().unwrap();
|
||||||
|
assert_eq!(rows.len(), 5);
|
||||||
|
// newest first: the refusal, then the buffered Responses, the streamed Responses, the streamed Chat, the buffered Chat
|
||||||
|
assert_eq!(rows[0]["state"], "error");
|
||||||
|
assert!(rows[0]["http_status"].as_u64().unwrap() >= 400);
|
||||||
|
let expected = [("/v1/responses", "whole"), ("/v1/responses", "resp"), ("/v1/chat/completions", "stream"), ("/v1/chat/completions", "hello")];
|
||||||
|
for (row, (path, output)) in rows[1..].iter().zip(expected) {
|
||||||
|
assert_eq!(row["path"], path);
|
||||||
|
assert_eq!(row["state"], "completed", "{row}");
|
||||||
|
assert_eq!(row["http_status"], 200);
|
||||||
|
assert!(row.get("input").is_none() && row.get("output").is_none(), "summaries carry no payload");
|
||||||
|
assert!(row["wallclock_s"].as_f64().unwrap() >= row["first_token_s"].as_f64().unwrap());
|
||||||
|
let detail = parse(&stack.get(&format!("/api/requests?id={}", row["id"].as_str().unwrap())).await.1);
|
||||||
|
assert_eq!(detail["output"], output, "{detail}");
|
||||||
|
assert!(detail["input"].as_str().unwrap().contains("\"model\": \"fixture\""));
|
||||||
|
assert!(detail["usage"].is_object(), "{detail}");
|
||||||
|
assert_eq!(detail["model"], "fixture");
|
||||||
|
}
|
||||||
|
let streamed_chat = parse(&stack.get(&format!("/api/requests?id={}", rows[3]["id"].as_str().unwrap())).await.1);
|
||||||
|
assert_eq!(streamed_chat["stream"], true);
|
||||||
|
assert!(streamed_chat.get("response").is_none(), "a stream has no single response body");
|
||||||
|
let buffered_chat = parse(&stack.get(&format!("/api/requests?id={}", rows[4]["id"].as_str().unwrap())).await.1);
|
||||||
|
assert_eq!(parse(buffered_chat["response"].as_str().unwrap())["choices"][0]["message"]["content"], "hello");
|
||||||
|
assert!(buffered_chat["input"].as_str().unwrap().contains("say <b>hi</b>"));
|
||||||
|
assert_eq!(stack.get("/api/requests?id=missing").await.0, 404);
|
||||||
|
stack.finish().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_request_monitor_is_off_by_default_and_keeps_nothing() {
|
||||||
|
let stack = Stack::start("bw-monitor-off").await;
|
||||||
|
stack.engine.push(Script::stop_with(&["x"], usage(2, 1, 0)));
|
||||||
|
assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200);
|
||||||
|
let (status, text) = stack.get("/api/requests").await;
|
||||||
|
assert_eq!(status, 404, "{text}");
|
||||||
|
assert_eq!(stack.get("/api/requests?id=anything").await.0, 404);
|
||||||
|
assert!(stack.state.monitor.summaries().is_empty());
|
||||||
|
let metrics: Value = serde_json::from_str(&stack.get("/metrics").await.1).unwrap();
|
||||||
|
assert_eq!(metrics["engine"]["api_monitor"], false);
|
||||||
|
// an engine that publishes no telemetry (yet): empty hardware blocks, no raw document, the rest of the document intact
|
||||||
|
assert_eq!(metrics["hardware"], json!({}));
|
||||||
|
assert_eq!(metrics["hardware_static"], json!({}));
|
||||||
|
assert!(metrics["telemetry"].is_null());
|
||||||
|
assert_eq!(metrics["requests_kept"], 1);
|
||||||
|
stack.finish().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn metrics_carry_the_python_monitor_members_and_a_prometheus_view() {
|
||||||
|
let stack = Stack::start("bw-metrics-monitor").await;
|
||||||
|
stack.state.memory.set_telemetry(Some(engine_telemetry()));
|
||||||
|
stack.engine.push(Script::stop_with(&["a", "b"], usage(10, 2, 4)));
|
||||||
|
assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200);
|
||||||
|
stack.engine.push(Script::stop_with(&["c"], usage(6, 1, 0)));
|
||||||
|
assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200);
|
||||||
|
|
||||||
|
let metrics: Value = serde_json::from_str(&stack.get("/metrics").await.1).unwrap();
|
||||||
|
// the native members are untouched
|
||||||
|
assert_eq!(metrics["schema_version"], 1);
|
||||||
|
assert_eq!(metrics["generation"]["completed"], 2);
|
||||||
|
// the Python Monitor members
|
||||||
|
assert_eq!(metrics["engine"]["model"], "fixture");
|
||||||
|
assert_eq!(metrics["engine"]["max_context"], 262_144);
|
||||||
|
assert_eq!(metrics["engine"]["images"], false);
|
||||||
|
assert_eq!(metrics["live"]["state"], "idle");
|
||||||
|
assert_eq!(metrics["live"]["queued"], 0);
|
||||||
|
assert_eq!(metrics["requests_kept"], 2);
|
||||||
|
let requests = metrics["requests"].as_array().unwrap();
|
||||||
|
assert_eq!(requests.len(), 2);
|
||||||
|
assert_eq!(requests[0]["prompt_tokens"], 6);
|
||||||
|
assert_eq!(requests[1]["prompt_tokens"], 10);
|
||||||
|
assert_eq!(requests[1]["reused"], 4);
|
||||||
|
assert_eq!(requests[1]["output_tokens"], 2);
|
||||||
|
assert_eq!(requests[1]["finish"], "stop");
|
||||||
|
assert_eq!(metrics["totals"]["requests"], 2);
|
||||||
|
assert_eq!(metrics["totals"]["prompt_tokens"], 16);
|
||||||
|
assert_eq!(metrics["totals"]["reused"], 4);
|
||||||
|
assert_eq!(metrics["totals"]["output_tokens"], 3);
|
||||||
|
assert_eq!(metrics["hardware"]["gpu_util"], 91);
|
||||||
|
assert_eq!(metrics["hardware"]["gpu_mem_used"], 30000u64 * 1_048_576);
|
||||||
|
assert_eq!(metrics["hardware"]["gpu_temp"], 61);
|
||||||
|
assert_eq!(metrics["hardware"]["tok_s"], 0.0);
|
||||||
|
assert_eq!(metrics["hardware_static"]["gpu_name"], "NVIDIA GeForce RTX 5090");
|
||||||
|
assert_eq!(metrics["history"]["gpu_util"].as_array().unwrap().len(), 1);
|
||||||
|
assert!(metrics["time"].as_f64().unwrap() > 1.0e9);
|
||||||
|
assert_eq!(metrics["telemetry"]["context"]["max_tokens"], 262_144);
|
||||||
|
// `?requests=all` lists everything kept (here the same two)
|
||||||
|
let all: Value = serde_json::from_str(&stack.get("/metrics?requests=all").await.1).unwrap();
|
||||||
|
assert_eq!(all["requests"].as_array().unwrap().len(), 2);
|
||||||
|
|
||||||
|
// Prometheus text: by query and by the Accept header a scraper sends
|
||||||
|
let scrape = |accept: Option<&str>, query: &str| {
|
||||||
|
let mut request = stack.client.get(format!("{}/metrics{query}", stack.base));
|
||||||
|
if let Some(accept) = accept {
|
||||||
|
request = request.header("accept", accept);
|
||||||
|
}
|
||||||
|
request
|
||||||
|
};
|
||||||
|
for (accept, query) in [(None, "?format=prometheus"), (Some("application/openmetrics-text;version=1.0.0,text/plain;version=0.0.4;q=0.5,*/*;q=0.1"), "")] {
|
||||||
|
let response = scrape(accept, query).send().await.unwrap();
|
||||||
|
assert_eq!(response.status(), 200);
|
||||||
|
assert!(response.headers()["content-type"].to_str().unwrap().starts_with("text/plain; version=0.0.4"));
|
||||||
|
let text = response.text().await.unwrap();
|
||||||
|
assert!(text.contains("leleka_generations_completed_total 2\n"), "{text}");
|
||||||
|
assert!(text.contains("leleka_prompt_tokens_total 16\n") && text.contains("leleka_prompt_tokens_reused_total 4\n"));
|
||||||
|
assert!(text.contains("leleka_generated_tokens_total 3\n"));
|
||||||
|
assert!(text.contains("leleka_up 1\n"));
|
||||||
|
assert!(text.contains("leleka_gpu_utilization_percent 91\n"));
|
||||||
|
assert!(text.contains("leleka_gpu_memory_used_bytes 31457280000\n"));
|
||||||
|
assert!(text.contains("leleka_gpu_temperature_celsius 61\n"));
|
||||||
|
assert!(text.contains("leleka_host_memory_used_bytes 55448698880\n"), "{text}");
|
||||||
|
assert!(text.contains("leleka_context_live_tokens 101200\n") && text.contains("leleka_context_max_tokens 262144\n"));
|
||||||
|
assert!(text.contains("leleka_prefix_cache_token_hit_ratio 0.398\n"));
|
||||||
|
assert!(text.contains("leleka_decode_tokens_per_second{window=\"average\"} 100\n"));
|
||||||
|
assert!(text.contains("leleka_engine_phase{phase=\"idle\"} 1\n"));
|
||||||
|
}
|
||||||
|
// a JSON client keeps getting JSON
|
||||||
|
let json_reply = scrape(Some("application/json"), "").send().await.unwrap();
|
||||||
|
assert_eq!(json_reply.headers()["content-type"], "application/json");
|
||||||
|
stack.finish().await;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
//! GPU load for the operator (`leleka status`): utilisation, VRAM, power and clock through NVML, loaded with `dlopen`
|
//! 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.
|
//! so a host without the library simply reports nothing. Read-only queries; nothing here touches a CUDA context.
|
||||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
#[derive(Clone, Debug, Default, PartialEq)]
|
||||||
pub struct NvmlSample {
|
pub struct NvmlSample {
|
||||||
pub index: u32,
|
pub index: u32,
|
||||||
pub util_pct: u32,
|
pub util_pct: u32,
|
||||||
@@ -9,6 +9,8 @@ pub struct NvmlSample {
|
|||||||
pub vram_total_mib: u64,
|
pub vram_total_mib: u64,
|
||||||
pub power_w: Option<f64>,
|
pub power_w: Option<f64>,
|
||||||
pub sm_clock_mhz: Option<u32>,
|
pub sm_clock_mhz: Option<u32>,
|
||||||
|
pub temp_c: Option<u32>,
|
||||||
|
pub name: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A reusable handle to NVML's device `index`; `None` when the library, the symbols or the device are missing.
|
/// A reusable handle to NVML's device `index`; `None` when the library, the symbols or the device are missing.
|
||||||
@@ -48,7 +50,10 @@ mod imp {
|
|||||||
type GetMemory = unsafe extern "C" fn(*mut c_void, *mut MemoryInfo) -> 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 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;
|
type GetClock = unsafe extern "C" fn(*mut c_void, c_uint, *mut c_uint) -> c_int;
|
||||||
|
type GetTemperature = unsafe extern "C" fn(*mut c_void, c_uint, *mut c_uint) -> c_int;
|
||||||
|
type GetName = unsafe extern "C" fn(*mut c_void, *mut std::ffi::c_char, c_uint) -> c_int;
|
||||||
const NVML_CLOCK_SM: c_uint = 1;
|
const NVML_CLOCK_SM: c_uint = 1;
|
||||||
|
const NVML_TEMPERATURE_GPU: c_uint = 0;
|
||||||
|
|
||||||
pub(super) struct Handle {
|
pub(super) struct Handle {
|
||||||
library: *mut c_void,
|
library: *mut c_void,
|
||||||
@@ -58,6 +63,8 @@ mod imp {
|
|||||||
memory: GetMemory,
|
memory: GetMemory,
|
||||||
power: Option<GetPower>,
|
power: Option<GetPower>,
|
||||||
clock: Option<GetClock>,
|
clock: Option<GetClock>,
|
||||||
|
temperature: Option<GetTemperature>,
|
||||||
|
name: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
// SAFETY: NVML's query functions are thread-safe after nvmlInit; the handle is plain data and the library stays loaded.
|
// SAFETY: NVML's query functions are thread-safe after nvmlInit; the handle is plain data and the library stays loaded.
|
||||||
@@ -93,6 +100,8 @@ mod imp {
|
|||||||
let memory: GetMemory = std::mem::transmute(symbol(library, c"nvmlDeviceGetMemoryInfo")?);
|
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 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));
|
let clock = symbol(library, c"nvmlDeviceGetClockInfo").map(|p| std::mem::transmute::<*mut c_void, GetClock>(p));
|
||||||
|
let temperature = symbol(library, c"nvmlDeviceGetTemperature").map(|p| std::mem::transmute::<*mut c_void, GetTemperature>(p));
|
||||||
|
let get_name = symbol(library, c"nvmlDeviceGetName").map(|p| std::mem::transmute::<*mut c_void, GetName>(p));
|
||||||
if init() != 0 {
|
if init() != 0 {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
@@ -100,7 +109,15 @@ mod imp {
|
|||||||
if get_handle(index, &mut device) != 0 || device.is_null() {
|
if get_handle(index, &mut device) != 0 || device.is_null() {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
Some(Handle { library, device, index, utilization, memory, power, clock })
|
// The board name does not change: read it once.
|
||||||
|
let name = get_name.and_then(|f| {
|
||||||
|
let mut buffer = [0 as std::ffi::c_char; 96];
|
||||||
|
// SAFETY: a valid device handle and a buffer of the length passed.
|
||||||
|
(f(device, buffer.as_mut_ptr(), buffer.len() as c_uint) == 0)
|
||||||
|
.then(|| std::ffi::CStr::from_ptr(buffer.as_ptr()).to_string_lossy().into_owned())
|
||||||
|
.filter(|name| !name.is_empty())
|
||||||
|
});
|
||||||
|
Some(Handle { library, device, index, utilization, memory, power, clock, temperature, name })
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
if built.is_none() {
|
if built.is_none() {
|
||||||
@@ -130,6 +147,11 @@ mod imp {
|
|||||||
// SAFETY: as above.
|
// SAFETY: as above.
|
||||||
(unsafe { f(self.device, NVML_CLOCK_SM, &mut mhz) } == 0).then_some(mhz)
|
(unsafe { f(self.device, NVML_CLOCK_SM, &mut mhz) } == 0).then_some(mhz)
|
||||||
});
|
});
|
||||||
|
let temp_c = self.temperature.and_then(|f| {
|
||||||
|
let mut degrees: c_uint = 0;
|
||||||
|
// SAFETY: as above.
|
||||||
|
(unsafe { f(self.device, NVML_TEMPERATURE_GPU, &mut degrees) } == 0).then_some(degrees)
|
||||||
|
});
|
||||||
Some(NvmlSample {
|
Some(NvmlSample {
|
||||||
index: self.index,
|
index: self.index,
|
||||||
util_pct: utilization.gpu,
|
util_pct: utilization.gpu,
|
||||||
@@ -138,6 +160,8 @@ mod imp {
|
|||||||
vram_total_mib: memory.total >> 20,
|
vram_total_mib: memory.total >> 20,
|
||||||
power_w,
|
power_w,
|
||||||
sm_clock_mhz,
|
sm_clock_mhz,
|
||||||
|
temp_c,
|
||||||
|
name: self.name.clone(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+149
-9
@@ -1,6 +1,6 @@
|
|||||||
//! Command implementations behind `main`: `up`, `preflight`, `status`, `down`, `profiles`.
|
//! Command implementations behind `main`: `up`, `preflight`, `status`, `down`, `profiles`.
|
||||||
use crate::{
|
use crate::{
|
||||||
cli::{Command, Environment, USAGE, UpOptions, parse},
|
cli::{Command, Environment, ReconfigureArgs, USAGE, UpOptions, parse},
|
||||||
plan::{Context, Mode, Step, StepState, UnitScopeTag, gather, plan_steps, render_plan},
|
plan::{Context, Mode, Step, StepState, UnitScopeTag, gather, plan_steps, render_plan},
|
||||||
preflight::Report,
|
preflight::Report,
|
||||||
profile::{BUILTIN, Profile},
|
profile::{BUILTIN, Profile},
|
||||||
@@ -90,7 +90,7 @@ pub async fn main_native(args: Vec<String>) -> i32 {
|
|||||||
Command::Up(opts) => up(opts).await,
|
Command::Up(opts) => up(opts).await,
|
||||||
Command::Status(opts) => status(opts).await,
|
Command::Status(opts) => status(opts).await,
|
||||||
Command::Down(opts) => down(opts).await,
|
Command::Down(opts) => down(opts).await,
|
||||||
Command::Reconfigure(opts, settings) => reconfigure(opts, settings).await,
|
Command::Reconfigure(opts, args) => reconfigure(opts, args).await,
|
||||||
Command::Verify(opts) => verify(opts).await,
|
Command::Verify(opts) => verify(opts).await,
|
||||||
Command::Run { config, kar_fd } => {
|
Command::Run { config, kar_fd } => {
|
||||||
supervisor::run(supervisor::Options { config, kar_fd }).await
|
supervisor::run(supervisor::Options { config, kar_fd }).await
|
||||||
@@ -460,9 +460,18 @@ pub fn print_status(
|
|||||||
i32::from(!ready)
|
i32::from(!ready)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `leleka reconfigure`: POST the settings to the running gateway (same API key as every request).
|
/// `leleka reconfigure`.
|
||||||
async fn reconfigure(opts: UpOptions, settings: String) -> i32 {
|
///
|
||||||
|
/// Runtime settings go to the running engine through the gateway (`POST /v1/reconfigure`, same API key as every request). A
|
||||||
|
/// budget or preset change cannot be made that way: it is handed to the supervisor, which restarts only the engine process.
|
||||||
|
/// `--persist` then writes the result into `leleka.json` (through the supervisor when one runs, directly otherwise).
|
||||||
|
async fn reconfigure(opts: UpOptions, args: ReconfigureArgs) -> i32 {
|
||||||
let paths = opts.dirs.paths();
|
let paths = opts.dirs.paths();
|
||||||
|
let supervised = crate::plan::service_running(&paths);
|
||||||
|
if args.needs_restart() {
|
||||||
|
return reconfigure_by_restart(&opts, &args, supervised).await;
|
||||||
|
}
|
||||||
|
let settings = serde_json::Value::Object(args.settings.clone()).to_string();
|
||||||
let api = crate::config::RunConfig::read(&paths.run_config())
|
let api = crate::config::RunConfig::read(&paths.run_config())
|
||||||
.map(|config| config.ports.api)
|
.map(|config| config.ports.api)
|
||||||
.unwrap_or_else(|_| opts.ports.api.clone());
|
.unwrap_or_else(|_| opts.ports.api.clone());
|
||||||
@@ -474,26 +483,50 @@ async fn reconfigure(opts: UpOptions, settings: String) -> i32 {
|
|||||||
eprintln!("leleka: cannot reach the API address {api}");
|
eprintln!("leleka: cannot reach the API address {api}");
|
||||||
return 1;
|
return 1;
|
||||||
};
|
};
|
||||||
send_reconfigure(address, key.trim_end(), &settings, opts.json).await
|
let persist = args.persist.then(|| PersistTarget { paths: &paths, settings: &args.settings, supervised });
|
||||||
|
send_reconfigure(address, key.trim_end(), &settings, opts.json, persist).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where `--persist` writes after a successful runtime change.
|
||||||
|
pub struct PersistTarget<'a> {
|
||||||
|
pub paths: &'a crate::layout::Paths,
|
||||||
|
pub settings: &'a serde_json::Map<String, Value>,
|
||||||
|
/// A supervisor runs: it records the change in the configuration it holds.
|
||||||
|
pub supervised: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST the settings document to the gateway at `address` (a loopback address) and print the answer. Shared with the WSL bridge.
|
/// POST the settings document to the gateway at `address` (a loopback address) and print the answer. Shared with the WSL bridge.
|
||||||
pub async fn send_reconfigure(address: std::net::SocketAddr, key: &str, settings: &str, json: bool) -> i32 {
|
pub async fn send_reconfigure(address: std::net::SocketAddr, key: &str, settings: &str, json: bool, persist: Option<PersistTarget<'_>>) -> i32 {
|
||||||
eprintln!("leleka: reconfiguring {settings}; the engine reopens its serve stack (tens of seconds, requests wait meanwhile)");
|
eprintln!("leleka: reconfiguring {settings}; the engine reopens its serve stack (tens of seconds, requests wait meanwhile)");
|
||||||
let response = crate::http::post_json(address, "/v1/reconfigure", Some(key), settings, std::time::Duration::from_secs(1900)).await;
|
let response = crate::http::post_json(address, "/v1/reconfigure", Some(key), settings, std::time::Duration::from_secs(1900)).await;
|
||||||
match response {
|
match response {
|
||||||
Ok(response) => {
|
Ok(response) => {
|
||||||
let document: Value = serde_json::from_str(&response.body).unwrap_or(Value::Null);
|
let document: Value = serde_json::from_str(&response.body).unwrap_or(Value::Null);
|
||||||
|
let mut persisted = None;
|
||||||
|
if response.status == 200
|
||||||
|
&& let Some(target) = &persist
|
||||||
|
{
|
||||||
|
persisted = Some(persist_settings(target.paths, target.settings, target.supervised).await);
|
||||||
|
}
|
||||||
if json {
|
if json {
|
||||||
println!("{}", serde_json::to_string_pretty(&document).unwrap_or(response.body));
|
let mut shown = document.clone();
|
||||||
|
if let (Some(object), Some(result)) = (shown.as_object_mut(), &persisted) {
|
||||||
|
object.insert("persisted".into(), json!(result.is_ok()));
|
||||||
|
}
|
||||||
|
println!("{}", serde_json::to_string_pretty(&shown).unwrap_or(response.body));
|
||||||
} else if response.status == 200 {
|
} else if response.status == 200 {
|
||||||
println!("reconfigured; the engine runs with:");
|
println!("reconfigured; the engine runs with:");
|
||||||
print!("{}", render_settings(&document["settings"]));
|
print!("{}", render_settings(&document["settings"]));
|
||||||
|
match &persisted {
|
||||||
|
Some(Ok(note)) => println!("persisted: {note}"),
|
||||||
|
Some(Err(why)) => eprintln!("leleka: the engine runs with the new settings, but they were not persisted: {why}"),
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
let message = document["error"]["message"].as_str().unwrap_or(&response.body);
|
let message = document["error"]["message"].as_str().unwrap_or(&response.body);
|
||||||
eprintln!("leleka: the change was refused (HTTP {}): {message}", response.status);
|
eprintln!("leleka: the change was refused (HTTP {}): {message}", response.status);
|
||||||
}
|
}
|
||||||
i32::from(response.status != 200)
|
i32::from(response.status != 200 || persisted.is_some_and(|result| result.is_err()))
|
||||||
}
|
}
|
||||||
Err(message) => {
|
Err(message) => {
|
||||||
eprintln!("leleka: {message}");
|
eprintln!("leleka: {message}");
|
||||||
@@ -502,6 +535,112 @@ pub async fn send_reconfigure(address: std::net::SocketAddr, key: &str, settings
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `--persist` after a runtime change: the supervisor records it in the configuration it holds (so that a restart of the engine
|
||||||
|
/// keeps it) and writes the file; with no supervisor the file is edited directly.
|
||||||
|
async fn persist_settings(paths: &crate::layout::Paths, settings: &serde_json::Map<String, Value>, supervised: bool) -> Result<String, String> {
|
||||||
|
if !supervised {
|
||||||
|
let changed = crate::reconfigure::persist_offline(paths, settings)?;
|
||||||
|
return Ok(format!("leleka.json updated ({} changed; no supervisor was running)", changed.len()));
|
||||||
|
}
|
||||||
|
let request = crate::reconfigure::Request {
|
||||||
|
id: crate::reconfigure::new_request_id(),
|
||||||
|
settings: settings.clone(),
|
||||||
|
persist: true,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let outcome = ask_supervisor(paths, &request, std::time::Duration::from_secs(60), false).await?;
|
||||||
|
if outcome.state == crate::reconfigure::State::Done && outcome.persisted {
|
||||||
|
Ok(outcome.message)
|
||||||
|
} else {
|
||||||
|
Err(outcome.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Leave `request` for the supervisor and wait for its answer (`running` answers are progress, not the end).
|
||||||
|
async fn ask_supervisor(
|
||||||
|
paths: &crate::layout::Paths,
|
||||||
|
request: &crate::reconfigure::Request,
|
||||||
|
limit: std::time::Duration,
|
||||||
|
show_progress: bool,
|
||||||
|
) -> Result<crate::reconfigure::Outcome, String> {
|
||||||
|
use crate::reconfigure::{State, read_outcome, write_request};
|
||||||
|
write_request(paths, request)?;
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
let mut last = String::new();
|
||||||
|
loop {
|
||||||
|
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||||
|
match read_outcome(paths, &request.id) {
|
||||||
|
Some(outcome) if outcome.state != State::Running => return Ok(outcome),
|
||||||
|
Some(outcome) if show_progress && outcome.message != last => {
|
||||||
|
eprintln!("leleka: {}", outcome.message);
|
||||||
|
last = outcome.message;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
if !crate::plan::service_running(paths) {
|
||||||
|
return Err("the supervisor stopped before it answered; see the service log".into());
|
||||||
|
}
|
||||||
|
if started.elapsed() > limit {
|
||||||
|
let _ = std::fs::remove_file(paths.reconfigure_request());
|
||||||
|
return Err(format!("the supervisor did not answer within {} s", limit.as_secs()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A budget or preset change: the supervisor restarts the engine process with the new numbers.
|
||||||
|
async fn reconfigure_by_restart(opts: &UpOptions, args: &ReconfigureArgs, supervised: bool) -> i32 {
|
||||||
|
let paths = opts.dirs.paths();
|
||||||
|
if !supervised {
|
||||||
|
eprintln!(
|
||||||
|
"leleka: --gpu-budget-gib and --preset restart the engine process under the supervisor, and no supervisor runs for {}; start the service first (`leleka up`), or change the budget there: `leleka up --gpu-budget-gib N --preset P`",
|
||||||
|
paths.dirs.state.display()
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
let load_timeout = crate::config::RunConfig::read(&paths.run_config()).map_or(1800, |config| config.load_timeout_s);
|
||||||
|
let request = crate::reconfigure::Request {
|
||||||
|
id: crate::reconfigure::new_request_id(),
|
||||||
|
gpu_budget_gib: args.gpu_budget_gib,
|
||||||
|
preset: args.preset,
|
||||||
|
settings: args.settings.clone(),
|
||||||
|
persist: args.persist,
|
||||||
|
};
|
||||||
|
eprintln!("leleka: asking the supervisor to restart the engine with the new settings (the model loads again; the gateway and the API keep their ports)");
|
||||||
|
// two engine starts at worst (the new one fails, the previous one is restored), plus the stop and the host checks
|
||||||
|
let limit = std::time::Duration::from_secs(2 * load_timeout + 300);
|
||||||
|
let outcome = match ask_supervisor(&paths, &request, limit, !opts.json).await {
|
||||||
|
Ok(outcome) => outcome,
|
||||||
|
Err(why) => {
|
||||||
|
eprintln!("leleka: {why}");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let done = outcome.state == crate::reconfigure::State::Done;
|
||||||
|
if opts.json {
|
||||||
|
println!("{}", serde_json::to_string_pretty(&outcome).unwrap_or_default());
|
||||||
|
} else if done {
|
||||||
|
println!("reconfigured: {}", outcome.message);
|
||||||
|
if let Some(effective) = &outcome.effective {
|
||||||
|
print!("{}", render_effective(effective));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
eprintln!("leleka: the change was not made: {}", outcome.message);
|
||||||
|
}
|
||||||
|
i32::from(!done)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The numbers in force after a restart-in-place, one line each.
|
||||||
|
pub fn render_effective(effective: &Value) -> String {
|
||||||
|
let Some(object) = effective.as_object() else { return String::new() };
|
||||||
|
let mut out = String::new();
|
||||||
|
for (key, value) in object {
|
||||||
|
if !value.is_null() {
|
||||||
|
out.push_str(&format!(" {key:20} {value}\n"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
/// The settings block of the engine, one line per member.
|
/// The settings block of the engine, one line per member.
|
||||||
pub fn render_settings(settings: &Value) -> String {
|
pub fn render_settings(settings: &Value) -> String {
|
||||||
let Some(object) = settings.as_object() else { return String::new() };
|
let Some(object) = settings.as_object() else { return String::new() };
|
||||||
@@ -534,10 +673,11 @@ pub fn render_machine(machine: &Value) -> String {
|
|||||||
let gpu = &machine["gpu"];
|
let gpu = &machine["gpu"];
|
||||||
if gpu.is_object() {
|
if gpu.is_object() {
|
||||||
out.push_str(&format!(
|
out.push_str(&format!(
|
||||||
" gpu {}% busy (memory bus {}%), VRAM {} of {} GiB{}{}\n",
|
" gpu {}% busy (memory bus {}%), VRAM {} of {} GiB{}{}{}\n",
|
||||||
gpu["util_pct"], gpu["mem_util_pct"], gib(&gpu["vram_used_mib"]), gib(&gpu["vram_total_mib"]),
|
gpu["util_pct"], gpu["mem_util_pct"], gib(&gpu["vram_used_mib"]), gib(&gpu["vram_total_mib"]),
|
||||||
gpu["power_w"].as_f64().map_or(String::new(), |w| format!(", {w:.0} W")),
|
gpu["power_w"].as_f64().map_or(String::new(), |w| format!(", {w:.0} W")),
|
||||||
gpu["sm_clock_mhz"].as_u64().map_or(String::new(), |m| format!(", {m} MHz")),
|
gpu["sm_clock_mhz"].as_u64().map_or(String::new(), |m| format!(", {m} MHz")),
|
||||||
|
gpu["temp_c"].as_u64().map_or(String::new(), |t| format!(", {t} C")),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let cpu = &machine["cpu"];
|
let cpu = &machine["cpu"];
|
||||||
|
|||||||
@@ -91,6 +91,14 @@ fn engine(fake: &Path, args: &[String]) {
|
|||||||
eprintln!("fake engine: HF_TOKEN leaked into the engine environment");
|
eprintln!("fake engine: HF_TOKEN leaked into the engine environment");
|
||||||
std::process::exit(3);
|
std::process::exit(3);
|
||||||
}
|
}
|
||||||
|
// `fail-engine-budget` holds a `--gpu-budget` value (bytes) the engine refuses to start with: a new setting that
|
||||||
|
// does not come up, while the previous one does.
|
||||||
|
if let (Ok(refused), Some(budget)) = (fs::read_to_string(fake.join("fail-engine-budget")), flag(args, "--gpu-budget"))
|
||||||
|
&& refused.trim() == budget
|
||||||
|
{
|
||||||
|
eprintln!("fake engine: refusing a budget of {budget} bytes");
|
||||||
|
std::process::exit(9);
|
||||||
|
}
|
||||||
let listen = flag(args, "--listen").unwrap_or("127.0.0.1:0").to_owned();
|
let listen = flag(args, "--listen").unwrap_or("127.0.0.1:0").to_owned();
|
||||||
if let Some(fd) = flag(args, "--kar-archive-fd") {
|
if let Some(fd) = flag(args, "--kar-archive-fd") {
|
||||||
// The shim must have moved the descriptor to >= 3 and the engine must find a sealed, unlinked memfd.
|
// The shim must have moved the descriptor to >= 3 and the engine must find a sealed, unlinked memfd.
|
||||||
|
|||||||
+96
-10
@@ -51,7 +51,7 @@ UP / PREFLIGHT OPTIONS
|
|||||||
--service-user NAME system unit only: account the service runs as (default leleka, created if missing)
|
--service-user NAME system unit only: account the service runs as (default leleka, created if missing)
|
||||||
|
|
||||||
RECONFIGURE OPTIONS (any of them; the call waits for the request in flight, the engine reopens its serve stack in a few seconds, the weights stay
|
RECONFIGURE OPTIONS (any of them; the call waits for the request in flight, the engine reopens its serve stack in a few seconds, the weights stay
|
||||||
loaded; a refused change keeps the previous settings; the VRAM budget, the preset and --kv-resident need a restart: `leleka up`)
|
loaded; a refused change keeps the previous settings; --kv-resident is fixed per process and needs `leleka up`)
|
||||||
--context-tokens N tokens of context (1..262144)
|
--context-tokens N tokens of context (1..262144)
|
||||||
--prefill-capacity N prefill chunk: 256 512 1024 2048 3072 4096 6144 8192
|
--prefill-capacity N prefill chunk: 256 512 1024 2048 3072 4096 6144 8192
|
||||||
--kv-resident N only the value in force is accepted (the K/V window is fixed per process; restart to change it)
|
--kv-resident N only the value in force is accepted (the K/V window is fixed per process; restart to change it)
|
||||||
@@ -61,6 +61,10 @@ loaded; a refused change keeps the previous settings; the VRAM budget, the prese
|
|||||||
--prefix-retention-min N minutes an idle cached session is kept (0 = no limit)
|
--prefix-retention-min N minutes an idle cached session is kept (0 = no limit)
|
||||||
--cpu-workers N CPU expert workers (1..15)
|
--cpu-workers N CPU expert workers (1..15)
|
||||||
--spec-min-p P draft-probability floor (0..1)
|
--spec-min-p P draft-probability floor (0..1)
|
||||||
|
--gpu-budget-gib N VRAM budget of the engine (1..1024). Fixed when the CUDA context is created: the supervisor restarts
|
||||||
|
the engine process (the model loads again, minutes), the gateway and the API keep their ports
|
||||||
|
--preset dedicated|workstation resource preset (same restart); refused when the host cannot hold it
|
||||||
|
--persist keep the change across restarts of the service (writes leleka.json)
|
||||||
--assets/--state-dir/--prefix/--api-port/--json as for `up`; `leleka status` prints the settings in force
|
--assets/--state-dir/--prefix/--api-port/--json as for `up`; `leleka status` prints the settings in force
|
||||||
|
|
||||||
WINDOWS
|
WINDOWS
|
||||||
@@ -115,6 +119,26 @@ pub struct UpOptions {
|
|||||||
pub kar_fd: Option<u32>,
|
pub kar_fd: Option<u32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What `leleka reconfigure` was asked to change.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq)]
|
||||||
|
pub struct ReconfigureArgs {
|
||||||
|
/// Runtime settings (the members of `POST /v1/reconfigure`): the engine reopens its serve stack.
|
||||||
|
pub settings: serde_json::Map<String, serde_json::Value>,
|
||||||
|
/// New VRAM budget: needs a new engine process.
|
||||||
|
pub gpu_budget_gib: Option<u64>,
|
||||||
|
/// New resource preset: needs a new engine process.
|
||||||
|
pub preset: Option<crate::resources::Preset>,
|
||||||
|
/// Keep the change across restarts of the service (`leleka.json`).
|
||||||
|
pub persist: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ReconfigureArgs {
|
||||||
|
/// The budget and the preset are fixed when the CUDA context is created.
|
||||||
|
pub fn needs_restart(&self) -> bool {
|
||||||
|
self.gpu_budget_gib.is_some() || self.preset.is_some()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum Command {
|
pub enum Command {
|
||||||
Up(UpOptions),
|
Up(UpOptions),
|
||||||
@@ -126,8 +150,8 @@ pub enum Command {
|
|||||||
ExecInherit(Vec<String>),
|
ExecInherit(Vec<String>),
|
||||||
Status(UpOptions),
|
Status(UpOptions),
|
||||||
Down(UpOptions),
|
Down(UpOptions),
|
||||||
/// The options locate the running service; the document is the JSON object of settings to change.
|
/// The options locate the running service; the arguments are what to change.
|
||||||
Reconfigure(UpOptions, String),
|
Reconfigure(UpOptions, ReconfigureArgs),
|
||||||
Verify(UpOptions),
|
Verify(UpOptions),
|
||||||
Profiles(Option<String>),
|
Profiles(Option<String>),
|
||||||
Version,
|
Version,
|
||||||
@@ -393,9 +417,10 @@ const RECONFIGURE_FLAGS: &[(&str, &str)] = &[
|
|||||||
|
|
||||||
/// The settings flags of a `reconfigure` command line: returns the other arguments (they locate the service) and the JSON
|
/// The settings flags of a `reconfigure` command line: returns the other arguments (they locate the service) and the JSON
|
||||||
/// document the engine validates. Numbers stay numbers; the two cache members stay text.
|
/// document the engine validates. Numbers stay numbers; the two cache members stay text.
|
||||||
pub fn split_reconfigure(args: &[String]) -> Result<(Vec<String>, String), String> {
|
pub fn split_reconfigure(args: &[String]) -> Result<(Vec<String>, ReconfigureArgs), String> {
|
||||||
let mut rest: Vec<String> = Vec::new();
|
let mut rest: Vec<String> = Vec::new();
|
||||||
let mut document = serde_json::Map::new();
|
let mut document = serde_json::Map::new();
|
||||||
|
let mut extra = ReconfigureArgs::default();
|
||||||
let mut index = 0;
|
let mut index = 0;
|
||||||
while index < args.len() {
|
while index < args.len() {
|
||||||
let arg = &args[index];
|
let arg = &args[index];
|
||||||
@@ -403,6 +428,38 @@ pub fn split_reconfigure(args: &[String]) -> Result<(Vec<String>, String), Strin
|
|||||||
Some((name, value)) if name.starts_with("--") => (name, Some(value.to_owned())),
|
Some((name, value)) if name.starts_with("--") => (name, Some(value.to_owned())),
|
||||||
_ => (arg.as_str(), None),
|
_ => (arg.as_str(), None),
|
||||||
};
|
};
|
||||||
|
if name == "--persist" {
|
||||||
|
if inline.is_some() {
|
||||||
|
return Err("--persist takes no value".into());
|
||||||
|
}
|
||||||
|
extra.persist = true;
|
||||||
|
index += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if name == "--gpu-budget-gib" || name == "--preset" {
|
||||||
|
let value = match inline {
|
||||||
|
Some(value) => value,
|
||||||
|
None => {
|
||||||
|
index += 1;
|
||||||
|
args.get(index).ok_or_else(|| format!("{name} needs a value"))?.clone()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if name == "--preset" {
|
||||||
|
if extra.preset.replace(crate::resources::Preset::parse(&value)?).is_some() {
|
||||||
|
return Err(format!("{name} given twice"));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let gib: u64 = value.parse().map_err(|_| format!("{name} needs a whole number of GiB"))?;
|
||||||
|
if !(1..=1024).contains(&gib) {
|
||||||
|
return Err(format!("{name} must be 1..1024"));
|
||||||
|
}
|
||||||
|
if extra.gpu_budget_gib.replace(gib).is_some() {
|
||||||
|
return Err(format!("{name} given twice"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
index += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if let Some((_, member)) = RECONFIGURE_FLAGS.iter().find(|(flag, _)| *flag == name) {
|
if let Some((_, member)) = RECONFIGURE_FLAGS.iter().find(|(flag, _)| *flag == name) {
|
||||||
let value = match inline {
|
let value = match inline {
|
||||||
Some(value) => value,
|
Some(value) => value,
|
||||||
@@ -424,17 +481,18 @@ pub fn split_reconfigure(args: &[String]) -> Result<(Vec<String>, String), Strin
|
|||||||
}
|
}
|
||||||
index += 1;
|
index += 1;
|
||||||
}
|
}
|
||||||
if document.is_empty() {
|
if document.is_empty() && !extra.needs_restart() {
|
||||||
return Err("leleka reconfigure needs at least one setting; see `leleka --help`".into());
|
return Err("leleka reconfigure needs at least one setting; see `leleka --help`".into());
|
||||||
}
|
}
|
||||||
Ok((rest, serde_json::Value::Object(document).to_string()))
|
extra.settings = document;
|
||||||
|
Ok((rest, extra))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `leleka reconfigure`: pull the settings flags out, let `up_options` read the rest (where the service lives).
|
/// `leleka reconfigure`: pull the settings flags out, let `up_options` read the rest (where the service lives).
|
||||||
fn reconfigure_command(args: &[String], env: &Environment) -> Result<Command, String> {
|
fn reconfigure_command(args: &[String], env: &Environment) -> Result<Command, String> {
|
||||||
let (rest, document) = split_reconfigure(args)?;
|
let (rest, extra) = split_reconfigure(args)?;
|
||||||
let options = up_options(&rest, env)?;
|
let options = up_options(&rest, env)?;
|
||||||
Ok(Command::Reconfigure(options, document))
|
Ok(Command::Reconfigure(options, extra))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn parse(args: &[String], env: &Environment) -> Result<Command, String> {
|
pub fn parse(args: &[String], env: &Environment) -> Result<Command, String> {
|
||||||
@@ -571,14 +629,15 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn reconfigure_collects_the_settings_and_locates_the_service_with_the_up_flags() {
|
fn reconfigure_collects_the_settings_and_locates_the_service_with_the_up_flags() {
|
||||||
let Ok(Command::Reconfigure(options, document)) = parse_as(
|
let Ok(Command::Reconfigure(options, args)) = parse_as(
|
||||||
false,
|
false,
|
||||||
&["reconfigure", "--context-tokens", "65536", "--prefix-cache-tail=reply", "--prefix-cache-mib", "20480", "--spec-min-p", "0.5", "--state-dir", "/var/lib/leleka/state"],
|
&["reconfigure", "--context-tokens", "65536", "--prefix-cache-tail=reply", "--prefix-cache-mib", "20480", "--spec-min-p", "0.5", "--state-dir", "/var/lib/leleka/state"],
|
||||||
) else {
|
) else {
|
||||||
panic!("reconfigure did not parse");
|
panic!("reconfigure did not parse");
|
||||||
};
|
};
|
||||||
assert_eq!(options.dirs.state, std::path::PathBuf::from("/var/lib/leleka/state"));
|
assert_eq!(options.dirs.state, std::path::PathBuf::from("/var/lib/leleka/state"));
|
||||||
let value: serde_json::Value = serde_json::from_str(&document).unwrap();
|
assert!(!args.needs_restart() && !args.persist);
|
||||||
|
let value = serde_json::Value::Object(args.settings);
|
||||||
assert_eq!(value["context_tokens"], 65536);
|
assert_eq!(value["context_tokens"], 65536);
|
||||||
assert_eq!(value["prefix_cache_tail"], "reply");
|
assert_eq!(value["prefix_cache_tail"], "reply");
|
||||||
assert_eq!(value["prefix_cache_mib"], "20480");
|
assert_eq!(value["prefix_cache_mib"], "20480");
|
||||||
@@ -588,6 +647,33 @@ mod tests {
|
|||||||
assert!(parse_as(false, &["reconfigure", "--cpu-workers", "4", "--cpu-workers", "5"]).unwrap_err().contains("twice"));
|
assert!(parse_as(false, &["reconfigure", "--cpu-workers", "4", "--cpu-workers", "5"]).unwrap_err().contains("twice"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reconfigure_takes_the_budget_the_preset_and_persist_out_of_the_up_flags() {
|
||||||
|
let Ok(Command::Reconfigure(options, args)) = parse_as(
|
||||||
|
false,
|
||||||
|
&["reconfigure", "--gpu-budget-gib", "24", "--preset=workstation", "--persist", "--context-tokens", "65536", "--state-dir", "/s"],
|
||||||
|
) else {
|
||||||
|
panic!("reconfigure did not parse");
|
||||||
|
};
|
||||||
|
assert!(args.needs_restart() && args.persist);
|
||||||
|
assert_eq!(args.gpu_budget_gib, Some(24));
|
||||||
|
assert_eq!(args.preset, Some(crate::resources::Preset::Workstation));
|
||||||
|
assert_eq!(args.settings["context_tokens"], 65536);
|
||||||
|
// they are the restart request, not `up` options: the service is located by the remaining flags only
|
||||||
|
assert_eq!(options.dirs.state, std::path::PathBuf::from("/s"));
|
||||||
|
assert_eq!(options.gpu_budget_gib, None);
|
||||||
|
assert_eq!(options.preset, crate::resources::Preset::Dedicated);
|
||||||
|
// the budget or the preset alone is a request; nothing at all is not
|
||||||
|
assert!(matches!(parse_as(false, &["reconfigure", "--preset", "dedicated"]), Ok(Command::Reconfigure(..))));
|
||||||
|
assert!(matches!(parse_as(false, &["reconfigure", "--gpu-budget-gib", "20"]), Ok(Command::Reconfigure(..))));
|
||||||
|
assert!(parse_as(false, &["reconfigure", "--persist"]).unwrap_err().contains("at least one setting"));
|
||||||
|
assert!(parse_as(false, &["reconfigure", "--gpu-budget-gib", "0"]).unwrap_err().contains("1..1024"));
|
||||||
|
assert!(parse_as(false, &["reconfigure", "--gpu-budget-gib", "many"]).unwrap_err().contains("whole number"));
|
||||||
|
assert!(parse_as(false, &["reconfigure", "--preset", "shared"]).unwrap_err().contains("unknown preset"));
|
||||||
|
assert!(parse_as(false, &["reconfigure", "--persist=yes", "--cpu-workers", "2"]).unwrap_err().contains("no value"));
|
||||||
|
assert!(parse_as(false, &["reconfigure", "--gpu-budget-gib", "20", "--gpu-budget-gib", "21"]).unwrap_err().contains("twice"));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn api_bind_is_explicit_and_only_for_the_api() {
|
fn api_bind_is_explicit_and_only_for_the_api() {
|
||||||
let Command::Up(options) = parse_as(false, &["up", "--api-bind", "0.0.0.0"]).unwrap()
|
let Command::Up(options) = parse_as(false, &["up", "--api-bind", "0.0.0.0"]).unwrap()
|
||||||
|
|||||||
@@ -44,6 +44,10 @@ pub struct RunConfig {
|
|||||||
pub ports: Ports,
|
pub ports: Ports,
|
||||||
pub gpu: u32,
|
pub gpu: u32,
|
||||||
pub profile: Profile,
|
pub profile: Profile,
|
||||||
|
/// The profile as `up` resolved it before the resource preset changed it (flags applied): what `leleka reconfigure --preset`
|
||||||
|
/// recomputes the preset from, so that going back to `dedicated` undoes `workstation`. Absent in files written by older builds.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub base_profile: Option<Profile>,
|
||||||
/// The resource preset `up` applied (the profile and `engine_env` already carry its numbers).
|
/// The resource preset `up` applied (the profile and `engine_env` already carry its numbers).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub preset: crate::resources::Preset,
|
pub preset: crate::resources::Preset,
|
||||||
@@ -91,6 +95,7 @@ impl RunConfig {
|
|||||||
ports,
|
ports,
|
||||||
gpu,
|
gpu,
|
||||||
profile,
|
profile,
|
||||||
|
base_profile: None,
|
||||||
preset: crate::resources::Preset::default(),
|
preset: crate::resources::Preset::default(),
|
||||||
engine_env,
|
engine_env,
|
||||||
load_timeout_s: 1800,
|
load_timeout_s: 1800,
|
||||||
|
|||||||
@@ -152,6 +152,14 @@ impl Paths {
|
|||||||
pub fn status_file(&self) -> PathBuf {
|
pub fn status_file(&self) -> PathBuf {
|
||||||
self.run_dir().join("status.json")
|
self.run_dir().join("status.json")
|
||||||
}
|
}
|
||||||
|
/// A pending `leleka reconfigure` for the supervisor (`reconfigure.rs`); consumed by it.
|
||||||
|
pub fn reconfigure_request(&self) -> PathBuf {
|
||||||
|
self.run_dir().join("reconfigure-request.json")
|
||||||
|
}
|
||||||
|
/// The supervisor's answer to the request with the same id.
|
||||||
|
pub fn reconfigure_result(&self) -> PathBuf {
|
||||||
|
self.run_dir().join("reconfigure-result.json")
|
||||||
|
}
|
||||||
pub fn stamps(&self) -> PathBuf {
|
pub fn stamps(&self) -> PathBuf {
|
||||||
self.dirs.state.join("stamps")
|
self.dirs.state.join("stamps")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ pub mod manifest;
|
|||||||
pub mod plan;
|
pub mod plan;
|
||||||
pub mod preflight;
|
pub mod preflight;
|
||||||
pub mod profile;
|
pub mod profile;
|
||||||
|
pub mod reconfigure;
|
||||||
pub mod resources;
|
pub mod resources;
|
||||||
pub mod sealed;
|
pub mod sealed;
|
||||||
pub mod steps;
|
pub mod steps;
|
||||||
|
|||||||
@@ -258,7 +258,10 @@ pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option<String>) -> Context
|
|||||||
Ok(p) => {
|
Ok(p) => {
|
||||||
needs.expert_profile = expert_profile_state(p, &opts.dirs.assets);
|
needs.expert_profile = expert_profile_state(p, &opts.dirs.assets);
|
||||||
let mut engine_env = BTreeMap::new();
|
let mut engine_env = BTreeMap::new();
|
||||||
let resources = crate::resources::compute(&facts, gpu, p, opts.preset);
|
let base_profile = p.clone();
|
||||||
|
// An inherited sealed archive is already resident: it is not part of what the engine still needs from the host.
|
||||||
|
let planned_host = if opts.kar_fd.is_some() { crate::resources::with_resident_archive(&facts) } else { facts.clone() };
|
||||||
|
let resources = crate::resources::compute(&planned_host, gpu, p, opts.preset);
|
||||||
crate::resources::apply(&resources, p, &mut engine_env, opts.gpu_budget_gib.is_some());
|
crate::resources::apply(&resources, p, &mut engine_env, opts.gpu_budget_gib.is_some());
|
||||||
needs.resources = Some(resources);
|
needs.resources = Some(resources);
|
||||||
if needs.expert_profile == Some(ExpertProfileState::Valid)
|
if needs.expert_profile == Some(ExpertProfileState::Valid)
|
||||||
@@ -281,6 +284,7 @@ pub fn gather(opts: &UpOptions, var: &dyn Fn(&str) -> Option<String>) -> Context
|
|||||||
engine_env,
|
engine_env,
|
||||||
);
|
);
|
||||||
config.preset = opts.preset;
|
config.preset = opts.preset;
|
||||||
|
config.base_profile = Some(base_profile);
|
||||||
let report = evaluate(&facts, p, &needs);
|
let report = evaluate(&facts, p, &needs);
|
||||||
(Some(config), Some(report))
|
(Some(config), Some(report))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -94,6 +94,13 @@ pub struct MemoryBudget {
|
|||||||
/// where the agent's next turn resumes: the slot-equivalent resume, `docs/prefix-cache.md`). Absent: the engine's default (off).
|
/// where the agent's next turn resumes: the slot-equivalent resume, `docs/prefix-cache.md`). Absent: the engine's default (off).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub prefix_cache_tail: Option<String>,
|
pub prefix_cache_tail: Option<String>,
|
||||||
|
/// `--prefix-cache-block`: tokens per prefix block and chunk-grid step (a multiple of 256, at most 8192; 0 = the prefill chunk).
|
||||||
|
/// Only passed while the prefix cache is on.
|
||||||
|
#[serde(default)]
|
||||||
|
pub prefix_cache_block: Option<u32>,
|
||||||
|
/// Minutes an idle cached session is kept (`LELEKA_PREFIX_RETENTION_S`; 0 = no time limit). Only passed while the cache is on.
|
||||||
|
#[serde(default)]
|
||||||
|
pub prefix_retention_min: Option<u64>,
|
||||||
/// Below this much available host memory the caches shed (`LELEKA_MEMORY_SOFT_FLOOR_MIB`).
|
/// Below this much available host memory the caches shed (`LELEKA_MEMORY_SOFT_FLOOR_MIB`).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub soft_floor_mib: Option<u64>,
|
pub soft_floor_mib: Option<u64>,
|
||||||
@@ -130,6 +137,11 @@ impl MemoryBudget {
|
|||||||
{
|
{
|
||||||
return Err("memory.prefix_cache_tail must be off, prompt or reply".into());
|
return Err("memory.prefix_cache_tail must be off, prompt or reply".into());
|
||||||
}
|
}
|
||||||
|
if let Some(block) = self.prefix_cache_block
|
||||||
|
&& (block % 256 != 0 || block > 8192)
|
||||||
|
{
|
||||||
|
return Err("memory.prefix_cache_block must be a multiple of 256, at most 8192 (0 = the prefill chunk)".into());
|
||||||
|
}
|
||||||
if let (Some(soft), Some(hard)) = (self.soft_floor_mib, self.hard_floor_mib)
|
if let (Some(soft), Some(hard)) = (self.soft_floor_mib, self.hard_floor_mib)
|
||||||
&& hard >= soft
|
&& hard >= soft
|
||||||
{
|
{
|
||||||
@@ -157,9 +169,19 @@ impl MemoryBudget {
|
|||||||
if let Some(tail) = &self.prefix_cache_tail {
|
if let Some(tail) = &self.prefix_cache_tail {
|
||||||
args.extend(["--prefix-cache-tail".to_owned(), tail.clone()]);
|
args.extend(["--prefix-cache-tail".to_owned(), tail.clone()]);
|
||||||
}
|
}
|
||||||
|
if let Some(block) = self.prefix_cache_block
|
||||||
|
&& self.prefix_cache_on()
|
||||||
|
{
|
||||||
|
args.extend(["--prefix-cache-block".to_owned(), block.to_string()]);
|
||||||
|
}
|
||||||
args
|
args
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The prefix cache is configured and not switched off (`0`).
|
||||||
|
pub fn prefix_cache_on(&self) -> bool {
|
||||||
|
self.prefix_cache_mib.as_deref().is_some_and(|mib| mib != "0")
|
||||||
|
}
|
||||||
|
|
||||||
/// The engine environment this section adds.
|
/// The engine environment this section adds.
|
||||||
pub fn env(&self) -> BTreeMap<String, String> {
|
pub fn env(&self) -> BTreeMap<String, String> {
|
||||||
let mut env = BTreeMap::new();
|
let mut env = BTreeMap::new();
|
||||||
@@ -185,6 +207,9 @@ impl MemoryBudget {
|
|||||||
self.cache_share_percent.map(|v| v.to_string()),
|
self.cache_share_percent.map(|v| v.to_string()),
|
||||||
);
|
);
|
||||||
put("LELEKA_MEMORY_LOCK", self.lock.clone());
|
put("LELEKA_MEMORY_LOCK", self.lock.clone());
|
||||||
|
if self.prefix_cache_on() {
|
||||||
|
put("LELEKA_PREFIX_RETENTION_S", self.prefix_retention_min.map(|minutes| minutes.saturating_mul(60).to_string()));
|
||||||
|
}
|
||||||
put(
|
put(
|
||||||
"LELEKA_MEMORY_HEAL",
|
"LELEKA_MEMORY_HEAL",
|
||||||
self.heal.map(|v| if v { "1" } else { "0" }.to_owned()),
|
self.heal.map(|v| if v { "1" } else { "0" }.to_owned()),
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -94,6 +94,15 @@ pub fn workstation_ram_target(total: u64) -> u64 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The host as the planner should see it when the sealed archive memfd is already resident (an inherited `--kar-fd`, or the
|
||||||
|
/// descriptor a running supervisor holds): its pages are already missing from `MemAvailable`, and `compute` charges the archive to the
|
||||||
|
/// footprint of the pinned form, so without this the archive is paid for twice and a host that fits is told it does not.
|
||||||
|
pub fn with_resident_archive(facts: &Facts) -> Facts {
|
||||||
|
let mut facts = facts.clone();
|
||||||
|
facts.memory.available = facts.memory.available.saturating_add(ARCHIVE_BYTES);
|
||||||
|
facts
|
||||||
|
}
|
||||||
|
|
||||||
pub fn compute(facts: &Facts, gpu: Option<&Gpu>, profile: &Profile, preset: Preset) -> ResourcePlan {
|
pub fn compute(facts: &Facts, gpu: Option<&Gpu>, profile: &Profile, preset: Preset) -> ResourcePlan {
|
||||||
let mut plan = ResourcePlan {
|
let mut plan = ResourcePlan {
|
||||||
preset,
|
preset,
|
||||||
@@ -335,6 +344,22 @@ mod tests {
|
|||||||
assert!(env.is_empty());
|
assert!(env.is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_resident_sealed_archive_is_not_charged_to_the_footprint_twice() {
|
||||||
|
// the server with the 51.5 GiB memfd already resident: 121 GiB total, 9 GiB available (no other consumer left)
|
||||||
|
let resident = host(32, 121, 9);
|
||||||
|
let charged_twice = compute(&resident, Some(&gpu(32607, 32100)), &server(), Preset::Dedicated);
|
||||||
|
assert!(charged_twice.mapped_resident_gib.is_some(), "without the correction the pinned form looks impossible");
|
||||||
|
let corrected = compute(&with_resident_archive(&resident), Some(&gpu(32607, 32100)), &server(), Preset::Dedicated);
|
||||||
|
assert_eq!(corrected.mapped_resident_gib, None, "the archive is already paid for: only the engine's 3 GiB remain");
|
||||||
|
assert!(corrected.ram_expected_free_after_bytes.is_some());
|
||||||
|
// a host that really lacks the engine's own memory is still sent to the mapped form
|
||||||
|
let tiny = host(32, 121, 2);
|
||||||
|
assert!(compute(&with_resident_archive(&tiny), Some(&gpu(32607, 32100)), &server(), Preset::Dedicated).mapped_resident_gib.is_some());
|
||||||
|
// saturating, not wrapping
|
||||||
|
assert!(with_resident_archive(&host(1, 1, u64::MAX / GIB)).memory.available >= u64::MAX / 2);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn unknown_core_count_leaves_the_engine_default() {
|
fn unknown_core_count_leaves_the_engine_default() {
|
||||||
let plan = compute(&host(0, 121, 100), None, &server(), Preset::Workstation);
|
let plan = compute(&host(0, 121, 100), None, &server(), Preset::Workstation);
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ use crate::{
|
|||||||
http,
|
http,
|
||||||
layout::{MTP_PROFILE, Paths},
|
layout::{MTP_PROFILE, Paths},
|
||||||
profile::{ARCHIVE_BYTES, KarSource, archive_sha256},
|
profile::{ARCHIVE_BYTES, KarSource, archive_sha256},
|
||||||
sealed,
|
reconfigure, sealed,
|
||||||
};
|
};
|
||||||
use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps};
|
use leleka_model_format::verify_stamp::{FileIdentity, VerifyStamps};
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
@@ -744,11 +744,28 @@ impl Supervisor {
|
|||||||
));
|
));
|
||||||
let mut ready_since = Instant::now();
|
let mut ready_since = Instant::now();
|
||||||
let (mut gateway_restarts, mut api_restarts) = (0u32, 0u32);
|
let (mut gateway_restarts, mut api_restarts) = (0u32, 0u32);
|
||||||
|
// `leleka reconfigure` leaves a request file; look for it once a second.
|
||||||
|
let mut requests = tokio::time::interval(Duration::from_secs(1));
|
||||||
|
requests.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||||
|
|
||||||
// 4. supervise
|
// 4. supervise
|
||||||
let result: Result<(), Flow> = loop {
|
let result: Result<(), Flow> = loop {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
_ = self.shutdown.changed() => break Ok(()),
|
_ = self.shutdown.changed() => break Ok(()),
|
||||||
|
_ = requests.tick() => {
|
||||||
|
let Some(taken) = reconfigure::take_request(&self.paths) else { continue };
|
||||||
|
match taken {
|
||||||
|
Err(message) => {
|
||||||
|
self.log.line(&format!("reconfigure: {message}"));
|
||||||
|
self.answer("", reconfigure::State::Refused, message, false);
|
||||||
|
}
|
||||||
|
Ok(request) => match self.reconfigure(request, &mut engine, &mut gateway, &mut api).await {
|
||||||
|
Ok(()) => ready_since = Instant::now(),
|
||||||
|
Err(Flow::Stopped) => break Ok(()),
|
||||||
|
Err(flow) => break Err(flow),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
status = engine.wait() => {
|
status = engine.wait() => {
|
||||||
let text = status.map_or_else(|e| e.to_string(), |s| s.to_string());
|
let text = status.map_or_else(|e| e.to_string(), |s| s.to_string());
|
||||||
self.log.line(&format!("engine exited ({text}); the API reports not-ready until it is back"));
|
self.log.line(&format!("engine exited ({text}); the API reports not-ready until it is back"));
|
||||||
@@ -1103,6 +1120,168 @@ impl Supervisor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Leave the supervisor answer to a reconfigure request (best effort: the CLI times out without one).
|
||||||
|
fn answer(&self, id: &str, state: reconfigure::State, message: impl Into<String>, persisted: bool) {
|
||||||
|
let outcome = reconfigure::Outcome {
|
||||||
|
id: id.to_owned(),
|
||||||
|
state,
|
||||||
|
message: message.into(),
|
||||||
|
effective: Some(reconfigure::effective(&self.config)),
|
||||||
|
persisted,
|
||||||
|
};
|
||||||
|
if let Err(error) = reconfigure::write_outcome(&self.paths, &outcome) {
|
||||||
|
self.log.line(&format!("reconfigure: cannot write the answer: {error}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the host offers now, for the resource planner.
|
||||||
|
fn host_facts(&self) -> crate::facts::Facts {
|
||||||
|
crate::facts::probe(&crate::facts::ProbeRequest {
|
||||||
|
dirs: Vec::new(),
|
||||||
|
ports: Vec::new(),
|
||||||
|
binary_dir: None,
|
||||||
|
binaries: Vec::new(),
|
||||||
|
extra_library_dirs: Vec::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stop the API process and start it again (its configuration changed). The port stays the same.
|
||||||
|
async fn restart_api(&mut self, api: &mut Child) -> Result<(), Flow> {
|
||||||
|
self.kill_children(&mut [Some(&mut *api)]).await;
|
||||||
|
let args = vec![
|
||||||
|
"serve".to_owned(),
|
||||||
|
"--config".to_owned(),
|
||||||
|
self.paths.strata_config().display().to_string(),
|
||||||
|
];
|
||||||
|
*api = self.spawn("api", &self.paths.bin("strata-next"), &args, &BTreeMap::new(), None)?;
|
||||||
|
self.pids[2] = api.id();
|
||||||
|
self.wait_api_ready(api).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `leleka reconfigure` request.
|
||||||
|
///
|
||||||
|
/// Settings alone were applied to the live engine by the CLI; only the configuration in force is updated (and written when
|
||||||
|
/// asked). A budget or preset change restarts the engine process, and only that: the sealed archive descriptor this
|
||||||
|
/// process holds goes to the new engine, the gateway and the API keep their processes and ports. The planner checks the
|
||||||
|
/// request twice, first without disturbing the service (only what is impossible even with the engine gone is refused), then
|
||||||
|
/// with the engine stopped and the real free memory of the host. Whatever goes wrong after the stop, the previous settings
|
||||||
|
/// are started again. `Err` only when no engine can be started at all.
|
||||||
|
async fn reconfigure(
|
||||||
|
&mut self,
|
||||||
|
request: reconfigure::Request,
|
||||||
|
engine: &mut Child,
|
||||||
|
gateway: &mut Child,
|
||||||
|
api: &mut Child,
|
||||||
|
) -> Result<(), Flow> {
|
||||||
|
let id = request.id.clone();
|
||||||
|
self.log.line(&format!(
|
||||||
|
"reconfigure {id}: budget {:?} GiB, preset {:?}, settings {}, persist {}",
|
||||||
|
request.gpu_budget_gib,
|
||||||
|
request.preset.map(|p| p.as_str()),
|
||||||
|
serde_json::Value::Object(request.settings.clone()),
|
||||||
|
request.persist
|
||||||
|
));
|
||||||
|
if !request.needs_restart() {
|
||||||
|
let mut next = self.config.clone();
|
||||||
|
match reconfigure::record_settings(&mut next, &request.settings) {
|
||||||
|
Err(why) => self.answer(&id, reconfigure::State::Refused, why, false),
|
||||||
|
Ok(changed) => {
|
||||||
|
self.config = next;
|
||||||
|
let (persisted, note) = if request.persist {
|
||||||
|
match reconfigure::persist(&self.paths, &self.config) {
|
||||||
|
Ok(()) => (true, "written to leleka.json".to_owned()),
|
||||||
|
Err(why) => (false, format!("not persisted: {why}")),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
(false, "in force until the service restarts".to_owned())
|
||||||
|
};
|
||||||
|
self.answer(&id, reconfigure::State::Done, format!("recorded {changed:?}; {note}"), persisted);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let resident = self.archive.is_some();
|
||||||
|
let facts = self.host_facts();
|
||||||
|
match reconfigure::plan(&self.config, &request, &reconfigure::optimistic(&facts), resident) {
|
||||||
|
Err(why) => {
|
||||||
|
self.log.line(&format!("reconfigure {id} refused before any change: {why}"));
|
||||||
|
self.answer(&id, reconfigure::State::Refused, format!("{why}; nothing was changed"), false);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
Ok(planned) if planned.unchanged => {
|
||||||
|
self.answer(&id, reconfigure::State::Done, "the engine already runs with these settings", false);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
Ok(_) => {}
|
||||||
|
}
|
||||||
|
self.answer(&id, reconfigure::State::Running, "stopping the engine", false);
|
||||||
|
self.set_phase(Phase::EngineRestarting, "reconfiguring: restarting the engine");
|
||||||
|
self.log.line("reconfigure: stopping the engine (the sealed archive stays with the supervisor)");
|
||||||
|
self.kill_children(&mut [Some(&mut *engine)]).await;
|
||||||
|
self.pids[0] = None;
|
||||||
|
// The memory of the card returns when the process is gone; give the driver a moment before asking what is free.
|
||||||
|
let mut verdict = Err(String::new());
|
||||||
|
for attempt in 0..10 {
|
||||||
|
if !self.pause(Duration::from_secs(1)).await {
|
||||||
|
return Err(Flow::Stopped);
|
||||||
|
}
|
||||||
|
verdict = reconfigure::plan(&self.config, &request, &self.host_facts(), resident);
|
||||||
|
let waiting_for_vram = matches!(&verdict, Err(why) if why.starts_with("GPU memory"));
|
||||||
|
if !waiting_for_vram || attempt == 9 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let previous = self.config.clone();
|
||||||
|
let refusal = match verdict {
|
||||||
|
Ok(planned) => {
|
||||||
|
self.config = planned.config;
|
||||||
|
self.log.line(&format!("reconfigure: starting the engine with {}", reconfigure::effective(&self.config)));
|
||||||
|
match self.start_engine(gateway).await {
|
||||||
|
Ok(child) => {
|
||||||
|
*engine = child;
|
||||||
|
let mut persisted = false;
|
||||||
|
let mut note = "in force until the service restarts".to_owned();
|
||||||
|
if request.persist {
|
||||||
|
match reconfigure::persist(&self.paths, &self.config) {
|
||||||
|
Ok(()) => {
|
||||||
|
persisted = true;
|
||||||
|
note = "written to leleka.json".to_owned();
|
||||||
|
// the API advertises the context of strata.json: follow it
|
||||||
|
if self.config.profile.context_tokens != previous.profile.context_tokens {
|
||||||
|
self.restart_api(api).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(why) => note = format!("not persisted: {why}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.set_phase(Phase::Ready, "ready (engine reconfigured)");
|
||||||
|
self.log.line("reconfigure: done");
|
||||||
|
self.answer(&id, reconfigure::State::Done, format!("the engine runs with the new settings; {note}"), persisted);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
Err(Flow::Stopped) => return Err(Flow::Stopped),
|
||||||
|
Err(Flow::Fatal(failure)) => failure.message,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(why) => why,
|
||||||
|
};
|
||||||
|
// Refused on the stopped host, or the new engine did not come up: put the previous engine back.
|
||||||
|
self.config = previous;
|
||||||
|
self.log.line(&format!("reconfigure {id}: {refusal}; restoring the previous settings"));
|
||||||
|
let child = match self.start_engine(gateway).await {
|
||||||
|
Ok(child) => child,
|
||||||
|
Err(flow) => {
|
||||||
|
let why = format!("{refusal}; the previous settings could not be restored either");
|
||||||
|
self.answer(&id, reconfigure::State::Failed, why, false);
|
||||||
|
return Err(flow);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
*engine = child;
|
||||||
|
self.set_phase(Phase::Ready, "ready (previous settings restored)");
|
||||||
|
self.answer(&id, reconfigure::State::Refused, format!("{refusal}; the previous settings are back"), false);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// SIGINT (graceful for all three programs), then SIGKILL after the grace period.
|
/// SIGINT (graceful for all three programs), then SIGKILL after the grace period.
|
||||||
async fn kill_children(&self, children: &mut [Option<&mut Child>]) {
|
async fn kill_children(&self, children: &mut [Option<&mut Child>]) {
|
||||||
for child in children.iter_mut().flatten() {
|
for child in children.iter_mut().flatten() {
|
||||||
|
|||||||
@@ -347,13 +347,18 @@ async fn status(args: &[String]) -> i32 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn reconfigure(args: &[String]) -> i32 {
|
async fn reconfigure(args: &[String]) -> i32 {
|
||||||
let (rest, document) = match split_reconfigure(args) {
|
let (rest, extra) = match split_reconfigure(args) {
|
||||||
Ok(pair) => pair,
|
Ok(pair) => pair,
|
||||||
Err(message) => {
|
Err(message) => {
|
||||||
note(&message);
|
note(&message);
|
||||||
return 2;
|
return 2;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
// A restart of the engine process or a persisted change needs the supervisor and the files inside the distribution: run the Linux command there.
|
||||||
|
if extra.needs_restart() || extra.persist {
|
||||||
|
return forward("reconfigure", args).await;
|
||||||
|
}
|
||||||
|
let document = serde_json::Value::Object(extra.settings.clone()).to_string();
|
||||||
let session = match open_session(&rest, false) {
|
let session = match open_session(&rest, false) {
|
||||||
Ok(session) => session,
|
Ok(session) => session,
|
||||||
Err(message) => {
|
Err(message) => {
|
||||||
@@ -372,7 +377,7 @@ async fn reconfigure(args: &[String]) -> i32 {
|
|||||||
return 1;
|
return 1;
|
||||||
};
|
};
|
||||||
let json = session.forwarded.args.iter().any(|a| a == "--json");
|
let json = session.forwarded.args.iter().any(|a| a == "--json");
|
||||||
send_reconfigure(address, key.trim_end(), &document, json).await
|
send_reconfigure(address, key.trim_end(), &document, json, None).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn down(args: &[String]) -> i32 {
|
async fn down(args: &[String]) -> i32 {
|
||||||
|
|||||||
@@ -956,3 +956,251 @@ fn profiles_and_usage_commands() {
|
|||||||
assert_eq!(bad.status.code(), Some(2));
|
assert_eq!(bad.status.code(), Some(2));
|
||||||
assert!(String::from_utf8_lossy(&bad.stderr).contains("unknown option"));
|
assert!(String::from_utf8_lossy(&bad.stderr).contains("unknown option"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------------------------ leleka reconfigure
|
||||||
|
|
||||||
|
mod reconfigure_flow {
|
||||||
|
use super::*;
|
||||||
|
use leleka_deploy::reconfigure::{Outcome, Request, State, read_outcome, write_request};
|
||||||
|
use leleka_deploy::resources::Preset;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
const GIB: u64 = 1 << 30;
|
||||||
|
|
||||||
|
fn request(id: &str, budget_gib: Option<u64>, preset: Option<Preset>, settings: serde_json::Value, persist: bool) -> Request {
|
||||||
|
Request {
|
||||||
|
id: id.to_owned(),
|
||||||
|
gpu_budget_gib: budget_gib,
|
||||||
|
preset,
|
||||||
|
settings: settings.as_object().cloned().unwrap_or_default(),
|
||||||
|
persist,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ask(fixture: &Fixture, request: &Request, limit: Duration) -> Outcome {
|
||||||
|
write_request(&fixture.dirs.paths(), request).unwrap();
|
||||||
|
let started = Instant::now();
|
||||||
|
loop {
|
||||||
|
if let Some(outcome) = read_outcome(&fixture.dirs.paths(), &request.id)
|
||||||
|
&& outcome.state != State::Running
|
||||||
|
{
|
||||||
|
return outcome;
|
||||||
|
}
|
||||||
|
assert!(started.elapsed() < limit, "no answer to {}; logs:\n{}", request.id, fixture.logs());
|
||||||
|
std::thread::sleep(Duration::from_millis(200));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A supervisor with the fake runtime programs and an inherited sealed archive, ready.
|
||||||
|
struct Service {
|
||||||
|
fixture: Fixture,
|
||||||
|
supervisor: Child,
|
||||||
|
_memfd: fs::File,
|
||||||
|
first: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start(name: &str) -> Service {
|
||||||
|
let fixture = Fixture::new(name);
|
||||||
|
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
|
||||||
|
let mut profile = Profile::builtin("rtx3080-16g").unwrap();
|
||||||
|
profile.kar_source = KarSource::Memfd;
|
||||||
|
let config = fixture.write_state(profile);
|
||||||
|
let memfd = inheritable_sealed_memfd(&vec![7u8; 100_000]);
|
||||||
|
let supervisor = start_supervisor(&fixture, &config, Some(std::os::fd::AsRawFd::as_raw_fd(&memfd)));
|
||||||
|
let first = fixture.wait_for("ready", Duration::from_secs(120), |s| s["phase"] == "ready");
|
||||||
|
Service { fixture, supervisor, _memfd: memfd, first }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Service {
|
||||||
|
fn starts(&self) -> Vec<String> {
|
||||||
|
fs::read_to_string(self.fixture.fake_dir().join("calls.log"))
|
||||||
|
.unwrap()
|
||||||
|
.lines()
|
||||||
|
.filter(|line| line.starts_with("leleka-inference "))
|
||||||
|
.map(str::to_owned)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stop(mut self) {
|
||||||
|
signal(u64::from(self.supervisor.id()), "TERM");
|
||||||
|
assert!(wait_exit(&mut self.supervisor, Duration::from_secs(60)).is_some_and(|s| s.success()), "{}", self.fixture.logs());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_new_budget_restarts_only_the_engine_with_the_same_sealed_archive() {
|
||||||
|
let service = start("reconf-budget");
|
||||||
|
let fixture = &service.fixture;
|
||||||
|
let (engine, gateway, api) = (
|
||||||
|
service.first["engine_pid"].as_u64().unwrap(),
|
||||||
|
service.first["gateway_pid"].as_u64().unwrap(),
|
||||||
|
service.first["api_pid"].as_u64().unwrap(),
|
||||||
|
);
|
||||||
|
let before = fs::read_to_string(fixture.dirs.paths().run_config()).unwrap();
|
||||||
|
let outcome = ask(fixture, &request("budget", Some(2), None, json!({}), false), Duration::from_secs(120));
|
||||||
|
assert_eq!(outcome.state, State::Done, "{}\n{}", outcome.message, fixture.logs());
|
||||||
|
assert!(!outcome.persisted);
|
||||||
|
assert_eq!(outcome.effective.as_ref().unwrap()["gpu_budget_gib"], 2.0);
|
||||||
|
let after = fixture.wait_for("ready again", Duration::from_secs(60), |s| s["phase"] == "ready");
|
||||||
|
assert_ne!(after["engine_pid"].as_u64().unwrap(), engine, "the engine process is new");
|
||||||
|
assert!(!pid_alive(engine), "the old engine is gone");
|
||||||
|
assert_eq!(after["gateway_pid"].as_u64().unwrap(), gateway, "the gateway keeps its process");
|
||||||
|
assert_eq!(after["api_pid"].as_u64().unwrap(), api, "the API keeps its process");
|
||||||
|
assert_eq!(after["engine_restarts"], 0, "a planned restart is not a crash");
|
||||||
|
assert_eq!(fixture.http_status("/ready"), 200);
|
||||||
|
let starts = service.starts();
|
||||||
|
assert_eq!(starts.len(), 2, "{starts:?}");
|
||||||
|
assert!(starts[0].contains(&format!("--gpu-budget {}", 15 * GIB)), "{}", starts[0]);
|
||||||
|
assert!(starts[1].contains(&format!("--gpu-budget {}", 2 * GIB)), "{}", starts[1]);
|
||||||
|
// the sealed descriptor of the first engine was handed on, and it is the one already verified
|
||||||
|
assert!(starts[1].contains("--kar-archive-fd") && starts[1].contains("--kar-attested-by-stamp"), "{}", starts[1]);
|
||||||
|
let engine_log = fs::read_to_string(fixture.dirs.paths().logs().join("engine.log")).unwrap();
|
||||||
|
assert_eq!(engine_log.matches("kar fd ").count(), 2, "{engine_log}");
|
||||||
|
// not persisted: the file still has the old budget
|
||||||
|
assert_eq!(fs::read_to_string(fixture.dirs.paths().run_config()).unwrap(), before);
|
||||||
|
// asking for what is in force is answered at once, without another restart
|
||||||
|
let same = ask(fixture, &request("same", Some(2), None, json!({}), false), Duration::from_secs(20));
|
||||||
|
assert_eq!((same.state, same.message.contains("already")), (State::Done, true), "{}", same.message);
|
||||||
|
assert_eq!(service.starts().len(), 2);
|
||||||
|
service.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn persist_writes_the_files_and_a_crash_restart_keeps_the_new_numbers() {
|
||||||
|
let service = start("reconf-persist");
|
||||||
|
let fixture = &service.fixture;
|
||||||
|
let gateway = service.first["gateway_pid"].as_u64().unwrap();
|
||||||
|
let api = service.first["api_pid"].as_u64().unwrap();
|
||||||
|
let outcome = ask(
|
||||||
|
fixture,
|
||||||
|
&request("persist", Some(3), Some(Preset::Workstation), json!({"context_tokens": 4096, "cpu_workers": 3}), true),
|
||||||
|
Duration::from_secs(120),
|
||||||
|
);
|
||||||
|
assert_eq!(outcome.state, State::Done, "{}\n{}", outcome.message, fixture.logs());
|
||||||
|
assert!(outcome.persisted, "{}", outcome.message);
|
||||||
|
let config = leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap();
|
||||||
|
assert_eq!(config.profile.gpu_budget_bytes, 3 * GIB);
|
||||||
|
assert_eq!(config.profile.context_tokens, 4096);
|
||||||
|
assert_eq!(config.preset, Preset::Workstation);
|
||||||
|
assert!(config.base_profile.is_some(), "the unmodified profile is kept to undo the preset");
|
||||||
|
assert_eq!(config.engine_environment().get("LELEKA_ORIGINAL_SERVE_CPU_WORKERS").map(String::as_str), Some("3"));
|
||||||
|
// the API advertises the new context: its process was restarted on the same port, the gateway was not
|
||||||
|
let strata: serde_json::Value = serde_json::from_str(&fs::read_to_string(fixture.dirs.paths().strata_config()).unwrap()).unwrap();
|
||||||
|
assert_eq!(strata["runtime"]["max_context"], 4096);
|
||||||
|
let after = fixture.wait_for("ready again", Duration::from_secs(60), |s| s["phase"] == "ready");
|
||||||
|
assert_ne!(after["api_pid"].as_u64().unwrap(), api);
|
||||||
|
assert_eq!(after["gateway_pid"].as_u64().unwrap(), gateway);
|
||||||
|
assert_eq!(fixture.http_status("/ready"), 200);
|
||||||
|
// a crash of the new engine restarts it with the new numbers, not the old ones
|
||||||
|
signal(after["engine_pid"].as_u64().unwrap(), "KILL");
|
||||||
|
let again = fixture.wait_for("crash restart", Duration::from_secs(60), |s| s["phase"] == "ready" && s["engine_restarts"] == 1);
|
||||||
|
assert_ne!(again["engine_pid"], after["engine_pid"]);
|
||||||
|
let starts = service.starts();
|
||||||
|
let last = starts.last().unwrap();
|
||||||
|
assert!(last.contains(&format!("--gpu-budget {}", 3 * GIB)) && last.contains("--context-tokens 4096"), "{last}");
|
||||||
|
service.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn settings_alone_are_recorded_and_persisted_without_a_restart() {
|
||||||
|
let service = start("reconf-record");
|
||||||
|
let fixture = &service.fixture;
|
||||||
|
let engine = service.first["engine_pid"].as_u64().unwrap();
|
||||||
|
let outcome = ask(fixture, &request("record", None, None, json!({"prefix_cache_tail": "prompt", "spec_min_p": 0.25}), true), Duration::from_secs(30));
|
||||||
|
assert_eq!((outcome.state, outcome.persisted), (State::Done, true), "{}", outcome.message);
|
||||||
|
let config = leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap();
|
||||||
|
assert_eq!(config.profile.memory.prefix_cache_tail.as_deref(), Some("prompt"));
|
||||||
|
assert_eq!(config.profile.spec_min_p, Some(0.25));
|
||||||
|
assert_eq!(fixture.status().unwrap()["engine_pid"].as_u64().unwrap(), engine, "no restart");
|
||||||
|
assert_eq!(service.starts().len(), 1);
|
||||||
|
// not persisted: in force for this supervisor only
|
||||||
|
let quiet = ask(fixture, &request("quiet", None, None, json!({"context_tokens": 2048}), false), Duration::from_secs(30));
|
||||||
|
assert_eq!((quiet.state, quiet.persisted), (State::Done, false));
|
||||||
|
let file = leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap();
|
||||||
|
assert_ne!(file.profile.context_tokens, 2048);
|
||||||
|
// an invalid document is refused and changes nothing
|
||||||
|
let bad = ask(fixture, &request("bad", None, None, json!({"cpu_workers": 99}), true), Duration::from_secs(30));
|
||||||
|
assert_eq!(bad.state, State::Refused);
|
||||||
|
assert!(bad.message.contains("cpu_workers"), "{}", bad.message);
|
||||||
|
service.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn what_the_planner_refuses_changes_nothing_and_a_failing_new_engine_restores_the_old_one() {
|
||||||
|
let service = start("reconf-refuse");
|
||||||
|
let fixture = &service.fixture;
|
||||||
|
let engine = service.first["engine_pid"].as_u64().unwrap();
|
||||||
|
// refused before the engine is touched
|
||||||
|
let bad = ask(fixture, &request("bad", Some(2), None, json!({"cpu_workers": 99}), false), Duration::from_secs(30));
|
||||||
|
assert_eq!(bad.state, State::Refused);
|
||||||
|
assert!(bad.message.contains("nothing was changed"), "{}", bad.message);
|
||||||
|
let unknown = ask(fixture, &request("unknown", Some(2), None, json!({"nonsense": 1}), false), Duration::from_secs(30));
|
||||||
|
assert_eq!(unknown.state, State::Refused);
|
||||||
|
assert_eq!(fixture.status().unwrap()["engine_pid"].as_u64().unwrap(), engine, "the engine was not stopped");
|
||||||
|
assert!(pid_alive(engine));
|
||||||
|
// a budget the new engine cannot start with: the previous engine is started again with the previous numbers
|
||||||
|
fs::write(fixture.fake_dir().join("fail-engine-budget"), (4 * GIB).to_string()).unwrap();
|
||||||
|
let outcome = ask(fixture, &request("fails", Some(4), None, json!({}), true), Duration::from_secs(180));
|
||||||
|
assert_eq!(outcome.state, State::Refused, "{}\n{}", outcome.message, fixture.logs());
|
||||||
|
assert!(outcome.message.contains("previous settings are back"), "{}", outcome.message);
|
||||||
|
let restored = fixture.wait_for("restored", Duration::from_secs(60), |s| s["phase"] == "ready");
|
||||||
|
assert_ne!(restored["engine_pid"].as_u64().unwrap(), engine);
|
||||||
|
assert_eq!(fixture.http_status("/ready"), 200);
|
||||||
|
let starts = service.starts();
|
||||||
|
assert_eq!(starts.len(), 3, "{starts:?}");
|
||||||
|
assert!(starts[1].contains(&format!("--gpu-budget {}", 4 * GIB)) && starts[2].contains(&format!("--gpu-budget {}", 15 * GIB)), "{starts:?}");
|
||||||
|
// nothing was persisted from the failed attempt
|
||||||
|
let config = leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap();
|
||||||
|
assert_eq!(config.profile.gpu_budget_bytes, 15 * GIB);
|
||||||
|
service.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_cli_asks_the_supervisor_and_prints_the_answer() {
|
||||||
|
let service = start("reconf-cli");
|
||||||
|
let dirs = service.fixture.dirs.clone();
|
||||||
|
let run = |args: &[&str]| {
|
||||||
|
Process::new(LELEKA)
|
||||||
|
.arg("reconfigure")
|
||||||
|
.args(args)
|
||||||
|
.arg("--state-dir")
|
||||||
|
.arg(&dirs.state)
|
||||||
|
.arg("--assets")
|
||||||
|
.arg(&dirs.assets)
|
||||||
|
.arg("--prefix")
|
||||||
|
.arg(&dirs.prefix)
|
||||||
|
.output()
|
||||||
|
.unwrap()
|
||||||
|
};
|
||||||
|
let output = run(&["--gpu-budget-gib", "5", "--persist"]);
|
||||||
|
let text = String::from_utf8_lossy(&output.stdout).into_owned() + &String::from_utf8_lossy(&output.stderr);
|
||||||
|
assert!(output.status.success(), "{text}\n{}", service.fixture.logs());
|
||||||
|
assert!(text.contains("reconfigured") && text.contains("gpu_budget_gib"), "{text}");
|
||||||
|
let config = leleka_deploy::config::RunConfig::read(&dirs.paths().run_config()).unwrap();
|
||||||
|
assert_eq!(config.profile.gpu_budget_bytes, 5 * GIB);
|
||||||
|
// a refusal is a non-zero exit with the reason
|
||||||
|
let refused = run(&["--gpu-budget-gib", "6", "--cpu-workers", "70"]);
|
||||||
|
assert!(!refused.status.success());
|
||||||
|
let text = String::from_utf8_lossy(&refused.stderr);
|
||||||
|
assert!(text.contains("cpu_workers") || text.contains("1..=64") || text.contains("cpu-workers"), "{text}");
|
||||||
|
service.stop();
|
||||||
|
// without a supervisor the restart path says what to do instead of hanging
|
||||||
|
let stopped = run(&["--preset", "workstation"]);
|
||||||
|
assert!(!stopped.status.success());
|
||||||
|
assert!(String::from_utf8_lossy(&stopped.stderr).contains("no supervisor runs"), "{}", String::from_utf8_lossy(&stopped.stderr));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn when_not_even_the_previous_engine_comes_back_the_service_fails_with_an_answer() {
|
||||||
|
let mut service = start("reconf-lost");
|
||||||
|
let fixture = &service.fixture;
|
||||||
|
// from now on no engine starts at all: the new one fails, and so does the restored one
|
||||||
|
fs::write(fixture.fake_dir().join("fail-engine"), "").unwrap();
|
||||||
|
let outcome = ask(fixture, &request("lost", Some(4), None, json!({}), false), Duration::from_secs(120));
|
||||||
|
assert_eq!(outcome.state, State::Failed, "{}\n{}", outcome.message, fixture.logs());
|
||||||
|
assert!(outcome.message.contains("could not be restored"), "{}", outcome.message);
|
||||||
|
let status = wait_exit(&mut service.supervisor, Duration::from_secs(60)).expect("the supervisor must give up");
|
||||||
|
assert_eq!(status.code(), Some(1));
|
||||||
|
assert_eq!(fixture.status().unwrap()["phase"], "failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ pub mod lock;
|
|||||||
pub mod plan;
|
pub mod plan;
|
||||||
pub mod pressure;
|
pub mod pressure;
|
||||||
pub mod procfs;
|
pub mod procfs;
|
||||||
|
pub mod smi;
|
||||||
pub mod telemetry;
|
pub mod telemetry;
|
||||||
pub mod winproc;
|
pub mod winproc;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,227 @@
|
|||||||
|
//! GPU telemetry through `nvidia-smi`, for hosts where NVML (`libnvidia-ml`) cannot be loaded from inside the process:
|
||||||
|
//! WSL2 (the driver lives on the Windows side and `nvidia-smi` is a shim under `/usr/lib/wsl/lib`), containers that
|
||||||
|
//! mount the device nodes but not the management library, and drivers whose library the loader does not find.
|
||||||
|
//!
|
||||||
|
//! The probe runs `nvidia-smi --query-gpu=... --format=csv,noheader,nounits -i N` at most once per [`MIN_INTERVAL`]
|
||||||
|
//! (the sampler asks once a second, a process start is cheap but not free) and kills a run that takes longer than
|
||||||
|
//! [`RUN_LIMIT`]. The parser is a pure function over the CSV text and is unit-tested on real output samples, including
|
||||||
|
//! the `[N/A]` and `[Not Supported]` placeholders.
|
||||||
|
use crate::telemetry::GpuSample;
|
||||||
|
use std::{
|
||||||
|
io::Read,
|
||||||
|
process::{Command, Stdio},
|
||||||
|
sync::Mutex,
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The `--query-gpu` fields, in the order [`parse_csv`] reads them.
|
||||||
|
pub const QUERY: &str = "index,utilization.gpu,utilization.memory,memory.used,memory.total,power.draw,clocks.sm,temperature.gpu,name";
|
||||||
|
/// A new process at most this often; the sample in between is the previous one.
|
||||||
|
pub const MIN_INTERVAL: Duration = Duration::from_secs(2);
|
||||||
|
/// A `nvidia-smi` that has not answered by now is killed (a wedged driver can block it for a long time).
|
||||||
|
pub const RUN_LIMIT: Duration = Duration::from_secs(5);
|
||||||
|
|
||||||
|
/// Where `nvidia-smi` is looked for besides `PATH`: the WSL2 shim and the usual package locations.
|
||||||
|
const EXTRA_LOCATIONS: [&str; 3] = ["/usr/lib/wsl/lib/nvidia-smi", "/usr/bin/nvidia-smi", "/usr/local/nvidia/bin/nvidia-smi"];
|
||||||
|
|
||||||
|
/// A field that is a number, or `None` for the placeholders `[N/A]`, `[Not Supported]`, `N/A`, `[Unknown Error]` and anything else.
|
||||||
|
fn number(field: &str) -> Option<f64> {
|
||||||
|
let field = field.trim();
|
||||||
|
if field.is_empty() || field.starts_with('[') || field.eq_ignore_ascii_case("n/a") {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
field.parse::<f64>().ok().filter(|v| v.is_finite() && *v >= 0.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse the CSV `nvidia-smi` printed for [`QUERY`] (`--format=csv,noheader,nounits`) and return device `index`.
|
||||||
|
///
|
||||||
|
/// Memory is the one required figure: without used and total VRAM the row is useless and the answer is `None`.
|
||||||
|
/// Utilisation, power, clock and temperature are optional (a laptop GPU often reports `[N/A]` for power).
|
||||||
|
pub fn parse_csv(text: &str, index: u32) -> Option<GpuSample> {
|
||||||
|
for line in text.lines() {
|
||||||
|
let fields: Vec<&str> = line.split(',').map(str::trim).collect();
|
||||||
|
if fields.len() < 9 || fields[0].parse::<u32>().ok() != Some(index) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let used = number(fields[3])?;
|
||||||
|
let total = number(fields[4])?;
|
||||||
|
if total <= 0.0 || used > total * 1.01 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
// The name is the last field and may itself contain commas on some boards: rejoin whatever is left.
|
||||||
|
let name = fields[8..].join(", ");
|
||||||
|
return Some(GpuSample {
|
||||||
|
index,
|
||||||
|
util_pct: number(fields[1]).map_or(0, |v| v.round() as u32),
|
||||||
|
mem_util_pct: number(fields[2]).map_or(0, |v| v.round() as u32),
|
||||||
|
vram_used_mib: used.round() as u64,
|
||||||
|
vram_total_mib: total.round() as u64,
|
||||||
|
power_w: number(fields[5]),
|
||||||
|
sm_clock_mhz: number(fields[6]).map(|v| v.round() as u32),
|
||||||
|
temp_c: number(fields[7]).map(|v| v.round() as u32),
|
||||||
|
name: (!name.is_empty() && !name.starts_with('[')).then_some(name),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first existing `nvidia-smi` in `PATH`, then in [`EXTRA_LOCATIONS`].
|
||||||
|
pub fn find_binary() -> Option<std::path::PathBuf> {
|
||||||
|
let from_path = std::env::var_os("PATH").and_then(|paths| {
|
||||||
|
std::env::split_paths(&paths).map(|dir| dir.join("nvidia-smi")).find(|candidate| candidate.is_file())
|
||||||
|
});
|
||||||
|
from_path.or_else(|| EXTRA_LOCATIONS.iter().map(std::path::PathBuf::from).find(|candidate| candidate.is_file()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run `nvidia-smi` for [`QUERY`] on device `index` and parse the answer. `None`: the binary is missing, failed, timed out or
|
||||||
|
/// printed something unusable.
|
||||||
|
pub fn query(binary: &std::path::Path, index: u32) -> Option<GpuSample> {
|
||||||
|
let mut child = Command::new(binary)
|
||||||
|
.arg(format!("--query-gpu={QUERY}"))
|
||||||
|
.arg("--format=csv,noheader,nounits")
|
||||||
|
.arg("-i")
|
||||||
|
.arg(index.to_string())
|
||||||
|
.stdin(Stdio::null())
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::null())
|
||||||
|
.spawn()
|
||||||
|
.ok()?;
|
||||||
|
let mut stdout = child.stdout.take()?;
|
||||||
|
let started = Instant::now();
|
||||||
|
loop {
|
||||||
|
match child.try_wait() {
|
||||||
|
Ok(Some(status)) => {
|
||||||
|
if !status.success() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut text = String::new();
|
||||||
|
stdout.by_ref().take(64 * 1024).read_to_string(&mut text).ok()?;
|
||||||
|
return parse_csv(&text, index);
|
||||||
|
}
|
||||||
|
Ok(None) if started.elapsed() < RUN_LIMIT => std::thread::sleep(Duration::from_millis(10)),
|
||||||
|
_ => {
|
||||||
|
let _ = child.kill();
|
||||||
|
let _ = child.wait();
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A rate-limited probe for the telemetry sampler: `None` when no `nvidia-smi` exists on this host.
|
||||||
|
pub fn probe(index: u32) -> Option<Box<dyn Fn() -> Option<GpuSample> + Send + Sync>> {
|
||||||
|
Some(probe_with(find_binary()?, index))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`probe`] over a given binary.
|
||||||
|
pub fn probe_with(binary: std::path::PathBuf, index: u32) -> Box<dyn Fn() -> Option<GpuSample> + Send + Sync> {
|
||||||
|
let last: Mutex<Option<(Instant, Option<GpuSample>)>> = Mutex::new(None);
|
||||||
|
Box::new(move || {
|
||||||
|
let mut last = last.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||||
|
if let Some((at, sample)) = last.as_ref()
|
||||||
|
&& at.elapsed() < MIN_INTERVAL
|
||||||
|
{
|
||||||
|
return sample.clone();
|
||||||
|
}
|
||||||
|
let sample = query(&binary, index);
|
||||||
|
*last = Some((Instant::now(), sample.clone()));
|
||||||
|
sample
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_desktop_board_parses_with_all_fields() {
|
||||||
|
let text = "0, 87, 41, 30112, 32607, 478.52, 2842, 63, NVIDIA GeForce RTX 5090\n";
|
||||||
|
let sample = parse_csv(text, 0).unwrap();
|
||||||
|
assert_eq!((sample.util_pct, sample.mem_util_pct), (87, 41));
|
||||||
|
assert_eq!((sample.vram_used_mib, sample.vram_total_mib), (30112, 32607));
|
||||||
|
assert_eq!(sample.power_w, Some(478.52));
|
||||||
|
assert_eq!((sample.sm_clock_mhz, sample.temp_c), (Some(2842), Some(63)));
|
||||||
|
assert_eq!(sample.name.as_deref(), Some("NVIDIA GeForce RTX 5090"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn output_captured_from_real_drivers_parses() {
|
||||||
|
// `nvidia-smi --query-gpu=<QUERY> --format=csv,noheader,nounits` on the RTX 5090 server (driver 595.99.02, Linux)
|
||||||
|
let server = parse_csv("0, 94, 21, 31606, 32607, 271.40, 2887, 58, NVIDIA GeForce RTX 5090\n", 0).unwrap();
|
||||||
|
assert_eq!((server.util_pct, server.vram_used_mib, server.vram_total_mib), (94, 31606, 32607));
|
||||||
|
assert_eq!((server.power_w, server.sm_clock_mhz, server.temp_c), (Some(271.4), Some(2887), Some(58)));
|
||||||
|
// and on the RTX 3080 Laptop through the Windows driver (the path WSL2 takes)
|
||||||
|
let laptop = parse_csv("0, 0, 100, 0, 16384, 32.83, 1545, 59, NVIDIA GeForce RTX 3080 Laptop GPU\n", 0).unwrap();
|
||||||
|
assert_eq!((laptop.vram_used_mib, laptop.vram_total_mib, laptop.temp_c), (0, 16384, Some(59)));
|
||||||
|
assert_eq!(laptop.name.as_deref(), Some("NVIDIA GeForce RTX 3080 Laptop GPU"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn placeholders_become_missing_values_not_zeros() {
|
||||||
|
// a laptop board under WSL2: power and clock are not reported
|
||||||
|
let text = "0, 3, 1, 1420, 16384, [N/A], [Not Supported], 47, NVIDIA GeForce RTX 3080 Laptop GPU\n";
|
||||||
|
let sample = parse_csv(text, 0).unwrap();
|
||||||
|
assert_eq!(sample.power_w, None);
|
||||||
|
assert_eq!(sample.sm_clock_mhz, None);
|
||||||
|
assert_eq!(sample.temp_c, Some(47));
|
||||||
|
assert_eq!(sample.vram_total_mib, 16384);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_requested_device_is_picked_from_several_rows() {
|
||||||
|
let text = "0, 10, 5, 1000, 24576, 100.0, 1500, 40, NVIDIA GeForce RTX 3090\n1, 99, 80, 20000, 32607, 450.1, 2900, 71, NVIDIA GeForce RTX 5090\n";
|
||||||
|
assert_eq!(parse_csv(text, 1).unwrap().vram_used_mib, 20000);
|
||||||
|
assert_eq!(parse_csv(text, 0).unwrap().name.as_deref(), Some("NVIDIA GeForce RTX 3090"));
|
||||||
|
assert_eq!(parse_csv(text, 2), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_row_without_memory_or_a_garbled_row_is_refused() {
|
||||||
|
assert_eq!(parse_csv("0, 1, 1, [N/A], [N/A], 1, 1, 1, X\n", 0), None);
|
||||||
|
assert_eq!(parse_csv("0, 1, 1, 100\n", 0), None);
|
||||||
|
assert_eq!(parse_csv("", 0), None);
|
||||||
|
assert_eq!(parse_csv("No devices were found\n", 0), None);
|
||||||
|
// used larger than total is a corrupt reading, not a number to publish
|
||||||
|
assert_eq!(parse_csv("0, 1, 1, 40000, 32607, 1, 1, 1, X\n", 0), None);
|
||||||
|
// a failure message on the same stream
|
||||||
|
assert_eq!(parse_csv("Failed to initialize NVML: Driver/library version mismatch\n", 0), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_name_with_a_comma_is_kept_whole_and_a_placeholder_name_is_dropped() {
|
||||||
|
let text = "0, 1, 1, 100, 200, 5, 300, 30, Odd Board, Rev B\n";
|
||||||
|
assert_eq!(parse_csv(text, 0).unwrap().name.as_deref(), Some("Odd Board, Rev B"));
|
||||||
|
let text = "0, 1, 1, 100, 200, 5, 300, 30, [N/A]\n";
|
||||||
|
assert_eq!(parse_csv(text, 0).unwrap().name, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn a_stand_in_binary_is_run_parsed_and_rate_limited() {
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
let dir = std::env::temp_dir().join(format!("leleka-smi-test-{}", std::process::id()));
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
let counter = dir.join("calls");
|
||||||
|
let script = dir.join("nvidia-smi");
|
||||||
|
// appends to a file on every call so the test can count the processes started
|
||||||
|
std::fs::write(
|
||||||
|
&script,
|
||||||
|
format!("#!/bin/sh\necho x >> {}\necho '0, 55, 20, 2048, 8192, 75.5, 1800, 50, Test GPU'\n", counter.display()),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||||
|
let sample = query(&script, 0).expect("the stand-in answers");
|
||||||
|
assert_eq!((sample.util_pct, sample.vram_used_mib), (55, 2048));
|
||||||
|
// the sampler's probe starts one process for two asks within the interval
|
||||||
|
let probe = probe_with(script.clone(), 0);
|
||||||
|
assert!(probe().is_some() && probe().is_some());
|
||||||
|
let calls = std::fs::read_to_string(&counter).unwrap().lines().count();
|
||||||
|
assert_eq!(calls, 2, "one direct query plus one probe run");
|
||||||
|
// a failing binary yields nothing
|
||||||
|
let failing = dir.join("failing");
|
||||||
|
std::fs::write(&failing, "#!/bin/sh\nexit 9\n").unwrap();
|
||||||
|
std::fs::set_permissions(&failing, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||||
|
assert_eq!(query(&failing, 0), None);
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,7 +23,7 @@ const USER_HZ: f64 = 100.0;
|
|||||||
/// Weight of the newest request in the running average of the throughput.
|
/// Weight of the newest request in the running average of the throughput.
|
||||||
const EMA_ALPHA: f64 = 0.3;
|
const EMA_ALPHA: f64 = 0.3;
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
|
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
|
||||||
pub struct GpuSample {
|
pub struct GpuSample {
|
||||||
pub index: u32,
|
pub index: u32,
|
||||||
/// Percent of the last sample period in which any kernel ran (NVML `utilization.gpu`).
|
/// Percent of the last sample period in which any kernel ran (NVML `utilization.gpu`).
|
||||||
@@ -34,6 +34,10 @@ pub struct GpuSample {
|
|||||||
pub vram_total_mib: u64,
|
pub vram_total_mib: u64,
|
||||||
pub power_w: Option<f64>,
|
pub power_w: Option<f64>,
|
||||||
pub sm_clock_mhz: Option<u32>,
|
pub sm_clock_mhz: Option<u32>,
|
||||||
|
/// Core temperature in degrees Celsius.
|
||||||
|
pub temp_c: Option<u32>,
|
||||||
|
/// Board name as the driver reports it.
|
||||||
|
pub name: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
type GpuProbe = Box<dyn Fn() -> Option<GpuSample> + Send + Sync>;
|
type GpuProbe = Box<dyn Fn() -> Option<GpuSample> + Send + Sync>;
|
||||||
@@ -53,6 +57,8 @@ struct State {
|
|||||||
started: Option<Instant>,
|
started: Option<Instant>,
|
||||||
first_token: Option<Instant>,
|
first_token: Option<Instant>,
|
||||||
produced_now: u64,
|
produced_now: u64,
|
||||||
|
/// Prompt tokens of the request in flight.
|
||||||
|
prompt_now: u64,
|
||||||
/// Lifetime counters.
|
/// Lifetime counters.
|
||||||
requests: u64,
|
requests: u64,
|
||||||
cache_hit_requests: u64,
|
cache_hit_requests: u64,
|
||||||
@@ -108,6 +114,7 @@ pub fn request_started(prompt_tokens: u64) {
|
|||||||
s.started = Some(Instant::now());
|
s.started = Some(Instant::now());
|
||||||
s.first_token = None;
|
s.first_token = None;
|
||||||
s.produced_now = 0;
|
s.produced_now = 0;
|
||||||
|
s.prompt_now = prompt_tokens;
|
||||||
s.context_live = prompt_tokens;
|
s.context_live = prompt_tokens;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -274,12 +281,21 @@ struct Context {
|
|||||||
used_pct: Option<f64>,
|
used_pct: Option<f64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The request in flight, while there is one.
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
struct LiveRequest {
|
||||||
|
prompt_tokens: u64,
|
||||||
|
generated_tokens: u64,
|
||||||
|
elapsed_s: f64,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
#[derive(Debug, Serialize)]
|
||||||
struct Document {
|
struct Document {
|
||||||
version: u32,
|
version: u32,
|
||||||
ts_ms: u64,
|
ts_ms: u64,
|
||||||
uptime_s: u64,
|
uptime_s: u64,
|
||||||
phase: Phase,
|
phase: Phase,
|
||||||
|
request: Option<LiveRequest>,
|
||||||
gpu: Option<GpuSample>,
|
gpu: Option<GpuSample>,
|
||||||
ram: Option<Ram>,
|
ram: Option<Ram>,
|
||||||
cpu: Option<Cpu>,
|
cpu: Option<Cpu>,
|
||||||
@@ -329,7 +345,12 @@ fn render(state: &State, measured: &Measured) -> String {
|
|||||||
ts_ms: measured.now_ms,
|
ts_ms: measured.now_ms,
|
||||||
uptime_s: measured.uptime_s,
|
uptime_s: measured.uptime_s,
|
||||||
phase: state.phase,
|
phase: state.phase,
|
||||||
gpu: measured.gpu,
|
request: state.started.filter(|_| state.phase != Phase::Idle).map(|started| LiveRequest {
|
||||||
|
prompt_tokens: state.prompt_now,
|
||||||
|
generated_tokens: state.produced_now,
|
||||||
|
elapsed_s: (started.elapsed().as_secs_f64() * 10.0).round() / 10.0,
|
||||||
|
}),
|
||||||
|
gpu: measured.gpu.clone(),
|
||||||
ram,
|
ram,
|
||||||
cpu: measured.cpu.map(|(process, system)| Cpu {
|
cpu: measured.cpu.map(|(process, system)| Cpu {
|
||||||
cores: measured.cores,
|
cores: measured.cores,
|
||||||
@@ -439,7 +460,7 @@ mod tests {
|
|||||||
Measured {
|
Measured {
|
||||||
now_ms: 1,
|
now_ms: 1,
|
||||||
uptime_s: 5,
|
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) }),
|
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), temp_c: Some(61), name: Some("NVIDIA GeForce RTX 5090".into()) }),
|
||||||
meminfo: procfs::parse_meminfo("MemTotal: 125829120 kB\nMemAvailable: 70000000 kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n"),
|
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"),
|
status: procfs::parse_status("VmRSS:\t55000000 kB\nVmPin:\t3000000 kB\n"),
|
||||||
cores: 32,
|
cores: 32,
|
||||||
@@ -488,10 +509,30 @@ mod tests {
|
|||||||
assert_eq!(doc["context"]["live_tokens"], 101_200);
|
assert_eq!(doc["context"]["live_tokens"], 101_200);
|
||||||
assert_eq!(doc["context"]["max_tokens"], 262_144);
|
assert_eq!(doc["context"]["max_tokens"], 262_144);
|
||||||
assert_eq!(doc["gpu"]["util_pct"], 91);
|
assert_eq!(doc["gpu"]["util_pct"], 91);
|
||||||
|
assert_eq!(doc["gpu"]["temp_c"], 61);
|
||||||
|
assert_eq!(doc["gpu"]["name"], "NVIDIA GeForce RTX 5090");
|
||||||
|
assert!(doc["request"].is_null(), "no request in flight after the last one finished");
|
||||||
assert_eq!(doc["ram"]["total_mib"], 122_880);
|
assert_eq!(doc["ram"]["total_mib"], 122_880);
|
||||||
assert_eq!(doc["cpu"]["process_busy_cores"], 7.4);
|
assert_eq!(doc["cpu"]["process_busy_cores"], 7.4);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_request_in_flight_is_reported_with_its_progress() {
|
||||||
|
let _serial = lock(&SERIAL);
|
||||||
|
*lock(&STATE) = None;
|
||||||
|
request_started(5_000);
|
||||||
|
tokens_delivered(3);
|
||||||
|
tokens_delivered(4);
|
||||||
|
let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap();
|
||||||
|
assert_eq!(doc["phase"], "decode");
|
||||||
|
assert_eq!(doc["request"]["prompt_tokens"], 5_000);
|
||||||
|
assert_eq!(doc["request"]["generated_tokens"], 7);
|
||||||
|
assert!(doc["request"]["elapsed_s"].as_f64().unwrap() >= 0.0);
|
||||||
|
request_aborted();
|
||||||
|
let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap();
|
||||||
|
assert!(doc["request"].is_null());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn an_empty_state_renders_nulls_not_zeros_for_unmeasured_rates() {
|
fn an_empty_state_renders_nulls_not_zeros_for_unmeasured_rates() {
|
||||||
let _serial = lock(&SERIAL);
|
let _serial = lock(&SERIAL);
|
||||||
|
|||||||
@@ -297,6 +297,29 @@ mod runner {
|
|||||||
Tokenizer, Usage, Utf8Pending, BACKPRESSURE_TIMEOUT, GENERATION_TIMEOUT, QUEUE,
|
Tokenizer, Usage, Utf8Pending, BACKPRESSURE_TIMEOUT, GENERATION_TIMEOUT, QUEUE,
|
||||||
};
|
};
|
||||||
use super::{context_fits, OriginalServeOptions, PrefixTail, PREFIX_SUMMARY};
|
use super::{context_fits, OriginalServeOptions, PrefixTail, PREFIX_SUMMARY};
|
||||||
|
|
||||||
|
type GpuProbe = Box<dyn Fn() -> Option<leleka_memory::telemetry::GpuSample> + Send + Sync>;
|
||||||
|
|
||||||
|
/// The telemetry sampler's view of the GPU: NVML when `libnvidia-ml` loads, otherwise polling `nvidia-smi` (WSL2, containers
|
||||||
|
/// without the management library), otherwise nothing (the document then has no `gpu` block).
|
||||||
|
fn gpu_probe(ordinal: u32) -> Option<GpuProbe> {
|
||||||
|
match leleka_cuda_driver::nvml::Nvml::open(ordinal) {
|
||||||
|
Some(nvml) => Some(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,
|
||||||
|
temp_c: s.temp_c,
|
||||||
|
name: s.name,
|
||||||
|
})
|
||||||
|
})),
|
||||||
|
None => leleka_memory::smi::probe(ordinal),
|
||||||
|
}
|
||||||
|
}
|
||||||
use crate::qwen_forward::{
|
use crate::qwen_forward::{
|
||||||
contract::Error as ForwardError,
|
contract::Error as ForwardError,
|
||||||
original_serve_engine::ServeStop,
|
original_serve_engine::ServeStop,
|
||||||
@@ -646,22 +669,7 @@ mod runner {
|
|||||||
leleka_memory::telemetry::set_settings(crate::serve_tuning::describe(&options, context_tokens, workers, None));
|
leleka_memory::telemetry::set_settings(crate::serve_tuning::describe(&options, context_tokens, workers, None));
|
||||||
// operator telemetry: GPU/RAM/CPU once a second, throughput and cache hits recorded per request
|
// 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));
|
leleka_memory::telemetry::set_context_max(u64::from(context_tokens));
|
||||||
let _telemetry = leleka_memory::telemetry::start(
|
let _telemetry = leleka_memory::telemetry::start(gpu_probe(crate::backend::GPU_ORDINAL.load(Ordering::Relaxed)), Duration::from_secs(1));
|
||||||
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);
|
let mut stack = Some(stack);
|
||||||
if shared.shutdown.load(Ordering::Acquire) {
|
if shared.shutdown.load(Ordering::Acquire) {
|
||||||
if let Some(stack) = stack.take() {
|
if let Some(stack) = stack.take() {
|
||||||
|
|||||||
@@ -1235,6 +1235,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
|||||||
oracle += best.iter().take(slots[layer]).map(|&u| f64::from(u)).sum::<f64>();
|
oracle += best.iter().take(slots[layer]).map(|&u| f64::from(u)).sum::<f64>();
|
||||||
by_initial += (0..512).filter(|&e| initial[range.start + e]).map(|e| f64::from(usage[range.start + e])).sum::<f64>();
|
by_initial += (0..512).filter(|&e| initial[range.start + e]).map(|e| f64::from(usage[range.start + e])).sum::<f64>();
|
||||||
}
|
}
|
||||||
|
// Opt-in: `seed_counts` is only recorded under LELEKA_SEED_TRACE, so this returns early (and prints nothing) otherwise.
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"DBG seed-coverage: decode entries {total:.0}; covered by the starting set {:.1}%, the prompt's top experts {:.1}%, the decode's own top experts {:.1}% (oracle)",
|
"DBG seed-coverage: decode entries {total:.0}; covered by the starting set {:.1}%, the prompt's top experts {:.1}%, the decode's own top experts {:.1}% (oracle)",
|
||||||
100.0 * by_initial / total,
|
100.0 * by_initial / total,
|
||||||
|
|||||||
@@ -0,0 +1,142 @@
|
|||||||
|
//! Production serving prints nothing of the bring-up diagnostics.
|
||||||
|
//!
|
||||||
|
//! Every `eprintln!("DBG ...")` / `eprintln!("PROBE ...")` in the production code of `leleka-runtime` and `leleka-cuda-driver` must be
|
||||||
|
//! silent unless somebody asked for it: through `bringup_trace!` (`LELEKA_BRINGUP_TRACE`), or under a dedicated opt-in switch of its
|
||||||
|
//! own (`LELEKA_SERVE_PROFILE`, `LELEKA_SPEC_TRACE`, `LELEKA_SEED_TRACE`, `LELEKA_TRACE_PLE`, ...), which the print has to sit
|
||||||
|
//! behind within a few lines. Test-only modules (the `#[ignore]`d GPU smokes, whose output is their evidence) are exempt.
|
||||||
|
//!
|
||||||
|
//! This reads the sources; it does not execute anything and needs no GPU. It exists so that a new unguarded `DBG` line cannot slip
|
||||||
|
//! into a release unnoticed (the review that gated the existing ones is in `docs/port-remaining.md`).
|
||||||
|
use std::{
|
||||||
|
fs,
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// A print counts as guarded when one of these appears on its line or within [`LOOKBACK`] lines above it.
|
||||||
|
const GUARDS: &[&str] = &[
|
||||||
|
"bringup_trace",
|
||||||
|
"enabled()",
|
||||||
|
"stats_enabled",
|
||||||
|
"trace_enabled",
|
||||||
|
"trace_ple()",
|
||||||
|
"trace_residual()",
|
||||||
|
"trace_logprobs()",
|
||||||
|
"LELEKA_SEED_TRACE",
|
||||||
|
"seed_coverage_trace",
|
||||||
|
"window_clock",
|
||||||
|
"gpu_profile.is_empty()",
|
||||||
|
];
|
||||||
|
const LOOKBACK: usize = 20;
|
||||||
|
|
||||||
|
fn rust_files(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||||
|
let Ok(entries) = fs::read_dir(dir) else { return };
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let path = entry.path();
|
||||||
|
if path.is_dir() {
|
||||||
|
rust_files(&path, out);
|
||||||
|
} else if path.extension().is_some_and(|e| e == "rs") {
|
||||||
|
out.push(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Files that only exist in test builds: declared as `mod name;` right after a `#[cfg(test)]`-like attribute, or marked `#![cfg(test)]`.
|
||||||
|
fn test_only(files: &[PathBuf]) -> Vec<PathBuf> {
|
||||||
|
let mut gated = Vec::new();
|
||||||
|
for file in files {
|
||||||
|
let text = fs::read_to_string(file).unwrap_or_default();
|
||||||
|
if text.lines().take(40).any(|l| l.trim_start().starts_with("#![cfg(test)]") || l.trim_start().starts_with("#![cfg(all(test")) {
|
||||||
|
gated.push(file.clone());
|
||||||
|
}
|
||||||
|
let lines: Vec<&str> = text.lines().collect();
|
||||||
|
for (index, line) in lines.iter().enumerate() {
|
||||||
|
let trimmed = line.trim_start();
|
||||||
|
let declared = trimmed.strip_prefix("pub(crate) mod ").or_else(|| trimmed.strip_prefix("pub(super) mod ")).or_else(|| trimmed.strip_prefix("pub mod ")).or_else(|| trimmed.strip_prefix("mod "));
|
||||||
|
let Some(name) = declared.and_then(|rest| rest.strip_suffix(';')) else { continue };
|
||||||
|
let above = lines[index.saturating_sub(3)..index].join(" ");
|
||||||
|
if above.contains("cfg(test)") || above.contains("cfg(all(test") || above.contains("cfg(any(test") {
|
||||||
|
let dir = file.parent().unwrap();
|
||||||
|
gated.push(dir.join(format!("{name}.rs")));
|
||||||
|
gated.push(dir.join(name).join("mod.rs"));
|
||||||
|
// `#[path = "other_name.rs"] mod name;`
|
||||||
|
if let Some(path) = above.split("#[path = \"").nth(1).and_then(|rest| rest.split('"').next()) {
|
||||||
|
gated.push(dir.join(path));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
gated
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first string literal of the macro call starting at `at` in `lines`, or `None`.
|
||||||
|
fn first_literal(lines: &[&str], at: usize, column: usize) -> Option<String> {
|
||||||
|
let mut text = String::from(&lines[at][column..]);
|
||||||
|
for line in lines.iter().skip(at + 1).take(2) {
|
||||||
|
text.push(' ');
|
||||||
|
text.push_str(line);
|
||||||
|
}
|
||||||
|
let start = text.find('"')? + 1;
|
||||||
|
Some(text[start..].chars().take(12).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn findings(root: &Path) -> Vec<String> {
|
||||||
|
let mut files = Vec::new();
|
||||||
|
for crate_dir in ["crates/leleka-runtime/src", "crates/cuda-driver/src"] {
|
||||||
|
rust_files(&root.join(crate_dir), &mut files);
|
||||||
|
}
|
||||||
|
let exempt = test_only(&files);
|
||||||
|
let mut bad = Vec::new();
|
||||||
|
for file in &files {
|
||||||
|
if exempt.contains(file) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let text = fs::read_to_string(file).unwrap_or_default();
|
||||||
|
let lines: Vec<&str> = text.lines().collect();
|
||||||
|
// from the first `#[cfg(test)] mod tests` on, the rest of the file is test code
|
||||||
|
let end = lines
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.position(|(i, l)| l.trim() == "#[cfg(test)]" && lines.get(i + 1).is_some_and(|n| n.trim_start().starts_with("mod ")))
|
||||||
|
.unwrap_or(lines.len());
|
||||||
|
for (index, line) in lines.iter().enumerate().take(end) {
|
||||||
|
let Some(column) = ["eprintln!(", "eprint!(", "println!("].iter().filter_map(|m| line.find(m).map(|c| c + m.len())).min() else { continue };
|
||||||
|
let Some(literal) = first_literal(&lines, index, column) else { continue };
|
||||||
|
if !(literal.starts_with("DBG") || literal.starts_with("PROBE")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let from = index.saturating_sub(LOOKBACK);
|
||||||
|
let context = lines[from..=index].join("\n");
|
||||||
|
if !GUARDS.iter().any(|guard| context.contains(guard)) {
|
||||||
|
bad.push(format!("{}:{}: {}", file.strip_prefix(root).unwrap_or(file).display(), index + 1, line.trim()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bad
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_production_dbg_or_probe_print_is_behind_a_switch() {
|
||||||
|
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||||
|
let bad = findings(&root);
|
||||||
|
assert!(
|
||||||
|
bad.is_empty(),
|
||||||
|
"these DBG/PROBE prints fire without LELEKA_BRINGUP_TRACE or a switch of their own; route them through bringup_trace! (or add the switch to GUARDS if it is a real opt-in):\n{}",
|
||||||
|
bad.join("\n")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_scan_sees_the_prints_it_is_meant_to_guard() {
|
||||||
|
// A scan that finds nothing would pass forever: make sure it reads the files and recognises both shapes.
|
||||||
|
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||||
|
let mut files = Vec::new();
|
||||||
|
rust_files(&root.join("crates/leleka-runtime/src"), &mut files);
|
||||||
|
let total: usize = files
|
||||||
|
.iter()
|
||||||
|
.map(|f| fs::read_to_string(f).unwrap_or_default().matches("DBG").count())
|
||||||
|
.sum();
|
||||||
|
assert!(total > 20, "only {total} DBG mentions: is the source path wrong?");
|
||||||
|
let lines = [" eprintln!(\"DBG x {}\", 1);", " eprintln!(", " \"PROBE y\","];
|
||||||
|
assert_eq!(first_literal(&lines, 0, 14).as_deref(), Some("DBG x {}\", 1"));
|
||||||
|
assert_eq!(first_literal(&lines, 1, 14).as_deref(), Some("PROBE y\","));
|
||||||
|
}
|
||||||
@@ -301,6 +301,45 @@ Existing `T`/`PP`/`DONE` events are forwarded unchanged. These metrics support
|
|||||||
observation; paired workload and quality measurements remain necessary for any
|
observation; paired workload and quality measurements remain necessary for any
|
||||||
performance claim.
|
performance claim.
|
||||||
|
|
||||||
|
### Monitor members, Prometheus text and `GET /api/requests`
|
||||||
|
|
||||||
|
`/metrics` also carries the members of the Python service's Monitor (`engine/strata/serve/server.py` `Service.metrics`), added beside the
|
||||||
|
native ones above, which are unchanged (`schema_version` stays 1):
|
||||||
|
|
||||||
|
| member | content |
|
||||||
|
| --- | --- |
|
||||||
|
| `engine` | `model`, `max_context`, `images`, `version`, `api_monitor`, and `settings` (the settings the engine reports: context, prefill chunk, caches, workers) |
|
||||||
|
| `live` | `state` (`idle`, `reading`, `generating`, or the worker state while it is not ready), `active`, `queued` (generations waiting for the engine), `phase`, `prompt_tokens`, `generated`, `elapsed_s`, `tok_s`, `tok_s_mean`, `prefill_tok_s_mean`; `prompt_read`, `prompt_total`, `max_tokens` and `tok_s_window_s` are `null` (the runtime does not report them) |
|
||||||
|
| `requests`, `requests_kept` | the last 12 settled generations, newest first (`?requests=all`: every one kept, up to 500): `time`, `duration_s`, `finish` (`stop`, `length`, `cancel`, `disconnect`, `error`), `prompt_tokens`, `reused`, `output_tokens`, `engine_generated`, `prompt_ms`, `decode_ms`, `decode_tok_s`, `hit_rate`, `drafts_offered`, `drafts_accepted`; `null` where the engine did not say or the attempt had no DONE. Counts and timings only, no payload |
|
||||||
|
| `totals` | since the process started: `requests`, `prompt_tokens`, `reused`, `output_tokens`, `prompt_ms`, `decode_ms`, `drafts_offered`, `drafts_accepted` |
|
||||||
|
| `hardware`, `hardware_static`, `history` | the engine's telemetry document (GPU, host RAM, CPU, throughput) in the Python names and units (bytes, percent, watts, degrees Celsius): `gpu_util`, `gpu_mem_used`, `gpu_mem_total`, `gpu_temp`, `gpu_power`, `cpu`, `ram_used`, `ram_total`, `tok_s`, `prefill_tok_s_mean`, ...; `gpu_name`, `gpu_count`, `threads`; and `history`, the last 60 samples of the headline series (one per engine health tick, 2 s by default; a burst of ticks within a second counts once). A figure the engine does not report is absent, never zero; the three are empty while the engine publishes no telemetry (it publishes once the model is loaded) |
|
||||||
|
| `telemetry`, `time` | the raw telemetry document (the same as `/v1/status` `machine`, without its age) and the wall-clock second |
|
||||||
|
|
||||||
|
The GPU block comes from NVML; where `libnvidia-ml` cannot be loaded (WSL2, containers without the management library) the engine polls
|
||||||
|
`nvidia-smi --query-gpu=...` instead (at most every 2 s, `leleka-memory/src/smi.rs`), so the block is present on those hosts too.
|
||||||
|
|
||||||
|
**Prometheus.** `GET /metrics?format=prometheus`, or any request whose `Accept` asks for `text/plain` or OpenMetrics before JSON (what a
|
||||||
|
Prometheus scraper sends), returns the text exposition (`text/plain; version=0.0.4`) of the same document under the same bearer-key rule:
|
||||||
|
counters `leleka_generations_{started,completed,cancelled,failed}_total`, `leleka_prompt_tokens_total`,
|
||||||
|
`leleka_prompt_tokens_reused_total`, `leleka_generated_tokens_total`, `leleka_{prefill,decode}_seconds_total`, draft counters,
|
||||||
|
`leleka_memory_gate_rejections_total`; gauges `leleka_up`, `leleka_generation_active`, `leleka_requests_queued`, `leleka_queue_used`,
|
||||||
|
`leleka_context_{max,live}_tokens`, `leleka_context_used_percent`, `leleka_gpu_{utilization_percent,memory_used_bytes,memory_total_bytes,temperature_celsius,power_watts,sm_clock_megahertz}`,
|
||||||
|
`leleka_host_{memory_used_bytes,memory_total_bytes,swap_used_bytes,cpu_busy_percent}`, `leleka_engine_{resident_bytes,pinned_bytes,cpu_busy_cores}`,
|
||||||
|
`leleka_decode_tokens_per_second{window=live|last|average|lifetime}`, `leleka_prefill_tokens_per_second{window=last|average|lifetime}`,
|
||||||
|
`leleka_prefix_cache_*`, `leleka_engine_phase{phase=...}` and `leleka_info{model=...}`. Unmeasured figures are not exposed (no zeros for "unknown").
|
||||||
|
The table in `control-plane/src/prometheus.rs` is the contract. JSON stays the default for every other client.
|
||||||
|
|
||||||
|
**`GET /api/requests`** is the Python service's opt-in request monitor. It is off unless the config sets `"api_monitor": true` (then
|
||||||
|
the route answers 404, as the Original's does): it keeps prompts and answers in memory. It records `/v1/chat/completions`,
|
||||||
|
`/v1/messages` and `/v1/responses` (the Original: the first two), the last 100 of them, bounded to 256 KiB per captured text
|
||||||
|
(`input_truncated`, `output_truncated`, `reasoning_truncated`, `response_truncated`). Without `id` it lists them newest first without
|
||||||
|
payload (`{"requests": [...], "retention": 100, "persistent": false, "loaded": ..., "auto_load": ...}`); `?id=ID` returns one whole
|
||||||
|
record (`input` as pretty JSON, `output`, `reasoning`, `response` of a buffered reply, `usage`, `error`, `http_status`,
|
||||||
|
`first_token_s`, `wallclock_s`), or 404 `request no longer retained` once evicted. States: `queued` until the first generated text,
|
||||||
|
`generating`, then `completed`, `error` (an error body or HTTP status >= 400) or `disconnected` (the consumer left before the stream
|
||||||
|
ended). Headers and API keys are never captured. Differences from the Python monitor: `queue_s` and `load_s` are `null` (the wait for
|
||||||
|
the engine is not attributed per request; `live.queued` shows the queue), and there is no `/api-monitor` HTML page.
|
||||||
|
|
||||||
The Rust control plane has a `POST /v1/responses` route and a reusable response trace builder. The route parses a subset of Responses requests and returns OpenAI-shaped JSON errors. It returns `503 worker_not_ready` until the engine handshake completes. With a configured native tokenizer it can execute a text, function-call, reasoning and validated structured-output preview. It accepts string input or a text-only array of messages and paired function calls/results. Non-streaming and live SSE paths are connected to the resident worker; ordinary unstructured streams with effort none send text deltas and complete, schema-validated function calls before worker `DONE`. Reasoning streams send live reasoning deltas and buffer final answer/tool items; structured text is validated before publication. Unsupported live features return `501 unsupported_live_feature`; a ready worker without tokenizer returns `501 inference_adapter_missing`. Text/tool JSON and SSE, continuation, cancellation and crash recovery have passed small real-model Linux GPU checks; full recorded-agent qualification remains open.
|
The Rust control plane has a `POST /v1/responses` route and a reusable response trace builder. The route parses a subset of Responses requests and returns OpenAI-shaped JSON errors. It returns `503 worker_not_ready` until the engine handshake completes. With a configured native tokenizer it can execute a text, function-call, reasoning and validated structured-output preview. It accepts string input or a text-only array of messages and paired function calls/results. Non-streaming and live SSE paths are connected to the resident worker; ordinary unstructured streams with effort none send text deltas and complete, schema-validated function calls before worker `DONE`. Reasoning streams send live reasoning deltas and buffer final answer/tool items; structured text is validated before publication. Unsupported live features return `501 unsupported_live_feature`; a ready worker without tokenizer returns `501 inference_adapter_missing`. Text/tool JSON and SSE, continuation, cancellation and crash recovery have passed small real-model Linux GPU checks; full recorded-agent qualification remains open.
|
||||||
|
|
||||||
The offline trace builder accepts text fragments, function-call argument fragments, and token usage. It assembles a non-streaming response or an ordered SSE stream ending in `response.completed`. Tool arguments must form a JSON object. `text.format` supports `text`, `json_object`, and `json_schema` validation in both live serving and the offline builder. External schema references are rejected. The synthetic fixture at `benchmarks/fixtures/responses/structured-tool.json` demonstrates text plus a tool call; it is not evidence of live Codex compatibility.
|
The offline trace builder accepts text fragments, function-call argument fragments, and token usage. It assembles a non-streaming response or an ordered SSE stream ending in `response.completed`. Tool arguments must form a JSON object. `text.format` supports `text`, `json_object`, and `json_schema` validation in both live serving and the offline builder. External schema references are rejected. The synthetic fixture at `benchmarks/fixtures/responses/structured-tool.json` demonstrates text plus a tool call; it is not evidence of live Codex compatibility.
|
||||||
|
|||||||
+31
-5
@@ -138,12 +138,12 @@ gRPC `Snapshot.telemetry_json` -> the gateway -> `GET /v1/status` `machine` -> `
|
|||||||
|
|
||||||
| block | figures |
|
| block | figures |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `gpu` | utilisation %, memory-bus %, VRAM used/total (NVML, loaded with `dlopen`; absent when NVML is not installed), power, SM clock |
|
| `gpu` | utilisation %, memory-bus %, VRAM used/total, power, SM clock, temperature, board name (NVML, loaded with `dlopen`; where `libnvidia-ml` cannot be loaded, WSL2 and containers, the engine polls `nvidia-smi` instead, at most every 2 s; absent when neither exists) |
|
||||||
| `ram` | host total/available, engine resident and pinned, swap in use |
|
| `ram` | host total/available, engine resident and pinned, swap in use |
|
||||||
| `cpu` | engine CPU in busy cores (of the cores this process may use), whole-system busy % |
|
| `cpu` | engine CPU in busy cores (of the cores this process may use), whole-system busy % |
|
||||||
| `throughput` | prefill tok/s (last request, running average, lifetime) and decode tok/s (same, plus the live rate of the request in flight) |
|
| `throughput` | prefill tok/s (last request, running average, lifetime) and decode tok/s (same, plus the live rate of the request in flight) |
|
||||||
| `cache` | requests and how many reused a checkpoint, prompt tokens reused of all, the last request's reused/prompt tokens |
|
| `cache` | requests and how many reused a checkpoint, prompt tokens reused of all, the last request's reused/prompt tokens |
|
||||||
| `context` | tokens live in the session, the configured maximum, percent used; `phase` idle/prefill/decode |
|
| `context` | tokens live in the session, the configured maximum, percent used; `phase` idle/prefill/decode; `request` (prompt and generated tokens, seconds) while one runs |
|
||||||
|
|
||||||
Prefill rate counts the tokens actually prefilled (prompt minus reused). Rates are `null` until a request has been measured.
|
Prefill rate counts the tokens actually prefilled (prompt minus reused). Rates are `null` until a request has been measured.
|
||||||
|
|
||||||
@@ -172,9 +172,35 @@ leleka status # prints "settings in force" with the engine telemetry
|
|||||||
|
|
||||||
The same call is `POST /v1/reconfigure` with the JSON document (`{"context_tokens": 131072, ...}`; same bearer key; the answer carries the
|
The same call is `POST /v1/reconfigure` with the JSON document (`{"context_tokens": 131072, ...}`; same bearer key; the answer carries the
|
||||||
effective settings) and gRPC `Runtime.Reconfigure`. The prefix cache is rebuilt empty (its host images belong to the old stack), so the
|
effective settings) and gRPC `Runtime.Reconfigure`. The prefix cache is rebuilt empty (its host images belong to the old stack), so the
|
||||||
next request of every session reads its prompt again once. Run-time changes do not survive a restart: to keep them, change the profile
|
next request of every session reads its prompt again once.
|
||||||
(`--context-tokens`, `memory.prefix_cache_*`) or the preset and run `leleka up` again. What cannot change at run time is fixed when the CUDA
|
|
||||||
context is created: the VRAM budget (`--gpu-budget-gib`) and the preset; those take a restart.
|
**Keeping a change (`--persist`).** Without it a change lasts until the service restarts. With `--persist` the supervisor also writes the
|
||||||
|
result into `STATE/leleka.json` (profile fields: `context_tokens`, `prefill_capacity`, `kv_resident`, `spec_min_p`,
|
||||||
|
`memory.prefix_cache_{mib,tail,block}`, `memory.prefix_retention_min`, and `engine_env.LELEKA_ORIGINAL_SERVE_CPU_WORKERS` for the workers) and
|
||||||
|
regenerates `strata.json`, so a restart of the service, and a restart of a crashed engine, start with the new numbers. The file written is the
|
||||||
|
configuration in force, so a change made earlier without `--persist` in the same service life is written with it. With no supervisor running
|
||||||
|
the file is edited directly.
|
||||||
|
|
||||||
|
**Budget and preset: restart in place.** The VRAM budget and the resource preset are fixed when the CUDA context is created, so the running
|
||||||
|
engine cannot reopen them. `leleka reconfigure --gpu-budget-gib 24 --preset workstation` (either alone, plus any runtime settings and
|
||||||
|
`--persist`) hands the request to the supervisor (a small file in `STATE/run/`, answered in `reconfigure-result.json`), which
|
||||||
|
|
||||||
|
1. checks it with the resource planner (`resources.rs`) without disturbing the service, and refuses what cannot work even with the engine gone
|
||||||
|
(a budget above the card, the workstation preset on a card that is mostly taken, an explicit budget the preset cannot give, an invalid
|
||||||
|
runtime setting, a host too small to keep the sealed archive and the preset's free memory at once);
|
||||||
|
2. stops the engine process (SIGINT, then SIGKILL after the grace period) and checks again against what the host really has free;
|
||||||
|
3. starts the engine again with the new numbers (`--gpu-budget`, the preset's CPU workers and RAM floors, the runtime settings), handing it the
|
||||||
|
sealed archive descriptor the supervisor still holds (no second 55 GB copy, no second hash: the first engine already verified this memfd),
|
||||||
|
and loads the model (minutes);
|
||||||
|
4. keeps the gateway and the API in their processes and on their ports; requests that arrive during the restart see `/ready` 503. With
|
||||||
|
`--persist` and a new context the API process is restarted too (seconds), because `strata.json` carries the context it advertises.
|
||||||
|
|
||||||
|
If the planner refuses after the stop, or the new engine does not come up, the previous settings are started again and the call answers
|
||||||
|
`... ; the previous settings are back` with a non-zero exit. A request that equals what is in force is answered at once. A planned restart does
|
||||||
|
not count against the crash-restart limit. The planner needs the supervisor to hold the archive (`kar_source: memfd`) and refuses a plan that
|
||||||
|
would switch the installation to the file-backed form: `leleka up` decides that. Going back from `workstation` to `dedicated` restores the
|
||||||
|
profile as `up` resolved it (`base_profile` in `leleka.json`, written since this feature; an older file can leave `workstation` only through
|
||||||
|
`leleka up --preset dedicated`).
|
||||||
|
|
||||||
## 5. Flags
|
## 5. Flags
|
||||||
|
|
||||||
|
|||||||
+100
-3
@@ -136,7 +136,104 @@ before any driver call. Not done (needs nvcc and a GPU): compiling the three `.c
|
|||||||
the smokes. The "misc" kernels of `mmq_original_prefill_misc.cu` already have their owner
|
the smokes. The "misc" kernels of `mmq_original_prefill_misc.cu` already have their owner
|
||||||
(`mmq_original_prefill_misc.rs`), so only the poison fill of `device.cu` was open.
|
(`mmq_original_prefill_misc.rs`), so only the poison fill of `device.cu` was open.
|
||||||
|
|
||||||
## 5-7. Not started
|
## 5. KAR routed / prefill experts: feasibility note (decision: not ported)
|
||||||
|
|
||||||
* 5 (KAR routed/prefill experts): `engine/strata/src/core/experimental_routed.hpp` and `prefill/experimental_experts.hpp` are not in the imported tree (only `docs/experiments/2026-10-14-experimental-modes-port.md` names them as unported local patches), so there is no source to transcribe; the local-patch source has to be located first.
|
**What the brief calls them.** The Original-side local patch of 2026-10-06/07 that lets an explicit, default-off experimental arm of the
|
||||||
* 6 (multi-GPU verify stage handoff) and 7 (`/api/requests` monitor, extra `/metrics` fields): open.
|
C++ engine take every routed expert row from the KAR GPU component (`gpu/kar`, the "KAR miss callback") instead of from the native bank:
|
||||||
|
`STRATA_NEXT_KAR_PREFILL=1` (prefill dispatches the grouped expert rows to the callback) and `STRATA_NEXT_KAR_ALL_ROUTED=1` (additionally the
|
||||||
|
target's native routed storage, cache slots and staging rings are not allocated). The patch's own provenance note calls it "an experimental
|
||||||
|
quality arm, not full compressed-model residency or a qualified speedup".
|
||||||
|
|
||||||
|
**What is missing from the imported tree (this branch).** `engine/strata/` is the pinned upstream snapshot and has none of the patch:
|
||||||
|
|
||||||
|
* `include/strata/core/experimental_routed.hpp` (the admission profile `validate_experimental_routed_profile`, `dispatch_experimental_all_routed`
|
||||||
|
with its input/output validation, `dispatch_experimental_routed_window`),
|
||||||
|
* `include/strata/prefill/experimental_experts.hpp` (`dispatch_grouped_experts`, the grouped, batch-of-8 prefill dispatch),
|
||||||
|
* the call-site hunks: `src/core/verify.cpp` (+52 lines: the early multi-token callback before any native lookahead, an absent native
|
||||||
|
tier), `src/prefill/prefill.cpp` (+123: the allocation mode that omits the routed GU/MMQ/staging buffers), `src/core/expert_source.cpp`,
|
||||||
|
`src/program/generate.cpp` (+93: option parsing and admission), and the header edits (`expert_source.hpp`, `verify.hpp`, `prefill.hpp`),
|
||||||
|
* the contract tests `tests/kar-all-routed-contract.cpp`, `tests/kar-prefill-contract.cpp` with their scripts, and the CI workflow.
|
||||||
|
|
||||||
|
**The earlier note ("the local-patch source has to be located first") is out of date: it is located.** It exists in this repository's object
|
||||||
|
store, only on the remote-tracking branch `origin/codex/stra10-bounded-kar-cache-gitea` (commits `33f075f` "explicit bounded batched prefill
|
||||||
|
backend" and `b6563e3` "isolate target native routed storage in explicit mode", based on the import commit `4013e0c`; neither is an ancestor of
|
||||||
|
this branch). `git show b6563e3:engine/strata/include/strata/core/experimental_routed.hpp` prints it and `git diff 4013e0c b6563e3 -- engine/strata`
|
||||||
|
is the whole patch (about 230 changed lines in the four `.cpp` files plus the two headers). The Rust port has no counterpart of the `gpu/kar`
|
||||||
|
miss callback either: what exists is `KarExpertSource::routed_mlp` (KAR level 2..5 decode on CUDA, `NativeBackendConfig::kar_expert_source`),
|
||||||
|
which feeds the preview path's `MoeExpertStage`, not the Original serve path (verifier window MoE, grouped prefill MMQ, CPU pool).
|
||||||
|
|
||||||
|
**What can be done from what exists.** Only the pure half: the two headers are about 200 lines of host-only contracts (flag parsing, the
|
||||||
|
admission profile, finite/range/duplicate-expert validation, `kind == 3` ownership, grouping offsets, the batch limit of 8), and the authors'
|
||||||
|
C++ contract tests can be compiled from the git objects on a dev machine to produce goldens, the way the other `experimental-ref` oracles were
|
||||||
|
made. That is about a day of work with a full oracle, and it would be dead code: the consumers (a native-bank-free verifier window and a
|
||||||
|
native-bank-free prefill carve) live in the sealed GPU paths and cannot be validated without a GPU run.
|
||||||
|
|
||||||
|
**Decision.** Do not port. The arm is a quality experiment of the earlier Strata-next line. It requires `--expert-cache 0`, `--pcie-frac 0`, one
|
||||||
|
GPU, a fixed prefill chunk and no CPU pool (each a throughput loss against the product configuration), it keeps the MTP drafter's native experts
|
||||||
|
anyway (so it can claim no VRAM saving), and nothing in the charter's milestones consumes it. If a compressed-residency product is wanted later, the
|
||||||
|
entry point is `KarExpertSource` plus a KAR owner in `original_verify_window_moe*.rs` and `original_moe_prompt_device.rs`, designed against the
|
||||||
|
Rust owners rather than transcribed from the C++ patch; keep the patch only as a reference for the contracts above.
|
||||||
|
|
||||||
|
## 6. Multi-GPU verify stage handoff: feasibility note (decision: not done)
|
||||||
|
|
||||||
|
**Scope in the Original.** `Verifier::set_stage(layer_begin, layer_end, handoff_in, handoff_out)` and `set_next` (`verify.hpp:104-118`,
|
||||||
|
`verify.cpp:191,436,853,1230,1395-1423`): a verifier runs layers `[lb, le)` of every window. A stage that does not start at layer 0 reads the
|
||||||
|
previous stage's residual `R` (hc x n_embd), pending write `bo` (n_embd) and `inject` (hc) per token (`handoff_floats`) from mapped pinned
|
||||||
|
memory instead of embedding the tokens; one that does not end at the last layer writes them and has no head; `run`, `commit`, `wait_commit`,
|
||||||
|
`window_logprobs` and `copy_logits` chain into `next_`. It is one piece of the layer split of `docs/MULTI_GPU.md`.
|
||||||
|
|
||||||
|
**What the port has.** `OriginalVerifier` loops all 48 layers and has no stage bounds, no hand-off buffers and no next-stage owner
|
||||||
|
(`PORT-GAPS-MODE17.md`). Around it the layer split needs the rest of that document, none of which exists in Rust: a second CUDA context with its
|
||||||
|
own streams, graphs and doorbells (the driver `Context` is thread-confined and `GPU_ORDINAL` is process-global, so two contexts on one thread need
|
||||||
|
explicit context switching), a session and KV per stage (`session.cpp`), a prompt pipeline across stages (a chunk flowing through the cards, 1.5 GB
|
||||||
|
of prefill buffers each), an expert cache and adaptive swaps per stage, the MTP drafter and the head on the last stage, per-stage checkpoints for
|
||||||
|
the conversation and prefix caches, the `--layer-split auto` placement search over the expert profile, and the WDDM pin caps.
|
||||||
|
|
||||||
|
**Cost and value.** The verifier slice alone (stage bounds in the window planners, the hand-off read and write, forwarding on the last stage) is
|
||||||
|
small, perhaps two days, and it has a one-GPU check: the Original runs both stages on one device (`--layer-split K --split-device 0`) and compares
|
||||||
|
bit for bit with the unsplit window, so the handoff could be validated on the single RTX 5090. On its own it delivers nothing a user can run. The
|
||||||
|
usable feature is the whole list above: weeks of work that can only be qualified with two cards on one host (this project has one card per
|
||||||
|
machine: the 5090 server and the 3080 laptop), for a product whose targets are single-GPU hosts (the profiles are `rtx5090-32g` and
|
||||||
|
`rtx3080-16g`). The Original's own measurements say a second card helps when the routed experts do not fit the faster one (+18-20 % on
|
||||||
|
prompts, decode on par); the 5090 profile already keeps a 50 GB resident host bank and a VRAM expert tier.
|
||||||
|
|
||||||
|
**Decision.** Nothing implemented. Revisit only if a two-card host becomes a product target; then do the verifier slice first, behind the
|
||||||
|
one-device bit-exact check, before any of the surrounding work.
|
||||||
|
|
||||||
|
## 7. `/api/requests` monitor and the extra `/metrics` fields: done
|
||||||
|
|
||||||
|
`control-plane/src/request_monitor.rs`, `hardware_view.rs`, `prometheus.rs` and `app.rs` `metrics_document`; the reference behaviour is
|
||||||
|
`Service.begin_request` / `request_records` / `metrics` in `engine/strata/serve/server.py` and `serve/test_monitor.py`. The contract, the
|
||||||
|
differences from Python and the Prometheus series are in `docs/api-contract.md` ("Monitor members, Prometheus text and `GET /api/requests`").
|
||||||
|
Tests: the `request_monitor`, `hardware_view`, `prometheus` and `metrics` unit tests and `tests/backend_worker_http.rs`
|
||||||
|
(`the_request_monitor_*`, `metrics_carry_the_python_monitor_members_and_a_prometheus_view`). Not carried over: the `/api-monitor` HTML page and
|
||||||
|
per-request `queue_s` / `load_s` attribution. The telemetry block comes from NVML or, where `libnvidia-ml` cannot be loaded (WSL2, containers),
|
||||||
|
from polling `nvidia-smi` (`leleka-memory/src/smi.rs`).
|
||||||
|
|
||||||
|
## 8. Bring-up diagnostics are silent in production
|
||||||
|
|
||||||
|
Review of every `eprintln!`/`println!` compiled into the production libraries of `leleka-runtime` and `leleka-cuda-driver` (found with
|
||||||
|
`cargo clippy -p leleka-runtime -p leleka-cuda-driver --lib -- -A clippy::all -W clippy::print_stderr -W clippy::print_stdout`, which skips test
|
||||||
|
code): no `DBG` / `PROBE` / `PREFILL-*` print fires without an explicit opt-in. The unconditional ones were already routed through
|
||||||
|
`bringup_trace!` (`LELEKA_BRINGUP_TRACE`) by the earlier gating pass; what remains outside that macro is one of:
|
||||||
|
|
||||||
|
| print | fires only under |
|
||||||
|
| --- | --- |
|
||||||
|
| `PREFILL-ALLOC`, `PREFILL-STALL`, `PREFILL-SITE` (`compute_drain.rs`) | `LELEKA_PREFILL_ALLOC_TRACE=1`, `LELEKA_PREFILL_STALL_TRACE=1` |
|
||||||
|
| `DBG mtp ... graph`, `DBG graph window/commit` (`mtp_original_full_drafter.rs`, `original_verify_schedule.rs`) | `LELEKA_SERVE_PROFILE` (`host_profile::enabled`) |
|
||||||
|
| `DBG profile`, `DBG window`, `DBG vram`, `DBG tier request` (`original_serve_profile.rs`, `original_serve_host.rs`, `original_serve_stack.rs`) | `LELEKA_SERVE_PROFILE` |
|
||||||
|
| `DBG spec-stats`, `DBG spec-trace` | `LELEKA_SPEC_STATS`, `LELEKA_SPEC_TRACE` |
|
||||||
|
| `DBG verify-profile` | `STRATA_VERIFY_PROFILE` |
|
||||||
|
| `DBG seed`, `DBG seed-coverage` | `LELEKA_SEED_TRACE` |
|
||||||
|
| `DBG ple` (`input.rs`) | `LELEKA_TRACE_PLE` |
|
||||||
|
| `DBG residual*`, the logprobs line (`original_serve_native.rs`) | `LELEKA_TRACE_RESIDUAL=<dir>`, `LELEKA_TRACE_LOGPROBS=<k>` |
|
||||||
|
| `PREFILL-R` (`executor_original_prompt.rs`) | `LELEKA_TRACE_PREFILL_R` |
|
||||||
|
| `driver error: ...` (nine `driver_error` helpers) | `LELEKA_TRACE_DRIVER_ERRORS` |
|
||||||
|
| `PREFILL-PROFILE`, `PREFILL-COMMANDS` (`prefill_profile.rs`) | `LELEKA_BRINGUP_TRACE` (its own `enabled()`) |
|
||||||
|
| cpu pool notices and the router-lookahead summary (`original_serve_pool.rs`) | the non-default pool modes (`LELEKA_CPU_POOL`, `LELEKA_CPU_POOL_FENCE=job`, `LELEKA_CPU_POOL_LOOKAHEAD=on`) |
|
||||||
|
| `OriginalNativeOutput::load: ... refused`, `DenseWeightCache::new_original_prompt_capacity: ... refused`, `leleka-ple-reader-unavailable`, `native embedding: cannot pin`, `resident RAM budget ...` | operator-facing notices on a refusal or a fallback, not diagnostics (kept) |
|
||||||
|
|
||||||
|
The test-only smokes (`backend_original_serve_*smoke*.rs`, `_replay.rs`, `_arms.rs`, `*_gpu.rs`) print `DBG`/`PROBE` lines as their evidence and are not
|
||||||
|
compiled outside `cargo test`. A source scan, `crates/leleka-runtime/tests/bringup_prints_gated.rs`, now fails when a production `DBG`/`PROBE` print has
|
||||||
|
neither `bringup_trace!` nor one of the opt-in switches in the lines above it. The only source change of this pass is one comment in
|
||||||
|
`original_serve_stack.rs`; behaviour is unchanged.
|
||||||
|
|||||||
+2
-2
@@ -100,7 +100,7 @@ A `.cu` file may sit at **S** while its Rust host side sits at **L** or **O**; b
|
|||||||
| CPU expert pool | `crates/native-cpu-expert` | full source, Linux x86-64 only | L; parity binary exists, not run |
|
| CPU expert pool | `crates/native-cpu-expert` | full source, Linux x86-64 only | L; parity binary exists, not run |
|
||||||
| Expert cache, slots, stager, file source, STRP profile, adaptive policy | `cuda-driver/src/original_{expert_cache,expert_slots,expert_stager,file_expert_source}*.rs`, `leleka-runtime/.../cache_*.rs`, `original_cache_startup.rs` | full for the host owners; RAM-source and non-Linux paths absent | L, T for pure policy |
|
| Expert cache, slots, stager, file source, STRP profile, adaptive policy | `cuda-driver/src/original_{expert_cache,expert_slots,expert_stager,file_expert_source}*.rs`, `leleka-runtime/.../cache_*.rs`, `original_cache_startup.rs` | full for the host owners; RAM-source and non-Linux paths absent | L, T for pure policy |
|
||||||
| `pinned.cu` shared-file arena | `model-format/src/pinned_arena_plan.rs` | planner (header, registration plan, parallel load) | T |
|
| `pinned.cu` shared-file arena | `model-format/src/pinned_arena_plan.rs` | planner (header, registration plan, parallel load) | T |
|
||||||
| Layer split, remote experts, `set_stage` handoff | `experimental-ref/src/remote_experts.rs` (planner only) | planner; second-GPU context, staging and launches absent | O for selection, grouping, metadata, scatter |
|
| Layer split, remote experts, `set_stage` handoff | `experimental-ref/src/remote_experts.rs` (planner only) | planner; second-GPU context, staging and launches absent; handoff not done by decision (`docs/port-remaining.md` section 6) | O for selection, grouping, metadata, scatter |
|
||||||
|
|
||||||
## MTP, verifier, prefill and session
|
## MTP, verifier, prefill and session
|
||||||
|
|
||||||
@@ -126,7 +126,7 @@ A `.cu` file may sit at **S** while its Rust host side sits at **L** or **O**; b
|
|||||||
| KV streaming planner and CLOCK resolver | `experimental-ref/src/kv_stream.rs`, `experimental_kv_stream.cu` | references full | O (480 plan cases + resolver) |
|
| KV streaming planner and CLOCK resolver | `experimental-ref/src/kv_stream.rs`, `experimental_kv_stream.cu` | references full | O (480 plan cases + resolver) |
|
||||||
| `kv_q8.cu` INT8 append, `kv_stream.cu` resolve/copy/reset/stage, `--kv-resident` (serve path) | `qsa_prompt_kv.cu`, `mtp_original_kv.cu`, `qsa_prompt_resolver.{cu,rs}`, `qsa_resident_transport.rs`, `serving_context::configure_kv_resident`, `StackConfig::{kv_format, kv_resident}` | full for INT8; fp16/q4_0/k8v4 excluded on the serve path (`docs/kv-streaming.md`) | G: `kv_stream_gpu` model-free proofs on the RTX 5090 (2026-10-16); real-model long-context run pending |
|
| `kv_q8.cu` INT8 append, `kv_stream.cu` resolve/copy/reset/stage, `--kv-resident` (serve path) | `qsa_prompt_kv.cu`, `mtp_original_kv.cu`, `qsa_prompt_resolver.{cu,rs}`, `qsa_resident_transport.rs`, `serving_context::configure_kv_resident`, `StackConfig::{kv_format, kv_resident}` | full for INT8; fp16/q4_0/k8v4 excluded on the serve path (`docs/kv-streaming.md`) | G: `kv_stream_gpu` model-free proofs on the RTX 5090 (2026-10-16); real-model long-context run pending |
|
||||||
| Experimental driver facade, opt-in, pins | `cuda-driver/src/experimental{,_gpu,_gpu_smoke}.rs`, `leleka-runtime/src/experimental.rs` | full; every mode refuses at Load until the consumer is wired (`FORWARD_CONSUMER_WIRED`) | L; entry signatures cross-checked against the `.cu` text (T) |
|
| Experimental driver facade, opt-in, pins | `cuda-driver/src/experimental{,_gpu,_gpu_smoke}.rs`, `leleka-runtime/src/experimental.rs` | full; every mode refuses at Load until the consumer is wired (`FORWARD_CONSUMER_WIRED`) | L; entry signatures cross-checked against the `.cu` text (T) |
|
||||||
| `experimental_routed.hpp`, `experimental_experts.hpp` prefill patches | none | absent | not applicable |
|
| `experimental_routed.hpp`, `experimental_experts.hpp` prefill patches | none | absent from the imported tree; the patch source is in the git objects of `origin/codex/stra10-bounded-kar-cache-gitea` (`b6563e3`); decision: not ported (`docs/port-remaining.md` section 5) | not applicable |
|
||||||
|
|
||||||
## What is open for every row
|
## What is open for every row
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user