Files
leleka/control-plane/src/memory_view.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 72fc3b0820 style: cargo fmt on strata-control, strata-desktop-core, leleka-runtime-client; clear Clippy lints and two red tests on main
Mechanical rustfmt (control-plane, desktop-core and the runtime client had 360 hunks of drift; the CI format steps for control-plane and
desktop-core were red), plus, found by running `cargo clippy -D warnings` and the tests on Linux:
* control-plane/tests/log_failure_sse.rs `no_panicking_log_macros_in_the_serving_crate` was red on main since the observability merge: two
  test-only `eprintln!` samples (prometheus.rs, request_log.rs) trip its source scan. They now write to stderr with `write_fmt` and
  ignore a failed write, which is what the test asks for; the output is the same.
* tool_output.rs `is_multiple_of(2)`, an unneeded `mut` in a control-plane test, a collapsible `if` in leleka-inference.rs,
  `#[allow(dead_code)]` on observer_adaptive_slots (compiled into leleka-inference-evaluation too).
* crates/deploy/src/facts.rs: `lab_holder_running` moved above `mod tests` (clippy::items_after_test_module); code moved, not changed.
Kept as its own commit so it can be redone with `cargo fmt` if other branches touch these crates first. No behaviour change.

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

267 lines
10 KiB
Rust

