From 51a4eceff06de74ae98a83061eaf2cec30fca326 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 24 Nov 2026 03:44:23 +0100 Subject: [PATCH] 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. --- architecture.json | 1 - control-plane/examples/cp_replay/stack.rs | 1 + control-plane/src/app/admin_routes.rs | 2 +- control-plane/src/app/routes.rs | 1 + control-plane/src/app/state.rs | 3 + control-plane/src/backend_worker.rs | 2 + control-plane/src/backend_worker/attach.rs | 4 +- control-plane/src/prometheus/render.rs | 4 +- control-plane/src/prometheus/tests.rs | 9 +- control-plane/src/request_log.rs | 40 ++-- control-plane/src/request_log/metrics_text.rs | 192 +++++++++--------- control-plane/src/request_log/observation.rs | 21 +- .../src/request_log/request_context.rs | 9 +- control-plane/src/request_log/tests.rs | 32 +-- control-plane/src/serve/engine.rs | 1 + .../tests/backend_worker_http/harness.rs | 1 + .../backend_worker_http/second_worker.rs | 1 + .../tests/memory_gate_http/harness.rs | 1 + .../tests/api_over_runtime/harness.rs | 1 + 19 files changed, 178 insertions(+), 148 deletions(-) diff --git a/architecture.json b/architecture.json index dfb28e88..96a4d87a 100644 --- a/architecture.json +++ b/architecture.json @@ -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"}, diff --git a/control-plane/examples/cp_replay/stack.rs b/control-plane/examples/cp_replay/stack.rs index 19eecf28..563831d0 100644 --- a/control-plane/examples/cp_replay/stack.rs +++ b/control-plane/examples/cp_replay/stack.rs @@ -29,6 +29,7 @@ fn worker_config(tokenizer: Arc) -> BackendWorkerConfig { cancel_drain_timeout: Duration::from_secs(5), prefix_view: None, memory_view: None, + request_metrics: Default::default(), } } diff --git a/control-plane/src/app/admin_routes.rs b/control-plane/src/app/admin_routes.rs index be3483db..63df4029 100644 --- a/control-plane/src/app/admin_routes.rs +++ b/control-plane/src/app/admin_routes.rs @@ -77,7 +77,7 @@ pub(super) async fn metrics(State(state): State, 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), diff --git a/control-plane/src/app/routes.rs b/control-plane/src/app/routes.rs index 025783ee..0a675949 100644 --- a/control-plane/src/app/routes.rs +++ b/control-plane/src/app/routes.rs @@ -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); diff --git a/control-plane/src/app/state.rs b/control-plane/src/app/state.rs index a5494986..5c60fef4 100644 --- a/control-plane/src/app/state.rs +++ b/control-plane/src/app/state.rs @@ -80,6 +80,8 @@ pub struct Services { /// The MCP servers configured for the operator (`GET /mcp`). pub mcp: Option, pub settings: Arc, + /// The request counters and histograms that `/metrics` renders: written by the request middleware and the worker. + pub request_metrics: Arc, /// 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, } diff --git a/control-plane/src/backend_worker.rs b/control-plane/src/backend_worker.rs index d1959735..1f8aa372 100644 --- a/control-plane/src/backend_worker.rs +++ b/control-plane/src/backend_worker.rs @@ -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>, + /// Where the worker counts the engine attaches and losses that `/metrics` renders. + pub request_metrics: Arc, } type Engine = Arc>>; diff --git a/control-plane/src/backend_worker/attach.rs b/control-plane/src/backend_worker/attach.rs index 1d97c7ae..c060c9a7 100644 --- a/control-plane/src/backend_worker/attach.rs +++ b/control-plane/src/backend_worker/attach.rs @@ -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; } diff --git a/control-plane/src/prometheus/render.rs b/control-plane/src/prometheus/render.rs index a0dea8b0..e1e46314 100644 --- a/control-plane/src/prometheus/render.rs +++ b/control-plane/src/prometheus/render.rs @@ -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 } diff --git a/control-plane/src/prometheus/tests.rs b/control-plane/src/prometheus/tests.rs index 15b4021b..6d8f2a7f 100644 --- a/control-plane/src/prometheus/tests.rs +++ b/control-plane/src/prometheus/tests.rs @@ -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 diff --git a/control-plane/src/request_log.rs b/control-plane/src/request_log.rs index ecf9f531..bcdb016e 100644 --- a/control-plane/src/request_log.rs +++ b/control-plane/src/request_log.rs @@ -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, clock: crate::ports::SharedClock, + metrics: Arc, } /// What the request middleware leaves for the handler and the worker. @@ -101,6 +102,7 @@ pub struct Observe { pub model: Option, pub memory: Arc, pub clock: crate::ports::SharedClock, + pub metrics: Arc, } /// Everything the line says, resolved. @@ -128,7 +130,7 @@ pub struct Record { pub hardware: Option, } -struct Registry { +pub struct RequestMetrics { requests: Vec, errors: Vec, restarts: AtomicU64, @@ -143,20 +145,24 @@ struct Registry { prefill_tps: Histogram, } -static REGISTRY: LazyLock = 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 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; diff --git a/control-plane/src/request_log/metrics_text.rs b/control-plane/src/request_log/metrics_text.rs index f76b098f..275c9e91 100644 --- a/control-plane/src/request_log/metrics_text.rs +++ b/control-plane/src/request_log/metrics_text.rs @@ -1,107 +1,109 @@ //! 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 _; -/// 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())]); -} +impl RequestMetrics { + /// The worker attached to a loaded engine (at start and after every restart). + 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); -} + /// Append the request metrics in the Prometheus text format. + 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; - 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}"); + /// `leleka_requests_total` by endpoint and outcome (a zero line when there is none). + 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.", + "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"); + } } - if !any { - let _ = writeln!(out, "leleka_requests_total{{endpoint=\"responses\",outcome=\"stop\"}} 0"); + + /// `leleka_request_errors_total` by error class. + 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.", + "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}"); + } + } + + /// The engine lost, attached and restart-request counters. + fn render_engine_counters(&self, out: &mut String) { + let reg = self; + let counters = [ + ( + "leleka_engine_lost_total", + "Times the API lost the engine (it restarted, hung or stopped answering).", + ®.engine_lost, + ), + ( + "leleka_engine_attached_total", + "Times the API attached to a loaded engine (the first start counts).", + ®.engine_attached, + ), + ("leleka_requests_engine_restart_total", "Requests during which the engine was lost.", ®.restarts), + ]; + for (name, help, value) in counters { + leleka_obs::hist::header(name, help, "counter", out); + let _ = writeln!(out, "{name} {}", value.load(Ordering::Relaxed)); + } + } + + /// The time, token and rate histograms of the requests. + 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(&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(&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); + reg.prefill_tps.render( + "leleka_request_prefill_tokens_per_second", + "Prefill rate per request (uncached prompt tokens).", + out, + ); } } - -/// `leleka_request_errors_total` by error class. -fn render_errors(out: &mut String) { - let reg = &*REGISTRY; - 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}"); - } -} - -/// The engine lost, attached and restart-request counters. -fn render_engine_counters(out: &mut String) { - let reg = &*REGISTRY; - let counters = [ - ( - "leleka_engine_lost_total", - "Times the API lost the engine (it restarted, hung or stopped answering).", - ®.engine_lost, - ), - ( - "leleka_engine_attached_total", - "Times the API attached to a loaded engine (the first start counts).", - ®.engine_attached, - ), - ("leleka_requests_engine_restart_total", "Requests during which the engine was lost.", ®.restarts), - ]; - for (name, help, value) in counters { - leleka_obs::hist::header(name, help, "counter", out); - let _ = writeln!(out, "{name} {}", value.load(Ordering::Relaxed)); - } -} - -/// The time, token and rate histograms of the requests. -fn render_histograms(out: &mut String) { - render_time_histograms(out); - render_size_histograms(out); -} - -/// The time histograms: first token, duration and queue wait. -fn render_time_histograms(out: &mut String) { - let reg = &*REGISTRY; - 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; - 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, - ); -} diff --git a/control-plane/src/request_log/observation.rs b/control-plane/src/request_log/observation.rs index 885c4c8e..bed12cd4 100644 --- a/control-plane/src/request_log/observation.rs +++ b/control-plane/src/request_log/observation.rs @@ -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, 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 { } } -/// 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())]); +impl RequestMetrics { + /// The worker lost the engine (a structured warning is logged; the count feeds `leleka_engine_lost_total`). + 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())]); + } } diff --git a/control-plane/src/request_log/request_context.rs b/control-plane/src/request_log/request_context.rs index 20992a04..e5751b35 100644 --- a/control-plane/src/request_log/request_context.rs +++ b/control-plane/src/request_log/request_context.rs @@ -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>, clock: crate::ports::SharedClock, + metrics: Arc, ) -> 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); } } } diff --git a/control-plane/src/request_log/tests.rs b/control-plane/src/request_log/tests.rs index 3bebbd65..14eb701b 100644 --- a/control-plane/src/request_log/tests.rs +++ b/control-plane/src/request_log/tests.rs @@ -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) -> 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>) { - let app = rejecting_router(); +async fn serve_rejecting_handler( + metrics: Arc, +) -> (String, tokio::task::JoinHandle>) { + 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 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::::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() { diff --git a/control-plane/src/serve/engine.rs b/control-plane/src/serve/engine.rs index b3e056b7..c387a4d5 100644 --- a/control-plane/src/serve/engine.rs +++ b/control-plane/src/serve/engine.rs @@ -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(), } } diff --git a/control-plane/tests/backend_worker_http/harness.rs b/control-plane/tests/backend_worker_http/harness.rs index 5a5a58c9..24661a82 100644 --- a/control-plane/tests/backend_worker_http/harness.rs +++ b/control-plane/tests/backend_worker_http/harness.rs @@ -102,6 +102,7 @@ fn default_worker_config(tokenizer: Arc) -> BackendWorkerConfig { cancel_drain_timeout: Duration::from_secs(5), prefix_view: None, memory_view: None, + request_metrics: Default::default(), } } diff --git a/control-plane/tests/backend_worker_http/second_worker.rs b/control-plane/tests/backend_worker_http/second_worker.rs index 9efd8ae6..65c235ea 100644 --- a/control-plane/tests/backend_worker_http/second_worker.rs +++ b/control-plane/tests/backend_worker_http/second_worker.rs @@ -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(), } } diff --git a/control-plane/tests/memory_gate_http/harness.rs b/control-plane/tests/memory_gate_http/harness.rs index f6cf8778..68beaf80 100644 --- a/control-plane/tests/memory_gate_http/harness.rs +++ b/control-plane/tests/memory_gate_http/harness.rs @@ -54,6 +54,7 @@ fn worker_config(tokenizer: Arc, memory: &Arc) -> Backend cancel_drain_timeout: Duration::from_secs(5), prefix_view: None, memory_view: Some(memory.clone()), + request_metrics: Default::default(), } } diff --git a/desktop-core/tests/api_over_runtime/harness.rs b/desktop-core/tests/api_over_runtime/harness.rs index 89abd279..b03a96db 100644 --- a/desktop-core/tests/api_over_runtime/harness.rs +++ b/desktop-core/tests/api_over_runtime/harness.rs @@ -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(), } }