The request middleware, the backend worker and the metrics handler now share one RequestMetrics value that Services holds, so the LazyLock registry of request_log.rs and its architecture.json exception are gone. The middleware gets it through Observe, the worker through BackendWorkerConfig, and prometheus::render takes it as an argument; the counters, histograms, labels and log lines are unchanged, and the unit tests now count into a registry of their own instead of one shared by the whole test process.
179 lines
6.0 KiB
Rust
179 lines
6.0 KiB
Rust
//! 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<String>,
|
|
endpoint: usize,
|
|
stream: Option<bool>,
|
|
model: Option<String>,
|
|
profile: Option<String>,
|
|
admitted: Instant,
|
|
engine_start: Option<Instant>,
|
|
first_token: Option<Instant>,
|
|
done: Option<DoneInfo>,
|
|
error: Option<(&'static str, String)>,
|
|
http_status: Option<u16>,
|
|
restart: bool,
|
|
emitted: bool,
|
|
memory: Option<Arc<crate::memory_view::MemoryView>>,
|
|
}
|
|
|
|
/// One request's record while it is in flight. Shared by `Arc`; written once.
|
|
pub struct ReqCtx {
|
|
state: Mutex<Live>,
|
|
clock: crate::ports::SharedClock,
|
|
metrics: Arc<RequestMetrics>,
|
|
}
|
|
|
|
/// What the request middleware leaves for the handler and the worker.
|
|
#[derive(Clone, Default)]
|
|
pub struct ObsHandle(pub Option<Arc<ReqCtx>>);
|
|
|
|
tokio::task_local! {
|
|
static CURRENT: Arc<ReqCtx>;
|
|
}
|
|
|
|
/// What the middleware needs from the application.
|
|
#[derive(Clone)]
|
|
pub struct Observe {
|
|
pub model: Option<String>,
|
|
pub memory: Arc<crate::memory_view::MemoryView>,
|
|
pub clock: crate::ports::SharedClock,
|
|
pub metrics: Arc<RequestMetrics>,
|
|
}
|
|
|
|
/// Everything the line says, resolved.
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct Record {
|
|
pub id: String,
|
|
pub sid: Option<String>,
|
|
pub endpoint: usize,
|
|
pub stream: Option<bool>,
|
|
pub model: Option<String>,
|
|
pub profile: Option<String>,
|
|
pub status: Option<u16>,
|
|
pub outcome: &'static str,
|
|
pub prompt_tokens: Option<u64>,
|
|
pub cached_tokens: Option<u64>,
|
|
pub output_tokens: Option<u64>,
|
|
pub queue_ms: Option<u64>,
|
|
pub ttft_ms: Option<u64>,
|
|
pub prefill_tps: Option<f64>,
|
|
pub decode_tps: Option<f64>,
|
|
pub total_ms: u64,
|
|
pub restart: bool,
|
|
pub error_class: &'static str,
|
|
pub error: Option<String>,
|
|
pub hardware: Option<crate::memory_view::Brief>,
|
|
}
|
|
|
|
pub struct RequestMetrics {
|
|
requests: Vec<AtomicU64>,
|
|
errors: Vec<AtomicU64>,
|
|
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::*;
|