//! 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 (`: retry_after=: `), 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, pub temp_c: Option, /// NVML clocks-throttle-reasons bit mask (0: none). pub throttle: Option, pub gate: Option, pub ram_available_mib: Option, } #[derive(Default)] pub struct MemoryView { latest: RwLock>, /// The engine's telemetry document (`Backend::telemetry_report`) and when it was copied. telemetry: RwLock>, /// 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) { let value = report .and_then(|text| serde_json::from_str::(&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) { let value = document .and_then(|text| serde_json::from_str::(&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 { 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 { 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 { let rest = &message[message.find(MARK)? + MARK.len()..]; let digits: String = rest.chars().take_while(char::is_ascii_digit).collect(); digits.parse::().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); } }