control-plane: the request counters of /metrics belong to Services, not a process cell (STRA-338)

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.
This commit is contained in:
Pavlo Ratushnyi
2026-11-24 03:44:23 +01:00
parent 128a6fb18b
commit 51a4eceff0
19 changed files with 178 additions and 148 deletions
-1
View File
@@ -152,7 +152,6 @@
{"crate": "leleka-backend-api", "file": "src/scripted.rs", "ratchet": "dyn-trait", "reason": "the scripted test engine stores the test's responder closure"},
{"crate": "leleka-gateway-domain", "file": "src/responses/schema.rs", "ratchet": "process-global", "reason": "kept: pure memo (not state): the validity of a tool schema keyed by its compact text, so the dozen schemas of a coding agent compile once, not three times per request; the result depends on the key alone, so no caller can observe the cache; a per-request owner would defeat it"},
{"crate": "leleka-gateway-text", "file": "src/prompt/renderer.rs", "ratchet": "process-global", "reason": "kept: the compiled pinned chat template is an immutable constant of the build, compiled on first use and read by every request; a pure memo of a constant"},
{"crate": "leleka-control-plane", "file": "src/request_log.rs", "ratchet": "process-global", "reason": "kept for now (NOT a boundary): the request counters and histograms that /metrics renders are written by the request middleware and read by the metrics handler; both reach AppState, so the registry can move into Services. Left because it touches the request path of every endpoint and the metrics tests; follow-up of STRA-338"},
{"crate": "leleka-control-plane", "file": "src/stage_trace.rs", "ratchet": "process-global", "reason": "kept: diagnostic stage table of the replay harness and STRATA_STAGE_TRACE; time() and span() are called from deep helpers (render, tokenize) that carry no state argument, and the output is diagnostic only, never read by serving logic"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/settings/source.rs", "ratchet": "env-read", "reason": "the one reader of the process environment of the engine: ProcessEnv is the adapter of the EnvSource port, and Settings parses every variable into typed fields there (S13)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_engine/round_tally/serve_rounds.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per traced port call, only when the bring-up trace is on); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
@@ -29,6 +29,7 @@ fn worker_config(tokenizer: Arc<Tokenizer>) -> BackendWorkerConfig {
cancel_drain_timeout: Duration::from_secs(5),
prefix_view: None,
memory_view: None,
request_metrics: Default::default(),
}
}
+1 -1
View File
@@ -77,7 +77,7 @@ pub(super) async fn metrics(State(state): State<AppState>, RawQuery(query): RawQ
let all = query.as_deref().is_some_and(|q| q.split('&').any(|pair| pair == "requests=all"));
let document = metrics_document(&state, all).await;
if crate::prometheus::wanted(query.as_deref(), accept) {
let mut response = crate::prometheus::render(&document).into_response();
let mut response = crate::prometheus::render(&document, &state.services.request_metrics).into_response();
response.headers_mut().insert(
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_static(crate::prometheus::CONTENT_TYPE),
+1
View File
@@ -87,6 +87,7 @@ pub fn router(state: AppState) -> Router {
model: state.model.name.clone(),
memory: state.model.memory.clone(),
clock: state.services.clock.clone(),
metrics: state.services.request_metrics.clone(),
};
let routes = model_routes(server_routes(Router::new()));
let routes = chat_routes(response_routes(routes, &state, &observe), &state, &observe);
+3
View File
@@ -80,6 +80,8 @@ pub struct Services {
/// The MCP servers configured for the operator (`GET /mcp`).
pub mcp: Option<SharedToolHub>,
pub settings: Arc<crate::settings::Settings>,
/// The request counters and histograms that `/metrics` renders: written by the request middleware and the worker.
pub request_metrics: Arc<crate::request_log::RequestMetrics>,
/// Wall and monotonic time: queue deadlines, uptime, response timestamps.
pub clock: SharedClock,
pub started_at: SystemTime,
@@ -135,6 +137,7 @@ impl Default for Services {
monitor: Arc::new(Default::default()),
mcp: None,
settings: Arc::new(crate::settings::Settings::default()),
request_metrics: Arc::default(),
started_at: clock.system_time(),
clock,
}
+2
View File
@@ -74,6 +74,8 @@ pub struct BackendWorkerConfig {
/// Where the engine's memory-governor report is copied (health tick and after every request); `None` = not shown,
/// no gate.
pub memory_view: Option<Arc<crate::memory_view::MemoryView>>,
/// Where the worker counts the engine attaches and losses that `/metrics` renders.
pub request_metrics: Arc<crate::request_log::RequestMetrics>,
}
type Engine = Arc<Mutex<Box<dyn api::Backend>>>;
+2 -2
View File
@@ -167,7 +167,7 @@ impl AttachLoop {
/// The engine has the model: report ready and answer the `Load` requests that waited.
async fn become_ready(&mut self) {
self.attached_before = true;
crate::request_log::note_engine_attached();
self.config.request_metrics.note_engine_attached();
self.publish_ready_status().await;
self.answer_waiting_loads();
}
@@ -238,7 +238,7 @@ impl AttachLoop {
/// The engine is gone: record why and fail the worker.
async fn report_engine_lost(&self, reason: &str) {
crate::request_log::note_engine_lost(reason);
self.config.request_metrics.note_engine_lost(reason);
update(&self.status, WorkerState::Failed, None).await;
}
+2 -2
View File
@@ -35,7 +35,7 @@ pub(super) fn format_value(value: f64) -> String {
}
/// Render the `/metrics` document. `model` (when the document has one) labels `leleka_info`.
pub fn render(document: &Value) -> String {
pub fn render(document: &Value, requests: &crate::request_log::RequestMetrics) -> String {
let mut out = String::new();
let mut described: Vec<&str> = Vec::new();
for series in SERIES {
@@ -54,7 +54,7 @@ pub fn render(document: &Value) -> String {
let _ = writeln!(out, "# TYPE leleka_info gauge");
let model = document.get("model").and_then(Value::as_str).unwrap_or("");
let _ = writeln!(out, "leleka_info{{model=\"{}\"}} 1", escape(model));
crate::request_log::render_prometheus(&mut out);
requests.render_prometheus(&mut out);
out
}
+5 -4
View File
@@ -2,6 +2,7 @@
//! their fixed labels, unmeasured figures left out, and the choice of format by query or `Accept` header.
use super::*;
use crate::request_log::RequestMetrics;
use serde_json::json;
fn document() -> Value {
@@ -27,7 +28,7 @@ fn document() -> Value {
#[test]
fn counters_gauges_and_labels_render_in_the_text_format() {
let text = render(&document());
let text = render(&document(), &RequestMetrics::default());
assert!(text.contains("# TYPE leleka_generations_started_total counter\nleleka_generations_started_total 5\n"));
assert!(text.contains("leleka_prefill_seconds_total 2.5\n"));
assert!(text.contains("leleka_decode_seconds_total 1.25\n"));
@@ -85,7 +86,7 @@ const ENGINE_LINES: [&str; 16] = [
#[test]
fn engine_gauges_counters_and_throttle_reasons_are_exposed_with_fixed_labels() {
let text = render(&engine_document());
let text = render(&engine_document(), &RequestMetrics::default());
for expected in ENGINE_LINES {
assert!(text.contains(expected), "{expected} missing:\n{text}");
}
@@ -108,11 +109,11 @@ fn engine_gauges_counters_and_throttle_reasons_are_exposed_with_fixed_labels() {
#[test]
fn unmeasured_figures_are_not_exposed() {
let text = render(&document());
let text = render(&document(), &RequestMetrics::default());
// null in the document: no lifetime decode rate, no GPU clock, no swap
assert!(!text.contains("window=\"lifetime\""));
assert!(!text.contains("leleka_gpu_sm_clock_megahertz"));
let bare = render(&json!({"model": "m", "up": false}));
let bare = render(&json!({"model": "m", "up": false}), &RequestMetrics::default());
assert!(bare.contains("leleka_up 0\n"));
assert!(!bare.contains("leleka_gpu_") && !bare.contains("leleka_engine_phase"));
// every line is HELP, TYPE or a sample
+11 -5
View File
@@ -11,10 +11,10 @@
//! 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
//! 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, LazyLock, Mutex,
Arc, Mutex,
atomic::{AtomicU64, Ordering},
};
@@ -85,6 +85,7 @@ struct Live {
pub struct ReqCtx {
state: Mutex<Live>,
clock: crate::ports::SharedClock,
metrics: Arc<RequestMetrics>,
}
/// What the request middleware leaves for the handler and the worker.
@@ -101,6 +102,7 @@ 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.
@@ -128,7 +130,7 @@ pub struct Record {
pub hardware: Option<crate::memory_view::Brief>,
}
struct Registry {
pub struct RequestMetrics {
requests: Vec<AtomicU64>,
errors: Vec<AtomicU64>,
restarts: AtomicU64,
@@ -143,7 +145,9 @@ struct Registry {
prefill_tps: Histogram,
}
static REGISTRY: LazyLock<Registry> = LazyLock::new(|| Registry {
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),
@@ -156,7 +160,9 @@ static REGISTRY: LazyLock<Registry> = LazyLock::new(|| Registry {
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;
+23 -21
View File
@@ -1,26 +1,27 @@
//! The request metrics in the Prometheus text format (requests by endpoint and outcome, errors by class, engine lost,
//! attached and restart counters, time and token histograms) and the note that a worker attached to a loaded engine.
use super::{ENDPOINTS, ERROR_CLASSES, OUTCOMES, Ordering, REGISTRY};
use super::{ENDPOINTS, ERROR_CLASSES, OUTCOMES, Ordering, RequestMetrics};
use std::fmt::Write as _;
impl RequestMetrics {
/// 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;
pub fn note_engine_attached(&self) {
let n = self.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) {
render_requests(out);
render_errors(out);
render_engine_counters(out);
render_histograms(out);
pub fn render_prometheus(&self, out: &mut String) {
self.render_requests(out);
self.render_errors(out);
self.render_engine_counters(out);
self.render_histograms(out);
}
/// `leleka_requests_total` by endpoint and outcome (a zero line when there is none).
fn render_requests(out: &mut String) {
let reg = &*REGISTRY;
fn render_requests(&self, out: &mut String) {
let reg = self;
leleka_obs::hist::header(
"leleka_requests_total",
"Generation requests by endpoint and how they ended.",
@@ -43,8 +44,8 @@ fn render_requests(out: &mut String) {
}
/// `leleka_request_errors_total` by error class.
fn render_errors(out: &mut String) {
let reg = &*REGISTRY;
fn render_errors(&self, out: &mut String) {
let reg = self;
leleka_obs::hist::header(
"leleka_request_errors_total",
"Failed or rejected requests by error class.",
@@ -58,8 +59,8 @@ fn render_errors(out: &mut String) {
}
/// The engine lost, attached and restart-request counters.
fn render_engine_counters(out: &mut String) {
let reg = &*REGISTRY;
fn render_engine_counters(&self, out: &mut String) {
let reg = self;
let counters = [
(
"leleka_engine_lost_total",
@@ -80,22 +81,22 @@ fn render_engine_counters(out: &mut String) {
}
/// The time, token and rate histograms of the requests.
fn render_histograms(out: &mut String) {
render_time_histograms(out);
render_size_histograms(out);
fn render_histograms(&self, out: &mut String) {
self.render_time_histograms(out);
self.render_size_histograms(out);
}
/// The time histograms: first token, duration and queue wait.
fn render_time_histograms(out: &mut String) {
let reg = &*REGISTRY;
fn render_time_histograms(&self, out: &mut String) {
let reg = self;
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);
}
/// The token-count and token-rate histograms.
fn render_size_histograms(out: &mut String) {
let reg = &*REGISTRY;
fn render_size_histograms(&self, out: &mut String) {
let reg = self;
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);
@@ -105,3 +106,4 @@ fn render_size_histograms(out: &mut String) {
out,
);
}
}
+10 -7
View File
@@ -3,7 +3,7 @@
use super::{
Arc, CURRENT, Done, ENDPOINTS, ERROR_CLASSES, HeaderValue, Instant, Live, Next, OUTCOMES, ObsHandle, Observe,
Ordering, REGISTRY, REQUEST_ID_HEADER, Record, Registry, ReqCtx, ReqIdentity, Request, Response, State, V,
Ordering, REQUEST_ID_HEADER, Record, ReqCtx, ReqIdentity, Request, RequestMetrics, Response, State, V,
class_of_status, endpoint_index, session_tag,
};
@@ -69,7 +69,8 @@ pub async fn observe(State(observe): State<Observe>, request: Request, next: Nex
sid: session_tag(request.headers()),
model: observe.model.clone(),
};
let ctx = Arc::new(ReqCtx::new(identity, Some(observe.memory.clone()), observe.clock.clone()));
let ctx =
Arc::new(ReqCtx::new(identity, Some(observe.memory.clone()), observe.clock.clone(), observe.metrics.clone()));
let id = ctx.id();
let mut response = CURRENT.scope(ctx.clone(), next.run(request)).await;
ctx.set_http_status(response.status().as_u16());
@@ -224,13 +225,13 @@ impl Record {
}
}
pub(super) fn publish(&self) {
REGISTRY.observe(self);
pub(super) fn publish(&self, metrics: &RequestMetrics) {
metrics.observe(self);
leleka_obs::record("api", "request", &self.fields());
}
}
impl Registry {
impl RequestMetrics {
pub(super) 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);
@@ -268,8 +269,10 @@ impl Registry {
}
}
impl RequestMetrics {
/// 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);
pub fn note_engine_lost(&self, reason: &str) {
self.engine_lost.fetch_add(1, Ordering::Relaxed);
leleka_obs::warn("api", "engine_lost", &[("reason", reason.into())]);
}
}
@@ -2,7 +2,8 @@
//! the classifiers that keep free text out of the line: endpoint index, session tag by digest, error class.
use super::{
Arc, Digest, Done, DoneInfo, Finish, HeaderMap, Live, Mutex, ObsHandle, Record, ReqCtx, SESSION_HEADERS, Sha256,
Arc, Digest, Done, DoneInfo, Finish, HeaderMap, Live, Mutex, ObsHandle, Record, ReqCtx, RequestMetrics,
SESSION_HEADERS, Sha256,
};
pub fn endpoint_index(path: &str) -> usize {
@@ -76,6 +77,7 @@ impl ReqCtx {
identity: ReqIdentity,
memory: Option<Arc<crate::memory_view::MemoryView>>,
clock: crate::ports::SharedClock,
metrics: Arc<RequestMetrics>,
) -> Self {
Self {
state: Mutex::new(Live {
@@ -96,6 +98,7 @@ impl ReqCtx {
memory,
}),
clock,
metrics,
}
}
@@ -171,7 +174,7 @@ impl ReqCtx {
Some(Record::from_state(s, self.clock.now()))
});
if let Some(Some(record)) = record {
record.publish();
record.publish(&self.metrics);
}
}
}
@@ -186,7 +189,7 @@ impl Drop for ReqCtx {
_ => None,
};
if let Some(record) = record {
record.publish();
record.publish(&self.metrics);
}
}
}
+18 -14
View File
@@ -34,14 +34,14 @@ fn ctx() -> ReqCtx {
sid: Some("s-0123456789".into()),
model: Some("qwen-iq3".into()),
};
ReqCtx::new(identity, None, crate::adapters::SystemClock::shared())
ReqCtx::new(identity, None, crate::adapters::SystemClock::shared(), Arc::default())
}
#[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());
let c = ReqCtx::new(identity, None, clock.clone(), Arc::default());
clock.advance(std::time::Duration::from_millis(40));
c.engine_start();
clock.advance(std::time::Duration::from_millis(60));
@@ -189,19 +189,20 @@ fn the_session_header_is_hashed_not_copied() {
assert_eq!(session_tag(&headers).unwrap(), tag);
}
fn counted(endpoint: &str, outcome: &str) -> u64 {
fn counted(metrics: &RequestMetrics, endpoint: &str, outcome: &str) -> u64 {
let mut text = String::new();
render_prometheus(&mut text);
metrics.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 {
fn rejecting_router(metrics: Arc<RequestMetrics>) -> axum::Router {
let observe = Observe {
model: Some("m".into()),
memory: Arc::new(Default::default()),
clock: crate::adapters::SystemClock::shared(),
metrics,
};
axum::Router::new()
.route(
@@ -217,8 +218,10 @@ fn rejecting_router() -> axum::Router {
}
/// 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();
async fn serve_rejecting_handler(
metrics: Arc<RequestMetrics>,
) -> (String, tokio::task::JoinHandle<std::io::Result<()>>) {
let app = rejecting_router(metrics);
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 });
@@ -227,10 +230,10 @@ async fn serve_rejecting_handler() -> (String, tokio::task::JoinHandle<std::io::
/// 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 {
async fn counted_after(metrics: &RequestMetrics, before: u64) -> u64 {
let mut after = before;
for _ in 0..50 {
after = counted("chat", "rejected");
after = counted(metrics, "chat", "rejected");
if after > before {
break;
}
@@ -241,14 +244,15 @@ async fn counted_after(before: u64) -> u64 {
#[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 metrics = Arc::<RequestMetrics>::default();
let (url, server) = serve_rejecting_handler(metrics.clone()).await;
let before = counted(&metrics, "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;
let after = counted_after(&metrics, before).await;
assert!(after > before, "the rejection must be counted: {before} -> {after}");
server.abort();
}
@@ -259,9 +263,9 @@ fn the_prometheus_text_has_fixed_labels_and_valid_lines() {
c.engine_start();
c.first_token();
c.done(&done("DONE 10 100 5.0 100.0 length"), false);
record_of(&c).publish();
record_of(&c).publish(&c.metrics);
let mut text = String::new();
render_prometheus(&mut text);
c.metrics.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() {
+1
View File
@@ -51,6 +51,7 @@ pub(super) fn worker_config(
cancel_drain_timeout: Duration::from_secs(20),
prefix_view: Some(state.model.prefix_cache.clone()),
memory_view: Some(state.model.memory.clone()),
request_metrics: state.services.request_metrics.clone(),
}
}
@@ -102,6 +102,7 @@ fn default_worker_config(tokenizer: Arc<Tokenizer>) -> BackendWorkerConfig {
cancel_drain_timeout: Duration::from_secs(5),
prefix_view: None,
memory_view: None,
request_metrics: Default::default(),
}
}
@@ -32,6 +32,7 @@ fn worker_config(stack: &Stack) -> BackendWorkerConfig {
cancel_drain_timeout: Duration::from_secs(1),
prefix_view: None,
memory_view: None,
request_metrics: Default::default(),
}
}
@@ -54,6 +54,7 @@ fn worker_config(tokenizer: Arc<Tokenizer>, memory: &Arc<MemoryView>) -> Backend
cancel_drain_timeout: Duration::from_secs(5),
prefix_view: None,
memory_view: Some(memory.clone()),
request_metrics: Default::default(),
}
}
@@ -198,6 +198,7 @@ fn worker_config(
cancel_drain_timeout: Duration::from_secs(5),
prefix_view: Some(prefix_view),
memory_view: None,
request_metrics: Default::default(),
}
}