infr-server 0.2.0

OpenAI-compatible HTTP server for the infr LLM inference engine
Documentation
//! `GET /metrics`: the server's counters in the Prometheus text exposition format (version 0.0.4,
//! <https://prometheus.io/docs/instrumenting/exposition_formats/>), the format vLLM, TGI and
//! llama-server's `--metrics` all expose. Names carry an `infr_` prefix and follow Prometheus'
//! naming guide: counters end in `_total`, durations are seconds.
//!
//! Counters are lifetime values that only ever grow, so a scraper's `rate()` turns them into
//! throughput over whatever window it likes. That is the job the periodic `serve stats` line does
//! in the log, from its own drained interval counters, which this module never touches.

use std::fmt::Write as _;
use std::sync::atomic::{AtomicU64, Ordering};

use axum::{
    extract::State,
    http::{header::CONTENT_TYPE, HeaderMap},
    response::{IntoResponse, Response},
};

use crate::{auth_gate, AppState, GeneratorStatus, ReqRecord};

/// The media type of the text exposition format.
const CONTENT_TYPE_TEXT: &str = "text/plain; version=0.0.4; charset=utf-8";

/// The never-drained half of [`crate::ServeStats`]. Fed from the same two fold points the periodic
/// line is, so the log and `/metrics` cannot disagree about what counted as a request.
///
/// Token counts arrive only at completion, from the generator's authoritative
/// [`crate::ChatOutcome`], so they never need the signed correction the live interval count does: a
/// counter that steps backwards reads to Prometheus as a process restart. The price is that a
/// failed request's partial tokens are not counted here, and a long generation lands in one step
/// when it ends.
#[derive(Debug, Default)]
pub(crate) struct Lifetime {
    ok: AtomicU64,
    failed: AtomicU64,
    prompt_tokens: AtomicU64,
    gen_tokens: AtomicU64,
    prefill_nanos: AtomicU64,
    decode_nanos: AtomicU64,
}

impl Lifetime {
    pub(crate) fn fold_completion(&self, rec: &ReqRecord) {
        let nanos = |d: std::time::Duration| u64::try_from(d.as_nanos()).unwrap_or(u64::MAX);
        self.ok.fetch_add(1, Ordering::Relaxed);
        self.prompt_tokens
            .fetch_add(u64::from(rec.prompt_tokens), Ordering::Relaxed);
        self.gen_tokens
            .fetch_add(u64::from(rec.gen_tokens), Ordering::Relaxed);
        self.prefill_nanos
            .fetch_add(nanos(rec.prefill), Ordering::Relaxed);
        self.decode_nanos
            .fetch_add(nanos(rec.decode), Ordering::Relaxed);
    }

    pub(crate) fn fold_failure(&self) {
        self.failed.fetch_add(1, Ordering::Relaxed);
    }
}

/// Gated by the same bearer check as `/v1/models`, for the same reason: it names every hosted
/// model. Prometheus sends the token through a scrape config's `authorization` block.
pub(crate) async fn metrics_handler(State(state): State<AppState>, headers: HeaderMap) -> Response {
    if let Some(denied) = auth_gate(&state.cfg, &headers) {
        return denied;
    }
    ([(CONTENT_TYPE, CONTENT_TYPE_TEXT)], render(&state)).into_response()
}

