use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Instant;
use axum::{extract::State, Json};
use serde::Serialize;
use super::AppState;
pub const EFFECTIVE_CONFIG_SCHEMA_VERSION: u32 = 1;
pub const CLOCK_SOURCE: &str =
"chrono::Utc::now (CLOCK_REALTIME) + std::time::Instant (CLOCK_MONOTONIC)";
#[derive(Debug)]
pub struct ServerClock {
started_utc: String,
started_unix: i64,
started: Instant,
pid: u32,
}
impl ServerClock {
#[must_use]
pub fn new() -> Self {
let now = chrono::Utc::now();
Self {
started_utc: now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
started_unix: now.timestamp(),
started: Instant::now(),
pid: std::process::id(),
}
}
#[must_use]
pub fn process() -> Arc<Self> {
static CLOCK: std::sync::OnceLock<Arc<ServerClock>> = std::sync::OnceLock::new();
CLOCK.get_or_init(|| Arc::new(ServerClock::new())).clone()
}
#[must_use]
pub fn started_utc(&self) -> &str {
&self.started_utc
}
#[must_use]
pub fn started_unix_secs(&self) -> i64 {
self.started_unix
}
#[must_use]
pub fn uptime_sec(&self) -> f64 {
self.started.elapsed().as_secs_f64()
}
#[must_use]
pub fn pid(&self) -> u32 {
self.pid
}
#[must_use]
pub fn report(&self) -> ServerReport {
ServerReport {
version: crate::VERSION,
build_commit: option_env!("APR_GIT_SHA").map(str::to_string),
pid: self.pid,
started_utc: self.started_utc.clone(),
clock_source: CLOCK_SOURCE,
uptime_sec: self.uptime_sec(),
}
}
}
impl Default for ServerClock {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ServerReport {
pub version: &'static str,
pub build_commit: Option<String>,
pub pid: u32,
pub started_utc: String,
pub clock_source: &'static str,
pub uptime_sec: f64,
}
#[derive(Debug, Default)]
pub struct InFlightCounter {
now: AtomicUsize,
peak: AtomicUsize,
}
impl InFlightCounter {
#[must_use]
pub fn new() -> Arc<Self> {
Arc::new(Self::default())
}
pub fn enter(&self) -> usize {
let now = self.now.fetch_add(1, Ordering::AcqRel) + 1;
self.peak.fetch_max(now, Ordering::AcqRel);
now
}
pub fn set(&self, active: usize) {
self.now.store(active, Ordering::Release);
self.peak.fetch_max(active, Ordering::AcqRel);
}
pub fn leave(&self) {
let _ = self
.now
.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| {
Some(n.saturating_sub(1))
});
}
#[must_use]
pub fn in_flight_now(&self) -> usize {
self.now.load(Ordering::Acquire)
}
#[must_use]
pub fn peak_in_flight(&self) -> usize {
self.peak.load(Ordering::Acquire)
}
}
pub const ADMISSION_POLICY: &str = "queue";
#[derive(Debug, Default)]
pub struct AdmissionCounter {
rejected: AtomicU64,
}
impl AdmissionCounter {
#[must_use]
pub fn new() -> Arc<Self> {
Arc::new(Self::default())
}
pub fn record_rejected(&self) -> u64 {
self.rejected.fetch_add(1, Ordering::AcqRel) + 1
}
#[must_use]
pub fn rejected(&self) -> u64 {
self.rejected.load(Ordering::Acquire)
}
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct OffloadReport {
pub gpu_layers_requested: String,
pub gpu_layers_resolved: u32,
pub gpu_layers_total: u32,
pub offload_policy: &'static str,
pub autofit_applied: Vec<String>,
pub explicit_args: Vec<String>,
#[serde(skip_serializing)]
pub build_features: Vec<String>,
#[serde(skip_serializing)]
pub build_commit: Option<String>,
}
#[must_use]
pub fn pp14_holds(report: &OffloadReport) -> bool {
!report
.autofit_applied
.iter()
.any(|applied| report.explicit_args.iter().any(|arg| arg == applied))
}
#[derive(Debug, Clone, Serialize)]
pub struct SchedulerReport {
pub kind: &'static str,
pub max_in_flight: usize,
pub window_ms: u64,
pub prefill_chunk_size: Option<usize>,
pub token_budget: Option<usize>,
pub slots_admitted: usize,
pub admission_ceiling_reason: &'static str,
pub in_flight_now: Option<usize>,
pub peak_in_flight: Option<usize>,
}
#[must_use]
pub fn admission_ceiling_reason(max_batch_source: Option<&str>) -> &'static str {
match max_batch_source {
Some("env") => "env",
Some("computed") => "kv_budget",
_ => "default",
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ModelReport {
pub path: Option<String>,
pub size_bytes: Option<u64>,
pub format: Option<String>,
pub quantization: Option<String>,
pub architecture: Option<String>,
pub context_length: Option<usize>,
pub model_max_context_length: Option<usize>,
pub content_hash: Option<String>,
pub parameter_count: Option<u64>,
pub loaded: bool,
}
impl ModelReport {
fn from_state(state: &AppState) -> Self {
let source = state.model_source();
Self {
path: source.and_then(|s| s.path().map(str::to_string)),
size_bytes: source.and_then(super::ModelSourceInfo::size_bytes),
format: source.and_then(|s| s.format().map(str::to_string)),
quantization: source.and_then(|s| s.quantization().map(str::to_string)),
architecture: source
.and_then(|s| s.architecture().map(str::to_string))
.or_else(|| state.model_architecture()),
context_length: source.and_then(super::ModelSourceInfo::context_length),
model_max_context_length: source
.and_then(super::ModelSourceInfo::model_max_context_length),
content_hash: source.and_then(|s| s.content_hash().map(str::to_string)),
parameter_count: source.and_then(super::ModelSourceInfo::parameter_count),
loaded: state.model_loaded(),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct KvReport {
pub bytes_used: Option<usize>,
pub bytes_reserved: Option<usize>,
pub admission_rejected: u64,
pub admission_policy: &'static str,
pub preempted_swap: u64,
pub kv_per_slot_bytes: Option<usize>,
pub kv_slots_allocated: Option<usize>,
pub kv_slots_max: Option<usize>,
pub kv_blocks_total: Option<usize>,
pub kv_layout: &'static str,
}
#[derive(Debug, Clone, Serialize)]
pub struct EffectiveConfigResponse {
pub schema_version: u32,
pub server: ServerReport,
pub compute_class: &'static str,
pub build_features: Vec<&'static str>,
pub build_features_cli: Option<Vec<String>>,
pub backend_loaded: Vec<&'static str>,
pub model: ModelReport,
pub offload: Option<OffloadReport>,
pub scheduler: Option<SchedulerReport>,
pub cuda: Option<serde_json::Value>,
pub kv: Option<KvReport>,
pub lock_contended: bool,
}
#[must_use]
pub fn build_features() -> Vec<&'static str> {
let mut features: Vec<&'static str> = Vec::new();
if cfg!(feature = "server") {
features.push("server");
}
if cfg!(feature = "cli") {
features.push("cli");
}
if cfg!(feature = "gpu") {
features.push("gpu");
}
if cfg!(feature = "cuda") {
features.push("cuda");
}
features
}
#[must_use]
pub fn backend_loaded(state: &AppState) -> Vec<&'static str> {
let mut loaded: Vec<&'static str> = Vec::new();
#[cfg(feature = "cuda")]
{
if state.has_cuda_model()
|| state.safetensors_cuda_model().is_some()
|| state.apr_q4k_tx().is_some()
{
loaded.push("cuda");
}
}
#[cfg(feature = "gpu")]
if state.has_gpu_model() || state.has_cached_model() {
loaded.push("wgpu");
}
if state.quantized_model().is_some() || state.apr_transformer().is_some() {
loaded.push("cpu");
}
loaded
}
#[must_use]
pub fn compute_class_from_residency(state: &AppState) -> &'static str {
match backend_loaded(state).first() {
Some(first) => first,
None => "unknown",
}
}
#[must_use]
pub fn effective_config(state: &AppState) -> EffectiveConfigResponse {
let effective = state.effective_config_state();
let cuda_snapshot = cuda_snapshot(state);
EffectiveConfigResponse {
schema_version: EFFECTIVE_CONFIG_SCHEMA_VERSION,
server: {
let mut server = effective.clock.report();
if server.build_commit.is_none() {
server.build_commit = effective
.offload
.as_ref()
.and_then(|o| o.build_commit.clone());
}
server
},
compute_class: compute_class_from_residency(state),
build_features: build_features(),
build_features_cli: effective.offload.as_ref().map(|o| o.build_features.clone()),
backend_loaded: backend_loaded(state),
model: ModelReport::from_state(state),
offload: effective.offload.as_ref().map(|o| (**o).clone()),
scheduler: effective.scheduler.as_ref().map(|report| {
let mut report = (**report).clone();
if let Some(counter) = effective.in_flight.as_ref() {
report.in_flight_now = Some(counter.in_flight_now());
report.peak_in_flight = Some(counter.peak_in_flight());
}
report
}),
cuda: cuda_snapshot.cuda,
kv: cuda_snapshot.kv,
lock_contended: cuda_snapshot.lock_contended,
}
}
struct CudaSnapshot {
cuda: Option<serde_json::Value>,
kv: Option<KvReport>,
lock_contended: bool,
}
#[cfg(not(feature = "cuda"))]
fn cuda_snapshot(_state: &AppState) -> CudaSnapshot {
CudaSnapshot {
cuda: None,
kv: None,
lock_contended: false,
}
}
#[cfg(feature = "cuda")]
fn cuda_snapshot(state: &AppState) -> CudaSnapshot {
let Some(lock) = state.cuda_model() else {
return CudaSnapshot {
cuda: None,
kv: None,
lock_contended: false,
};
};
let Ok(model) = lock.try_read() else {
return CudaSnapshot {
cuda: None,
kv: None,
lock_contended: true,
};
};
let vram = model.vram_report();
let kv = KvReport {
bytes_used: Some(vram.kv_bytes_reserved),
bytes_reserved: Some(vram.kv_bytes_reserved),
admission_rejected: state.effective_config_state().admission.rejected(),
admission_policy: ADMISSION_POLICY,
preempted_swap: 0,
kv_per_slot_bytes: Some(vram.kv_per_slot_bytes),
kv_slots_allocated: Some(vram.kv_slots_allocated),
kv_slots_max: Some(vram.kv_slots_max),
kv_blocks_total: None,
kv_layout: vram.kv_layout,
};
let block = serde_json::json!({
"gpu_profile": model.executor().gpu_profile(),
"graphs": model.executor().graph_config(),
"prefill_path": model.prefill_path(),
"max_batch": model.max_batch_sizing(),
"vram": vram,
});
CudaSnapshot {
cuda: Some(block),
kv: Some(kv),
lock_contended: false,
}
}
pub(crate) async fn effective_config_handler(
State(state): State<AppState>,
) -> Json<EffectiveConfigResponse> {
if state.is_verbose() {
eprintln!("[VERBOSE] GET /v1/effective-config");
}
Json(effective_config(&state))
}
#[derive(Clone)]
pub struct EffectiveConfigState {
pub(crate) clock: Arc<ServerClock>,
pub(crate) offload: Option<Arc<OffloadReport>>,
pub(crate) scheduler: Option<Arc<SchedulerReport>>,
pub(crate) in_flight: Option<Arc<InFlightCounter>>,
pub(crate) admission: Arc<AdmissionCounter>,
}
impl EffectiveConfigState {
#[must_use]
pub fn new() -> Self {
Self {
clock: ServerClock::process(),
offload: None,
scheduler: None,
in_flight: None,
admission: AdmissionCounter::new(),
}
}
}
impl Default for EffectiveConfigState {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod effective_config_tests {
use super::*;
fn report(autofit: &[&str], explicit: &[&str]) -> OffloadReport {
OffloadReport {
gpu_layers_requested: "all".to_string(),
gpu_layers_resolved: 28,
gpu_layers_total: 28,
offload_policy: "all_or_nothing",
autofit_applied: autofit.iter().map(|s| (*s).to_string()).collect(),
explicit_args: explicit.iter().map(|s| (*s).to_string()).collect(),
build_features: vec!["cuda".to_string()],
build_commit: None,
}
}
#[test]
fn autofit_override() {
assert!(
!pp14_holds(&report(&["gpu_layers"], &["gpu_layers", "context_length"])),
"auto-fit and the operator both claiming `gpu_layers` must be REFUSED"
);
}
#[test]
fn autofit_ok() {
assert!(pp14_holds(&report(&[], &["gpu_layers"])));
assert!(pp14_holds(&report(&["context_length"], &["gpu_layers"])));
assert!(pp14_holds(&report(&[], &[])));
}
#[test]
fn admission_ceiling_reason_table() {
assert_eq!(admission_ceiling_reason(Some("env")), "env");
assert_eq!(admission_ceiling_reason(Some("computed")), "kv_budget");
assert_eq!(admission_ceiling_reason(None), "default");
assert_eq!(admission_ceiling_reason(Some("something-else")), "default");
assert_ne!(
admission_ceiling_reason(Some("env")),
admission_ceiling_reason(Some("computed")),
"an operator ceiling and a KV-budget ceiling must not read the same"
);
}
#[test]
#[test]
fn in_flight_counter_set_mirrors_the_scheduler_and_keeps_the_peak() {
let c = InFlightCounter::new();
c.set(3);
c.set(5);
c.set(2);
assert_eq!(c.in_flight_now(), 2);
assert_eq!(c.peak_in_flight(), 5);
c.set(0);
assert_eq!(c.in_flight_now(), 0);
assert_eq!(
c.peak_in_flight(),
5,
"the peak is what the band achieved, not what is left"
);
}
fn in_flight_counter_tracks_peak_and_saturates() {
let counter = InFlightCounter::new();
assert_eq!(counter.enter(), 1);
assert_eq!(counter.enter(), 2);
assert_eq!(counter.enter(), 3);
counter.leave();
counter.leave();
assert_eq!(counter.in_flight_now(), 1);
assert_eq!(counter.peak_in_flight(), 3, "peak is the high-water mark");
counter.leave();
counter.leave();
assert_eq!(
counter.in_flight_now(),
0,
"an unmatched leave must saturate, not wrap to usize::MAX"
);
assert_eq!(counter.peak_in_flight(), 3);
}
fn kv_fixture(admission_rejected: u64) -> KvReport {
KvReport {
bytes_used: Some(2_348_810_240),
bytes_reserved: Some(2_348_810_240),
admission_rejected,
admission_policy: ADMISSION_POLICY,
preempted_swap: 0,
kv_per_slot_bytes: Some(469_762_048),
kv_slots_allocated: Some(4),
kv_slots_max: Some(32),
kv_blocks_total: None,
kv_layout: "contiguous_per_slot",
}
}
#[test]
fn kv_block_reports_all_four_numbers_arm_d_reads() {
let json = serde_json::to_value(kv_fixture(0)).expect("serialize");
for field in [
"bytes_used",
"bytes_reserved",
"admission_rejected",
"preempted_swap",
] {
assert!(
json[field].as_u64().is_some(),
"`kv.{field}` must be a number: Arm D's block is built only when \
both byte figures parse; a null counter is kept and named, a null byte figure DELETES the block:\n{json}"
);
}
assert_eq!(
json["admission_policy"].as_str(),
Some("queue"),
"`admission_rejected: 0` is only readable beside the policy it counts \
under:\n{json}"
);
assert_eq!(
json["kv_layout"].as_str(),
Some("contiguous_per_slot"),
"`preempted_swap: 0` is only readable beside the layout that has no \
swap path:\n{json}"
);
assert!(
json["kv_blocks_total"].is_null(),
"there is no block table to count:\n{json}"
);
}
#[test]
fn admission_rejected_reports_what_was_counted() {
let none = serde_json::to_value(kv_fixture(0)).expect("serialize");
let some = serde_json::to_value(kv_fixture(3)).expect("serialize");
assert_eq!(none["admission_rejected"].as_u64(), Some(0));
assert_eq!(some["admission_rejected"].as_u64(), Some(3));
assert_ne!(
none["admission_rejected"], some["admission_rejected"],
"a server that refused three requests must not report what an idle one does"
);
}
#[test]
fn admission_counter_counts_each_refusal() {
let counter = AdmissionCounter::new();
assert_eq!(counter.rejected(), 0, "nothing refused yet");
assert_eq!(counter.record_rejected(), 1, "the total AFTER this refusal");
assert_eq!(counter.record_rejected(), 2);
assert_eq!(counter.rejected(), 2);
let shared = Arc::clone(&counter);
shared.record_rejected();
assert_eq!(
counter.rejected(),
3,
"a clone of the handle must count into the same total"
);
}
#[test]
fn process_clock_is_shared() {
let a = ServerClock::process();
let b = ServerClock::process();
assert_eq!(a.started_utc(), b.started_utc());
assert_eq!(a.started_unix_secs(), b.started_unix_secs());
assert_eq!(a.pid(), std::process::id());
}
#[test]
fn started_utc_is_rfc3339_utc() {
let clock = ServerClock::new();
let parsed = chrono::DateTime::parse_from_rfc3339(clock.started_utc())
.expect("started_utc must be RFC 3339");
assert_eq!(parsed.offset().local_minus_utc(), 0, "must be UTC");
assert!(
clock.started_utc().ends_with('Z'),
"UTC is written with Z, got {}",
clock.started_utc()
);
assert_eq!(parsed.timestamp(), clock.started_unix_secs());
}
#[test]
fn uptime_is_monotonic() {
let clock = ServerClock::new();
let first = clock.uptime_sec();
let second = clock.uptime_sec();
assert!(second >= first, "{second} < {first}");
assert!(first >= 0.0);
}
#[test]
fn build_features_agree_with_cfg() {
let features = build_features();
assert_eq!(features.contains(&"server"), cfg!(feature = "server"));
assert_eq!(features.contains(&"cli"), cfg!(feature = "cli"));
assert_eq!(features.contains(&"gpu"), cfg!(feature = "gpu"));
assert_eq!(features.contains(&"cuda"), cfg!(feature = "cuda"));
assert!(
features.len() <= 4,
"a feature reported that this crate does not have: {features:?}"
);
}
#[test]
fn a_cuda_class_is_only_valid_on_a_cuda_build() {
let features = build_features();
let valid = |class: &str| class != "cuda" || features.contains(&"cuda");
assert!(valid("cpu"), "cpu is producible by every build");
assert!(valid("unknown"));
assert_eq!(
valid("cuda"),
cfg!(feature = "cuda"),
"`compute_class: cuda` on a build without the cuda feature is \
INVALID-BUILD, and this is the comparison that says so"
);
}
}