Files
leleka/control-plane/src/request_log.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 92fd4c636c observability: middleware test, display scrub in leleka logs, engine line fields in leleka-memory, keep "fatal:" in the supervisor's message
* request_log: a test drives the real `observe` layer over HTTP (id header, session header hashed, rejection counted).
* leleka logs scrubs credentials once more on display (lines written by other programs or older builds).
* the engine's per-request line is built by leleka_memory::telemetry::request_line_fields (pure, tested for content and size: 313 bytes);
  the tier share of one request is tier_shares().
* the supervisor's fatal event keeps the "fatal: " text in its message, which crates/deploy/tests/e2e.rs and operators' greps rely on
  (crates/deploy e2e on Linux: an_engine_that_cannot_start_fails_the_service_and_names_the_log passes again).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 23:30:32 +01:00

804 lines
31 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 [`render_prometheus`], whose labels are enums of
//! fixed size (endpoint x outcome, error class): there is no label whose value comes from a client.
use std::{
fmt::Write as _,
sync::{
Arc, LazyLock, Mutex,
atomic::{AtomicU64, Ordering},
},
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"];
pub fn endpoint_index(path: &str) -> usize {
match path {
"/v1/responses" => 0,
"/v1/chat/completions" => 1,
"/v1/messages" => 2,
_ => 3,
}
}
/// The session id of the log: a short digest of what the client sent, so lines of one conversation correlate and the
/// client's own identifier (which could be a user id) is not written down.
pub fn session_tag(headers: &HeaderMap) -> Option<String> {
let raw = SESSION_HEADERS.iter().find_map(|name| headers.get(*name)).and_then(|v| v.to_str().ok()).map(str::trim).filter(|v| !v.is_empty())?;
let digest = Sha256::digest(raw.as_bytes());
Some(format!("s-{}", hex::encode(&digest[..5])))
}
/// A short error class and whether the message is our own wording (safe to log) rather than something that might echo input.
pub fn classify_error(message: &str) -> (&'static str, bool) {
let m = message;
if m.starts_with("engine made no progress") {
("stall", true)
} else if m.contains("exceeded configured execution deadline") {
("deadline", true)
} else if m.contains("memory_pressure") {
("memory_pressure", true)
} else if m.starts_with("engine refused the generation") {
("engine_refused", true)
} else if m.starts_with("engine stream ended") || m.contains("without a terminal event") {
("stream_ended", true)
} else if m.starts_with("engine did not terminate the generation") {
("cancel_timeout", true)
} else if m.contains("worker is restarting") || m.contains("not attached to the engine") || m.contains("runtime restarted") || m.contains("stopped before completing") {
("engine_lost", true)
} else {
("other", false)
}
}
/// The class of a rejection by HTTP status (a request that never reached the engine).
pub fn class_of_status(status: u16) -> &'static str {
match status {
400 | 404 | 405 | 413 | 415 | 422 => "bad_request",
429 => "overloaded",
503 => "unavailable",
_ => "other",
}
}
#[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>,
}
impl ReqCtx {
pub fn new(id: String, endpoint: usize, sid: Option<String>, model: Option<String>, memory: Option<Arc<crate::memory_view::MemoryView>>) -> Self {
Self {
state: Mutex::new(Live {
id,
sid,
endpoint,
stream: None,
model,
profile: std::env::var("LELEKA_PROFILE").ok().filter(|p| !p.is_empty()),
admitted: Instant::now(),
engine_start: None,
first_token: None,
done: None,
error: None,
http_status: None,
restart: false,
emitted: false,
memory,
}),
}
}
fn with<T>(&self, f: impl FnOnce(&mut Live) -> T) -> Option<T> {
self.state.lock().ok().map(|mut s| f(&mut s))
}
pub fn id(&self) -> String {
self.with(|s| s.id.clone()).unwrap_or_default()
}
pub fn set_stream(&self, stream: bool) {
self.with(|s| s.stream = Some(stream));
}
pub fn set_http_status(&self, status: u16) {
self.with(|s| s.http_status = Some(status));
}
/// The worker handed the request to the engine: the queue wait ends.
pub fn engine_start(&self) {
self.with(|s| {
s.engine_start.get_or_insert_with(Instant::now);
});
}
pub fn first_token(&self) {
self.with(|s| {
s.first_token.get_or_insert_with(Instant::now);
});
}
pub fn done(&self, done: &Done, disconnected: bool) {
self.with(|s| {
s.done = Some(DoneInfo {
prompt_tokens: done.prompt_tokens,
cached_tokens: done.reused.unwrap_or(0),
output_tokens: done.generated,
decode_ms: done.decode_ms,
finish: match done.finish {
Finish::Stop => "stop",
Finish::Length => "length",
Finish::Cancel => "cancel",
},
disconnected,
});
});
}
pub fn error(&self, message: &str) {
let (class, ours) = classify_error(message);
let shown = if ours { leleka_obs::redact::clip(message, 160).to_owned() } else { format!("{} bytes", message.len()) };
self.with(|s| {
if s.error.is_none() {
s.error = Some((class, shown));
}
});
}
/// The engine was lost while this request was in flight.
pub fn engine_restarted(&self) {
self.with(|s| s.restart = true);
}
/// Write the record now (once).
pub fn finalize(&self) {
let record = self.with(|s| {
if s.emitted {
return None;
}
s.emitted = true;
Some(Record::from_state(s))
});
if let Some(Some(record)) = record {
record.publish();
}
}
}
impl Drop for ReqCtx {
fn drop(&mut self) {
let record = match self.state.get_mut() {
Ok(state) if !state.emitted => {
state.emitted = true;
Some(Record::from_state(state))
}
_ => None,
};
if let Some(record) = record {
record.publish();
}
}
}
/// What the request middleware leaves for the handler and the worker.
#[derive(Clone, Default)]
pub struct ObsHandle(pub Option<Arc<ReqCtx>>);
impl std::fmt::Debug for ObsHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("ObsHandle")
}
}
impl PartialEq for ObsHandle {
/// Never part of a request's identity.
fn eq(&self, _: &Self) -> bool {
true
}
}
tokio::task_local! {
static CURRENT: Arc<ReqCtx>;
}
impl ObsHandle {
/// The request being served by the current task, if the `observe` middleware wrapped it.
pub fn current() -> Self {
Self(CURRENT.try_with(Arc::clone).ok())
}
pub fn id(&self) -> Option<String> {
self.0.as_ref().map(|c| c.id())
}
pub fn set_stream(&self, stream: bool) {
if let Some(c) = &self.0 {
c.set_stream(stream);
}
}
pub fn engine_start(&self) {
if let Some(c) = &self.0 {
c.engine_start();
}
}
pub fn first_token(&self) {
if let Some(c) = &self.0 {
c.first_token();
}
}
pub fn done(&self, done: &Done, disconnected: bool) {
if let Some(c) = &self.0 {
c.done(done, disconnected);
}
}
pub fn error(&self, message: &str) {
if let Some(c) = &self.0 {
c.error(message);
}
}
pub fn engine_restarted(&self) {
if let Some(c) = &self.0 {
c.engine_restarted();
}
}
pub fn finalize(&self) {
if let Some(c) = &self.0 {
c.finalize();
}
}
}
/// What the middleware needs from the application.
#[derive(Clone)]
pub struct Observe {
pub model: Option<String>,
pub memory: Arc<crate::memory_view::MemoryView>,
}
/// Outermost layer of the three generation routes: gives the request an id (and a response header carrying it), reads the
/// session header, and keeps the record for the handler. A rejection (status 4xx/5xx before the engine) is recorded here.
pub async fn observe(State(observe): State<Observe>, request: Request, next: Next) -> Response {
let endpoint = endpoint_index(request.uri().path());
let ctx = Arc::new(ReqCtx::new(
uuid::Uuid::new_v4().to_string(),
endpoint,
session_tag(request.headers()),
observe.model.clone(),
Some(observe.memory.clone()),
));
let id = ctx.id();
let mut response = CURRENT.scope(ctx.clone(), next.run(request)).await;
ctx.set_http_status(response.status().as_u16());
if let Ok(value) = HeaderValue::from_str(&id) {
response.headers_mut().insert(REQUEST_ID_HEADER, value);
}
response
}
/// 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>,
}
fn round1(v: f64) -> f64 {
(v * 10.0).round() / 10.0
}
impl Record {
fn from_state(s: &Live) -> Record {
let now = Instant::now();
let ms = |from: Instant, to: Instant| u64::try_from(to.saturating_duration_since(from).as_millis()).unwrap_or(u64::MAX);
let queue_ms = s.engine_start.map(|t| ms(s.admitted, t));
let ttft_ms = s.first_token.map(|t| ms(s.admitted, t));
let (prompt_tokens, cached_tokens, output_tokens) = match &s.done {
Some(d) => (Some(d.prompt_tokens), Some(d.cached_tokens), Some(d.output_tokens)),
None => (None, None, None),
};
let prefill_tps = match (&s.done, s.engine_start, s.first_token) {
(Some(d), Some(start), Some(first)) => {
let fresh = d.prompt_tokens.saturating_sub(d.cached_tokens);
let secs = first.saturating_duration_since(start).as_secs_f64();
(fresh > 0 && secs > 0.0).then(|| round1(fresh as f64 / secs))
}
_ => None,
};
let decode_tps = s
.done
.as_ref()
.and_then(|d| (d.output_tokens > 1).then(|| crate::metrics::token_rate(d.output_tokens, d.decode_ms)).flatten())
.map(round1);
let http_failed = s.http_status.is_some_and(|c| c >= 400);
let outcome = match (&s.done, &s.error) {
(Some(d), _) if d.disconnected => "disconnect",
(Some(d), _) => d.finish,
(None, Some(_)) if s.engine_start.is_some() => "error",
(None, Some(_)) => "rejected",
(None, None) if http_failed => "rejected",
(None, None) => "abandoned",
};
let (error_class, error) = match (&s.error, http_failed, outcome) {
(Some((class, text)), _, _) => (*class, Some(text.clone())),
(None, true, _) => (class_of_status(s.http_status.unwrap_or(0)), None),
_ => ("none", None),
};
Record {
id: s.id.clone(),
sid: s.sid.clone(),
endpoint: s.endpoint,
stream: s.stream,
model: s.model.clone(),
profile: s.profile.clone(),
status: s.http_status,
outcome,
prompt_tokens,
cached_tokens,
output_tokens,
queue_ms,
ttft_ms,
prefill_tps,
decode_tps,
total_ms: ms(s.admitted, now),
restart: s.restart,
error_class,
error,
hardware: s.memory.as_ref().and_then(|m| m.brief()),
}
}
/// The fields of the line, in order. A figure that was not measured is left out (a missing key means unknown), which
/// also keeps the line short.
pub fn fields(&self) -> Vec<leleka_obs::Field<'_>> {
let mut f: Vec<leleka_obs::Field<'_>> = Vec::with_capacity(28);
macro_rules! put {
($key:expr, $value:expr) => {{
let value: V<'_> = $value;
if !matches!(value, V::Null) {
f.push(($key, value));
}
}};
}
put!("rid", V::Str(&self.id));
put!("sid", self.sid.as_deref().into());
put!("ep", V::Str(ENDPOINTS[self.endpoint]));
put!("stream", self.stream.into());
put!("model", self.model.as_deref().into());
put!("prof", self.profile.as_deref().into());
put!("http", self.status.map(u64::from).into());
put!("fin", V::Str(self.outcome));
put!("ptok", self.prompt_tokens.into());
put!("ctok", self.cached_tokens.into());
put!("otok", self.output_tokens.into());
put!("q_ms", self.queue_ms.into());
put!("ttft_ms", self.ttft_ms.into());
put!("pf_tps", self.prefill_tps.into());
put!("dec_tps", self.decode_tps.into());
put!("ms", V::UInt(self.total_ms));
put!("restart", V::Bool(self.restart));
put!("err", V::Str(self.error_class));
put!("err_msg", self.error.as_deref().into());
if let Some(h) = &self.hardware {
put!("gpu_mhz", h.sm_clock_mhz.into());
put!("gpu_c", h.temp_c.into());
put!("thr", h.throttle.into());
put!("mem", h.gate.as_deref().into());
put!("ram_free_mb", h.ram_available_mib.into());
}
f
}
fn publish(&self) {
REGISTRY.observe(self);
leleka_obs::record("api", "request", &self.fields());
}
}
struct Registry {
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,
}
static REGISTRY: LazyLock<Registry> = LazyLock::new(|| Registry {
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]),
});
impl Registry {
fn observe(&self, r: &Record) {
let outcome = OUTCOMES.iter().position(|o| *o == r.outcome).unwrap_or(OUTCOMES.len() - 1);
self.requests[r.endpoint * OUTCOMES.len() + outcome].fetch_add(1, Ordering::Relaxed);
if r.error_class != "none" {
let class = ERROR_CLASSES.iter().position(|c| *c == r.error_class).unwrap_or(ERROR_CLASSES.len() - 1);
self.errors[class].fetch_add(1, Ordering::Relaxed);
}
if r.restart {
self.restarts.fetch_add(1, Ordering::Relaxed);
}
self.duration.observe(r.total_ms as f64 / 1000.0);
if let Some(q) = r.queue_ms {
self.queue.observe(q as f64 / 1000.0);
}
if let Some(t) = r.ttft_ms {
self.ttft.observe(t as f64 / 1000.0);
}
if let Some(p) = r.prompt_tokens {
self.prompt_tokens.observe(p as f64);
}
if let Some(o) = r.output_tokens {
self.output_tokens.observe(o as f64);
}
if let Some(v) = r.decode_tps {
self.decode_tps.observe(v);
}
if let Some(v) = r.prefill_tps {
self.prefill_tps.observe(v);
}
}
}
/// The worker lost the engine (a structured warning is logged; the count feeds `leleka_engine_lost_total`).
pub fn note_engine_lost(reason: &str) {
REGISTRY.engine_lost.fetch_add(1, Ordering::Relaxed);
leleka_obs::warn("api", "engine_lost", &[("reason", reason.into())]);
}
/// The worker attached to a loaded engine (at start and after every restart).
pub fn note_engine_attached() {
let n = REGISTRY.engine_attached.fetch_add(1, Ordering::Relaxed) + 1;
leleka_obs::emit_always(leleka_obs::Level::Info, "api", "engine_attached", &[("attaches", n.into())]);
}
/// Append the request metrics in the Prometheus text format.
pub fn render_prometheus(out: &mut String) {
let reg = &*REGISTRY;
leleka_obs::hist::header("leleka_requests_total", "Generation requests by endpoint and how they ended.", "counter", out);
let mut any = false;
for (e, endpoint) in ENDPOINTS.iter().enumerate() {
for (o, outcome) in OUTCOMES.iter().enumerate() {
let n = reg.requests[e * OUTCOMES.len() + o].load(Ordering::Relaxed);
if n > 0 {
any = true;
let _ = writeln!(out, "leleka_requests_total{{endpoint=\"{endpoint}\",outcome=\"{outcome}\"}} {n}");
}
}
}
if !any {
let _ = writeln!(out, "leleka_requests_total{{endpoint=\"responses\",outcome=\"stop\"}} 0");
}
leleka_obs::hist::header("leleka_request_errors_total", "Failed or rejected requests by error class.", "counter", out);
for (c, class) in ERROR_CLASSES.iter().enumerate().skip(1) {
let n = reg.errors[c].load(Ordering::Relaxed);
let _ = writeln!(out, "leleka_request_errors_total{{class=\"{class}\"}} {n}");
}
leleka_obs::hist::header("leleka_engine_lost_total", "Times the API lost the engine (it restarted, hung or stopped answering).", "counter", out);
let _ = writeln!(out, "leleka_engine_lost_total {}", reg.engine_lost.load(Ordering::Relaxed));
leleka_obs::hist::header("leleka_engine_attached_total", "Times the API attached to a loaded engine (the first start counts).", "counter", out);
let _ = writeln!(out, "leleka_engine_attached_total {}", reg.engine_attached.load(Ordering::Relaxed));
leleka_obs::hist::header("leleka_requests_engine_restart_total", "Requests during which the engine was lost.", "counter", out);
let _ = writeln!(out, "leleka_requests_engine_restart_total {}", reg.restarts.load(Ordering::Relaxed));
reg.ttft.render("leleka_request_ttft_seconds", "Time from arrival to the first generated token.", out);
reg.duration.render("leleka_request_duration_seconds", "Time from arrival to the end of the request.", out);
reg.queue.render("leleka_request_queue_wait_seconds", "Time a request waited before the engine took it.", out);
reg.prompt_tokens.render("leleka_request_prompt_tokens", "Prompt tokens per request.", out);
reg.output_tokens.render("leleka_request_output_tokens", "Output tokens per request.", out);
reg.decode_tps.render("leleka_request_decode_tokens_per_second", "Decode rate per request.", out);
reg.prefill_tps.render("leleka_request_prefill_tokens_per_second", "Prefill rate per request (uncached prompt tokens).", out);
}
#[cfg(test)]
mod tests {
use super::*;
use leleka_obs::{Format, Level, Settings};
const JSON: Settings = Settings { min_level: Level::Info, format: Format::Json, debug: false, legacy: false };
fn done(line: &str) -> Done {
let crate::wire::Event::Done(done) = crate::wire::parse_line(line).unwrap().unwrap() else { panic!() };
done
}
fn record_of(ctx: &ReqCtx) -> Record {
let record = ctx.with(|s| Record::from_state(s)).unwrap();
ctx.with(|s| s.emitted = true); // do not publish from the test
record
}
fn line(record: &Record) -> String {
leleka_obs::format_line(&JSON, 1_793_613_072_345, Level::Info, "api", "request", &record.fields(), 0)
}
fn ctx() -> ReqCtx {
ReqCtx::new("0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d".into(), 0, Some("s-0123456789".into()), Some("qwen-iq3".into()), None)
}
#[test]
fn a_completed_request_has_the_figures_an_analysis_needs() {
let c = ctx();
c.set_stream(true);
c.engine_start();
std::thread::sleep(std::time::Duration::from_millis(15));
c.first_token();
c.done(&done("DONE 400 182341 900.0 5600.0 stop 0 0 181900"), false);
let r = record_of(&c);
assert_eq!(r.outcome, "stop");
assert_eq!((r.prompt_tokens, r.output_tokens), (Some(182341), Some(400)));
assert!(r.ttft_ms.unwrap() >= 15 && r.queue_ms.unwrap() < r.ttft_ms.unwrap());
assert!(r.prefill_tps.is_some() && r.decode_tps.is_some());
let text = line(&r);
for key in ["\"rid\":\"0b1c", "\"sid\":\"s-01", "\"ep\":\"responses\"", "\"stream\":true", "\"fin\":\"stop\"", "\"ptok\":182341", "\"otok\":400", "\"restart\":false", "\"err\":\"none\""] {
assert!(text.contains(key), "{key} missing: {text}");
}
}
#[test]
fn the_line_is_one_json_object_under_a_kilobyte_even_when_every_field_is_present() {
let mut r = Record {
id: "0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d".into(),
sid: Some("s-0123456789".into()),
endpoint: 2,
stream: Some(true),
model: Some("qwen3.8-flash-next-gsq-iq3".into()),
profile: Some("laptop-workstation".into()),
status: Some(200),
outcome: "disconnect",
prompt_tokens: Some(262_144),
cached_tokens: Some(262_000),
output_tokens: Some(65_536),
queue_ms: Some(123_456),
ttft_ms: Some(1_234_567),
prefill_tps: Some(16_000.5),
decode_tps: Some(149.9),
total_ms: 3_600_000,
restart: true,
error_class: "engine_refused",
error: Some("engine refused the generation: ".to_owned() + &"x".repeat(200)),
hardware: Some(crate::memory_view::Brief {
sm_clock_mhz: Some(2_850),
temp_c: Some(84),
throttle: Some(0x44),
gate: Some("normal".into()),
ram_available_mib: Some(120_000),
}),
};
let text = line(&r);
assert!(text.len() < 1024, "{} bytes: {text}", text.len());
assert!(!text.contains('\n') && text.starts_with('{') && text.ends_with('}'));
// a typical request is smaller still
r.error = None;
r.error_class = "none";
r.restart = false;
let typical = line(&r);
assert!(typical.len() < 700, "{}", typical.len());
// the volume estimate quoted in the report: bytes per request, worst case and typical (cargo test -- --nocapture)
eprintln!("RECORD-BYTES worst={} typical={}\nRECORD-SAMPLE {typical}", text.len(), typical.len());
}
#[test]
fn neither_prompt_text_nor_credentials_can_reach_the_line() {
leleka_obs::register_secret("sk-test-super-secret-key-0123456789");
let c = ctx();
c.engine_start();
// an engine error that echoes input is reduced to a length: it is not one of our own messages
c.error("tokenizer failed on: my password is sk-test-super-secret-key-0123456789 and the prompt text");
let r = record_of(&c);
let text = line(&r);
assert_eq!(r.error_class, "other");
assert!(!text.contains("sk-test") && !text.contains("password") && !text.contains("prompt text"), "{text}");
assert!(text.contains("\"err_msg\":\"91 bytes\""), "{text}");
// our own wording is kept
let c = ctx();
c.engine_start();
c.error("engine made no progress for 30 s during a request (stall watchdog)");
let r = record_of(&c);
assert_eq!(r.error_class, "stall");
assert!(line(&r).contains("engine made no progress"));
}
#[test]
fn rejections_abandonment_and_failures_are_told_apart() {
let c = ctx();
c.set_http_status(503);
assert_eq!(record_of(&c).outcome, "rejected");
assert_eq!(record_of(&c).error_class, "unavailable");
let c = ctx();
assert_eq!(record_of(&c).outcome, "abandoned");
let c = ctx();
c.engine_start();
c.error("engine stream ended without a terminal event");
c.engine_restarted();
let r = record_of(&c);
assert_eq!((r.outcome, r.error_class, r.restart), ("error", "stream_ended", true));
let c = ctx();
c.engine_start();
c.done(&done("DONE 3 10 1.0 4.0 stop"), true);
assert_eq!(record_of(&c).outcome, "disconnect");
}
#[test]
fn the_record_is_published_once() {
let c = ctx();
c.finalize();
c.finalize();
assert_eq!(c.with(|s| s.emitted), Some(true));
}
#[test]
fn the_session_header_is_hashed_not_copied() {
let mut headers = HeaderMap::new();
assert_eq!(session_tag(&headers), None);
headers.insert("session_id", HeaderValue::from_static("user-4417-conversation"));
let tag = session_tag(&headers).unwrap();
assert!(tag.starts_with("s-") && tag.len() == 12 && !tag.contains("4417"), "{tag}");
assert_eq!(session_tag(&headers).unwrap(), tag);
}
fn counted(endpoint: &str, outcome: &str) -> u64 {
let mut text = String::new();
render_prometheus(&mut text);
let prefix = format!("leleka_requests_total{{endpoint=\"{endpoint}\",outcome=\"{outcome}\"}} ");
text.lines().find_map(|l| l.strip_prefix(prefix.as_str())).and_then(|n| n.parse().ok()).unwrap_or(0)
}
#[tokio::test]
async fn the_middleware_names_the_request_hands_it_to_the_handler_and_records_a_rejection() {
let observe = Observe { model: Some("m".into()), memory: Arc::new(Default::default()) };
let app = axum::Router::new()
.route(
"/v1/chat/completions",
axum::routing::post(|| async {
let handle = ObsHandle::current();
assert!(handle.0.is_some(), "the handler must see the request's record");
handle.set_stream(false);
(axum::http::StatusCode::SERVICE_UNAVAILABLE, "busy")
}),
)
.layer(axum::middleware::from_fn_with_state(observe, super::observe));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}/v1/chat/completions", listener.local_addr().unwrap());
let server = tokio::spawn(async move { axum::serve(listener, app).await });
let before = counted("chat", "rejected");
let response = reqwest::Client::new().post(url).header("session_id", "conv-4417").body("{}").send().await.unwrap();
assert_eq!(response.status(), 503);
let id = response.headers()[REQUEST_ID_HEADER].to_str().unwrap().to_owned();
assert!(uuid::Uuid::parse_str(&id).is_ok(), "{id}");
assert!(!id.contains("4417"));
// the record is written when the last reference to it is gone, just after the response
let mut after = before;
for _ in 0..50 {
after = counted("chat", "rejected");
if after > before {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
assert!(after > before, "the rejection must be counted: {before} -> {after}");
server.abort();
}
#[test]
fn the_prometheus_text_has_fixed_labels_and_valid_lines() {
let c = ctx();
c.engine_start();
c.first_token();
c.done(&done("DONE 10 100 5.0 100.0 length"), false);
record_of(&c).publish();
let mut text = String::new();
render_prometheus(&mut text);
assert!(text.contains("leleka_requests_total{endpoint=\"responses\",outcome=\"length\"}"), "{text}");
assert!(text.contains("# TYPE leleka_request_ttft_seconds histogram"));
for line in text.lines() {
assert!(line.starts_with("# HELP ") || line.starts_with("# TYPE ") || line.starts_with("leleka_"), "{line}");
assert!(!line.contains("0b1c2d3e"), "no request id in a metric: {line}");
}
}
}