Files
leleka/control-plane/src/request_log/tests.rs
T

343 lines
11 KiB
Rust

//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).
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, ctx.clock.now()))
.unwrap();
ctx.with(|s| s.emitted = true); // do not publish from the test
record
}
fn line(record: &Record) -> String {
leleka_obs::format_line(
&JSON,
leleka_obs::EventHead {
ts_ms: 1_793_613_072_345,
level: Level::Info,
comp: "api",
ev: "request",
},
&record.fields(),
0,
)
}
fn ctx() -> ReqCtx {
let identity = ReqIdentity {
id: "0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d".into(),
endpoint: 0,
sid: Some("s-0123456789".into()),
model: Some("qwen-iq3".into()),
};
ReqCtx::new(identity, None, crate::adapters::SystemClock::shared())
}
#[test]
fn the_record_stamps_come_from_the_injected_clock() {
let clock = crate::ports::fakes::ManualClock::new(1_700_000_000);
let identity = ReqIdentity {
id: "rid".into(),
endpoint: 0,
sid: None,
model: None,
};
let c = ReqCtx::new(identity, None, clock.clone());
clock.advance(std::time::Duration::from_millis(40));
c.engine_start();
clock.advance(std::time::Duration::from_millis(60));
c.first_token();
let r = record_of(&c);
assert_eq!((r.queue_ms, r.ttft_ms), (Some(40), Some(100)));
}
#[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}");
}
}
/// A record with every field present, at the largest sizes the line can take.
fn full_record() -> Record {
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),
}),
}
}
#[test]
fn the_line_is_one_json_object_under_a_kilobyte_even_when_every_field_is_present() {
let mut r = full_record();
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)
let _ = std::io::Write::write_fmt(
&mut std::io::stderr(),
format_args!(
"RECORD-BYTES worst={} typical={}\nRECORD-SAMPLE {typical}\n",
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)
}
/// A router whose handler asserts it sees the request's record and answers 503, behind the `observe` middleware.
fn rejecting_router() -> axum::Router {
let observe = Observe {
model: Some("m".into()),
memory: Arc::new(Default::default()),
clock: crate::adapters::SystemClock::shared(),
};
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,
))
}
/// Serves `rejecting_router` on a free port; returns its URL and the server task.
async fn serve_rejecting_handler() -> (String, tokio::task::JoinHandle<std::io::Result<()>>) {
let app = rejecting_router();
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 });
(url, server)
}
/// The rejected-chat count once it rises above `before`. The record is written when the last reference to it is gone,
/// just after the response.
async fn counted_after(before: u64) -> u64 {
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;
}
after
}
#[tokio::test]
async fn the_middleware_names_the_request_hands_it_to_the_handler_and_records_a_rejection() {
let (url, server) = serve_rejecting_handler().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"));
let after = counted_after(before).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}"
);
}
}