//! The per-request record and the request metrics. //! //! One line per generation request, written when the request ends: request and session id, dialect, model, tokens //! (prompt, cached, output), queue wait, time to first token, prefill and decode rates, finish reason, error class and //! whether the engine was lost meanwhile. No prompt or output text, no credential: the record is built from numbers and //! fixed vocabularies only, and the log layer ([`leleka_obs`]) scrubs whatever string it is given anyway. //! //! The record lives in a [`ReqCtx`] that the `observe` middleware creates when a generation route is entered. The //! handler copies it into the [`Generate`](crate::wire::Generate) it queues (an [`ObsHandle`]), the worker marks the //! engine start, the first token and the terminal event on it, and the line is written exactly once: when the worker //! finalises the request, or, for a request that never reached the engine (a rejection, a client that left the queue), //! when the last reference is dropped. //! //! The same moment feeds the Prometheus histograms and counters of [`RequestMetrics`], whose labels are enums of //! fixed size (endpoint x outcome, error class): there is no label whose value comes from a client. use std::sync::{ Arc, Mutex, atomic::{AtomicU64, Ordering}, }; use tokio::time::Instant; use axum::{ extract::{Request, State}, http::{HeaderMap, HeaderValue}, middleware::Next, response::Response, }; use leleka_obs::{V, hist::Histogram}; use sha2::{Digest, Sha256}; use crate::wire::{Done, Finish}; pub const ENDPOINTS: [&str; 4] = ["responses", "chat", "messages", "other"]; pub const OUTCOMES: [&str; 7] = ["stop", "length", "cancel", "disconnect", "error", "rejected", "abandoned"]; pub const ERROR_CLASSES: [&str; 12] = [ "none", "stall", "deadline", "memory_pressure", "engine_refused", "engine_lost", "stream_ended", "cancel_timeout", "bad_request", "overloaded", "unavailable", "other", ]; /// The header that names the request to the client, so that a user can quote it in a report. pub const REQUEST_ID_HEADER: &str = "x-leleka-request-id"; /// Headers that carry a client session (Codex CLI sends `session_id`), in order of preference. const SESSION_HEADERS: [&str; 4] = ["session_id", "x-session-id", "conversation_id", "x-conversation-id"]; #[derive(Clone, Debug, Default)] struct DoneInfo { prompt_tokens: u64, cached_tokens: u64, output_tokens: u64, decode_ms: f64, finish: &'static str, disconnected: bool, } struct Live { id: String, sid: Option, endpoint: usize, stream: Option, model: Option, profile: Option, admitted: Instant, engine_start: Option, first_token: Option, done: Option, error: Option<(&'static str, String)>, http_status: Option, restart: bool, emitted: bool, memory: Option>, } /// One request's record while it is in flight. Shared by `Arc`; written once. pub struct ReqCtx { state: Mutex, clock: crate::ports::SharedClock, metrics: Arc, } /// What the request middleware leaves for the handler and the worker. #[derive(Clone, Default)] pub struct ObsHandle(pub Option>); tokio::task_local! { static CURRENT: Arc; } /// What the middleware needs from the application. #[derive(Clone)] pub struct Observe { pub model: Option, pub memory: Arc, pub clock: crate::ports::SharedClock, pub metrics: Arc, } /// Everything the line says, resolved. #[derive(Debug, Clone, PartialEq)] pub struct Record { pub id: String, pub sid: Option, pub endpoint: usize, pub stream: Option, pub model: Option, pub profile: Option, pub status: Option, pub outcome: &'static str, pub prompt_tokens: Option, pub cached_tokens: Option, pub output_tokens: Option, pub queue_ms: Option, pub ttft_ms: Option, pub prefill_tps: Option, pub decode_tps: Option, pub total_ms: u64, pub restart: bool, pub error_class: &'static str, pub error: Option, pub hardware: Option, } pub struct RequestMetrics { requests: Vec, errors: Vec, restarts: AtomicU64, engine_lost: AtomicU64, engine_attached: AtomicU64, ttft: Histogram, duration: Histogram, queue: Histogram, prompt_tokens: Histogram, output_tokens: Histogram, decode_tps: Histogram, prefill_tps: Histogram, } impl Default for RequestMetrics { fn default() -> Self { Self { requests: (0..ENDPOINTS.len() * OUTCOMES.len()).map(|_| AtomicU64::new(0)).collect(), errors: (0..ERROR_CLASSES.len()).map(|_| AtomicU64::new(0)).collect(), restarts: AtomicU64::new(0), engine_lost: AtomicU64::new(0), engine_attached: AtomicU64::new(0), ttft: Histogram::new(&[0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0]), duration: Histogram::new(&[0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0, 1800.0]), queue: Histogram::new(&[0.001, 0.01, 0.1, 0.5, 1.0, 5.0, 15.0, 60.0]), prompt_tokens: Histogram::new(&[256.0, 1024.0, 4096.0, 16384.0, 65536.0, 131072.0, 262144.0]), output_tokens: Histogram::new(&[16.0, 64.0, 256.0, 1024.0, 4096.0, 16384.0, 65536.0]), decode_tps: Histogram::new(&[5.0, 10.0, 20.0, 40.0, 60.0, 80.0, 100.0, 150.0]), prefill_tps: Histogram::new(&[100.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, 16000.0]), } } } #[cfg(test)] mod tests; mod request_context; #[allow(unused_imports)] pub use request_context::*; mod observation; #[allow(unused_imports)] pub use observation::*; mod metrics_text; #[allow(unused_imports)] pub use metrics_text::*;