/// The whole exposition body.
fn render(state: &AppState) -> String {
    let stats = &state.stats;
    let life = &stats.lifetime;
    let load = |a: &AtomicU64| a.load(Ordering::Relaxed);
    let secs = |a: &AtomicU64| load(a) as f64 / 1e9;
    let mut out = String::new();

    family(
        &mut out,
        "infr_build_info",
        "gauge",
        "Always 1; the labels carry the build.",
    );
    sample(
        &mut out,
        "infr_build_info",
        &[("version", env!("CARGO_PKG_VERSION"))],
        1,
    );

    family(
        &mut out,
        "infr_requests_total",
        "counter",
        "Chat requests finished, by result. A request cut short by the deadline is ok: it returns \
         its partial completion.",
    );
    sample(
        &mut out,
        "infr_requests_total",
        &[("result", "ok")],
        load(&life.ok),
    );
    sample(
        &mut out,
        "infr_requests_total",
        &[("result", "error")],
        load(&life.failed),
    );

    let counters = [
        (
            "infr_prompt_tokens_total",
            "Prompt tokens finished requests prefilled, as the generator reports them: the Vulkan \
             seam counts only the suffix it ran, not a prefix reused from its KV cache.",
            load(&life.prompt_tokens) as f64,
        ),
        (
            "infr_generation_tokens_total",
            "Tokens generated by finished requests. A failed request's partial tokens are not \
             counted.",
            load(&life.gen_tokens) as f64,
        ),
        (
            "infr_prefill_seconds_total",
            "Time finished requests spent before their first token.",
            secs(&life.prefill_nanos),
        ),
        (
            "infr_decode_seconds_total",
            "Time finished requests spent after their first token.",
            secs(&life.decode_nanos),
        ),
    ];
    for (name, help, value) in counters {
        family(&mut out, name, "counter", help);
        sample(&mut out, name, &[], value);
    }

    family(
        &mut out,
        "infr_requests_running",
        "gauge",
        "Requests holding a slot and generating.",
    );
    sample(&mut out, "infr_requests_running", &[], load(&stats.active));
    family(
        &mut out,
        "infr_requests_waiting",
        "gauge",
        "Requests queued for a free slot.",
    );
    sample(&mut out, "infr_requests_waiting", &[], load(&stats.queued));

    family(
        &mut out,
        "infr_slots",
        "gauge",
        "Concurrent generation slots per model (--parallel).",
    );
    for m in state.models.iter() {
        sample(&mut out, "infr_slots", &[("model", &m.id)], m.capacity);
    }
    family(
        &mut out,
        "infr_slots_busy",
        "gauge",
        "Slots generating right now, per model.",
    );
    for m in state.models.iter() {
        sample(&mut out, "infr_slots_busy", &[("model", &m.id)], m.busy());
    }

    // What each generator can see of its device. A model whose backend reports nothing gets no
    // sample, which Prometheus reads as "no data" rather than as a zero.
    let reported: Vec<_> = state
        .models
        .iter()
        .filter_map(|m| Some((&*m.id, m.engine.as_ref()?.status())))
        .collect();
    type Reading = fn(&GeneratorStatus) -> Option<u64>;
    let gauges: [(&str, &str, Reading); 3] = [
        (
            "infr_context_tokens",
            "Context window each slot holds, per model.",
            |s| s.ctx_per_slot.map(|c| c as u64),
        ),
        (
            "infr_device_memory_total_bytes",
            "Memory of the device serving each model; on an integrated GPU, the shared pool.",
            |s| Some(s.memory?.total_bytes),
        ),
        (
            "infr_device_memory_available_bytes",
            "Device memory this process could still allocate, by the driver's budget.",
            |s| Some(s.memory?.available_bytes),
        ),
    ];
    for (name, help, read) in gauges {
        family(&mut out, name, "gauge", help);
        for (id, s) in &reported {
            if let Some(v) = read(s) {
                sample(&mut out, name, &[("model", id)], v);
            }
        }
    }
    out
}

/// A metric family's `# HELP` and `# TYPE` lines.
fn family(out: &mut String, name: &str, kind: &str, help: &str) {
    // HELP text escapes only backslash and line feed.
    let help = help.replace('\\', r"\\").replace('\n', r"\n");
    let _ = writeln!(out, "# HELP {name} {help}\n# TYPE {name} {kind}");
}

/// One sample line: `name{label="value",...} value`.
fn sample(out: &mut String, name: &str, labels: &[(&str, &str)], value: impl std::fmt::Display) {
    out.push_str(name);
    if !labels.is_empty() {
        out.push('{');
        for (i, (k, v)) in labels.iter().enumerate() {
            if i > 0 {
                out.push(',');
            }
            let _ = write!(out, "{k}=\"{}\"", escape_label(v));
        }
        out.push('}');
    }
    let _ = writeln!(out, " {value}");
}