//! The engine's memory-governor report as this control plane last saw it, and the gate that turns it into a fast
//! `503 memory_pressure` with `Retry-After` before a request is queued (`docs/memory-safety.md`).
//!
//! The engine's governor decides the level (`normal`, `shed`, `reject`) from `MemAvailable`, PSI, the cgroup events and the
//! swap-out rate; it publishes a JSON report with every sample. The worker copies the report here on its health tick and
//! after every request. The gate trusts only a fresh report: an old one (the engine stopped answering) never blocks traffic,
//! because the worker's own readiness already covers an engine that is gone.
use std::sync::RwLock;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use axum::{
http::{HeaderValue, StatusCode, header},
response::{IntoResponse, Response},
};
use serde_json::{Value, json};
/// A report older than this does not close the gate.
pub const FRESH_FOR: Duration = Duration::from_secs(30);
/// The text an engine-side refusal carries (`<code>: retry_after=<seconds>: <why>`), found anywhere in a failure message.
const MARK: &str = "memory_pressure: retry_after=";
/// Why a request was refused up front.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Closed {
pub retry_after_secs: u64,
pub reason: String,
}
/// The few figures of the engine's last telemetry and memory reports that explain a slow request: the GPU clock and
/// temperature, why the driver is holding the clock down, the memory gate's level and the free host RAM.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Brief {
pub sm_clock_mhz: Option<u64>,
pub temp_c: Option<u64>,
/// NVML clocks-throttle-reasons bit mask (0: none).
pub throttle: Option<u64>,
pub gate: Option<String>,
pub ram_available_mib: Option<u64>,
}
#[derive(Default)]
pub struct MemoryView {
latest: RwLock<Option<(Value, Instant)>>,
/// The engine's telemetry document (`Backend::telemetry_report`) and when it was copied.
telemetry: RwLock<Option<(Value, Instant)>>,
/// A minute of the headline telemetry series (`GET /metrics` `history`).
series: crate::hardware_view::Series,
gated: AtomicU64,
}
impl MemoryView {
/// Replace the stored report (`None`: the engine has no governor, or is unreachable).
pub fn set(&self, report: Option<String>) {
let value = report
.and_then(|text| serde_json::from_str::<Value>(&text).ok())
.filter(Value::is_object);
if let Ok(mut latest) = self.latest.write() {
*latest = value.map(|value| (value, Instant::now()));
}
}
/// Replace the stored telemetry document (`None`: the engine reports none, or is unreachable).
pub fn set_telemetry(&self, document: Option<String>) {
let value = document
.and_then(|text| serde_json::from_str::<Value>(&text).ok())
.filter(Value::is_object);
if let Some(value) = &value {
self.series.push(&crate::hardware_view::hardware_now(value));
}
if let Ok(mut latest) = self.telemetry.write() {
*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(),
)
}
/// The headline hardware figures as of the last report (`None` when the engine has reported nothing fresh).
pub fn brief(&self) -> Option<Brief> {
let telemetry = self.telemetry.read().ok()?;
let (document, at) = telemetry.as_ref()?;
if at.elapsed() > FRESH_FOR {
return None;
}
let gate = self.latest.read().ok().and_then(|latest| {
latest
.as_ref()
.filter(|(_, at)| at.elapsed() <= FRESH_FOR)
.and_then(|(report, _)| report["gate"]["level"].as_str().map(str::to_owned))
});
Some(Brief {
sm_clock_mhz: document["gpu"]["sm_clock_mhz"].as_u64(),
temp_c: document["gpu"]["temp_c"].as_u64(),
throttle: document["gpu"]["throttle_reasons"].as_u64(),
gate,
ram_available_mib: document["ram"]["available_mib"].as_u64(),
})
}
/// For `GET /v1/status` `machine`: the engine's telemetry with its age; a document older than [`FRESH_FOR`] is `null`.
pub fn telemetry_status(&self) -> Value {
let Ok(latest) = self.telemetry.read() else {
return Value::Null;
};
match latest.as_ref() {
Some((value, at)) if at.elapsed() <= FRESH_FOR => {
let mut value = value.clone();
value["age_ms"] = json!(at.elapsed().as_millis() as u64);
value
}
_ => Value::Null,
}
}
/// For `GET /v1/status`: the report with its age and this process's gate counter; `null` when there is none.
pub fn status(&self) -> Value {
let Ok(latest) = self.latest.read() else {
return Value::Null;
};
match latest.as_ref() {
Some((value, at)) => {
let mut value = value.clone();
value["age_ms"] = json!(at.elapsed().as_millis() as u64);
value["gate_rejections"] = json!(self.gated.load(Ordering::Relaxed));
value
}
None => Value::Null,
}
}
/// The gate: `Some` when the engine reported `reject` within [`FRESH_FOR`].
pub fn closed(&self) -> Option<Closed> {
let latest = self.latest.read().ok()?;
let (report, at) = latest.as_ref()?;
if at.elapsed() > FRESH_FOR || report["gate"]["level"] != "reject" {
return None;
}
self.gated.fetch_add(1, Ordering::Relaxed);
Some(Closed {
retry_after_secs: report["gate"]["retry_after_secs"]
.as_u64()
.unwrap_or(15)
.clamp(1, 600),
reason: report["gate"]["reason"]
.as_str()
.unwrap_or("host memory is under pressure")
.to_owned(),
})
}
/// Requests this process refused at the gate.
pub fn gate_rejections(&self) -> u64 {
self.gated.load(Ordering::Relaxed)
}
}
/// `503` with `Retry-After`, in the error envelope of the Responses API.
pub fn refusal_response(retry_after_secs: u64, reason: &str) -> Response {
let body = json!({"error": {
"message": format!("the server is short of host memory ({reason}); retry in {retry_after_secs} s"),
"type": "server_error", "param": null, "code": "memory_pressure",
}});
let mut response = (StatusCode::SERVICE_UNAVAILABLE, axum::Json(body)).into_response();
if let Ok(value) = HeaderValue::from_str(&retry_after_secs.to_string()) {
response.headers_mut().insert(header::RETRY_AFTER, value);
}
response
}
/// Whether an engine failure message is a memory-pressure refusal, and the Retry-After it carries.
pub fn parse_refusal(message: &str) -> Option<u64> {
let rest = &message[message.find(MARK)? + MARK.len()..];
let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
digits.parse::<u64>().ok().map(|s| s.clamp(1, 600))
}
/// The error `code` a failure message maps to.
pub fn failure_code(message: &str) -> &'static str {
if parse_refusal(message).is_some() {
"memory_pressure"
} else {
"generation_failed"
}
}
#[cfg(test)]
mod tests {
use super::*;
fn report(level: &str, retry: u64) -> String {
json!({"version": 1, "gate": {"level": level, "retry_after_secs": retry, "reason": "available 1024 MiB below the hard floor 2048 MiB"}}).to_string()
}
#[test]
fn the_gate_closes_only_on_a_fresh_reject() {
let view = MemoryView::default();
assert!(view.closed().is_none(), "no report: open");
view.set(Some(report("normal", 0)));
assert!(view.closed().is_none());
view.set(Some(report("shed", 5)));
assert!(view.closed().is_none(), "shedding still serves");
view.set(Some(report("reject", 15)));
let closed = view.closed().unwrap();
assert_eq!(closed.retry_after_secs, 15);
assert!(closed.reason.contains("hard floor"));
assert_eq!(view.gate_rejections(), 1);
view.set(Some("not json".into()));
assert!(view.closed().is_none(), "garbage never closes the gate");
view.set(None);
assert!(view.status().is_null());
}
#[test]
fn a_stale_report_does_not_block_traffic() {
let view = MemoryView::default();
view.set(Some(report("reject", 15)));
// age the report past the freshness window
let aged = view
.latest
.read()
.unwrap()
.clone()
.map(|(v, _)| (v, Instant::now() - FRESH_FOR - Duration::from_secs(1)));
*view.latest.write().unwrap() = aged;
assert!(view.closed().is_none());
assert!(view.status()["age_ms"].as_u64().unwrap() >= 30_000);
}
#[test]
fn the_refusal_response_is_a_503_with_retry_after() {
let r = refusal_response(15, "host memory is under pressure");
assert_eq!(r.status(), StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(r.headers().get(header::RETRY_AFTER).unwrap(), "15");
}
#[test]
fn engine_side_refusals_are_recognised_inside_wrapped_messages() {
let wrapped = "engine refused the generation: ResourceExhausted: runtime: memory_pressure: retry_after=15: host memory is under pressure (ResourceExhausted)";
assert_eq!(parse_refusal(wrapped), Some(15));
assert_eq!(failure_code(wrapped), "memory_pressure");
assert_eq!(
failure_code("engine made no progress for 30 s"),
"generation_failed"
);
assert_eq!(
parse_refusal("memory_pressure: retry_after=99999: x"),
Some(600)
);
assert_eq!(parse_refusal("memory_pressure: retry_after=: x"), None);
}
}