Tests become directory modules named after what they test, with a shared fixtures/harness module:
control-plane/src/{responses,ggml_bridge,gguf_f32_stream,prepare_preview}/tests/, desktop-core/src/runtime_rpc/tests/;
integration targets become tests/<name>/main.rs plus topic modules and a harness (backend_worker_http, vision_http,
memory_gate_http, tool_corpus, mcp_hub, api_over_runtime, runtime_gateway_sdet, native_tools_sdet,
native_tools_retry_sdet, managed_worker, gateway); target names are unchanged. Sources: leleka-inference.rs becomes
src/bin/leleka-inference/ (main.rs plus one module per operator option group), the cp_replay example becomes
examples/cp_replay/, and the tonic service impl of runtime_rpc delegates to session_rpc, model_rpc and generate_rpc
(bodies unchanged). impl_* modules are renamed after what they hold (base_provenance, count_tokens, manifest_fetch,
fetcher, record, capture, in_flight, tool_policy, tool_plan, server). The self-spawning tests that name themselves
(credential_child, the managed worker fixture) use the new module path or stay at the target root.
Test ids: 543 before and after in both crates (strata-control, strata-desktop-core, --all-targets), 0 missing, 0 new,
0 outcome changes; 241 ids differ only in the module path. Warnings in the two crates: 0 before and after.
Counts (strata-control / strata-desktop-core): oversize files 19 -> 0 (13 + 6). Functions over 30 lines, complexity 10,
nesting 4, wide lines, prod: 187/135/17/199 -> 187/135/17/196 and 81/59/6/54 -> 81/59/6/54; test: 214/17/30/133 ->
214/17/30/133 and 65/3/3/30 -> 65/3/3/27. The 211 functions that moved verbatim are in limits-allowlist.json (owner
STRA-338) because the diff gate treats a moved function as added; the entries fall as the functions are shortened.
274 lines
11 KiB
Rust
274 lines
11 KiB
Rust
//! The request monitor and the metrics endpoint.
|
|
|
|
use crate::harness::{Stack, body, usage};
|
|
use leleka_backend_api::scripted::Script;
|
|
use serde_json::{Value, json};
|
|
|
|
/// The telemetry document an engine publishes (`leleka-memory`'s `telemetry.rs`), as the worker copies it into the view.
|
|
fn engine_telemetry() -> String {
|
|
json!({
|
|
"version": 1, "phase": "idle", "request": null,
|
|
"gpu": {"index": 0, "util_pct": 91, "mem_util_pct": 40, "vram_used_mib": 30000, "vram_total_mib": 32607,
|
|
"power_w": 480.5, "sm_clock_mhz": 2900, "temp_c": 61, "name": "NVIDIA GeForce RTX 5090"},
|
|
"ram": {"total_mib": 122880, "available_mib": 70000, "process_rss_mib": 55000, "process_pinned_mib": 3000, "swap_used_mib": 0},
|
|
"cpu": {"cores": 32, "process_busy_cores": 7.4, "system_busy_pct": 31.0},
|
|
"throughput": {"decode_tok_s_last": 100.0, "decode_tok_s_avg": 100.0, "decode_tok_s_lifetime": 100.0, "decode_tok_s_live": null,
|
|
"prefill_tok_s_last": 5050.0, "prefill_tok_s_avg": 5050.0, "prefill_tok_s_lifetime": 5000.0},
|
|
"cache": {"requests": 2, "hit_requests": 1, "hit_ratio": 0.5, "prompt_tokens": 201000, "reused_tokens": 80000, "token_hit_ratio": 0.398, "last_prompt_tokens": 101000, "last_reused_tokens": 0},
|
|
"context": {"live_tokens": 101200, "max_tokens": 262144, "used_pct": 38.6},
|
|
"settings": {"context_tokens": 262144},
|
|
})
|
|
.to_string()
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn the_request_monitor_records_prompts_answers_and_usage_in_the_three_dialects() {
|
|
let stack = Stack::start_monitored("bw-monitor").await;
|
|
let parse = |body: &str| -> Value { serde_json::from_str(body).unwrap() };
|
|
assert_eq!(
|
|
parse(&stack.get("/api/requests").await.1)["requests"]
|
|
.as_array()
|
|
.unwrap()
|
|
.len(),
|
|
0
|
|
);
|
|
|
|
stack
|
|
.engine
|
|
.push(Script::stop_with(&["hel", "lo"], usage(7, 2, 0)));
|
|
let chat =
|
|
json!({"model": "fixture", "messages": [{"role": "user", "content": "say <b>hi</b>"}]});
|
|
assert_eq!(stack.post("/v1/chat/completions", &chat).await.0, 200);
|
|
stack
|
|
.engine
|
|
.push(Script::stop_with(&["str", "eam"], usage(7, 2, 0)));
|
|
let streamed = json!({"model": "fixture", "stream": true, "stream_options": {"include_usage": true}, "messages": [{"role": "user", "content": "go"}]});
|
|
assert_eq!(stack.post("/v1/chat/completions", &streamed).await.0, 200);
|
|
stack
|
|
.engine
|
|
.push(Script::stop_with(&["res", "p"], usage(4, 2, 1)));
|
|
assert_eq!(
|
|
stack
|
|
.post("/v1/responses", &body(json!({"stream": true})))
|
|
.await
|
|
.0,
|
|
200
|
|
);
|
|
stack
|
|
.engine
|
|
.push(Script::stop_with(&["whole"], usage(4, 1, 0)));
|
|
assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200);
|
|
// a refused request is recorded as an error with its status, not as a success
|
|
let (status, _) = stack
|
|
.post(
|
|
"/v1/responses",
|
|
&json!({"model": "fixture", "input": "x", "bogus": 1}),
|
|
)
|
|
.await;
|
|
assert!(status >= 400);
|
|
|
|
let listed = parse(&stack.get("/api/requests").await.1);
|
|
assert_eq!(listed["retention"], 100);
|
|
assert_eq!(listed["persistent"], false);
|
|
assert_eq!(listed["loaded"], true);
|
|
let rows = listed["requests"].as_array().unwrap();
|
|
assert_eq!(rows.len(), 5);
|
|
// newest first: the refusal, then the buffered Responses, the streamed Responses, the streamed Chat, the buffered Chat
|
|
assert_eq!(rows[0]["state"], "error");
|
|
assert!(rows[0]["http_status"].as_u64().unwrap() >= 400);
|
|
let expected = [
|
|
("/v1/responses", "whole"),
|
|
("/v1/responses", "resp"),
|
|
("/v1/chat/completions", "stream"),
|
|
("/v1/chat/completions", "hello"),
|
|
];
|
|
for (row, (path, output)) in rows[1..].iter().zip(expected) {
|
|
assert_eq!(row["path"], path);
|
|
assert_eq!(row["state"], "completed", "{row}");
|
|
assert_eq!(row["http_status"], 200);
|
|
assert!(
|
|
row.get("input").is_none() && row.get("output").is_none(),
|
|
"summaries carry no payload"
|
|
);
|
|
assert!(row["wallclock_s"].as_f64().unwrap() >= row["first_token_s"].as_f64().unwrap());
|
|
let detail = parse(
|
|
&stack
|
|
.get(&format!("/api/requests?id={}", row["id"].as_str().unwrap()))
|
|
.await
|
|
.1,
|
|
);
|
|
assert_eq!(detail["output"], output, "{detail}");
|
|
assert!(
|
|
detail["input"]
|
|
.as_str()
|
|
.unwrap()
|
|
.contains("\"model\": \"fixture\"")
|
|
);
|
|
assert!(detail["usage"].is_object(), "{detail}");
|
|
assert_eq!(detail["model"], "fixture");
|
|
}
|
|
let streamed_chat = parse(
|
|
&stack
|
|
.get(&format!(
|
|
"/api/requests?id={}",
|
|
rows[3]["id"].as_str().unwrap()
|
|
))
|
|
.await
|
|
.1,
|
|
);
|
|
assert_eq!(streamed_chat["stream"], true);
|
|
assert!(
|
|
streamed_chat.get("response").is_none(),
|
|
"a stream has no single response body"
|
|
);
|
|
let buffered_chat = parse(
|
|
&stack
|
|
.get(&format!(
|
|
"/api/requests?id={}",
|
|
rows[4]["id"].as_str().unwrap()
|
|
))
|
|
.await
|
|
.1,
|
|
);
|
|
assert_eq!(
|
|
parse(buffered_chat["response"].as_str().unwrap())["choices"][0]["message"]["content"],
|
|
"hello"
|
|
);
|
|
assert!(
|
|
buffered_chat["input"]
|
|
.as_str()
|
|
.unwrap()
|
|
.contains("say <b>hi</b>")
|
|
);
|
|
assert_eq!(stack.get("/api/requests?id=missing").await.0, 404);
|
|
stack.finish().await;
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn the_request_monitor_is_off_by_default_and_keeps_nothing() {
|
|
let stack = Stack::start("bw-monitor-off").await;
|
|
stack.engine.push(Script::stop_with(&["x"], usage(2, 1, 0)));
|
|
assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200);
|
|
let (status, text) = stack.get("/api/requests").await;
|
|
assert_eq!(status, 404, "{text}");
|
|
assert_eq!(stack.get("/api/requests?id=anything").await.0, 404);
|
|
assert!(stack.state.services.monitor.summaries().is_empty());
|
|
let metrics: Value = serde_json::from_str(&stack.get("/metrics").await.1).unwrap();
|
|
assert_eq!(metrics["engine"]["api_monitor"], false);
|
|
// an engine that publishes no telemetry (yet): empty hardware blocks, no raw document, the rest of the document intact
|
|
assert_eq!(metrics["hardware"], json!({}));
|
|
assert_eq!(metrics["hardware_static"], json!({}));
|
|
assert!(metrics["telemetry"].is_null());
|
|
assert_eq!(metrics["requests_kept"], 1);
|
|
stack.finish().await;
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn metrics_carry_the_python_monitor_members_and_a_prometheus_view() {
|
|
let stack = Stack::start("bw-metrics-monitor").await;
|
|
stack
|
|
.state
|
|
.model
|
|
.memory
|
|
.set_telemetry(Some(engine_telemetry()));
|
|
stack
|
|
.engine
|
|
.push(Script::stop_with(&["a", "b"], usage(10, 2, 4)));
|
|
assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200);
|
|
stack.engine.push(Script::stop_with(&["c"], usage(6, 1, 0)));
|
|
assert_eq!(stack.post("/v1/responses", &body(json!({}))).await.0, 200);
|
|
|
|
let metrics: Value = serde_json::from_str(&stack.get("/metrics").await.1).unwrap();
|
|
// the native members are untouched
|
|
assert_eq!(metrics["schema_version"], 1);
|
|
assert_eq!(metrics["generation"]["completed"], 2);
|
|
// the Python Monitor members
|
|
assert_eq!(metrics["engine"]["model"], "fixture");
|
|
assert_eq!(metrics["engine"]["max_context"], 262_144);
|
|
assert_eq!(metrics["engine"]["images"], false);
|
|
assert_eq!(metrics["live"]["state"], "idle");
|
|
assert_eq!(metrics["live"]["queued"], 0);
|
|
assert_eq!(metrics["requests_kept"], 2);
|
|
let requests = metrics["requests"].as_array().unwrap();
|
|
assert_eq!(requests.len(), 2);
|
|
assert_eq!(requests[0]["prompt_tokens"], 6);
|
|
assert_eq!(requests[1]["prompt_tokens"], 10);
|
|
assert_eq!(requests[1]["reused"], 4);
|
|
assert_eq!(requests[1]["output_tokens"], 2);
|
|
assert_eq!(requests[1]["finish"], "stop");
|
|
assert_eq!(metrics["totals"]["requests"], 2);
|
|
assert_eq!(metrics["totals"]["prompt_tokens"], 16);
|
|
assert_eq!(metrics["totals"]["reused"], 4);
|
|
assert_eq!(metrics["totals"]["output_tokens"], 3);
|
|
assert_eq!(metrics["hardware"]["gpu_util"], 91);
|
|
assert_eq!(metrics["hardware"]["gpu_mem_used"], 30000u64 * 1_048_576);
|
|
assert_eq!(metrics["hardware"]["gpu_temp"], 61);
|
|
assert_eq!(metrics["hardware"]["tok_s"], 0.0);
|
|
assert_eq!(
|
|
metrics["hardware_static"]["gpu_name"],
|
|
"NVIDIA GeForce RTX 5090"
|
|
);
|
|
assert_eq!(metrics["history"]["gpu_util"].as_array().unwrap().len(), 1);
|
|
assert!(metrics["time"].as_f64().unwrap() > 1.0e9);
|
|
assert_eq!(metrics["telemetry"]["context"]["max_tokens"], 262_144);
|
|
// `?requests=all` lists everything kept (here the same two)
|
|
let all: Value = serde_json::from_str(&stack.get("/metrics?requests=all").await.1).unwrap();
|
|
assert_eq!(all["requests"].as_array().unwrap().len(), 2);
|
|
|
|
// Prometheus text: by query and by the Accept header a scraper sends
|
|
let scrape = |accept: Option<&str>, query: &str| {
|
|
let mut request = stack.client.get(format!("{}/metrics{query}", stack.base));
|
|
if let Some(accept) = accept {
|
|
request = request.header("accept", accept);
|
|
}
|
|
request
|
|
};
|
|
for (accept, query) in [
|
|
(None, "?format=prometheus"),
|
|
(
|
|
Some(
|
|
"application/openmetrics-text;version=1.0.0,text/plain;version=0.0.4;q=0.5,*/*;q=0.1",
|
|
),
|
|
"",
|
|
),
|
|
] {
|
|
let response = scrape(accept, query).send().await.unwrap();
|
|
assert_eq!(response.status(), 200);
|
|
assert!(
|
|
response.headers()["content-type"]
|
|
.to_str()
|
|
.unwrap()
|
|
.starts_with("text/plain; version=0.0.4")
|
|
);
|
|
let text = response.text().await.unwrap();
|
|
assert!(
|
|
text.contains("leleka_generations_completed_total 2\n"),
|
|
"{text}"
|
|
);
|
|
assert!(
|
|
text.contains("leleka_prompt_tokens_total 16\n")
|
|
&& text.contains("leleka_prompt_tokens_reused_total 4\n")
|
|
);
|
|
assert!(text.contains("leleka_generated_tokens_total 3\n"));
|
|
assert!(text.contains("leleka_up 1\n"));
|
|
assert!(text.contains("leleka_gpu_utilization_percent 91\n"));
|
|
assert!(text.contains("leleka_gpu_memory_used_bytes 31457280000\n"));
|
|
assert!(text.contains("leleka_gpu_temperature_celsius 61\n"));
|
|
assert!(
|
|
text.contains("leleka_host_memory_used_bytes 55448698880\n"),
|
|
"{text}"
|
|
);
|
|
assert!(
|
|
text.contains("leleka_context_live_tokens 101200\n")
|
|
&& text.contains("leleka_context_max_tokens 262144\n")
|
|
);
|
|
assert!(text.contains("leleka_prefix_cache_token_hit_ratio 0.398\n"));
|
|
assert!(text.contains("leleka_decode_tokens_per_second{window=\"average\"} 100\n"));
|
|
assert!(text.contains("leleka_engine_phase{phase=\"idle\"} 1\n"));
|
|
}
|
|
// a JSON client keeps getting JSON
|
|
let json_reply = scrape(Some("application/json"), "").send().await.unwrap();
|
|
assert_eq!(json_reply.headers()["content-type"], "application/json");
|
|
stack.finish().await;
|
|
}
|