/// A label value escapes backslash, double quote and line feed; nothing else.
fn escape_label(v: &str) -> String {
    let mut s = String::with_capacity(v.len());
    for c in v.chars() {
        match c {
            '\\' => s.push_str(r"\\"),
            '"' => s.push_str(r#"\""#),
            '\n' => s.push_str(r"\n"),
            c => s.push(c),
        }
    }
    s
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{build_router, ChatGenerator, Config, Finish, ReqTally};
    use axum::{body::Body, http::Request, http::StatusCode};
    use http_body_util::BodyExt;
    use std::sync::Arc;
    use tower::ServiceExt;

    /// The value of the one sample line that starts with `series` (name plus labels, exactly).
    fn value_of(body: &str, series: &str) -> f64 {
        let hits: Vec<&str> = body
            .lines()
            .filter_map(|l| l.strip_prefix(series)?.strip_prefix(' '))
            .collect();
        assert_eq!(
            hits.len(),
            1,
            "want exactly one `{series}` sample in:\n{body}"
        );
        hits[0].parse().unwrap()
    }

    #[test]
    fn label_values_escape_exactly_what_the_format_reserves() {
        assert_eq!(escape_label(r#"a\b"c"#), r#"a\\b\"c"#);
        assert_eq!(escape_label("x\ny"), r"x\ny");
        assert_eq!(escape_label("org/repo:Q4_K_M"), "org/repo:Q4_K_M");
    }

    /// Completions and failures land in the counters with their real values, and the gauges read
    /// the live slot and queue state.
    #[tokio::test]
    async fn counters_and_gauges_report_what_the_server_did() {
        let a: Arc<dyn ChatGenerator> = Arc::new(crate::tests::EchoGen("alpha"));
        let b: Arc<dyn ChatGenerator> = Arc::new(crate::tests::EchoGen("beta"));
        let state = AppState::multi(
            vec![("alpha".into(), a, 3), ("be\"ta".into(), b, 1)],
            Arc::new(Config::default()),
        );
        let rec = ReqTally::new().finish(
            crate::ChatOutcome {
                finish: Finish::Stop,
                prompt_tokens: 100,
                completion_tokens: 20,
            },
            Finish::Stop,
        );
        state.stats.fold_completion(&rec);
        state.stats.fold_completion(&rec);
        state.stats.fold_failure();
        let _held = state.models[0].slots.clone().acquire_owned().await.unwrap();
        let _active = crate::ActiveGuard::new(state.stats.clone());

        let body = render(&state);
        assert_eq!(value_of(&body, r#"infr_requests_total{result="ok"}"#), 2.0);
        assert_eq!(
            value_of(&body, r#"infr_requests_total{result="error"}"#),
            1.0
        );
        assert_eq!(value_of(&body, "infr_prompt_tokens_total"), 200.0);
        assert_eq!(value_of(&body, "infr_generation_tokens_total"), 40.0);
        assert_eq!(value_of(&body, "infr_requests_running"), 1.0);
        assert_eq!(value_of(&body, "infr_requests_waiting"), 0.0);
        assert_eq!(value_of(&body, r#"infr_slots{model="alpha"}"#), 3.0);
        assert_eq!(value_of(&body, r#"infr_slots_busy{model="alpha"}"#), 1.0);
        assert_eq!(value_of(&body, r#"infr_slots{model="be\"ta"}"#), 1.0);
        assert_eq!(value_of(&body, r#"infr_slots_busy{model="be\"ta"}"#), 0.0);
        assert!(value_of(&body, "infr_decode_seconds_total") >= 0.0);
        assert_eq!(
            value_of(&body, r#"infr_context_tokens{model="alpha"}"#),
            4096.0
        );
        assert_eq!(
            value_of(&body, r#"infr_device_memory_total_bytes{model="alpha"}"#),
            (8u64 << 30) as f64
        );
        assert_eq!(
            value_of(
                &body,
                r#"infr_device_memory_available_bytes{model="alpha"}"#
            ),
            (6u64 << 30) as f64
        );
        // Every family is declared once, before its samples.
        for name in ["infr_requests_total", "infr_slots", "infr_slots_busy"] {
            let decl = format!("# TYPE {name} ");
            assert_eq!(body.matches(&decl).count(), 1, "{name}:\n{body}");
            let first_sample = body.find(&format!("\n{name}")).unwrap();
            assert!(body.find(&decl).unwrap() < first_sample, "{name}:\n{body}");
        }
    }

    /// The interval drain behind the log line must not reset what a scraper sees.
    #[test]
    fn draining_the_log_interval_leaves_the_counters_alone() {
        let state = AppState::headless("m", Arc::new(Config::default()));
        state.stats.fold_failure();
        state.stats.drain(std::time::Duration::from_secs(1));
        let body = render(&state);
        assert_eq!(
            value_of(&body, r#"infr_requests_total{result="error"}"#),
            1.0
        );
    }

    /// A model with nothing to report about its device gets no sample at all, not a zero.
    #[test]
    fn an_unreported_device_has_no_samples() {
        let body = render(&AppState::headless("m", Arc::new(Config::default())));
        assert!(body.contains("# TYPE infr_device_memory_total_bytes gauge"));
        for name in ["infr_context_tokens", "infr_device_memory_total_bytes"] {
            assert!(!body.contains(&format!("\n{name}{{")), "{name}:\n{body}");
        }
    }

    #[tokio::test]
    async fn the_route_serves_the_text_format_behind_the_api_key() {
        let mut cfg = Config::default();
        cfg.serve.api_key = Some("s3cret".into());
        let state = AppState::headless("hidden-model", Arc::new(cfg));
        let get = |auth: Option<&str>| {
            let mut b = Request::builder().uri("/metrics");
            if let Some(a) = auth {
                b = b.header("authorization", a);
            }
            b.body(Body::empty()).unwrap()
        };

        let resp = build_router(state.clone())
            .oneshot(get(None))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        assert!(!String::from_utf8_lossy(&bytes).contains("hidden-model"));

        let resp = build_router(state)
            .oneshot(get(Some("Bearer s3cret")))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(resp.headers()[CONTENT_TYPE], CONTENT_TYPE_TEXT);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let body = String::from_utf8(bytes.to_vec()).unwrap();
        assert_eq!(value_of(&body, r#"infr_slots{model="hidden-model"}"#), 1.0);
    }
}