From 7c58f22a32653d57460c9b95df59a2d5b434a54d Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Thu, 26 Nov 2026 14:05:46 -0600 Subject: [PATCH 01/14] Add request latency histograms and process metrics `/metrics` reports counters, gauges, and the dashboard snapshot, but no distribution of request latency, so an operator cannot see tail latency, queue delay, prefill time, decode rate, or prompt size from a scrape, and generic Prometheus process dashboards have nothing to read. Issue #536 requests histograms for per-request latency and prompt size together with the standard process_* metrics. Fixed-bound histograms answer those questions without per-request storage, and the runtime already counts completions in one place, so recording the histograms there keeps the counter and the observations together. The runtime now keeps lifecycle instants on `Incoming` so they survive preemption: `Worker::reserve_and_pack` stamps the first model step that includes a request, `Worker::complete` stamps its first and last committed generated tokens, and `Metrics::request_completed` records queue, prefill, decode, time per output token, and prompt tokens while incrementing `requests_completed_total`. Both call sites that incremented the counter directly now call `request_completed`, so the counter cannot drift from the histograms. Cancelled and failed requests stay out of the request histograms. The generation handler records `request_e2e_seconds` when delivery completes a successful response, except for `/v1/messages/count_tokens`, and the existing first-response sampler now also observes `time_to_first_response_seconds` when it offers answer or reasoning text; its median gauge is unchanged. On Linux, `server/metrics/process.rs` derives `process_cpu_seconds_total`, `process_resident_memory_bytes`, `process_virtual_memory_bytes`, `process_start_time_seconds`, `process_open_fds`, and `process_max_fds` from procfs and `RLIMIT_NOFILE`, omitting only the metrics whose source cannot be read; other platforms write nothing. Names, types, and endpoints are documented in `docs/api.md`, and the JSON snapshot is unchanged. The claimed result is observability only: latency, prompt-size, and process resource distributions become scrapeable with no change to serving behavior. Evidence: `cargo test --locked --release --manifest-path helios/Cargo.toml --target-dir ~/.cache/hyperflare-target --features runtime-core,server --lib -- server::runtime::phase_tests` passed 109 tests, including `reasoning_budget_cuts_or_plainly_continues_with_exact_history_and_usage` (a preempted and readmitted request records one queue, prefill, and prompt-token observation), `first_response_http_nonstream_records_only_when_completed_body_is_offered`, `first_response_http_stream_excludes_pretext_failures_and_unpolled_bodies`, and `metrics_route_serves_prometheus_or_json_without_the_api_key`, whose text scrape carries the first-response histogram, an empty request histogram, and a resident memory gauge. `server::metrics::` passed 20 tests, including `request_histograms_bucket_completed_request_timings`, `render_reports_process_memory_descriptors_and_start_time`, and `parse_stat_reads_fields_after_a_parenthesized_command_with_a_paren`. The whole `server::` filter ran 326 tests with one failure, `messages_image_hints_end_after_expansion_for_text_and_segmented_templates`, which requires templates from `tests/frontend/prepare_templates.py` through `FLARE_TEST_TEMPLATE_DIR`; no templates are installed on this host, so that test is unrun here. Windows builds and the rest of the helios suite are left to CI. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=2e5b --- docs/api.md | 28 ++- helios/src/server.rs | 2 + helios/src/server/http.rs | 7 +- helios/src/server/latency.rs | 35 +++- helios/src/server/metrics.rs | 228 +++++++++++++++++++++++ helios/src/server/metrics/process.rs | 184 ++++++++++++++++++ helios/src/server/runtime.rs | 47 ++++- helios/src/server/runtime/phase_tests.rs | 35 ++++ 8 files changed, 546 insertions(+), 20 deletions(-) create mode 100644 helios/src/server/metrics/process.rs diff --git a/docs/api.md b/docs/api.md index 8eb8dbb3b..aec46e9fe 100644 --- a/docs/api.md +++ b/docs/api.md @@ -288,13 +288,35 @@ requires the serving key: both report aggregate state without request content. `GET /metrics` returns Prometheus text exposition format 0.0.4 by default. Counter and gauge names start with `flare_`, such as `flare_generated_tokens_total`, `flare_active_requests`, and -`flare_free_kv_pages`. The only histograms describe host prefix-store lookups: -`flare_host_cache_missing_tokens`, `flare_host_cache_estimated_transfer_ns`, and -`flare_host_cache_estimated_prefill_ns`. Beyond the JSON fields below, the +`flare_free_kv_pages`. Beyond the JSON fields below, the text includes speculative and proposal counters by batch, width, or depth, graph launches by kind, embedding row-cache counters, HTTP admission gauges, and uptime. +Histograms appear in the Prometheus format only. Host prefix-store histograms +report lookup cost and retirement: `flare_host_cache_missing_tokens`, +`flare_host_cache_estimated_transfer_ns`, +`flare_host_cache_estimated_prefill_ns`, and +`flare_host_cache_retirement_seconds`. Request histograms observe the served +response. `flare_request_e2e_seconds` counts each successful generation from +admission to the completed response, and +`flare_time_to_first_response_seconds` counts each response that offers answer +or reasoning text, from admission to that text, once the client reads it. The +runtime records one observation per completed generation in +`flare_request_queue_seconds` from model-scheduler arrival to the first model +step that includes the request, `flare_request_prefill_seconds` from that step to +the request's first committed generated token, `flare_request_decode_seconds` +from the first to the last committed generated token, +`flare_time_per_output_token_seconds` as decode time divided by generated tokens +after the first, and `flare_request_prompt_tokens` for prompt tokens including +tokens reused from the prefix cache. Cancelled and failed requests enter only +`flare_requests_cancelled_total` and `flare_requests_failed_total`. + +On Linux the text also carries `process_cpu_seconds_total`, +`process_resident_memory_bytes`, `process_virtual_memory_bytes`, +`process_start_time_seconds`, `process_open_fds`, and `process_max_fds` for the +serving process. Other platforms omit them. + The route returns one JSON object instead when the query contains `format=json`, or when the `Accept` header gives `application/json` a higher quality than `text/plain`; at equal quality the earlier media range wins. `format=prometheus` diff --git a/helios/src/server.rs b/helios/src/server.rs index 1adeeaf03..70ddb69b1 100644 --- a/helios/src/server.rs +++ b/helios/src/server.rs @@ -668,6 +668,7 @@ async fn metrics(State(state): State>, uri: Uri, headers: HeaderM use std::fmt::Write; let _ = writeln!(text, "# HELP flare_first_response_median_seconds Server-side HTTP admission to first offered answer or reasoning text.\n# TYPE flare_first_response_median_seconds gauge\nflare_first_response_median_seconds {median}"); } + state.first_response.render_histogram(&mut text); for (name, kind, help, value) in input_metrics { metrics::metric(&mut text, name, kind, help, value); } @@ -705,6 +706,7 @@ async fn metrics(State(state): State>, uri: Uri, headers: HeaderM ] { metrics::metric(&mut text, name, "gauge", help, value as u64); } + metrics::process::render(&mut text); ( [ (header::CONTENT_TYPE, "text/plain; version=0.0.4; charset=utf-8"), diff --git a/helios/src/server/http.rs b/helios/src/server/http.rs index af1728abf..4bdb37da1 100644 --- a/helios/src/server/http.rs +++ b/helios/src/server/http.rs @@ -600,6 +600,7 @@ pub(super) async fn generate( if streaming { let request_id = id.clone(); let log_to_stderr = state.log_to_stderr; + let metrics = state.model.metrics_handle(); let events = delivery.filter_map(move |event| { let event = match event { Delivery::Frame(frame) => { @@ -610,7 +611,10 @@ pub(super) async fn generate( if log_to_stderr { log_failure(&request_id, "stream", &error); } Some(Ok::<_, Infallible>(frame.sse())) } - Delivery::Complete(_) => None, + Delivery::Complete(_) => { + if !count { metrics.request_e2e.observe(&super::metrics::REQUEST_SECONDS, admitted_at.elapsed().as_nanos() as u64); } + None + } }; std::future::ready(event) }); @@ -625,6 +629,7 @@ pub(super) async fn generate( while let Some(event) = delivery.next().await { match event { Delivery::Complete(body) => { + if !count { state.model.metrics().request_e2e.observe(&super::metrics::REQUEST_SECONDS, admitted_at.elapsed().as_nanos() as u64); } let visible = super::latency::response_text(&body); let response = with_request_id(Json(body).into_response(), &id); if !visible { return response; } diff --git a/helios/src/server/latency.rs b/helios/src/server/latency.rs index 0f428cb76..15e58dd6c 100644 --- a/helios/src/server/latency.rs +++ b/helios/src/server/latency.rs @@ -31,7 +31,10 @@ struct Samples { dropped_at: Option, } #[derive(Default)] -pub(super) struct FirstResponseSamples(Mutex); +pub(super) struct FirstResponseSamples { + window: Mutex, + histogram: super::metrics::Histogram<21>, +} impl Samples { fn expire(&mut self, now: Instant) { while self @@ -67,7 +70,7 @@ impl FirstResponseSamples { } pub(super) fn snapshot(&self) -> FirstResponseSnapshot { let (mut seconds, truncated) = { - let mut samples = self.0.lock().unwrap_or_else(|e| e.into_inner()); + let mut samples = self.window.lock().unwrap_or_else(|e| e.into_inner()); samples.expire(Instant::now()); ( samples @@ -104,13 +107,29 @@ pub(super) struct FirstResponse { impl FirstResponse { pub(super) fn output(&mut self) { if !self.recorded { - let mut samples = self.samples.0.lock().unwrap_or_else(|e| e.into_inner()); - samples.record(self.started, Instant::now()); + let now = Instant::now(); + let mut samples = self.samples.window.lock().unwrap_or_else(|e| e.into_inner()); + samples.record(self.started, now); + self.samples.histogram.observe( + &super::metrics::REQUEST_SECONDS, + now.saturating_duration_since(self.started).as_nanos() as u64, + ); self.recorded = true; } } } +impl FirstResponseSamples { + pub(super) fn render_histogram(&self, text: &mut String) { + self.histogram.render( + text, + "time_to_first_response_seconds", + "Server-side HTTP admission to the first offered answer or reasoning text.", + &super::metrics::REQUEST_SECONDS, + ); + } +} + /// Only answer/reasoning text is eligible. Roles, keepalives, token observations, /// usage, signatures and tool-only content do not represent visible text here. pub(super) fn stream_text(value: &serde_json::Value) -> bool { @@ -176,13 +195,13 @@ mod tests { assert_eq!(empty.samples, 0); let now = Instant::now(); { - let mut values = samples.0.lock().unwrap(); + let mut values = samples.window.lock().unwrap(); for seconds in [4, 1, 2, 3] { values.values.push_back((now, Duration::from_secs(seconds))); } } assert_eq!(samples.snapshot().median_seconds, Some(2.5)); - samples.0.lock().unwrap().expire(now + WINDOW); + samples.window.lock().unwrap().expire(now + WINDOW); assert_eq!(samples.snapshot().median_seconds, None); } @@ -191,7 +210,7 @@ mod tests { let samples = FirstResponseSamples::default(); let now = Instant::now(); { - let mut values = samples.0.lock().unwrap(); + let mut values = samples.window.lock().unwrap(); for _ in 0..=CAPACITY { values.record(now, now); } @@ -200,7 +219,7 @@ mod tests { assert_eq!(snapshot.samples, CAPACITY as u64); assert_eq!(snapshot.window_seconds, 60); assert!(snapshot.truncated); - samples.0.lock().unwrap().expire(now + WINDOW); + samples.window.lock().unwrap().expire(now + WINDOW); let expired = samples.snapshot(); assert_eq!(expired.samples, 0); assert!(!expired.truncated); diff --git a/helios/src/server/metrics.rs b/helios/src/server/metrics.rs index a44f7c0f3..a5bbe1201 100644 --- a/helios/src/server/metrics.rs +++ b/helios/src/server/metrics.rs @@ -9,6 +9,7 @@ use std::{ sync::atomic::{AtomicU64, Ordering}, }; +pub(super) mod process; pub(super) mod scheduler; pub(super) fn input_metrics( @@ -208,6 +209,102 @@ const HOST_TIME_BUCKETS: [u64; 8] = [ ]; const HOST_TOKEN_BUCKETS: [u64; 8] = [64, 256, 1024, 4096, 16384, 65536, 262144, u64::MAX]; +/// Upper bucket bounds of a Prometheus histogram in its exposed unit, ending at +/// `f64::INFINITY`. Observations are integers of `1 / scale` exposed units. +pub(super) struct Buckets { + bounds: [f64; N], + scale: f64, +} + +pub(super) const REQUEST_SECONDS: Buckets<21> = Buckets { + bounds: [ + 0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 20.0, 40.0, 80.0, + 160.0, 320.0, 640.0, 1280.0, 2560.0, f64::INFINITY, + ], + scale: 1e9, +}; + +pub(super) const TOKEN_SECONDS: Buckets<19> = Buckets { + bounds: [ + 0.001, 0.0025, 0.005, 0.0075, 0.01, 0.015, 0.02, 0.03, 0.04, 0.05, 0.075, 0.1, 0.15, 0.2, + 0.3, 0.5, 1.0, 2.5, f64::INFINITY, + ], + scale: 1e9, +}; + +pub(super) const PROMPT_TOKENS: Buckets<21> = Buckets { + bounds: [ + 1.0, 8.0, 16.0, 32.0, 64.0, 128.0, 256.0, 512.0, 1024.0, 2048.0, 4096.0, 8192.0, 16384.0, + 32768.0, 65536.0, 131072.0, 262144.0, 524288.0, 1048576.0, 2097152.0, f64::INFINITY, + ], + scale: 1.0, +}; + +/// Fixed-bucket Prometheus histogram: per-bucket observations and the sum of the +/// observed values, both on the exposed unit's integer grid. +pub(super) struct Histogram { + counts: [AtomicU64; N], + sum: AtomicU64, +} + +impl Default for Histogram { + fn default() -> Self { + Self { + counts: std::array::from_fn(|_| AtomicU64::new(0)), + sum: AtomicU64::new(0), + } + } +} + +impl Histogram { + pub(super) fn observe(&self, buckets: &Buckets, value: u64) { + // Division is correctly rounded, so an integer grid point lands exactly on + // a bound written as the same decimal. + let exposed = value as f64 / buckets.scale; + let index = buckets + .bounds + .iter() + .position(|bound| exposed <= *bound) + .unwrap_or(N - 1); + self.counts[index].fetch_add(1, Ordering::Relaxed); + self.sum.fetch_add(value, Ordering::Relaxed); + } + + pub(super) fn render(&self, text: &mut String, name: &str, help: &str, buckets: &Buckets) { + let _ = writeln!( + text, + "# HELP flare_{name} {help}\n# TYPE flare_{name} histogram" + ); + let mut cumulative = 0; + for (index, bound) in buckets.bounds.iter().enumerate() { + cumulative += self.counts[index].load(Ordering::Relaxed); + let bound = if bound.is_infinite() { + "+Inf".to_string() + } else { + format!("{bound}") + }; + let _ = writeln!( + text, + "flare_{name}_bucket{{le=\"{bound}\"}} {cumulative}" + ); + } + let _ = writeln!( + text, + "flare_{name}_sum {}", + self.sum.load(Ordering::Relaxed) as f64 / buckets.scale + ); + let _ = writeln!(text, "flare_{name}_count {cumulative}"); + } +} + +/// Request lifecycle instants on the `observation::monotonic_ns` clock, kept across preemption. +#[derive(Clone, Copy, Debug, Default)] +pub(super) struct RequestTimes { + pub first_scheduled_ns: Option, + pub first_token_ns: Option, + pub last_token_ns: u64, +} + #[derive(Default)] pub(super) struct Metrics { pub scheduler_trace: scheduler::SchedulerMetrics, @@ -226,6 +323,12 @@ pub(super) struct Metrics { pub admitted: AtomicU64, pub http_requests: [AtomicU64; 5], pub completed: AtomicU64, + pub(super) request_e2e: Histogram<21>, + request_queue: Histogram<21>, + request_prefill: Histogram<21>, + request_decode: Histogram<21>, + time_per_output_token: Histogram<19>, + request_prompt_tokens: Histogram<21>, pub reasoning_budget_cuts: AtomicU64, pub cancelled: AtomicU64, pub failed: AtomicU64, @@ -345,6 +448,38 @@ impl Metrics { } } + /// Records one successfully completed generation in the completion counter and + /// the per-request histograms, so the two cannot diverge. + pub(super) fn request_completed( + &self, + arrival_ns: u64, + times: RequestTimes, + prompt_tokens: usize, + generated_tokens: u32, + ) { + self.completed.fetch_add(1, Ordering::Relaxed); + self.request_prompt_tokens + .observe(&PROMPT_TOKENS, prompt_tokens as u64); + if let Some(scheduled) = times.first_scheduled_ns { + self.request_queue + .observe(&REQUEST_SECONDS, scheduled.saturating_sub(arrival_ns)); + if let Some(first) = times.first_token_ns { + self.request_prefill + .observe(&REQUEST_SECONDS, first.saturating_sub(scheduled)); + } + } + if let Some(first) = times.first_token_ns + && generated_tokens > 1 + { + let decode = times.last_token_ns.saturating_sub(first); + self.request_decode.observe(&REQUEST_SECONDS, decode); + self.time_per_output_token.observe( + &TOKEN_SECONDS, + decode / u64::from(generated_tokens - 1), + ); + } + } + pub fn persistent_worker_snapshot(&self) -> Option { self.persistent_worker .as_ref() @@ -1245,6 +1380,42 @@ impl Metrics { count.load(Ordering::Relaxed) ); } + for (histogram, name, help) in [ + ( + &self.request_e2e, + "request_e2e_seconds", + "Server-side HTTP admission to the completed response of a successful generation request.", + ), + ( + &self.request_queue, + "request_queue_seconds", + "Model-scheduler arrival to the first model step that includes the request, for completed requests.", + ), + ( + &self.request_prefill, + "request_prefill_seconds", + "First model step that includes the request to its first committed generated token, for completed requests.", + ), + ( + &self.request_decode, + "request_decode_seconds", + "First to last committed generated token, for completed requests with at least two generated tokens.", + ), + ] { + histogram.render(&mut text, name, help, &REQUEST_SECONDS); + } + self.time_per_output_token.render( + &mut text, + "time_per_output_token_seconds", + "Decode time divided by generated tokens after the first, for completed requests with at least two generated tokens.", + &TOKEN_SECONDS, + ); + self.request_prompt_tokens.render( + &mut text, + "request_prompt_tokens", + "Prompt tokens per completed request, including tokens reused from the prefix cache.", + &PROMPT_TOKENS, + ); for (name, help, value) in [ ( "constrained_max_inflight", @@ -1471,6 +1642,63 @@ fn render_persistent_worker_metrics( mod tests { use super::*; + #[test] + fn request_histograms_bucket_completed_request_timings() { + let metrics = Metrics::new(0, 0, 0, 16); + metrics.request_completed( + 1_000_000_000, + RequestTimes { + first_scheduled_ns: Some(1_250_000_000), + first_token_ns: Some(1_750_000_000), + last_token_ns: 2_750_000_000, + }, + 3000, + 101, + ); + let text = metrics.render(); + for expected in [ + "flare_request_queue_seconds_bucket{le=\"0.25\"} 1", + "flare_request_queue_seconds_bucket{le=\"0.1\"} 0", + "flare_request_prefill_seconds_bucket{le=\"0.5\"} 1", + "flare_request_decode_seconds_sum 1", + "flare_time_per_output_token_seconds_bucket{le=\"0.01\"} 1", + "flare_time_per_output_token_seconds_bucket{le=\"0.0075\"} 0", + "flare_request_prompt_tokens_bucket{le=\"4096\"} 1", + "flare_request_prompt_tokens_bucket{le=\"2048\"} 0", + "flare_requests_completed_total 1", + ] { + assert!( + text.contains(&format!("\n{expected}\n")), + "missing {expected}" + ); + } + // A single generated token has no decode interval, and a request that never + // reached a model step has no queue or prefill observation. + metrics.request_completed( + 1_000_000_000, + RequestTimes { + first_scheduled_ns: None, + first_token_ns: Some(2_000_000_000), + last_token_ns: 2_500_000_000, + }, + 3000, + 1, + ); + let text = metrics.render(); + for expected in [ + "flare_request_queue_seconds_count 1", + "flare_request_prefill_seconds_count 1", + "flare_request_decode_seconds_count 1", + "flare_request_prompt_tokens_count 2", + "flare_requests_completed_total 2", + ] { + assert!( + text.contains(&format!("\n{expected}\n")), + "missing {expected}" + ); + } + } + #[test] fn checkpoint_metrics_report_capture_roles_rejection_reasons_work_and_reservations() { let metrics = Metrics::new(0, 0, 0, 16); diff --git a/helios/src/server/metrics/process.rs b/helios/src/server/metrics/process.rs new file mode 100644 index 000000000..02338ac98 --- /dev/null +++ b/helios/src/server/metrics/process.rs @@ -0,0 +1,184 @@ +/* SPDX-License-Identifier: Apache-2.0 */ +//! Standard Prometheus process metrics for the serving process. +//! +//! Every source is read directly from procfs or the process's resource limit. +//! A source that cannot be read or parsed omits only the metrics that depend on +//! it, so a scrape never fails and never panics on a missing or malformed file. + +/// Appends the `process_*` metrics. Outside Linux the function writes nothing. +pub(crate) fn render(text: &mut String) { + #[cfg(target_os = "linux")] + render_linux(text); + #[cfg(not(target_os = "linux"))] + let _ = text; +} + +/// Values parsed from `/proc/self/stat`: `utime`, `stime`, `starttime`, `vsize`, +/// and `rss` in the kernel's clock ticks, clock ticks since boot, bytes, and pages. +#[cfg(target_os = "linux")] +fn parse_stat(line: &str) -> Option<[u64; 5]> { + // The command name is parenthesized and may itself contain `)` and spaces, so + // the fields begin after the last `)`. + let tail = line.get(line.rfind(')')? + 1..)?; + let mut fields = tail.split_whitespace(); + // Field 3 (state) is the first token of the tail; stat field N is token N - 3. + let mut value = |skip: usize| -> Option { fields.nth(skip)?.parse().ok() }; + let utime = value(11)?; + let stime = value(0)?; + let starttime = value(6)?; + let vsize = value(0)?; + let rss = value(0)?; + Some([utime, stime, starttime, vsize, rss]) +} + +#[cfg(target_os = "linux")] +fn parse_btime(contents: &str) -> Option { + contents + .lines() + .find_map(|line| line.strip_prefix("btime ")) + .and_then(|value| value.trim().parse().ok()) +} + +#[cfg(target_os = "linux")] +fn metric(text: &mut String, name: &str, kind: &str, help: &str, value: impl std::fmt::Display) { + use std::fmt::Write; + let _ = writeln!( + text, + "# HELP {name} {help}\n# TYPE {name} {kind}\n{name} {value}" + ); +} + +#[cfg(target_os = "linux")] +fn render_linux(text: &mut String) { + // SAFETY: sysconf has no preconditions. + let ticks = unsafe { libc::sysconf(libc::_SC_CLK_TCK) }; + // SAFETY: sysconf has no preconditions. + let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; + let ticks = (ticks > 0).then_some(ticks as u64); + let page = (page > 0).then_some(page as u64); + let stat = std::fs::read_to_string("/proc/self/stat") + .ok() + .and_then(|line| parse_stat(&line)); + let btime = std::fs::read_to_string("/proc/stat") + .ok() + .and_then(|contents| parse_btime(&contents)); + let open_fds = std::fs::read_dir("/proc/self/fd") + .ok() + .map(|entries| entries.filter_map(Result::ok).count() as u64); + let max_fds = { + let mut limit = libc::rlimit { + rlim_cur: 0, + rlim_max: 0, + }; + // SAFETY: getrlimit writes into `limit`, which outlives the call and is a + // valid `rlimit` for `RLIMIT_NOFILE`. + let result = unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) }; + (result == 0).then_some(limit.rlim_cur) + }; + + if let (Some(stat), Some(ticks)) = (stat, ticks) { + metric( + text, + "process_cpu_seconds_total", + "counter", + "User and system CPU time consumed by the serving process.", + (stat[0] + stat[1]) as f64 / ticks as f64, + ); + } + if let Some(stat) = stat { + metric( + text, + "process_virtual_memory_bytes", + "gauge", + "Virtual memory size of the serving process.", + stat[3], + ); + } + if let (Some(stat), Some(page)) = (stat, page) { + metric( + text, + "process_resident_memory_bytes", + "gauge", + "Resident memory size of the serving process.", + stat[4] * page, + ); + } + if let (Some(stat), Some(btime), Some(ticks)) = (stat, btime, ticks) { + metric( + text, + "process_start_time_seconds", + "gauge", + "Start time of the serving process since the Unix epoch.", + btime as f64 + stat[2] as f64 / ticks as f64, + ); + } + if let Some(open_fds) = open_fds { + metric( + text, + "process_open_fds", + "gauge", + "Open file descriptors in the serving process, including the directory read that counts them.", + open_fds, + ); + } + if let Some(max_fds) = max_fds { + metric( + text, + "process_max_fds", + "gauge", + "Maximum open file descriptors for the serving process.", + max_fds, + ); + } +} + +#[cfg(all(test, target_os = "linux"))] +mod tests { + use super::*; + + fn value(text: &str, name: &str) -> f64 { + let prefix = format!("{name} "); + text.lines() + .find_map(|line| line.strip_prefix(&prefix)) + .unwrap_or_else(|| panic!("missing {name}")) + .parse() + .unwrap() + } + + #[test] + fn parse_stat_reads_fields_after_a_parenthesized_command_with_a_paren() { + assert_eq!( + parse_stat("42 (a) b) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21"), + Some([11, 12, 19, 20, 21]) + ); + assert_eq!(parse_stat("42 (no tail)"), None); + } + + #[test] + fn render_reports_process_memory_descriptors_and_start_time() { + let mut text = String::new(); + render(&mut text); + let resident = value(&text, "process_resident_memory_bytes"); + assert!(resident > 0.0, "{resident}"); + assert!(value(&text, "process_virtual_memory_bytes") >= resident); + assert!(value(&text, "process_max_fds") >= value(&text, "process_open_fds")); + assert!(value(&text, "process_open_fds") >= 1.0); + let start = value(&text, "process_start_time_seconds"); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs_f64(); + assert!(start > now - 3600.0, "{start} {now}"); + assert!(start <= now + 1.0, "{start} {now}"); + for name in [ + "process_cpu_seconds_total", + "process_resident_memory_bytes", + "process_virtual_memory_bytes", + "process_start_time_seconds", + "process_open_fds", + "process_max_fds", + ] { + assert!(text.contains(&format!("# TYPE {name} ")), "missing {name}"); + } + } +} diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index 6e61dc23f..8043820ec 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -192,6 +192,8 @@ struct Incoming { failure: Arc>>, metrics: Arc, observation: Option, + /// Lifecycle instants for completion histograms; preserved when a preempted request is parked. + times: super::metrics::RequestTimes, /// Consult the host prefix store at admission; cleared after a failed restore. host_lookup: bool, /// Admitted once already, so the admission counter is not advanced again. @@ -967,6 +969,7 @@ impl ModelRuntime { failure: failure.clone(), metrics: self.metrics.clone(), observation, + times: Default::default(), host_lookup: true, readmitted: false, blocked: None, @@ -1962,6 +1965,8 @@ impl<'a> Worker<'a> { continue; } } + request.incoming.times.first_token_ns.get_or_insert(completed_at_ns); + request.incoming.times.last_token_ns = completed_at_ns; request.incoming.observe_token(token.token); request.last_token = Some(token.token); let was_open = request @@ -2033,18 +2038,23 @@ impl<'a> Worker<'a> { .published_output(token.request, completion.fence)?; } if stop { - self.metrics.completed.fetch_add(1, Ordering::Relaxed); let live = self.scheduler.request(token.request)?; let skipped = burst_counts[slot].saturating_sub(positions[slot] as u32); + let prompt_tokens = + request.carried.prompt_tokens.unwrap_or(live.prompt_tokens); + let generated_tokens = request.carried.generated_tokens + + live.generated_tokens.saturating_sub(skipped); + self.metrics.request_completed( + request.incoming.arrival_ns, + request.incoming.times, + prompt_tokens, + generated_tokens, + ); request .incoming .emit(GenerationEvent::Finished { - prompt_tokens: request - .carried - .prompt_tokens - .unwrap_or(live.prompt_tokens), - generated_tokens: request.carried.generated_tokens - + live.generated_tokens.saturating_sub(skipped), + prompt_tokens, + generated_tokens, reused_prompt_tokens: request .carried .reused_prompt_tokens @@ -2309,7 +2319,12 @@ impl<'a> Worker<'a> { } else { false } || budget_stop; - self.metrics.completed.fetch_add(1, Ordering::Relaxed); + self.metrics.request_completed( + request.incoming.arrival_ns, + request.incoming.times, + request.carried.prompt_tokens.unwrap_or(prompt_tokens), + request.carried.generated_tokens + generated, + ); for token in request.stops.finish() { request .incoming @@ -2508,6 +2523,21 @@ impl<'a> Worker<'a> { fn reserve_and_pack(&mut self, step: &ScheduledPlan, fence: crate::cache::Fence) -> Result<()> { self.scheduler.commit(step, fence)?; + // Stamp here rather than at submission so a request that reaches a model step + // has one, including requests driven through reserve_and_pack directly. + let scheduled_ns = super::observation::monotonic_ns(); + for lane in &step.lanes { + if let Some(active) = self.active[lane.request.slot as usize] + .as_mut() + .filter(|a| a.request == lane.request) + { + active + .incoming + .times + .first_scheduled_ns + .get_or_insert(scheduled_ns); + } + } let inputs = self .inputs .as_mut() @@ -3564,6 +3594,7 @@ mod tests { failure: failure.clone(), metrics: Arc::new(super::super::metrics::Metrics::new(0, 0, 0, 16)), observation: None, + times: Default::default(), host_lookup: true, readmitted: false, prompt_score_end: 0, diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 6ca976e5d..c9332344f 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -242,6 +242,7 @@ impl Fixture { failure: failure.clone(), metrics: self.metrics.clone(), observation: Some(false), + times: Default::default(), host_lookup: true, readmitted: false, prompt_score_end: 0, @@ -566,6 +567,14 @@ fn reasoning_budget_cuts_or_plainly_continues_with_exact_history_and_usage() { assert_eq!(tokens.iter().filter(|&&token| token == 4).count(), 1); assert_eq!(finished, vec![(1, 3 + after, "length")]); assert_eq!(worker.metrics.completed.load(Ordering::Relaxed), 1); + let text = worker.metrics.render(); + for expected in [ + "\nflare_request_queue_seconds_count 1\n", + "\nflare_request_prefill_seconds_count 1\n", + "\nflare_request_prompt_tokens_sum 1\n", + ] { + assert!(text.contains(expected), "missing {expected}"); + } assert_eq!(worker.metrics.admitted.load(Ordering::Relaxed), 1); assert_eq!( worker.metrics.snapshot(false).generated_tokens, @@ -4488,6 +4497,11 @@ async fn first_response_http_stream_excludes_pretext_failures_and_unpolled_bodie let snapshot = state.first_response.snapshot(); assert_eq!(snapshot.samples, u64::from(emit_text && poll_body)); assert_eq!(snapshot.median_seconds.is_some(), emit_text && poll_body); + assert!(state + .model + .metrics() + .render() + .contains("\nflare_request_e2e_seconds_count 0\n")); } } @@ -4516,6 +4530,17 @@ async fn first_response_http_nonstream_records_only_when_completed_body_is_offer drop(response); } assert_eq!(state.first_response.snapshot().samples, u64::from(poll_body)); + assert!(state + .model + .metrics() + .render() + .contains("\nflare_request_e2e_seconds_count 1\n")); + let mut histogram = String::new(); + state.first_response.render_histogram(&mut histogram); + assert!(histogram.contains(&format!( + "\nflare_time_to_first_response_seconds_count {}\n", + u64::from(poll_body) + ))); } } @@ -5424,6 +5449,16 @@ async fn metrics_route_serves_prometheus_or_json_without_the_api_key() { assert!(value["first_response"]["median_seconds"].is_number()); let (_, _, body) = get("/metrics", None).await.unwrap(); assert!(body.contains("\nflare_first_response_median_seconds ")); + assert!( + body.contains("\nflare_time_to_first_response_seconds_count 1\n"), + "{body}" + ); + assert!( + body.contains("\nflare_request_e2e_seconds_bucket{le=\"+Inf\"} 0\n"), + "{body}" + ); + #[cfg(target_os = "linux")] + assert!(body.contains("\nprocess_resident_memory_bytes "), "{body}"); assert_eq!(get("/metrics?format=yaml", None).await.unwrap().0, 400); assert_eq!(get("/health", None).await.unwrap().0, 200); assert_eq!(get("/v1/models", None).await.unwrap().0, 401); From 3b4cf0cff3970353892beba739530ce0fa5bb110 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Thu, 26 Nov 2026 22:55:17 -0600 Subject: [PATCH 02/14] Exclude cancelled responses and reuse host helpers A review of the previous commit found three defects. A response cancelled by the parallel tool-call limit still reaches `Delivery::Complete`, so the HTTP arms observed `flare_request_e2e_seconds` for a request the runtime counts as cancelled, and both arms duplicated the same observation. The documentation claimed request histograms cover "the served response" and named only `flare_` series, contradicting the stream-drain condition, the two-token condition on decode histograms, and the `process_*` series. And `process.rs` read page size, the open-file limit, and the descriptor count with ad-hoc libc and procfs code instead of the host helpers the repository already owns. `generate` now observes the end-to-end histogram once, inside the delivery stream, guarded by `!encoder.tool_limit_reached`, and the two delivery arms only deliver. `disabled_parallel_calls_complete_http_and_stop_decoding` asserts that every path and stream mode in that test records zero end-to-end observations, which covers the cancellation path directly (it ran 326 tests in the `server::` filter, with the one pre-existing template-fixture failure). `docs/api.md` now separates the HTTP histograms, which count delivered responses and require a drained stream, from the runtime histograms, which count completed generations and record decode and time-per-output-token only with at least two generated tokens; it states cumulative-since-start, notes that a request's first model step can be a vision step, and exempts `process_*` from the `flare_` prefix. `process.rs` uses `crate::os::page_size()`, `crate::os::raise_open_file_limit(0)` (read-only), and the descriptor counter that core protection already keeps, re-exported within the crate; only `/proc/self/stat` and the `btime` parse stay local. No behavior changes beyond the cancelled-request exclusion, and no new cost on the serving path. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=2e5b --- docs/api.md | 39 +++++++++++++----------- helios/src/runtime_core/mod.rs | 1 + helios/src/runtime_core/protection.rs | 2 +- helios/src/server/http.rs | 15 +++++---- helios/src/server/metrics/process.rs | 22 +++---------- helios/src/server/runtime/phase_tests.rs | 10 ++++++ 6 files changed, 47 insertions(+), 42 deletions(-) diff --git a/docs/api.md b/docs/api.md index aec46e9fe..4949d8118 100644 --- a/docs/api.md +++ b/docs/api.md @@ -288,29 +288,32 @@ requires the serving key: both report aggregate state without request content. `GET /metrics` returns Prometheus text exposition format 0.0.4 by default. Counter and gauge names start with `flare_`, such as `flare_generated_tokens_total`, `flare_active_requests`, and -`flare_free_kv_pages`. Beyond the JSON fields below, the +`flare_free_kv_pages`, except the standard `process_*` series described below. +Beyond the JSON fields below, the text includes speculative and proposal counters by batch, width, or depth, graph launches by kind, embedding row-cache counters, HTTP admission gauges, and uptime. -Histograms appear in the Prometheus format only. Host prefix-store histograms -report lookup cost and retirement: `flare_host_cache_missing_tokens`, -`flare_host_cache_estimated_transfer_ns`, +Histograms appear in the Prometheus format only and accumulate since server +start. Host prefix-store histograms report lookup cost and retirement: +`flare_host_cache_missing_tokens`, `flare_host_cache_estimated_transfer_ns`, `flare_host_cache_estimated_prefill_ns`, and -`flare_host_cache_retirement_seconds`. Request histograms observe the served -response. `flare_request_e2e_seconds` counts each successful generation from -admission to the completed response, and -`flare_time_to_first_response_seconds` counts each response that offers answer -or reasoning text, from admission to that text, once the client reads it. The -runtime records one observation per completed generation in -`flare_request_queue_seconds` from model-scheduler arrival to the first model -step that includes the request, `flare_request_prefill_seconds` from that step to -the request's first committed generated token, `flare_request_decode_seconds` -from the first to the last committed generated token, -`flare_time_per_output_token_seconds` as decode time divided by generated tokens -after the first, and `flare_request_prompt_tokens` for prompt tokens including -tokens reused from the prefix cache. Cancelled and failed requests enter only -`flare_requests_cancelled_total` and `flare_requests_failed_total`. +`flare_host_cache_retirement_seconds`. + +The HTTP histograms observe delivery. `flare_request_e2e_seconds` counts each +successful generation from admission to the completed response; for a stream it +is observed when delivery completes, which requires the client to drain the +body. `flare_time_to_first_response_seconds` counts each response that offers +answer or reasoning text, from admission to that text, once the client reads it. + +The runtime histograms observe completed generations. `flare_request_queue_seconds` +spans model-scheduler arrival to the first model step that includes the request, +which can be a vision step; `flare_request_prefill_seconds` spans that step to +the request's first committed generated token; `flare_request_decode_seconds` +and `flare_time_per_output_token_seconds` are recorded only for requests with at +least two generated tokens; `flare_request_prompt_tokens` counts prompt tokens +including tokens reused from the prefix cache. Cancelled and failed requests +enter only `flare_requests_cancelled_total` and `flare_requests_failed_total`. On Linux the text also carries `process_cpu_seconds_total`, `process_resident_memory_bytes`, `process_virtual_memory_bytes`, diff --git a/helios/src/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index 1f2f01cf3..fc0d00027 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -60,6 +60,7 @@ pub use protection::{ AuthorizedCore, CoreClaim, CoreLicense, PayloadAuthorizedCore, PayloadSource, PayloadVerifiedCore, Publisher, VerifiedCore, verify_core_metadata, }; +pub(crate) use protection::open_descriptors; use std::path::Path; mod selection; mod serving; diff --git a/helios/src/runtime_core/protection.rs b/helios/src/runtime_core/protection.rs index affa8624f..1027c345f 100644 --- a/helios/src/runtime_core/protection.rs +++ b/helios/src/runtime_core/protection.rs @@ -288,7 +288,7 @@ fn open_file_budget(current: u64, required: u64, limit: u64) -> Result<()> { } /// Descriptors this process currently holds, when the platform can report them. -fn open_descriptors() -> Option { +pub(crate) fn open_descriptors() -> Option { #[cfg(target_os = "linux")] { std::fs::read_dir("/proc/self/fd") diff --git a/helios/src/server/http.rs b/helios/src/server/http.rs index 4bdb37da1..6b8baebce 100644 --- a/helios/src/server/http.rs +++ b/helios/src/server/http.rs @@ -595,12 +595,19 @@ pub(super) async fn generate( false, ); } + // One observation per successful response: a tool-limit cancellation reaches + // this point but the runtime counts it as cancelled, so it is excluded. + if !count && !encoder.tool_limit_reached { + state.model.metrics().request_e2e.observe( + &super::metrics::REQUEST_SECONDS, + admitted_at.elapsed().as_nanos() as u64, + ); + } yield Delivery::Complete(response); }; if streaming { let request_id = id.clone(); let log_to_stderr = state.log_to_stderr; - let metrics = state.model.metrics_handle(); let events = delivery.filter_map(move |event| { let event = match event { Delivery::Frame(frame) => { @@ -611,10 +618,7 @@ pub(super) async fn generate( if log_to_stderr { log_failure(&request_id, "stream", &error); } Some(Ok::<_, Infallible>(frame.sse())) } - Delivery::Complete(_) => { - if !count { metrics.request_e2e.observe(&super::metrics::REQUEST_SECONDS, admitted_at.elapsed().as_nanos() as u64); } - None - } + Delivery::Complete(_) => None, }; std::future::ready(event) }); @@ -629,7 +633,6 @@ pub(super) async fn generate( while let Some(event) = delivery.next().await { match event { Delivery::Complete(body) => { - if !count { state.model.metrics().request_e2e.observe(&super::metrics::REQUEST_SECONDS, admitted_at.elapsed().as_nanos() as u64); } let visible = super::latency::response_text(&body); let response = with_request_id(Json(body).into_response(), &id); if !visible { return response; } diff --git a/helios/src/server/metrics/process.rs b/helios/src/server/metrics/process.rs index 02338ac98..90ccdaeac 100644 --- a/helios/src/server/metrics/process.rs +++ b/helios/src/server/metrics/process.rs @@ -52,29 +52,17 @@ fn metric(text: &mut String, name: &str, kind: &str, help: &str, value: impl std fn render_linux(text: &mut String) { // SAFETY: sysconf has no preconditions. let ticks = unsafe { libc::sysconf(libc::_SC_CLK_TCK) }; - // SAFETY: sysconf has no preconditions. - let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; let ticks = (ticks > 0).then_some(ticks as u64); - let page = (page > 0).then_some(page as u64); + let page = crate::os::page_size() as u64; let stat = std::fs::read_to_string("/proc/self/stat") .ok() .and_then(|line| parse_stat(&line)); let btime = std::fs::read_to_string("/proc/stat") .ok() .and_then(|contents| parse_btime(&contents)); - let open_fds = std::fs::read_dir("/proc/self/fd") - .ok() - .map(|entries| entries.filter_map(Result::ok).count() as u64); - let max_fds = { - let mut limit = libc::rlimit { - rlim_cur: 0, - rlim_max: 0, - }; - // SAFETY: getrlimit writes into `limit`, which outlives the call and is a - // valid `rlimit` for `RLIMIT_NOFILE`. - let result = unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) }; - (result == 0).then_some(limit.rlim_cur) - }; + let open_fds = crate::runtime_core::open_descriptors(); + // A zero target only reads the current soft limit. + let max_fds = crate::os::raise_open_file_limit(0); if let (Some(stat), Some(ticks)) = (stat, ticks) { metric( @@ -94,7 +82,7 @@ fn render_linux(text: &mut String) { stat[3], ); } - if let (Some(stat), Some(page)) = (stat, page) { + if let Some(stat) = stat { metric( text, "process_resident_memory_bytes", diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index c9332344f..6377131c0 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -4673,6 +4673,16 @@ async fn disabled_parallel_calls_complete_http_and_stop_decoding() { assert!(worker.plan().unwrap().0.is_none(), "request must not keep decoding"); let bytes = tokio::time::timeout(std::time::Duration::from_secs(5), reader).await.unwrap().unwrap(); let text = std::str::from_utf8(&bytes).unwrap(); + // A tool-limit cancellation completes delivery but is not a successful + // generation, so it records no end-to-end observation. + assert!( + state + .model + .metrics() + .render() + .contains("\nflare_request_e2e_seconds_count 0\n"), + "{path} {stream}" + ); assert!(!text.contains(r#""d""#) && !text.contains(r#"\"d\""#), "{text}"); let frames: Vec = if stream { text.lines().filter_map(|line| line.strip_prefix("data: ")) From 4ed9c43f4fe17e4297fc0c47b5d70e65eedb4a2e Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Thu, 26 Nov 2026 23:02:24 -0600 Subject: [PATCH 03/14] Hoist completion values and tighten stat parsing Review nits on the previous commits: `Worker::publish` repeated the prompt and generated-token expressions in the metric call and the terminal event, the first-response histogram renderer sat in a second impl block, `parse_stat` accepted any line containing `)`, and the histogram test used a state a real request cannot reach (`first_scheduled_ns: None` with a token present). `publish` now hoists the two values as `complete` does, the renderer lives in the existing `FirstResponseSamples` impl, `parse_stat` rejects a line whose first field after the command name is not a process state character, and the zero-work case uses `RequestTimes::default()`, which is reachable through a zero-token completion. No behavior changes; the parsers and metrics output are unchanged for valid input. Evidence: `cargo test --locked --release --manifest-path helios/Cargo.toml --target-dir ~/.cache/hyperflare-target --features runtime-core,server --lib -- server::metrics` passed 20 tests, including the request histogram and both process-metrics tests, and `-- server::` passed 326 with the one pre-existing template-fixture failure. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=2e5b --- helios/src/server/latency.rs | 19 ++++++++----------- helios/src/server/metrics.rs | 15 +++------------ helios/src/server/metrics/process.rs | 7 ++++++- helios/src/server/runtime.rs | 14 +++++++------- 4 files changed, 24 insertions(+), 31 deletions(-) diff --git a/helios/src/server/latency.rs b/helios/src/server/latency.rs index 15e58dd6c..760739281 100644 --- a/helios/src/server/latency.rs +++ b/helios/src/server/latency.rs @@ -98,6 +98,14 @@ impl FirstResponseSamples { truncated, } } + pub(super) fn render_histogram(&self, text: &mut String) { + self.histogram.render( + text, + "time_to_first_response_seconds", + "Server-side HTTP admission to the first offered answer or reasoning text.", + &super::metrics::REQUEST_SECONDS, + ); + } } pub(super) struct FirstResponse { samples: Arc, @@ -119,17 +127,6 @@ impl FirstResponse { } } -impl FirstResponseSamples { - pub(super) fn render_histogram(&self, text: &mut String) { - self.histogram.render( - text, - "time_to_first_response_seconds", - "Server-side HTTP admission to the first offered answer or reasoning text.", - &super::metrics::REQUEST_SECONDS, - ); - } -} - /// Only answer/reasoning text is eligible. Roles, keepalives, token observations, /// usage, signatures and tool-only content do not represent visible text here. pub(super) fn stream_text(value: &serde_json::Value) -> bool { diff --git a/helios/src/server/metrics.rs b/helios/src/server/metrics.rs index a5bbe1201..38218abb8 100644 --- a/helios/src/server/metrics.rs +++ b/helios/src/server/metrics.rs @@ -1672,18 +1672,9 @@ mod tests { "missing {expected}" ); } - // A single generated token has no decode interval, and a request that never - // reached a model step has no queue or prefill observation. - metrics.request_completed( - 1_000_000_000, - RequestTimes { - first_scheduled_ns: None, - first_token_ns: Some(2_000_000_000), - last_token_ns: 2_500_000_000, - }, - 3000, - 1, - ); + // A zero-token completion reaches no model step and commits no token, so it + // adds only a prompt-size observation. + metrics.request_completed(1_000_000_000, RequestTimes::default(), 3000, 0); let text = metrics.render(); for expected in [ "flare_request_queue_seconds_count 1", diff --git a/helios/src/server/metrics/process.rs b/helios/src/server/metrics/process.rs index 90ccdaeac..957575f0e 100644 --- a/helios/src/server/metrics/process.rs +++ b/helios/src/server/metrics/process.rs @@ -21,9 +21,14 @@ fn parse_stat(line: &str) -> Option<[u64; 5]> { // the fields begin after the last `)`. let tail = line.get(line.rfind(')')? + 1..)?; let mut fields = tail.split_whitespace(); + // The state character follows the command name; rejecting a line without one + // keeps this parser from reading unrelated text that happens to contain `)`. + if !fields.next()?.chars().next().is_some_and(|state| "RSDZTtWXxKPI".contains(state)) { + return None; + } // Field 3 (state) is the first token of the tail; stat field N is token N - 3. let mut value = |skip: usize| -> Option { fields.nth(skip)?.parse().ok() }; - let utime = value(11)?; + let utime = value(10)?; let stime = value(0)?; let starttime = value(6)?; let vsize = value(0)?; diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index 8043820ec..db568d817 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -2319,11 +2319,14 @@ impl<'a> Worker<'a> { } else { false } || budget_stop; + let prompt_tokens = + request.carried.prompt_tokens.unwrap_or(prompt_tokens); + let generated_tokens = request.carried.generated_tokens + generated; self.metrics.request_completed( request.incoming.arrival_ns, request.incoming.times, - request.carried.prompt_tokens.unwrap_or(prompt_tokens), - request.carried.generated_tokens + generated, + prompt_tokens, + generated_tokens, ); for token in request.stops.finish() { request @@ -2341,11 +2344,8 @@ impl<'a> Worker<'a> { request .incoming .emit(GenerationEvent::Finished { - prompt_tokens: request - .carried - .prompt_tokens - .unwrap_or(prompt_tokens), - generated_tokens: request.carried.generated_tokens + generated, + prompt_tokens, + generated_tokens, reused_prompt_tokens: request .carried .reused_prompt_tokens From de6d989b878f887a1700748805bc3ac555ce0c23 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 14:56:42 -0600 Subject: [PATCH 04/14] Remove process metrics from the request latency change The process_* series (CPU time, resident and virtual memory, start time, open and maximum file descriptors) describe the serving process, not request latency, so they formed a second outcome inside a change whose purpose is request histograms. Their renderer also read procfs on every text scrape and called crate::runtime_core from server code, which does not compile when helios is built with only the server feature. This deletes helios/src/server/metrics/process.rs and its render call in the /metrics handler, the docs/api.md paragraph and the naming exception that described the series, the route-test assertion, and the open_descriptors re-export that only the renderer used. /metrics again exports only flare_-prefixed series, a text scrape reads no procfs files, and the server-only build compiles. cargo check --locked --manifest-path helios/Cargo.toml --features server is clean. cargo test --features runtime-core,server --lib -- server::metrics server::latency metrics_route_serves passed 23 tests. No GPU workload ran. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=2e5b --- docs/api.md | 8 +- helios/src/runtime_core/mod.rs | 1 - helios/src/runtime_core/protection.rs | 2 +- helios/src/server.rs | 1 - helios/src/server/metrics.rs | 1 - helios/src/server/metrics/process.rs | 177 ----------------------- helios/src/server/runtime/phase_tests.rs | 2 - 7 files changed, 2 insertions(+), 190 deletions(-) delete mode 100644 helios/src/server/metrics/process.rs diff --git a/docs/api.md b/docs/api.md index 4949d8118..20275868a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -288,8 +288,7 @@ requires the serving key: both report aggregate state without request content. `GET /metrics` returns Prometheus text exposition format 0.0.4 by default. Counter and gauge names start with `flare_`, such as `flare_generated_tokens_total`, `flare_active_requests`, and -`flare_free_kv_pages`, except the standard `process_*` series described below. -Beyond the JSON fields below, the +`flare_free_kv_pages`. Beyond the JSON fields below, the text includes speculative and proposal counters by batch, width, or depth, graph launches by kind, embedding row-cache counters, HTTP admission gauges, and uptime. @@ -315,11 +314,6 @@ least two generated tokens; `flare_request_prompt_tokens` counts prompt tokens including tokens reused from the prefix cache. Cancelled and failed requests enter only `flare_requests_cancelled_total` and `flare_requests_failed_total`. -On Linux the text also carries `process_cpu_seconds_total`, -`process_resident_memory_bytes`, `process_virtual_memory_bytes`, -`process_start_time_seconds`, `process_open_fds`, and `process_max_fds` for the -serving process. Other platforms omit them. - The route returns one JSON object instead when the query contains `format=json`, or when the `Accept` header gives `application/json` a higher quality than `text/plain`; at equal quality the earlier media range wins. `format=prometheus` diff --git a/helios/src/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index fc0d00027..1f2f01cf3 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -60,7 +60,6 @@ pub use protection::{ AuthorizedCore, CoreClaim, CoreLicense, PayloadAuthorizedCore, PayloadSource, PayloadVerifiedCore, Publisher, VerifiedCore, verify_core_metadata, }; -pub(crate) use protection::open_descriptors; use std::path::Path; mod selection; mod serving; diff --git a/helios/src/runtime_core/protection.rs b/helios/src/runtime_core/protection.rs index 1027c345f..affa8624f 100644 --- a/helios/src/runtime_core/protection.rs +++ b/helios/src/runtime_core/protection.rs @@ -288,7 +288,7 @@ fn open_file_budget(current: u64, required: u64, limit: u64) -> Result<()> { } /// Descriptors this process currently holds, when the platform can report them. -pub(crate) fn open_descriptors() -> Option { +fn open_descriptors() -> Option { #[cfg(target_os = "linux")] { std::fs::read_dir("/proc/self/fd") diff --git a/helios/src/server.rs b/helios/src/server.rs index 70ddb69b1..cd415e0f6 100644 --- a/helios/src/server.rs +++ b/helios/src/server.rs @@ -706,7 +706,6 @@ async fn metrics(State(state): State>, uri: Uri, headers: HeaderM ] { metrics::metric(&mut text, name, "gauge", help, value as u64); } - metrics::process::render(&mut text); ( [ (header::CONTENT_TYPE, "text/plain; version=0.0.4; charset=utf-8"), diff --git a/helios/src/server/metrics.rs b/helios/src/server/metrics.rs index 38218abb8..b1ef509bb 100644 --- a/helios/src/server/metrics.rs +++ b/helios/src/server/metrics.rs @@ -9,7 +9,6 @@ use std::{ sync::atomic::{AtomicU64, Ordering}, }; -pub(super) mod process; pub(super) mod scheduler; pub(super) fn input_metrics( diff --git a/helios/src/server/metrics/process.rs b/helios/src/server/metrics/process.rs deleted file mode 100644 index 957575f0e..000000000 --- a/helios/src/server/metrics/process.rs +++ /dev/null @@ -1,177 +0,0 @@ -/* SPDX-License-Identifier: Apache-2.0 */ -//! Standard Prometheus process metrics for the serving process. -//! -//! Every source is read directly from procfs or the process's resource limit. -//! A source that cannot be read or parsed omits only the metrics that depend on -//! it, so a scrape never fails and never panics on a missing or malformed file. - -/// Appends the `process_*` metrics. Outside Linux the function writes nothing. -pub(crate) fn render(text: &mut String) { - #[cfg(target_os = "linux")] - render_linux(text); - #[cfg(not(target_os = "linux"))] - let _ = text; -} - -/// Values parsed from `/proc/self/stat`: `utime`, `stime`, `starttime`, `vsize`, -/// and `rss` in the kernel's clock ticks, clock ticks since boot, bytes, and pages. -#[cfg(target_os = "linux")] -fn parse_stat(line: &str) -> Option<[u64; 5]> { - // The command name is parenthesized and may itself contain `)` and spaces, so - // the fields begin after the last `)`. - let tail = line.get(line.rfind(')')? + 1..)?; - let mut fields = tail.split_whitespace(); - // The state character follows the command name; rejecting a line without one - // keeps this parser from reading unrelated text that happens to contain `)`. - if !fields.next()?.chars().next().is_some_and(|state| "RSDZTtWXxKPI".contains(state)) { - return None; - } - // Field 3 (state) is the first token of the tail; stat field N is token N - 3. - let mut value = |skip: usize| -> Option { fields.nth(skip)?.parse().ok() }; - let utime = value(10)?; - let stime = value(0)?; - let starttime = value(6)?; - let vsize = value(0)?; - let rss = value(0)?; - Some([utime, stime, starttime, vsize, rss]) -} - -#[cfg(target_os = "linux")] -fn parse_btime(contents: &str) -> Option { - contents - .lines() - .find_map(|line| line.strip_prefix("btime ")) - .and_then(|value| value.trim().parse().ok()) -} - -#[cfg(target_os = "linux")] -fn metric(text: &mut String, name: &str, kind: &str, help: &str, value: impl std::fmt::Display) { - use std::fmt::Write; - let _ = writeln!( - text, - "# HELP {name} {help}\n# TYPE {name} {kind}\n{name} {value}" - ); -} - -#[cfg(target_os = "linux")] -fn render_linux(text: &mut String) { - // SAFETY: sysconf has no preconditions. - let ticks = unsafe { libc::sysconf(libc::_SC_CLK_TCK) }; - let ticks = (ticks > 0).then_some(ticks as u64); - let page = crate::os::page_size() as u64; - let stat = std::fs::read_to_string("/proc/self/stat") - .ok() - .and_then(|line| parse_stat(&line)); - let btime = std::fs::read_to_string("/proc/stat") - .ok() - .and_then(|contents| parse_btime(&contents)); - let open_fds = crate::runtime_core::open_descriptors(); - // A zero target only reads the current soft limit. - let max_fds = crate::os::raise_open_file_limit(0); - - if let (Some(stat), Some(ticks)) = (stat, ticks) { - metric( - text, - "process_cpu_seconds_total", - "counter", - "User and system CPU time consumed by the serving process.", - (stat[0] + stat[1]) as f64 / ticks as f64, - ); - } - if let Some(stat) = stat { - metric( - text, - "process_virtual_memory_bytes", - "gauge", - "Virtual memory size of the serving process.", - stat[3], - ); - } - if let Some(stat) = stat { - metric( - text, - "process_resident_memory_bytes", - "gauge", - "Resident memory size of the serving process.", - stat[4] * page, - ); - } - if let (Some(stat), Some(btime), Some(ticks)) = (stat, btime, ticks) { - metric( - text, - "process_start_time_seconds", - "gauge", - "Start time of the serving process since the Unix epoch.", - btime as f64 + stat[2] as f64 / ticks as f64, - ); - } - if let Some(open_fds) = open_fds { - metric( - text, - "process_open_fds", - "gauge", - "Open file descriptors in the serving process, including the directory read that counts them.", - open_fds, - ); - } - if let Some(max_fds) = max_fds { - metric( - text, - "process_max_fds", - "gauge", - "Maximum open file descriptors for the serving process.", - max_fds, - ); - } -} - -#[cfg(all(test, target_os = "linux"))] -mod tests { - use super::*; - - fn value(text: &str, name: &str) -> f64 { - let prefix = format!("{name} "); - text.lines() - .find_map(|line| line.strip_prefix(&prefix)) - .unwrap_or_else(|| panic!("missing {name}")) - .parse() - .unwrap() - } - - #[test] - fn parse_stat_reads_fields_after_a_parenthesized_command_with_a_paren() { - assert_eq!( - parse_stat("42 (a) b) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21"), - Some([11, 12, 19, 20, 21]) - ); - assert_eq!(parse_stat("42 (no tail)"), None); - } - - #[test] - fn render_reports_process_memory_descriptors_and_start_time() { - let mut text = String::new(); - render(&mut text); - let resident = value(&text, "process_resident_memory_bytes"); - assert!(resident > 0.0, "{resident}"); - assert!(value(&text, "process_virtual_memory_bytes") >= resident); - assert!(value(&text, "process_max_fds") >= value(&text, "process_open_fds")); - assert!(value(&text, "process_open_fds") >= 1.0); - let start = value(&text, "process_start_time_seconds"); - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_secs_f64(); - assert!(start > now - 3600.0, "{start} {now}"); - assert!(start <= now + 1.0, "{start} {now}"); - for name in [ - "process_cpu_seconds_total", - "process_resident_memory_bytes", - "process_virtual_memory_bytes", - "process_start_time_seconds", - "process_open_fds", - "process_max_fds", - ] { - assert!(text.contains(&format!("# TYPE {name} ")), "missing {name}"); - } - } -} diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 6377131c0..cb1fb1c0c 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -5467,8 +5467,6 @@ async fn metrics_route_serves_prometheus_or_json_without_the_api_key() { body.contains("\nflare_request_e2e_seconds_bucket{le=\"+Inf\"} 0\n"), "{body}" ); - #[cfg(target_os = "linux")] - assert!(body.contains("\nprocess_resident_memory_bytes "), "{body}"); assert_eq!(get("/metrics?format=yaml", None).await.unwrap().0, 400); assert_eq!(get("/health", None).await.unwrap().0, 200); assert_eq!(get("/v1/models", None).await.unwrap().0, 401); From 5898e156c23a06c9486f80aa4cdc881bfde9a93f Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 15:17:55 -0600 Subject: [PATCH 05/14] Add per-request histograms that match vLLM's request metrics `/metrics` has per-request histograms for end-to-end, queue, prefill, and decode time, time per output token, and prompt size, but none for the other per-request distributions vLLM exposes: time to first token inside the engine, inter-token latency, time from first scheduling to the last token, generated and freshly computed prompt tokens, the output limit, preemptions per request, the `n` parameter, and the largest output among one prompt's choices. A dashboard built on vLLM's metrics therefore has no Flare series to read for them. The project maintainer approved bringing Flare's metrics to vLLM parity for quantities Flare already has. Every one of these values already exists in the runtime worker or the HTTP generation handler at the points where the existing histograms record, so recording them there adds no instrumentation to GPU or cache paths. `Incoming.times` becomes `Incoming.record`, a `RequestRecord` that keeps the lifecycle instants, the output limit taken at first admission (the prompt's limit plus the tokens a reasoning budget defers), a preemption count that `Worker::park_if_preempted` increments when it parks a preempted request, and a 19-bucket histogram of intervals between the request's committing steps. `Worker::complete` calls `RequestRecord::tokens_committed` once per model step that commits tokens for a request, so a speculative round that commits several tokens adds one interval, as vLLM's per-iteration accounting does. The record moves with the request through parking and readmission. `Metrics::request_completed` takes the record and a `CompletedRequest` (prompt, reused, and generated tokens) and now also records `flare_time_to_first_token_seconds`, `flare_request_inference_seconds`, `flare_request_prefill_computed_tokens` (prompt minus tokens reused at first admission), `flare_request_generated_tokens`, `flare_request_max_tokens`, and `flare_request_preemptions`, and merges the request's intervals into `flare_inter_token_latency_seconds`. Cancelled and failed requests never reach `request_completed`, so they stay out of every new histogram, as they do out of the existing ones. The HTTP handler's end-to-end observation moves into `Metrics::response_completed`, which also records `flare_request_choices` (the `n` parameter) and `flare_request_max_choice_generated_tokens` once per prompt of a successful response; only `/v1/completions` accepts `n` above one, and each choice runs as its own model request. The prompt-token bucket constant is renamed `TOKEN_COUNTS` because every token-count histogram uses it; the preemption and `n` histograms use vLLM's default bounds, the preemption one with an added zero bound so never-preempted requests stay separate. `docs/api.md` defines each series, its units, and which requests it counts. The claimed result is observability only: the distributions above become scrapeable, and no admission, scheduling, or cache decision changes. The added cost, stated from the code and not measured, is one bucket search over at most 19 bounds and two uncontended atomic adds per committing step per request, about ten histogram observations and a 20-counter merge per completed request, two observations per prompt per HTTP response, and 168 bytes per queued or active request for the record's histogram, limit, and count. Evidence: `cargo test --locked --manifest-path helios/Cargo.toml --features runtime-core,server --target-dir /tmp/mc/target --lib -- server::metrics server::runtime` passed 148 tests (one ignored). `request_histograms_bucket_completed_request_timings` drives `tokens_committed` through three committing steps and checks every new histogram's buckets and sums, and that a zero-token completion adds only token and preemption observations. `response_histograms_count_choices_and_largest_choice_per_prompt` checks the per-prompt grouping of choices. `reasoning_budget_cuts_after_a_multi_token_speculative_completion` checks two inter-token observations for three committing steps that include a three-token speculative round, an output limit spanning the reasoning budget and its remainder, and zero preemptions for a reasoning park. `exercise_text_preemption` (through `reasoning_budget_survives_preemption_and_checkpoint_recomputation`) checks that the parked request carries one preemption and that the completed request lands in the one-preemption bucket. `prefill_computed_tokens_exclude_the_prefix_reused_at_admission` completes two identical prompts and checks 13 computed tokens for the first and zero for the second, which restored the first one's checkpoint. These tests run the worker without a GPU; serving on hardware has not been run. Time to first token starts at model-scheduler arrival rather than at HTTP arrival as in vLLM, and vLLM also observes aborted requests, which Flare excludes. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=2e5b --- docs/api.md | 38 +++- helios/src/server/http.rs | 7 +- helios/src/server/metrics.rs | 277 +++++++++++++++++++++-- helios/src/server/runtime.rs | 62 ++--- helios/src/server/runtime/phase_tests.rs | 57 ++++- 5 files changed, 384 insertions(+), 57 deletions(-) diff --git a/docs/api.md b/docs/api.md index 20275868a..e21853beb 100644 --- a/docs/api.md +++ b/docs/api.md @@ -304,15 +304,43 @@ successful generation from admission to the completed response; for a stream it is observed when delivery completes, which requires the client to drain the body. `flare_time_to_first_response_seconds` counts each response that offers answer or reasoning text, from admission to that text, once the client reads it. +With `flare_request_e2e_seconds`, each response also adds one observation per +prompt to `flare_request_choices`, the requested choice count `n`, and to +`flare_request_max_choice_generated_tokens`, the largest generated-token count +among that prompt's choices. Only `/v1/completions` accepts `n` above one or a +list of prompts; Flare runs each choice as its own model request. The runtime histograms observe completed generations. `flare_request_queue_seconds` spans model-scheduler arrival to the first model step that includes the request, which can be a vision step; `flare_request_prefill_seconds` spans that step to -the request's first committed generated token; `flare_request_decode_seconds` -and `flare_time_per_output_token_seconds` are recorded only for requests with at -least two generated tokens; `flare_request_prompt_tokens` counts prompt tokens -including tokens reused from the prefix cache. Cancelled and failed requests -enter only `flare_requests_cancelled_total` and `flare_requests_failed_total`. +the request's first committed generated token, and +`flare_request_inference_seconds` spans it to the last committed generated token. +`flare_time_to_first_token_seconds` spans model-scheduler arrival to the first +committed generated token; unlike `flare_time_to_first_response_seconds`, it +excludes HTTP preparation and counts tokens that produce no visible text. +`flare_request_decode_seconds` and `flare_time_per_output_token_seconds` are +recorded only for requests with at least two generated tokens. +`flare_inter_token_latency_seconds` observes, for every model step after the +first that commits generated tokens for a request, the time since the previous +such step: a speculative round committing several tokens is one observation, and +the interval that spans a preemption includes the wait for readmission. A +request's intervals enter the histogram when it completes. + +The runtime token histograms count per completed request. +`flare_request_prompt_tokens` counts prompt tokens including tokens reused from +the prefix cache, and `flare_request_prefill_computed_tokens` subtracts the +tokens that GPU or host prefix reuse supplied at the request's first admission; +recomputation after a preemption is not included. +`flare_request_generated_tokens` counts committed generated tokens, including +EOS, tokens withheld by text stops, and a forced reasoning close. +`flare_request_max_tokens` records the output limit at first admission: the +client's `max_tokens` or `max_completion_tokens`, else the server default capped +by the remaining context, including tokens a reasoning budget defers. +Prompt-scoring requests with a zero limit are not observed. +`flare_request_preemptions` counts how many times each request was preempted and +readmitted; its buckets are vLLM's preemption bounds with an added zero bound. +Cancelled and failed requests enter only `flare_requests_cancelled_total` and +`flare_requests_failed_total`. The route returns one JSON object instead when the query contains `format=json`, or when the `Accept` header gives `application/json` a higher quality than diff --git a/helios/src/server/http.rs b/helios/src/server/http.rs index 6b8baebce..7f54c7713 100644 --- a/helios/src/server/http.rs +++ b/helios/src/server/http.rs @@ -400,6 +400,7 @@ pub(super) async fn generate( let mut raw_tokens = Vec::new(); let mut timestamps = Vec::new(); let mut reused_total = 0; + let mut generated = vec![0u32; size]; if streaming && protocol == Protocol::Chat { // Chat has one choice and rejects streamed prompt logprobs, so no // output queue needs draining before the first raw token is ready. @@ -522,6 +523,7 @@ pub(super) async fn generate( .. } => { reused_total += reused_prompt_tokens; + generated[index] = generated_tokens; let result = decoders[index] .finish(if encoder.tool_limit_reached { crate::output::Termination::Cancelled } else { termination }) .and_then(|events| encoder.apply(index, events)) @@ -598,9 +600,10 @@ pub(super) async fn generate( // One observation per successful response: a tool-limit cancellation reaches // this point but the runtime counts it as cancelled, so it is excluded. if !count && !encoder.tool_limit_reached { - state.model.metrics().request_e2e.observe( - &super::metrics::REQUEST_SECONDS, + state.model.metrics().response_completed( admitted_at.elapsed().as_nanos() as u64, + decoded.request.choices, + &generated, ); } yield Delivery::Complete(response); diff --git a/helios/src/server/metrics.rs b/helios/src/server/metrics.rs index b1ef509bb..03613ffee 100644 --- a/helios/src/server/metrics.rs +++ b/helios/src/server/metrics.rs @@ -231,7 +231,7 @@ pub(super) const TOKEN_SECONDS: Buckets<19> = Buckets { scale: 1e9, }; -pub(super) const PROMPT_TOKENS: Buckets<21> = Buckets { +pub(super) const TOKEN_COUNTS: Buckets<21> = Buckets { bounds: [ 1.0, 8.0, 16.0, 32.0, 64.0, 128.0, 256.0, 512.0, 1024.0, 2048.0, 4096.0, 8192.0, 16384.0, 32768.0, 65536.0, 131072.0, 262144.0, 524288.0, 1048576.0, 2097152.0, f64::INFINITY, @@ -239,6 +239,19 @@ pub(super) const PROMPT_TOKENS: Buckets<21> = Buckets { scale: 1.0, }; +/// vLLM's preemption-count bounds with a leading zero bound, so never-preempted +/// requests stay separate from requests preempted once. +pub(super) const PREEMPTION_COUNTS: Buckets<9> = Buckets { + bounds: [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 10.0, 20.0, f64::INFINITY], + scale: 1.0, +}; + +/// vLLM's bounds for the `n` request parameter. +pub(super) const CHOICE_COUNTS: Buckets<6> = Buckets { + bounds: [1.0, 2.0, 5.0, 10.0, 20.0, f64::INFINITY], + scale: 1.0, +}; + /// Fixed-bucket Prometheus histogram: per-bucket observations and the sum of the /// observed values, both on the exposed unit's integer grid. pub(super) struct Histogram { @@ -269,6 +282,18 @@ impl Histogram { self.sum.fetch_add(value, Ordering::Relaxed); } + /// Adds the observations of `other`, which shares this histogram's buckets. + fn absorb(&self, other: &Self) { + for (count, added) in self.counts.iter().zip(&other.counts) { + let added = added.load(Ordering::Relaxed); + if added != 0 { + count.fetch_add(added, Ordering::Relaxed); + } + } + self.sum + .fetch_add(other.sum.load(Ordering::Relaxed), Ordering::Relaxed); + } + pub(super) fn render(&self, text: &mut String, name: &str, help: &str, buckets: &Buckets) { let _ = writeln!( text, @@ -304,6 +329,47 @@ pub(super) struct RequestTimes { pub last_token_ns: u64, } +/// Values a request accumulates for the completion histograms. The record moves +/// with the request through preemption and readmission and is observed once, by +/// [`Metrics::request_completed`], only if the request completes successfully. +#[derive(Default)] +pub(super) struct RequestRecord { + pub times: RequestTimes, + /// Output token limit at first admission, including tokens allowed after a + /// reasoning budget. + pub max_tokens: u32, + /// Times the request was preempted and parked for readmission. + pub preemptions: u32, + /// Intervals between successive model steps that committed generated tokens + /// for the request, merged into the server histogram on completion. + inter_token: Histogram<19>, +} + +impl RequestRecord { + /// Records a model step that committed at least one generated token for the + /// request at `now_ns`: the first stamps the first token, each later one adds + /// one inter-token interval, however many tokens the step committed. + pub(super) fn tokens_committed(&mut self, now_ns: u64) { + if self.times.first_token_ns.is_some() { + self.inter_token.observe( + &TOKEN_SECONDS, + now_ns.saturating_sub(self.times.last_token_ns), + ); + } else { + self.times.first_token_ns = Some(now_ns); + } + self.times.last_token_ns = now_ns; + } +} + +/// Token counts of one successfully completed request. +pub(super) struct CompletedRequest { + pub prompt_tokens: usize, + /// Prompt tokens supplied by GPU or host prefix reuse at first admission. + pub reused_prompt_tokens: u64, + pub generated_tokens: u32, +} + #[derive(Default)] pub(super) struct Metrics { pub scheduler_trace: scheduler::SchedulerMetrics, @@ -322,12 +388,21 @@ pub(super) struct Metrics { pub admitted: AtomicU64, pub http_requests: [AtomicU64; 5], pub completed: AtomicU64, - pub(super) request_e2e: Histogram<21>, + request_e2e: Histogram<21>, + request_choices: Histogram<6>, + request_max_choice_generated_tokens: Histogram<21>, request_queue: Histogram<21>, request_prefill: Histogram<21>, request_decode: Histogram<21>, + request_inference: Histogram<21>, + time_to_first_token: Histogram<21>, time_per_output_token: Histogram<19>, + inter_token_latency: Histogram<19>, request_prompt_tokens: Histogram<21>, + request_prefill_computed_tokens: Histogram<21>, + request_generated_tokens: Histogram<21>, + request_max_tokens: Histogram<21>, + request_preemptions: Histogram<9>, pub reasoning_budget_cuts: AtomicU64, pub cancelled: AtomicU64, pub failed: AtomicU64, @@ -452,19 +527,45 @@ impl Metrics { pub(super) fn request_completed( &self, arrival_ns: u64, - times: RequestTimes, - prompt_tokens: usize, - generated_tokens: u32, + record: &RequestRecord, + completed: CompletedRequest, ) { + let CompletedRequest { + prompt_tokens, + reused_prompt_tokens, + generated_tokens, + } = completed; + let times = record.times; self.completed.fetch_add(1, Ordering::Relaxed); self.request_prompt_tokens - .observe(&PROMPT_TOKENS, prompt_tokens as u64); + .observe(&TOKEN_COUNTS, prompt_tokens as u64); + self.request_prefill_computed_tokens.observe( + &TOKEN_COUNTS, + (prompt_tokens as u64).saturating_sub(reused_prompt_tokens), + ); + self.request_generated_tokens + .observe(&TOKEN_COUNTS, u64::from(generated_tokens)); + if record.max_tokens > 0 { + self.request_max_tokens + .observe(&TOKEN_COUNTS, u64::from(record.max_tokens)); + } + self.request_preemptions + .observe(&PREEMPTION_COUNTS, u64::from(record.preemptions)); + self.inter_token_latency.absorb(&record.inter_token); + if let Some(first) = times.first_token_ns { + self.time_to_first_token + .observe(&REQUEST_SECONDS, first.saturating_sub(arrival_ns)); + } if let Some(scheduled) = times.first_scheduled_ns { self.request_queue .observe(&REQUEST_SECONDS, scheduled.saturating_sub(arrival_ns)); if let Some(first) = times.first_token_ns { self.request_prefill .observe(&REQUEST_SECONDS, first.saturating_sub(scheduled)); + self.request_inference.observe( + &REQUEST_SECONDS, + times.last_token_ns.saturating_sub(scheduled), + ); } } if let Some(first) = times.first_token_ns @@ -479,6 +580,21 @@ impl Metrics { } } + /// Records one successful HTTP generation response delivered `elapsed_ns` + /// after admission. `generated` holds each choice's generated-token count in + /// response order, `choices` consecutive choices per prompt. + pub(super) fn response_completed(&self, elapsed_ns: u64, choices: usize, generated: &[u32]) { + self.request_e2e.observe(&REQUEST_SECONDS, elapsed_ns); + for prompt in generated.chunks(choices) { + self.request_choices + .observe(&CHOICE_COUNTS, choices as u64); + self.request_max_choice_generated_tokens.observe( + &TOKEN_COUNTS, + u64::from(prompt.iter().copied().max().unwrap_or(0)), + ); + } + } + pub fn persistent_worker_snapshot(&self) -> Option { self.persistent_worker .as_ref() @@ -1400,20 +1516,73 @@ impl Metrics { "request_decode_seconds", "First to last committed generated token, for completed requests with at least two generated tokens.", ), + ( + &self.request_inference, + "request_inference_seconds", + "First model step that includes the request to its last committed generated token, for completed requests.", + ), + ( + &self.time_to_first_token, + "time_to_first_token_seconds", + "Model-scheduler arrival to the first committed generated token, for completed requests.", + ), ] { histogram.render(&mut text, name, help, &REQUEST_SECONDS); } - self.time_per_output_token.render( + for (histogram, name, help) in [ + ( + &self.time_per_output_token, + "time_per_output_token_seconds", + "Decode time divided by generated tokens after the first, for completed requests with at least two generated tokens.", + ), + ( + &self.inter_token_latency, + "inter_token_latency_seconds", + "Interval between successive model steps that committed generated tokens for a request, observed once per step after the first, for completed requests.", + ), + ] { + histogram.render(&mut text, name, help, &TOKEN_SECONDS); + } + for (histogram, name, help) in [ + ( + &self.request_prompt_tokens, + "request_prompt_tokens", + "Prompt tokens per completed request, including tokens reused from the prefix cache.", + ), + ( + &self.request_prefill_computed_tokens, + "request_prefill_computed_tokens", + "Prompt tokens per completed request minus the tokens GPU or host prefix reuse supplied at its first admission.", + ), + ( + &self.request_generated_tokens, + "request_generated_tokens", + "Committed generated tokens per completed request, including EOS and tokens withheld by text stops.", + ), + ( + &self.request_max_tokens, + "request_max_tokens", + "Output token limit of each completed request: the client's limit, else the server default capped by the remaining context.", + ), + ( + &self.request_max_choice_generated_tokens, + "request_max_choice_generated_tokens", + "Largest generated-token count among the choices of one prompt, for successful HTTP generation responses.", + ), + ] { + histogram.render(&mut text, name, help, &TOKEN_COUNTS); + } + self.request_choices.render( &mut text, - "time_per_output_token_seconds", - "Decode time divided by generated tokens after the first, for completed requests with at least two generated tokens.", - &TOKEN_SECONDS, + "request_choices", + "Requested choices (the n parameter) per prompt, for successful HTTP generation responses.", + &CHOICE_COUNTS, ); - self.request_prompt_tokens.render( + self.request_preemptions.render( &mut text, - "request_prompt_tokens", - "Prompt tokens per completed request, including tokens reused from the prefix cache.", - &PROMPT_TOKENS, + "request_preemptions", + "Times each completed request was preempted and readmitted.", + &PREEMPTION_COUNTS, ); for (name, help, value) in [ ( @@ -1644,15 +1813,25 @@ mod tests { #[test] fn request_histograms_bucket_completed_request_timings() { let metrics = Metrics::new(0, 0, 0, 16); + let mut record = RequestRecord { + max_tokens: 256, + preemptions: 1, + ..Default::default() + }; + record.times.first_scheduled_ns = Some(1_250_000_000); + // Three committing steps: the first token, then a step committing several + // tokens and a final step, which add two inter-token intervals. + for now_ns in [1_750_000_000, 2_000_000_000, 2_750_000_000] { + record.tokens_committed(now_ns); + } metrics.request_completed( 1_000_000_000, - RequestTimes { - first_scheduled_ns: Some(1_250_000_000), - first_token_ns: Some(1_750_000_000), - last_token_ns: 2_750_000_000, + &record, + CompletedRequest { + prompt_tokens: 3000, + reused_prompt_tokens: 1000, + generated_tokens: 101, }, - 3000, - 101, ); let text = metrics.render(); for expected in [ @@ -1660,10 +1839,27 @@ mod tests { "flare_request_queue_seconds_bucket{le=\"0.1\"} 0", "flare_request_prefill_seconds_bucket{le=\"0.5\"} 1", "flare_request_decode_seconds_sum 1", + "flare_request_inference_seconds_bucket{le=\"2.5\"} 1", + "flare_request_inference_seconds_bucket{le=\"1\"} 0", + "flare_request_inference_seconds_sum 1.5", + "flare_time_to_first_token_seconds_bucket{le=\"1\"} 1", + "flare_time_to_first_token_seconds_bucket{le=\"0.5\"} 0", "flare_time_per_output_token_seconds_bucket{le=\"0.01\"} 1", "flare_time_per_output_token_seconds_bucket{le=\"0.0075\"} 0", + "flare_inter_token_latency_seconds_bucket{le=\"0.3\"} 1", + "flare_inter_token_latency_seconds_bucket{le=\"1\"} 2", + "flare_inter_token_latency_seconds_sum 1", + "flare_inter_token_latency_seconds_count 2", "flare_request_prompt_tokens_bucket{le=\"4096\"} 1", "flare_request_prompt_tokens_bucket{le=\"2048\"} 0", + "flare_request_prefill_computed_tokens_bucket{le=\"2048\"} 1", + "flare_request_prefill_computed_tokens_bucket{le=\"1024\"} 0", + "flare_request_prefill_computed_tokens_sum 2000", + "flare_request_generated_tokens_bucket{le=\"128\"} 1", + "flare_request_generated_tokens_bucket{le=\"64\"} 0", + "flare_request_max_tokens_sum 256", + "flare_request_preemptions_bucket{le=\"0\"} 0", + "flare_request_preemptions_bucket{le=\"1\"} 1", "flare_requests_completed_total 1", ] { assert!( @@ -1672,14 +1868,29 @@ mod tests { ); } // A zero-token completion reaches no model step and commits no token, so it - // adds only a prompt-size observation. - metrics.request_completed(1_000_000_000, RequestTimes::default(), 3000, 0); + // adds only token-count and preemption observations. + metrics.request_completed( + 1_000_000_000, + &RequestRecord::default(), + CompletedRequest { + prompt_tokens: 3000, + reused_prompt_tokens: 0, + generated_tokens: 0, + }, + ); let text = metrics.render(); for expected in [ "flare_request_queue_seconds_count 1", "flare_request_prefill_seconds_count 1", + "flare_request_inference_seconds_count 1", + "flare_time_to_first_token_seconds_count 1", "flare_request_decode_seconds_count 1", + "flare_inter_token_latency_seconds_count 2", + "flare_request_max_tokens_count 1", "flare_request_prompt_tokens_count 2", + "flare_request_prefill_computed_tokens_sum 5000", + "flare_request_generated_tokens_bucket{le=\"1\"} 1", + "flare_request_preemptions_bucket{le=\"0\"} 1", "flare_requests_completed_total 2", ] { assert!( @@ -1689,6 +1900,28 @@ mod tests { } } + #[test] + fn response_histograms_count_choices_and_largest_choice_per_prompt() { + let metrics = Metrics::new(0, 0, 0, 16); + // Two prompts with two choices each, as a completions batch orders them. + metrics.response_completed(300_000_000, 2, &[3, 9, 0, 4]); + metrics.response_completed(300_000_000, 1, &[7]); + let text = metrics.render(); + for expected in [ + "flare_request_e2e_seconds_count 2", + "flare_request_choices_bucket{le=\"1\"} 1", + "flare_request_choices_bucket{le=\"2\"} 3", + "flare_request_choices_sum 5", + "flare_request_max_choice_generated_tokens_count 3", + "flare_request_max_choice_generated_tokens_sum 20", + ] { + assert!( + text.contains(&format!("\n{expected}\n")), + "missing {expected}" + ); + } + } + #[test] fn checkpoint_metrics_report_capture_roles_rejection_reasons_work_and_reservations() { let metrics = Metrics::new(0, 0, 0, 16); diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index db568d817..863902729 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -192,8 +192,8 @@ struct Incoming { failure: Arc>>, metrics: Arc, observation: Option, - /// Lifecycle instants for completion histograms; preserved when a preempted request is parked. - times: super::metrics::RequestTimes, + /// Values for the completion histograms; preserved when a preempted request is parked. + record: super::metrics::RequestRecord, /// Consult the host prefix store at admission; cleared after a failed restore. host_lookup: bool, /// Admitted once already, so the admission counter is not advanced again. @@ -969,7 +969,7 @@ impl ModelRuntime { failure: failure.clone(), metrics: self.metrics.clone(), observation, - times: Default::default(), + record: Default::default(), host_lookup: true, readmitted: false, blocked: None, @@ -1666,6 +1666,8 @@ impl<'a> Worker<'a> { }; if !incoming.readmitted { self.metrics.admitted.fetch_add(1, Ordering::Relaxed); + incoming.record.max_tokens = incoming.prompt.max_new_tokens + + incoming.prompt.reasoning_cut.as_ref().map_or(0, |cut| cut.after); } if !pending_pool_answer { incoming.pool_lookup = None; @@ -1965,8 +1967,11 @@ impl<'a> Worker<'a> { continue; } } - request.incoming.times.first_token_ns.get_or_insert(completed_at_ns); - request.incoming.times.last_token_ns = completed_at_ns; + // A step that commits several tokens for one request, such as a + // speculative round, adds one inter-token interval. + if position == 0 { + request.incoming.record.tokens_committed(completed_at_ns); + } request.incoming.observe_token(token.token); request.last_token = Some(token.token); let was_open = request @@ -2044,21 +2049,25 @@ impl<'a> Worker<'a> { request.carried.prompt_tokens.unwrap_or(live.prompt_tokens); let generated_tokens = request.carried.generated_tokens + live.generated_tokens.saturating_sub(skipped); + let reused_prompt_tokens = request + .carried + .reused_prompt_tokens + .unwrap_or(live.reused_prompt_tokens()); self.metrics.request_completed( request.incoming.arrival_ns, - request.incoming.times, - prompt_tokens, - generated_tokens, + &request.incoming.record, + super::metrics::CompletedRequest { + prompt_tokens, + reused_prompt_tokens, + generated_tokens, + }, ); request .incoming .emit(GenerationEvent::Finished { prompt_tokens, generated_tokens, - reused_prompt_tokens: request - .carried - .reused_prompt_tokens - .unwrap_or(live.reused_prompt_tokens()), + reused_prompt_tokens, reason: "stop", termination: crate::output::Termination::UserStop, stop_sequence: request @@ -2322,11 +2331,16 @@ impl<'a> Worker<'a> { let prompt_tokens = request.carried.prompt_tokens.unwrap_or(prompt_tokens); let generated_tokens = request.carried.generated_tokens + generated; + let reused_prompt_tokens = + request.carried.reused_prompt_tokens.unwrap_or(reused); self.metrics.request_completed( request.incoming.arrival_ns, - request.incoming.times, - prompt_tokens, - generated_tokens, + &request.incoming.record, + super::metrics::CompletedRequest { + prompt_tokens, + reused_prompt_tokens, + generated_tokens, + }, ); for token in request.stops.finish() { request @@ -2346,10 +2360,7 @@ impl<'a> Worker<'a> { .emit(GenerationEvent::Finished { prompt_tokens, generated_tokens, - reused_prompt_tokens: request - .carried - .reused_prompt_tokens - .unwrap_or(reused), + reused_prompt_tokens, reason, stop_sequence: request .text_stops @@ -2396,13 +2407,9 @@ impl<'a> Worker<'a> { { return Ok(false); } - let remaining = self.active[slot] - .as_ref() - .unwrap() - .incoming - .prompt - .max_new_tokens - - live.generated_tokens; + let active = self.active[slot].as_mut().unwrap(); + let remaining = active.incoming.prompt.max_new_tokens - live.generated_tokens; + active.incoming.record.preemptions += 1; self.park(slot, &[], remaining)?; Ok(true) } @@ -2533,6 +2540,7 @@ impl<'a> Worker<'a> { { active .incoming + .record .times .first_scheduled_ns .get_or_insert(scheduled_ns); @@ -3594,7 +3602,7 @@ mod tests { failure: failure.clone(), metrics: Arc::new(super::super::metrics::Metrics::new(0, 0, 0, 16)), observation: None, - times: Default::default(), + record: Default::default(), host_lookup: true, readmitted: false, prompt_score_end: 0, diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index cb1fb1c0c..25c404c6f 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -242,7 +242,7 @@ impl Fixture { failure: failure.clone(), metrics: self.metrics.clone(), observation: Some(false), - times: Default::default(), + record: Default::default(), host_lookup: true, readmitted: false, prompt_score_end: 0, @@ -670,6 +670,21 @@ fn reasoning_budget_cuts_after_a_multi_token_speculative_completion() { budget_events(&mut generation), (vec![2], vec![(13, 6, "length")], vec![]) ); + // Committing steps: the prefill token, the three-token speculative round, and + // the token after readmission; the forced close is no model step. The reasoning + // park is not a preemption, and the output limit spans budget and remainder. + let text = worker.metrics.render(); + for expected in [ + "\nflare_inter_token_latency_seconds_count 2\n", + "\nflare_time_to_first_token_seconds_count 1\n", + "\nflare_request_inference_seconds_count 1\n", + "\nflare_request_generated_tokens_sum 6\n", + "\nflare_request_max_tokens_sum 6\n", + "\nflare_request_prefill_computed_tokens_sum 13\n", + "\nflare_request_preemptions_bucket{le=\"0\"} 1\n", + ] { + assert!(text.contains(expected), "missing {expected}"); + } } #[test] @@ -1664,6 +1679,35 @@ fn ignored_eos_at_the_output_limit_finishes_for_length() { ); } +#[test] +fn prefill_computed_tokens_exclude_the_prefix_reused_at_admission() { + let fixture = Fixture::new(); + let (sender, receiver) = mpsc::channel(); + let mut worker = fixture.worker(receiver); + let mut sequence = 0; + let mut reused = vec![]; + for token in [1, 2] { + let (incoming, mut generation) = fixture.incoming(vec![0; 13], 1); + sender.send(vec![incoming]).unwrap(); + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); + let handle = worker.active.iter().flatten().next().unwrap().request; + reused.push(worker.scheduler.request(handle).unwrap().reused_prompt_tokens()); + budget_pass(&mut worker, &mut sequence, &[token]); + assert_eq!(budget_events(&mut generation).1, vec![(13, 1, "length")]); + } + // The second request restores the first one's terminal checkpoint. + assert_eq!(reused, [0, 13]); + let text = fixture.metrics.render(); + for expected in [ + "\nflare_request_prompt_tokens_sum 26\n", + "\nflare_request_prefill_computed_tokens_bucket{le=\"1\"} 1\n", + "\nflare_request_prefill_computed_tokens_sum 13\n", + "\nflare_request_prefill_computed_tokens_count 2\n", + ] { + assert!(text.contains(expected), "missing {expected}"); + } +} + #[test] fn disabled_host_store_preserves_decode_prefix_reuse_and_cancellation() { let fixture = Fixture::new(); @@ -3934,6 +3978,7 @@ fn exercise_text_preemption( assert!(worker.scheduler.stats().preemptions > 0); let (incoming, parked) = worker.parked.front_mut().unwrap(); assert!(parked.carried.generated_tokens > 0); + assert_eq!(incoming.record.preemptions, 1); assert_eq!( incoming .prompt @@ -4070,6 +4115,16 @@ fn exercise_text_preemption( assert_eq!(emitted[index], expected); assert_eq!(finished, vec![(60, budget + cut.after, "length")]); assert!(worker.parked.is_empty()); + // The count taken at the park reaches the completed request's histogram. + let text = worker.metrics.render(); + for expected in [ + "\nflare_request_preemptions_bucket{le=\"0\"} 0\n", + "\nflare_request_preemptions_bucket{le=\"1\"} 1\n", + "\nflare_request_preemptions_count 1\n", + format!("\nflare_request_max_tokens_sum {}\n", budget + cut.after).as_str(), + ] { + assert!(text.contains(expected), "missing {expected}"); + } return; } } From 1a29417b002d4ec71bd5dfcde11ea81041167775 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 15:23:37 -0600 Subject: [PATCH 06/14] Count lookup tokens, output-limit stops, parked requests, and queue rejections Four quantities vLLM exposes as counters or gauges exist in Flare but no series reports them. `flare_cache_lookups_total` counts GPU prefix lookups, not the prompt tokens looked up, so the token hit rate that vLLM's `prefix_cache_queries` and `prefix_cache_hits` give cannot be computed from `flare_cache_reused_tokens_total` alone. `flare_requests_completed_total` does not separate requests that stopped at their output limit from those that stopped at EOS or a stop. `flare_pending_requests` reports only requests that await their first admission, so requests parked for readmission after a preemption, a reasoning budget cut, or a returned host-store restore are in no gauge. HTTP 429 responses and the runtime's capacity and channel refusals are not counted anywhere, unlike vLLM's `admission_rejections`. vLLM also reports the tokens each engine step processes; Flare's existing per-kind launch counts and token totals give only means, not that distribution. The project maintainer approved bringing Flare's metrics to vLLM parity for quantities Flare already has; each value here is already computed at the point where it is recorded. `RequestScheduler::admit_planned_with_checkpoint_accounting` adds the prompt length to `SchedulerStats::cache_lookup_tokens` beside `cache_lookups`, once per admitted request; prompt-scoring requests, which skip the lookup, add nothing. The field changes only when `cache_lookups` does, so the deferred-copy-out retry key that embeds `SchedulerStats` changes no more often than before. `CompletedRequest` gains `output_limit`, set where `Worker::publish` already decides the `length` finish reason (its EOS test now runs before the metrics call) and false on the token-stop completion in `Worker::complete`; `Metrics::request_completed` counts it in `flare_requests_output_limited_total`. A new `flare_requests_completed_total` label was not used because it would change that series' identity, and a separate counter by finish reason would duplicate it; stop completions are the difference between the two counters, and cancelled and failed requests keep their own counters. `Worker::publish_gauges`, extracted from the worker loop, stores `flare_parked_requests` beside `flare_pending_requests`. `Metrics::admission_rejected` counts `flare_admission_rejections_total{reason}` where the 429 and capacity errors are produced: `admit_http` and the extra choice slots in `http::generate` (`http_slots`) and `ModelRuntime::enqueue_many` (`generation_capacity`, `request_queue`). Paused admission and an unavailable runtime are not queue limits and stay uncounted. `Worker::complete` observes `flare_model_step_tokens`, the prompt tokens computed plus the generated tokens committed, for every completed prefill, resume, decode, speculative, or mixed graph, using the values it already passes to `Metrics::progress`. `docs/api.md` defines each series, and the pending gauge's help and JSON field now say "first admission". The claimed result is observability only; no admission, scheduling, or cache decision changes. The added cost, from the code and not measured, is one addition per admission, one histogram observation (a search over at most 21 bounds and two atomic adds) per completed text graph, one atomic store per worker-loop pass with progress, and one atomic add per rejection. Evidence: `cargo test --locked --manifest-path helios/Cargo.toml --features runtime-core,server --target-dir /tmp/mc/target --lib -- server::metrics server::runtime scheduler::tests` passed 236 tests (one ignored). The scheduler admission tests check 192 lookup tokens for three admitted 64-token prompts and none for refused attempts. `reasoning_budget_does_not_readmit_eos_or_user_stops` checks that EOS, text-stop, and token-stop completions count no output-limit stop, and `ignored_eos_at_the_output_limit_finishes_for_length` checks one, together with two text-graph observations totalling three tokens. `exercise_text_preemption` checks one parked and no pending request after a preemption. `full_runtime_queue_limits_count_admission_rejections` fills the worker channel and then the runtime capacity, and `full_http_admission_counts_a_queue_limit_rejection` sends a completion through the router with every HTTP slot held and checks the 429 and its count. These tests run without a GPU; serving on hardware has not been run. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=2e5b --- docs/api.md | 24 +++++- helios/src/scheduler.rs | 4 + helios/src/scheduler/tests.rs | 7 ++ helios/src/server.rs | 1 + helios/src/server/http.rs | 4 + helios/src/server/metrics.rs | 101 ++++++++++++++++++++++- helios/src/server/runtime.rs | 45 ++++++++-- helios/src/server/runtime/phase_tests.rs | 94 +++++++++++++++++++++ 8 files changed, 267 insertions(+), 13 deletions(-) diff --git a/docs/api.md b/docs/api.md index e21853beb..6dcccb6be 100644 --- a/docs/api.md +++ b/docs/api.md @@ -342,6 +342,28 @@ readmitted; its buckets are vLLM's preemption bounds with an added zero bound. Cancelled and failed requests enter only `flare_requests_cancelled_total` and `flare_requests_failed_total`. +`flare_requests_output_limited_total` counts completed requests that stopped at +their output token limit; the rest of `flare_requests_completed_total` stopped at +EOS, a stop sequence, or a stop string. `flare_cache_lookup_tokens_total` counts +the prompt tokens of admitted requests offered to GPU prefix lookups, including +readmissions, and `flare_cache_reused_tokens_total` counts the tokens found, so +their ratio is the token hit rate; prompt-scoring requests skip the lookup and +enter neither. `flare_pending_requests` counts requests waiting in the model +scheduler for their first admission, and `flare_parked_requests` counts requests +waiting there for readmission after a preemption, a reasoning budget cut, or a +host-store restore that failed or was retried; neither includes admitted +requests waiting for a host restore, which `flare_host_cache_inbound_waiting` +counts among `flare_active_requests`. `flare_admission_rejections_total{reason}` +counts generation requests refused because a queue limit was full: `http_slots` +when the HTTP admission slots, one per generated choice, are all reserved (HTTP +429), and `generation_capacity` or `request_queue` when the runtime's generation +capacity or the channel into the model worker is full. Paused admission and an +unavailable runtime return HTTP 503 and are not counted. +`flare_model_step_tokens` observes, for every completed prefill, resume, decode, +speculative, or mixed graph, the prompt tokens it computed plus the generated +tokens it committed; rejected draft positions and padding are excluded, and +initialization, restore, vision, and snapshot graphs are not observed. + The route returns one JSON object instead when the query contains `format=json`, or when the `Accept` header gives `application/json` a higher quality than `text/plain`; at equal quality the earlier media range wins. `format=prometheus` @@ -372,7 +394,7 @@ without the `flare_` prefix, such as `input_decoded_images_total`. | `accepted_drafts` | Accepted draft tokens, excluding the bonus token | `flare_accepted_draft_tokens_total` | | `draft_rounds` | Request rounds that offered at least one draft | `flare_draft_request_rounds_total` | | `active` | Model slots with a live request | `flare_active_requests` | -| `pending` | Requests waiting in the model scheduler | `flare_pending_requests` | +| `pending` | Requests waiting in the model scheduler for their first admission | `flare_pending_requests` | | `completed` | Requests whose generation completed successfully | `flare_requests_completed_total` | | `reasoning_budget_cuts` | Requests whose reasoning was closed by their hard token budget | `flare_reasoning_budget_cuts_total` | | `failed` | Requests failed by admission, execution, grammar, or output processing | `flare_requests_failed_total` | diff --git a/helios/src/scheduler.rs b/helios/src/scheduler.rs index 00e0457c2..e571dcf72 100644 --- a/helios/src/scheduler.rs +++ b/helios/src/scheduler.rs @@ -112,6 +112,8 @@ pub struct SchedulerCapabilities { pub struct SchedulerStats { pub cache_lookups: u64, pub cache_hits: u64, + /// Prompt tokens of admitted requests offered to GPU prefix lookups. + pub cache_lookup_tokens: u64, pub reused_tokens: u64, pub snapshot_publications: u64, pub snapshot_evictions: u64, @@ -1555,6 +1557,7 @@ impl RequestScheduler { } = plan; // Lookups count once per admitted request, not per attempt of a waiting one. let (hit, reused) = (lookup.checkpoint.is_some(), lookup.consumed_tokens); + let looked_up = if spec.prompt_logprobs { 0 } else { spec.prompt.len() as u64 }; let page_tokens = self.capabilities.page_tokens as u64; if let Some(inbound) = &inbound { let consumed = inbound.consumed_tokens; @@ -1761,6 +1764,7 @@ impl RequestScheduler { ticket.role = ticket.role.max(role); } self.stats.cache_lookups += u64::from(!spec.prompt_logprobs); + self.stats.cache_lookup_tokens += looked_up; self.stats.cache_hits += u64::from(hit); self.stats.reused_tokens += reused; if inbound.is_none() diff --git a/helios/src/scheduler/tests.rs b/helios/src/scheduler/tests.rs index da16005de..2bc0fb03b 100644 --- a/helios/src/scheduler/tests.rs +++ b/helios/src/scheduler/tests.rs @@ -892,6 +892,8 @@ fn terminal_checkpoint_full_prompt_hit_restores_and_resumes_without_prefill() { (stats.cache_lookups, stats.cache_hits, stats.reused_tokens), (3, 2, 128) ); + // Three admitted 64-token prompts were looked up, whether or not they hit. + assert_eq!(stats.cache_lookup_tokens, 192); assert_eq!( ( stats.active_requests, @@ -3238,11 +3240,16 @@ fn invalid_inbound_requests_reserve_nothing_and_planned_admission_matches_admit( assert_eq!(plan.resident_tokens(), 0); // Lookups count once per admitted request; the failed attempts above count none. assert_eq!(scheduler.stats().cache_lookups, 0); + assert_eq!(scheduler.stats().cache_lookup_tokens, 0); let admitted = scheduler .admit_planned(request.clone(), plan, None) .unwrap(); assert!(admitted.ticket.is_none()); assert_eq!(scheduler.stats().cache_lookups, 1); + assert_eq!( + scheduler.stats().cache_lookup_tokens, + request.prompt.len() as u64 + ); let live = scheduler.request(admitted.handle).unwrap(); assert_eq!(live.phase, RequestPhase::Initialize); assert_eq!(live.consumed_tokens, 0); diff --git a/helios/src/server.rs b/helios/src/server.rs index cd415e0f6..a8ce75298 100644 --- a/helios/src/server.rs +++ b/helios/src/server.rs @@ -813,6 +813,7 @@ async fn admit_http( Err(IngressRejection::Paused) => return http::error(protocol, StatusCode::SERVICE_UNAVAILABLE, "HTTP admission is paused"), Ok(permit) => Arc::new(permit), Err(IngressRejection::Full) => { + state.model.metrics().admission_rejected(metrics::AdmissionLimit::HttpSlots); let mut message = format!( "native HTTP admission is full: {} requests are active or queued", state.ingress_capacity diff --git a/helios/src/server/http.rs b/helios/src/server/http.rs index 7f54c7713..69414e417 100644 --- a/helios/src/server/http.rs +++ b/helios/src/server/http.rs @@ -234,6 +234,10 @@ pub(super) async fn generate( .clone() .try_acquire_many_owned((size - 1) as u32) .map_err(|_| { + prepare_state + .model + .metrics() + .admission_rejected(super::metrics::AdmissionLimit::HttpSlots); ( StatusCode::TOO_MANY_REQUESTS, "native generation admission is full".into(), diff --git a/helios/src/server/metrics.rs b/helios/src/server/metrics.rs index 03613ffee..841d01991 100644 --- a/helios/src/server/metrics.rs +++ b/helios/src/server/metrics.rs @@ -86,7 +86,7 @@ pub struct Snapshot { pub draft_rounds: u64, /// Physical model slots with a live request. pub active: u64, - /// Requests waiting inside the model scheduler, excluding its ingress channel. + /// Requests waiting inside the model scheduler for their first admission, excluding its ingress channel. pub pending: u64, /// Requests whose generation completed successfully. pub completed: u64, @@ -362,12 +362,26 @@ impl RequestRecord { } } -/// Token counts of one successfully completed request. +/// Token counts and termination of one successfully completed request. pub(super) struct CompletedRequest { pub prompt_tokens: usize, /// Prompt tokens supplied by GPU or host prefix reuse at first admission. pub reused_prompt_tokens: u64, pub generated_tokens: u32, + /// The request ended at its output token limit, not at EOS or a stop. + pub output_limit: bool, +} + +/// Queue limits that reject a generation request before the model scheduler +/// holds it; each is one `reason` of `flare_admission_rejections_total`. +#[derive(Clone, Copy)] +pub(super) enum AdmissionLimit { + /// HTTP admission slots, one per generated choice, are all reserved. + HttpSlots, + /// Runtime generation capacity is fully reserved. + GenerationCapacity, + /// The channel into the model worker is full. + RequestQueue, } #[derive(Default)] @@ -403,6 +417,9 @@ pub(super) struct Metrics { request_generated_tokens: Histogram<21>, request_max_tokens: Histogram<21>, request_preemptions: Histogram<9>, + model_step_tokens: Histogram<21>, + output_limited: AtomicU64, + admission_rejections: [AtomicU64; 3], pub reasoning_budget_cuts: AtomicU64, pub cancelled: AtomicU64, pub failed: AtomicU64, @@ -417,6 +434,7 @@ pub(super) struct Metrics { constrained_max_inflight: AtomicU64, cache_lookups: AtomicU64, cache_hits: AtomicU64, + cache_lookup_tokens: AtomicU64, cache_misses: AtomicU64, reused_tokens: AtomicU64, snapshot_publications: AtomicU64, @@ -439,6 +457,7 @@ pub(super) struct Metrics { cached_checkpoints: AtomicU64, cached_pages: AtomicU64, pub pending: AtomicU64, + pub parked: AtomicU64, host_lookups: AtomicU64, host_hits: AtomicU64, host_reused_tokens: AtomicU64, @@ -534,9 +553,13 @@ impl Metrics { prompt_tokens, reused_prompt_tokens, generated_tokens, + output_limit, } = completed; let times = record.times; self.completed.fetch_add(1, Ordering::Relaxed); + if output_limit { + self.output_limited.fetch_add(1, Ordering::Relaxed); + } self.request_prompt_tokens .observe(&TOKEN_COUNTS, prompt_tokens as u64); self.request_prefill_computed_tokens.observe( @@ -653,6 +676,16 @@ impl Metrics { } } + /// Records one completed text-model step that computed `tokens` prompt tokens + /// and committed generated tokens in total. + pub(super) fn model_step(&self, tokens: u64) { + self.model_step_tokens.observe(&TOKEN_COUNTS, tokens); + } + + pub(super) fn admission_rejected(&self, limit: AdmissionLimit) { + self.admission_rejections[limit as usize].fetch_add(1, Ordering::Relaxed); + } + pub fn launched(&self, kind: GraphKind) { let index = match kind { GraphKind::Init => 0, @@ -734,6 +767,7 @@ impl Metrics { for (target, value) in [ (&self.cache_lookups, stats.cache_lookups), (&self.cache_hits, stats.cache_hits), + (&self.cache_lookup_tokens, stats.cache_lookup_tokens), (&self.cache_misses, stats.cache_lookups - stats.cache_hits), (&self.reused_tokens, stats.reused_tokens), (&self.snapshot_publications, stats.snapshot_publications), @@ -1343,6 +1377,11 @@ impl Metrics { "Model requests failed by admission, execution, grammar, or output processing.", &self.failed, ), + ( + "requests_output_limited_total", + "Completed requests that stopped at their output token limit; the rest of flare_requests_completed_total stopped at EOS or a stop.", + &self.output_limited, + ), ( "mixed_grammar_decode_steps_total", "Successful decode and speculative submissions containing both grammar-constrained and unconstrained request lanes.", @@ -1358,6 +1397,11 @@ impl Metrics { "Prefix lookups returning a GPU-ready checkpoint.", &self.cache_hits, ), + ( + "cache_lookup_tokens_total", + "Prompt tokens of admitted requests offered to GPU prefix lookups; flare_cache_reused_tokens_total counts the tokens found.", + &self.cache_lookup_tokens, + ), ( "cache_reused_tokens_total", "Tokens covered by checkpoints returned from prefix lookups.", @@ -1584,6 +1628,26 @@ impl Metrics { "Times each completed request was preempted and readmitted.", &PREEMPTION_COUNTS, ); + self.model_step_tokens.render( + &mut text, + "model_step_tokens", + "Prompt tokens computed plus generated tokens committed by each completed text-model step.", + &TOKEN_COUNTS, + ); + let _ = writeln!( + text, + "# HELP flare_admission_rejections_total Generation requests rejected because a queue limit was full.\n# TYPE flare_admission_rejections_total counter" + ); + for (reason, count) in ["http_slots", "generation_capacity", "request_queue"] + .into_iter() + .zip(&self.admission_rejections) + { + let _ = writeln!( + text, + "flare_admission_rejections_total{{reason=\"{reason}\"}} {}", + count.load(Ordering::Relaxed) + ); + } for (name, help, value) in [ ( "constrained_max_inflight", @@ -1637,9 +1701,14 @@ impl Metrics { ), ( "pending_requests", - "Requests waiting inside the model scheduler, excluding its ingress channel.", + "Requests waiting inside the model scheduler for first admission, excluding its ingress channel.", &self.pending, ), + ( + "parked_requests", + "Requests waiting inside the model scheduler for readmission after a preemption, a reasoning budget cut, or a host-store restore that failed or was retried.", + &self.parked, + ), ( "host_cache_outbound_in_flight", "Host store copy-outs in progress.", @@ -1831,6 +1900,7 @@ mod tests { prompt_tokens: 3000, reused_prompt_tokens: 1000, generated_tokens: 101, + output_limit: true, }, ); let text = metrics.render(); @@ -1876,6 +1946,7 @@ mod tests { prompt_tokens: 3000, reused_prompt_tokens: 0, generated_tokens: 0, + output_limit: false, }, ); let text = metrics.render(); @@ -1892,6 +1963,7 @@ mod tests { "flare_request_generated_tokens_bucket{le=\"1\"} 1", "flare_request_preemptions_bucket{le=\"0\"} 1", "flare_requests_completed_total 2", + "flare_requests_output_limited_total 1", ] { assert!( text.contains(&format!("\n{expected}\n")), @@ -2211,6 +2283,7 @@ mod tests { reused_tokens: 192, free_pages: 10, cached_pages: 3, + cache_lookup_tokens: 320, host_lookups: 4, host_hits: 1, host_reused_tokens: 640, @@ -2218,6 +2291,16 @@ mod tests { ..SchedulerStats::default() }); metrics.launched(GraphKind::Restore); + metrics.parked.store(2, Ordering::Relaxed); + metrics.model_step(3); + metrics.model_step(20); + for limit in [ + AdmissionLimit::HttpSlots, + AdmissionLimit::HttpSlots, + AdmissionLimit::RequestQueue, + ] { + metrics.admission_rejected(limit); + } metrics.launched(GraphKind::Decode); metrics.launched(GraphKind::Decode); metrics.store(StoreStats { @@ -2254,6 +2337,7 @@ mod tests { ("free_kv_tokens", 1280), ("cached_kv_pages", 3), ("cached_kv_tokens", 384), + ("parked_requests", 2), ("host_cache_slots_in_use", 3), ("host_cache_slots_total", 8), ("host_cache_intake_slots", 2), @@ -2336,6 +2420,17 @@ mod tests { } assert!(text.contains("flare_host_cache_outbound_bytes_per_second 2500000000\n")); assert!(text.contains("flare_cache_misses_total 3\n")); + assert!(text.contains("\nflare_cache_lookup_tokens_total 320\n")); + for line in [ + "flare_model_step_tokens_bucket{le=\"8\"} 1", + "flare_model_step_tokens_bucket{le=\"32\"} 2", + "flare_model_step_tokens_sum 23", + "flare_admission_rejections_total{reason=\"http_slots\"} 2", + "flare_admission_rejections_total{reason=\"generation_capacity\"} 0", + "flare_admission_rejections_total{reason=\"request_queue\"} 1", + ] { + assert!(text.lines().any(|value| value == line), "{line}"); + } assert!(text.contains("flare_cache_reused_tokens_total 192\n")); assert!(text.contains("flare_graph_launches_total{kind=\"restore\"} 1\n")); assert!(!text.contains("mode=\"greedy\"")); diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index 863902729..18ef633d6 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -806,6 +806,7 @@ impl ModelRuntime { worker_metrics.scheduler(worker.scheduler.stats()); } worker_metrics.pending.store(0, Ordering::Relaxed); + worker_metrics.parked.store(0, Ordering::Relaxed); if shutdown.error.is_none() { shutdown.error = error; } @@ -923,6 +924,8 @@ impl ModelRuntime { .clone() .try_acquire_many_owned(count) .map_err(|_| { + self.metrics + .admission_rejected(super::metrics::AdmissionLimit::GenerationCapacity); Error::admission( AdmissionError::Capacity, "native generation capacity is full", @@ -998,6 +1001,8 @@ impl ModelRuntime { .try_send(incoming_group) .map_err(|error| match error { mpsc::TrySendError::Full(_) => { + self.metrics + .admission_rejected(super::metrics::AdmissionLimit::RequestQueue); Error::admission(AdmissionError::Capacity, "native request queue is full") } mpsc::TrySendError::Disconnected(_) => Error::admission( @@ -1209,10 +1214,7 @@ impl<'a> Worker<'a> { progress |= self.submit(executor, &step)?; } if progress { - self.metrics.scheduler(self.scheduler.stats()); - self.metrics - .pending - .store(self.pending.len() as u64, Ordering::Relaxed); + self.publish_gauges(); } self.metrics.scheduler_trace.details(|| { use super::metrics::scheduler::{RequestDetail, SchedulerDetail}; @@ -1257,6 +1259,17 @@ impl<'a> Worker<'a> { Ok(()) } + /// Publishes the scheduler statistics and the depth of each waiting queue. + fn publish_gauges(&self) { + self.metrics.scheduler(self.scheduler.stats()); + self.metrics + .pending + .store(self.pending.len() as u64, Ordering::Relaxed); + self.metrics + .parked + .store(self.parked.len() as u64, Ordering::Relaxed); + } + fn idle_wait(&self) -> std::time::Duration { if self .store @@ -1818,6 +1831,18 @@ impl<'a> Worker<'a> { self.metrics .progress(prefill, generated.len(), accepted, draft_rounds, verification_drafts, verification_rounds); + if matches!( + kind, + GraphKind::Prefill + | GraphKind::TerminalPrefill + | GraphKind::ScoredPrefill + | GraphKind::Resume + | GraphKind::Decode + | GraphKind::Speculative + | GraphKind::Mixed + ) { + self.metrics.model_step(prefill + generated.len() as u64); + } self.metrics.replay_completed(completed_at_ns, completion.timing, prefill); if prefill > 0 && self.store.is_some() { self.observe_prefill_rate(completion.fence, prefill); @@ -2060,6 +2085,7 @@ impl<'a> Worker<'a> { prompt_tokens, reused_prompt_tokens, generated_tokens, + output_limit: false, }, ); request @@ -2333,6 +2359,11 @@ impl<'a> Worker<'a> { let generated_tokens = request.carried.generated_tokens + generated; let reused_prompt_tokens = request.carried.reused_prompt_tokens.unwrap_or(reused); + let eos = !request.incoming.prompt.ignore_eos + && request + .last_token + .is_some_and(|token| self.config.eos_token_ids.contains(&token)); + let reason = if user_stop || eos { "stop" } else { "length" }; self.metrics.request_completed( request.incoming.arrival_ns, &request.incoming.record, @@ -2340,6 +2371,7 @@ impl<'a> Worker<'a> { prompt_tokens, reused_prompt_tokens, generated_tokens, + output_limit: reason == "length", }, ); for token in request.stops.finish() { @@ -2350,11 +2382,6 @@ impl<'a> Worker<'a> { None => GenerationEvent::Token(token), }); } - let eos = !request.incoming.prompt.ignore_eos - && request - .last_token - .is_some_and(|token| self.config.eos_token_ids.contains(&token)); - let reason = if user_stop || eos { "stop" } else { "length" }; request .incoming .emit(GenerationEvent::Finished { diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 25c404c6f..95ba448e7 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -1125,6 +1125,10 @@ fn reasoning_budget_does_not_readmit_eos_or_user_stops() { ); assert!(worker.parked.is_empty()); assert_eq!(worker.metrics.snapshot(false).reasoning_budget_cuts, 0); + // EOS, a text stop, and a token stop each complete without an output limit. + let text = worker.metrics.render(); + assert!(text.contains("\nflare_requests_completed_total 1\n")); + assert!(text.contains("\nflare_requests_output_limited_total 0\n")); } } @@ -1677,6 +1681,16 @@ fn ignored_eos_at_the_output_limit_finishes_for_length() { finished, vec![(2, "length", crate::output::Termination::OutputLimit)] ); + // The prefill step computes one prompt token and commits one generated token, + // the decode step commits one; initialization and snapshots are no text steps. + let text = fixture.metrics.render(); + for expected in [ + "\nflare_requests_output_limited_total 1\n", + "\nflare_model_step_tokens_count 2\n", + "\nflare_model_step_tokens_sum 3\n", + ] { + assert!(text.contains(expected), "missing {expected}"); + } } #[test] @@ -3870,6 +3884,40 @@ fn unread_response_keeps_its_budget_through_a_reasoning_continuation() { assert!(!generation.cancelled.load(Ordering::Acquire)); } +#[test] +fn full_runtime_queue_limits_count_admission_rejections() { + let fixture = Fixture::new(); + let (runtime, _receiver) = group_runtime(&fixture, 3); + let prompt = || { + Fixture::prompt_for( + vec![1, 2], + 4, + PromptData { + positions: vec![[0; 3], [1; 3]], + vision_token_indices: vec![-1; 2], + ..Default::default() + }, + ) + }; + // The worker channel holds two groups; the third is refused at the channel and + // releases its capacity, after which two choices exceed the one free permit. + let held = (0..2) + .map(|_| runtime.generate(prompt()).unwrap()) + .collect::>(); + assert!(runtime.generate(prompt()).is_err()); + assert_eq!(runtime.capacity.available_permits(), 1); + assert!(runtime.generate_many(vec![prompt(), prompt()]).is_err()); + let text = fixture.metrics.render(); + for line in [ + "flare_admission_rejections_total{reason=\"http_slots\"} 0", + "flare_admission_rejections_total{reason=\"generation_capacity\"} 1", + "flare_admission_rejections_total{reason=\"request_queue\"} 1", + ] { + assert!(text.lines().any(|value| value == line), "{line}"); + } + drop(held); +} + #[test] fn grouped_submission_validates_all_children_before_enqueue_and_releases_capacity() { let fixture = Fixture::new(); @@ -3979,6 +4027,11 @@ fn exercise_text_preemption( let (incoming, parked) = worker.parked.front_mut().unwrap(); assert!(parked.carried.generated_tokens > 0); assert_eq!(incoming.record.preemptions, 1); + worker.publish_gauges(); + let text = worker.metrics.render(); + assert!(text.contains("\nflare_parked_requests 1\n")); + assert!(text.contains("\nflare_pending_requests 0\n")); + let (incoming, parked) = worker.parked.front_mut().unwrap(); assert_eq!( incoming .prompt @@ -5439,6 +5492,47 @@ async fn ollama_discovery_uses_bearer_auth_without_generation_admission() { result.unwrap(); } +#[tokio::test] +async fn full_http_admission_counts_a_queue_limit_rejection() { + use std::io::{Read, Write}; + let (sender, _receiver) = mpsc::sync_channel(4); + let state = http_state(sender, None); + let held = state + .ingress_slots + .clone() + .acquire_many_owned(state.ingress_capacity as u32) + .await + .unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let router = super::super::router(state.clone(), &[], 65536); + let server = tokio::spawn(async move { axum::serve(listener, router).await }); + let status = tokio::task::spawn_blocking(move || { + let body = r#"{"prompt":"a","max_tokens":1}"#; + let mut stream = std::net::TcpStream::connect(address).unwrap(); + write!( + stream, + "POST /v1/completions HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) + .unwrap(); + let mut response = String::new(); + stream.read_to_string(&mut response).unwrap(); + response.split(' ').nth(1).unwrap().parse::().unwrap() + }) + .await + .unwrap(); + assert_eq!(status, 429); + assert!(state + .model + .metrics() + .render() + .lines() + .any(|line| line == "flare_admission_rejections_total{reason=\"http_slots\"} 1")); + server.abort(); + drop(held); +} + #[tokio::test] async fn metrics_route_serves_prometheus_or_json_without_the_api_key() { use std::io::{Read, Write}; From 63437afafbdb882c14b5bdc11d04f5fa9d2c78f3 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 15:24:39 -0600 Subject: [PATCH 07/14] Document how Flare's metrics correspond to vLLM's An operator moving dashboards or alerts from vLLM to Flare has to find, for each vLLM metric, the Flare series that measures the same quantity, the arithmetic that derives it, or the fact that Flare does not provide it. Flare deliberately exports no `vllm:` aliases and adds no second series for a quantity it already reports, so that correspondence exists only as documentation. `docs/api.md` gains a "Correspondence with vLLM metrics" table under "Health and metrics". It covers every metric in vLLM's General and Speculative Decoding tables, plus vLLM's aggregate speculative counters and connector families. Each row gives the Flare series or expression and the material difference in origin or population: time to first token starts at model-scheduler arrival, prefix lookup counters include readmissions, `num_requests_running` includes requests waiting for a host restore, and Flare's per-request histograms exclude cancelled and failed requests. Rows for corrupted requests, KV block residency, FLOPs estimates, LoRA, watermarking, sleep state, and KV connectors state that Flare does not provide them and why. The claimed result is documentation only; no code changes. Evidence: each Flare name in the table was checked against the renderer in `helios/src/server/metrics.rs` and `helios/src/server.rs`, and each vLLM name against vLLM's published production-metrics list and its Prometheus logger source. The table has not been exercised by a dashboard. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=2e5b --- docs/api.md | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/docs/api.md b/docs/api.md index 6dcccb6be..4cffa1a0e 100644 --- a/docs/api.md +++ b/docs/api.md @@ -463,6 +463,46 @@ capacity. For packed speculation, completion records report the prefixes allocat on the GPU before target verification. Prefill, resume sampling, inactive padding, failed lanes, and terminal rounds without progress do not enter this average. +### Correspondence with vLLM metrics + +Flare exports no `vllm:` names. The table gives the Flare series that measure +each metric in vLLM's production metric list, named here without the `vllm:` +prefix, and the metrics Flare does not provide. Flare's per-request histograms +exclude cancelled and failed requests, which vLLM's include. + +| vLLM metric | Flare series | +| --- | --- | +| `num_requests_running` | `flare_active_requests`, which includes admitted requests waiting for a host restore (`flare_host_cache_inbound_waiting`) | +| `num_requests_waiting` | `flare_pending_requests` + `flare_parked_requests` | +| `num_requests_waiting_by_reason` | No capacity or deferred split; `flare_pending_requests` (first admission) and `flare_parked_requests` (readmission) | +| `num_requests_kv_fetch_by_stage` | `flare_host_cache_inbound_waiting` and `flare_host_cache_inbound_in_flight` | +| `kv_cache_usage_perc` | (`flare_request_kv_pages` + `flare_reserved_kv_pages`) / `flare_total_kv_pages` | +| `prompt_tokens`, `prompt_tokens_by_source` | `flare_prefill_tokens_total` (computed, including recomputation after preemption), `flare_cache_reused_tokens_total` (GPU), `flare_host_cache_reused_tokens_total` (host) | +| `prompt_tokens_cached`, `prompt_tokens_cached_by_source` | `flare_cache_reused_tokens_total` (device) + `flare_host_cache_reused_tokens_total` (host DRAM, disk, or shared pool) | +| `prefix_cache_queries`, `prefix_cache_hits` | `flare_cache_lookup_tokens_total`, `flare_cache_reused_tokens_total`; both include readmissions | +| `external_prefix_cache_queries`, `external_prefix_cache_hits` | `flare_host_cache_lookups_total` (lookups, not tokens), `flare_host_cache_reused_tokens_total` | +| `mm_cache_queries`, `mm_cache_hits` | `flare_input_cache_payload_hits_total` + `flare_input_cache_payload_misses_total`, `flare_input_cache_payload_hits_total` | +| `generation_tokens` | `flare_generated_tokens_total` | +| `num_preemptions` | `flare_preemptions_total` | +| `request_success{finished_reason}` | `stop`: `flare_requests_completed_total` − `flare_requests_output_limited_total`; `length`: `flare_requests_output_limited_total`; `abort`: `flare_requests_cancelled_total`; `error`: `flare_requests_failed_total`; `repetition`: not provided | +| `admission_rejections{reason}` | `flare_admission_rejections_total{reason}`, with Flare's queue limits as reasons | +| `iteration_tokens_total` | `flare_model_step_tokens` | +| `e2e_request_latency_seconds` | `flare_request_e2e_seconds`, from HTTP admission | +| `time_to_first_token_seconds` | `flare_time_to_first_token_seconds`, from model-scheduler arrival; `flare_time_to_first_response_seconds` from HTTP admission to visible text | +| `inter_token_latency_seconds` | `flare_inter_token_latency_seconds` | +| `request_queue_time_seconds`, `request_prefill_time_seconds`, `request_decode_time_seconds`, `request_inference_time_seconds` | `flare_request_queue_seconds`, `flare_request_prefill_seconds`, `flare_request_decode_seconds`, `flare_request_inference_seconds` | +| `request_time_per_output_token_seconds` | `flare_time_per_output_token_seconds` | +| `request_prompt_tokens`, `request_generation_tokens`, `request_prefill_kv_computed_tokens` | `flare_request_prompt_tokens`, `flare_request_generated_tokens`, `flare_request_prefill_computed_tokens` | +| `request_params_max_tokens`, `request_params_n`, `request_max_num_generation_tokens` | `flare_request_max_tokens`, `flare_request_choices`, `flare_request_max_choice_generated_tokens` | +| `request_num_preemptions` | `flare_request_preemptions` | +| `spec_decode_num_drafts`, `spec_decode_num_draft_tokens`, `spec_decode_num_accepted_tokens` | `flare_draft_request_rounds_total`, `flare_verification_draft_tokens_total`, `flare_accepted_draft_tokens_total` | +| `spec_decode_num_verified_tokens_per_pos`, `spec_decode_num_accepted_tokens_per_pos`, `spec_decode_num_verified_tokens` | `flare_speculative_drafts_total{depth,source,outcome}` with `outcome` `offered` or `accepted`, summed over `source` (and over `depth` for the total) | +| `corrupted_requests` | Not provided: Flare does not inspect logits for NaN values | +| `kv_block_lifetime_seconds`, `kv_block_idle_before_evict_seconds`, `kv_block_reuse_gap_seconds` | Not provided: Flare does not sample KV page residency | +| `estimated_flops_per_gpu_total`, `estimated_read_bytes_per_gpu_total`, `estimated_write_bytes_per_gpu_total` | Not provided; `flare_decode_weight_bytes` gives the weight bytes one decode step reads per request | +| `lora_requests_info`, `watermark_requests`, `engine_sleep_state` | Not provided: Flare has no LoRA adapters, output watermarking, or sleep mode | +| KV connector metrics (`nixl_*`, `hisparse_*`, `simple_kv_offload_*`) | Not provided: Flare has no KV connectors; `flare_host_cache_*` series report its host prefix store | + ## Conversation and tool semantics The neutral request representation in `helios/src/server/inference.rs` separates From 151207f2e29c5d263701968ebceacb082684b3ae Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 15:44:48 -0600 Subject: [PATCH 08/14] State request-histogram populations from the code and drop duplicate assertions docs/api.md described a narrower instrument than the code records. The end-to-end histogram is observed once per delivered successful response, it excludes /v1/messages/count_tokens and responses the runtime counts as cancelled (including a parallel tool-limit stop), and it can be lower than flare_requests_completed_total because a multi-choice response adds one observation for several model-request completions and an abandoned stream adds none. The closing sentence claimed cancelled and failed requests enter only two counters, but flare_time_to_first_response_seconds observes a stream that offered text before it failed. The runtime paragraph now also says a zero-token completion still increments flare_requests_completed_total and enters the prompt-token histograms, while the queue observation needs a model step and time-to-first-token, prefill, and inference need a committed token. The vLLM table rows and its intro state the same populations. phase_tests.rs rendered the whole scrape three times in the failed-stream loop for one assertion and re-rendered the first-response histogram that the /metrics route test already exercises. Both duplicates are removed; the end-to-end exclusion for a failed response is still asserted, once, and the tool-limit count assertion is kept because it pins a distinct guard. Validation: cargo check --locked --manifest-path helios/Cargo.toml --features server (passes). cargo test --locked --manifest-path helios/Cargo.toml --features runtime-core,server --lib -- server:: scheduler:: cache::: 816 passed, 1 failed - the known server::protocol::decode::native_prompt_tests:: messages_image_hints_end_after_expansion_for_text_and_segmented_templates, which needs FLARE_TEST_TEMPLATE_DIR. Limitations: documentation and test-duplication only; no production code changes. The test-only drift assertion in Cache::stats and the first-response histogram on FirstResponseSamples are outside this change. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=2e5b --- docs/api.md | 48 +++++++++++++++--------- helios/src/server/runtime/phase_tests.rs | 7 +--- 2 files changed, 32 insertions(+), 23 deletions(-) diff --git a/docs/api.md b/docs/api.md index 4cffa1a0e..703f1bbb6 100644 --- a/docs/api.md +++ b/docs/api.md @@ -299,22 +299,32 @@ start. Host prefix-store histograms report lookup cost and retirement: `flare_host_cache_estimated_prefill_ns`, and `flare_host_cache_retirement_seconds`. -The HTTP histograms observe delivery. `flare_request_e2e_seconds` counts each -successful generation from admission to the completed response; for a stream it -is observed when delivery completes, which requires the client to drain the -body. `flare_time_to_first_response_seconds` counts each response that offers -answer or reasoning text, from admission to that text, once the client reads it. +The HTTP histograms observe delivery. `flare_request_e2e_seconds` observes each +successful generation response once, from admission to the completed response; +it excludes `/v1/messages/count_tokens` and responses the runtime records as +cancelled, such as a parallel tool-limit stop. It is observed once per delivered +response, while the runtime counts one completion per model request, so a +multi-choice response adds fewer observations than completions, and a stream the +client abandons before draining adds none. For a stream it is observed when +delivery completes, which requires the client to drain the body. +`flare_time_to_first_response_seconds` counts each response that offers answer or +reasoning text, from admission to that text, once the client reads it; a stream +that offers text before it fails still records this observation. With `flare_request_e2e_seconds`, each response also adds one observation per prompt to `flare_request_choices`, the requested choice count `n`, and to `flare_request_max_choice_generated_tokens`, the largest generated-token count among that prompt's choices. Only `/v1/completions` accepts `n` above one or a list of prompts; Flare runs each choice as its own model request. -The runtime histograms observe completed generations. `flare_request_queue_seconds` -spans model-scheduler arrival to the first model step that includes the request, -which can be a vision step; `flare_request_prefill_seconds` spans that step to -the request's first committed generated token, and -`flare_request_inference_seconds` spans it to the last committed generated token. +The runtime histograms observe requests whose model generation completes +successfully. `flare_request_queue_seconds` spans model-scheduler arrival to the +first model step that includes the request, which can be a vision step; it is +recorded only if the request reached such a step. +`flare_request_prefill_seconds` spans that step to the request's first committed +generated token, and `flare_request_inference_seconds` spans it to the last +committed generated token. A completion that committed no generated token still +increments `flare_requests_completed_total` and enters the token histograms +below, but records no time-to-first-token, prefill, or inference observation. `flare_time_to_first_token_seconds` spans model-scheduler arrival to the first committed generated token; unlike `flare_time_to_first_response_seconds`, it excludes HTTP preparation and counts tokens that produce no visible text. @@ -339,8 +349,10 @@ by the remaining context, including tokens a reasoning budget defers. Prompt-scoring requests with a zero limit are not observed. `flare_request_preemptions` counts how many times each request was preempted and readmitted; its buckets are vLLM's preemption bounds with an added zero bound. -Cancelled and failed requests enter only `flare_requests_cancelled_total` and -`flare_requests_failed_total`. +Cancelled and failed requests contribute no observation to the runtime histograms +here. Apart from counters, the only series that can observe them is +`flare_time_to_first_response_seconds`, and only when text was offered before the +failure. `flare_requests_output_limited_total` counts completed requests that stopped at their output token limit; the rest of `flare_requests_completed_total` stopped at @@ -467,8 +479,10 @@ failed lanes, and terminal rounds without progress do not enter this average. Flare exports no `vllm:` names. The table gives the Flare series that measure each metric in vLLM's production metric list, named here without the `vllm:` -prefix, and the metrics Flare does not provide. Flare's per-request histograms -exclude cancelled and failed requests, which vLLM's include. +prefix, and the metrics Flare does not provide. Flare's request histograms cover +successful completions, where vLLM's also observe failed and cancelled requests; +only `flare_time_to_first_response_seconds` can observe a response that later +fails. | vLLM metric | Flare series | | --- | --- | @@ -476,7 +490,7 @@ exclude cancelled and failed requests, which vLLM's include. | `num_requests_waiting` | `flare_pending_requests` + `flare_parked_requests` | | `num_requests_waiting_by_reason` | No capacity or deferred split; `flare_pending_requests` (first admission) and `flare_parked_requests` (readmission) | | `num_requests_kv_fetch_by_stage` | `flare_host_cache_inbound_waiting` and `flare_host_cache_inbound_in_flight` | -| `kv_cache_usage_perc` | (`flare_request_kv_pages` + `flare_reserved_kv_pages`) / `flare_total_kv_pages` | +| `kv_cache_usage_perc` | Not provided as one ratio; `flare_free_kv_pages`, `flare_cached_kv_pages`, and `flare_total_kv_pages` bound it | | `prompt_tokens`, `prompt_tokens_by_source` | `flare_prefill_tokens_total` (computed, including recomputation after preemption), `flare_cache_reused_tokens_total` (GPU), `flare_host_cache_reused_tokens_total` (host) | | `prompt_tokens_cached`, `prompt_tokens_cached_by_source` | `flare_cache_reused_tokens_total` (device) + `flare_host_cache_reused_tokens_total` (host DRAM, disk, or shared pool) | | `prefix_cache_queries`, `prefix_cache_hits` | `flare_cache_lookup_tokens_total`, `flare_cache_reused_tokens_total`; both include readmissions | @@ -487,8 +501,8 @@ exclude cancelled and failed requests, which vLLM's include. | `request_success{finished_reason}` | `stop`: `flare_requests_completed_total` − `flare_requests_output_limited_total`; `length`: `flare_requests_output_limited_total`; `abort`: `flare_requests_cancelled_total`; `error`: `flare_requests_failed_total`; `repetition`: not provided | | `admission_rejections{reason}` | `flare_admission_rejections_total{reason}`, with Flare's queue limits as reasons | | `iteration_tokens_total` | `flare_model_step_tokens` | -| `e2e_request_latency_seconds` | `flare_request_e2e_seconds`, from HTTP admission | -| `time_to_first_token_seconds` | `flare_time_to_first_token_seconds`, from model-scheduler arrival; `flare_time_to_first_response_seconds` from HTTP admission to visible text | +| `e2e_request_latency_seconds` | `flare_request_e2e_seconds`, from HTTP admission, for successful delivered responses and excluding token counting and tool-limit cancellations | +| `time_to_first_token_seconds` | `flare_time_to_first_token_seconds`, from model-scheduler arrival; `flare_time_to_first_response_seconds` from HTTP admission to visible text, also recorded when a stream that offered text later fails | | `inter_token_latency_seconds` | `flare_inter_token_latency_seconds` | | `request_queue_time_seconds`, `request_prefill_time_seconds`, `request_decode_time_seconds`, `request_inference_time_seconds` | `flare_request_queue_seconds`, `flare_request_prefill_seconds`, `flare_request_decode_seconds`, `flare_request_inference_seconds` | | `request_time_per_output_token_seconds` | `flare_time_per_output_token_seconds` | diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 95ba448e7..4051562df 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -4605,6 +4605,7 @@ async fn first_response_http_stream_excludes_pretext_failures_and_unpolled_bodie let snapshot = state.first_response.snapshot(); assert_eq!(snapshot.samples, u64::from(emit_text && poll_body)); assert_eq!(snapshot.median_seconds.is_some(), emit_text && poll_body); + // A failed response records no end-to-end observation in any case. assert!(state .model .metrics() @@ -4643,12 +4644,6 @@ async fn first_response_http_nonstream_records_only_when_completed_body_is_offer .metrics() .render() .contains("\nflare_request_e2e_seconds_count 1\n")); - let mut histogram = String::new(); - state.first_response.render_histogram(&mut histogram); - assert!(histogram.contains(&format!( - "\nflare_time_to_first_response_seconds_count {}\n", - u64::from(poll_body) - ))); } } From a85cb5c11a214b6195a1bd4412182ae3971f2056 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 20:26:26 -0600 Subject: [PATCH 09/14] Place request-histogram docs and test rows apart from the KV-page gauges The request-histogram documentation and two expected rows of the counter exposition test were inserted at the same lines as the KV-page gauge change (#549) adds its paragraph and rows, so whichever of the two merged second would stop on a textual conflict although the changes are independent. The histogram paragraphs in docs/api.md now follow the paragraph about the JSON format of the /metrics route instead of directly following the route's introduction, and in counters_expose_fixed_names_without_request_payloads the cache_lookup_tokens field and the parked_requests row move to the end of their lists. The text and assertions are unchanged; the test checks each row with `contains`, so row order does not matter. The two changes now merge in either order without manual resolution. cargo test --features runtime-core,server --lib -- server::metrics passed 19 tests, and `git merge-tree` of this branch with the KV-page branch reports no conflict. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=2e5b --- docs/api.md | 18 +++++++++--------- helios/src/server/metrics.rs | 4 ++-- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/api.md b/docs/api.md index 703f1bbb6..d6a33551b 100644 --- a/docs/api.md +++ b/docs/api.md @@ -293,6 +293,15 @@ text includes speculative and proposal counters by batch, width, or depth, graph launches by kind, embedding row-cache counters, HTTP admission gauges, and uptime. +The route returns one JSON object instead when the query contains `format=json`, +or when the `Accept` header gives `application/json` a higher quality than +`text/plain`; at equal quality the earlier media range wins. `format=prometheus` +selects text regardless of `Accept`, and any other `format` value returns HTTP +400. Requests without an `Accept` header, and Prometheus scrapers, receive text. +`flare_helios::server::Snapshot` deserializes the object, reading absent fields +as zero, and `flare_helios::server::view` holds the rate history and plots of +the serving terminal dashboard. + Histograms appear in the Prometheus format only and accumulate since server start. Host prefix-store histograms report lookup cost and retirement: `flare_host_cache_missing_tokens`, `flare_host_cache_estimated_transfer_ns`, @@ -376,15 +385,6 @@ speculative, or mixed graph, the prompt tokens it computed plus the generated tokens it committed; rejected draft positions and padding are excluded, and initialization, restore, vision, and snapshot graphs are not observed. -The route returns one JSON object instead when the query contains `format=json`, -or when the `Accept` header gives `application/json` a higher quality than -`text/plain`; at equal quality the earlier media range wins. `format=prometheus` -selects text regardless of `Accept`, and any other `format` value returns HTTP -400. Requests without an `Accept` header, and Prometheus scrapers, receive text. -`flare_helios::server::Snapshot` deserializes the object, reading absent fields -as zero, and `flare_helios::server::view` holds the rate history and plots of -the serving terminal dashboard. - The fields in the table are integers except `learned_drafter`. Totals count from server start; `active`, `pending`, the page fields, and the host record fields are instantaneous gauges. The object also contains `first_response`, an object with diff --git a/helios/src/server/metrics.rs b/helios/src/server/metrics.rs index 841d01991..b09366da4 100644 --- a/helios/src/server/metrics.rs +++ b/helios/src/server/metrics.rs @@ -2283,11 +2283,11 @@ mod tests { reused_tokens: 192, free_pages: 10, cached_pages: 3, - cache_lookup_tokens: 320, host_lookups: 4, host_hits: 1, host_reused_tokens: 640, inbound_waiting: 1, + cache_lookup_tokens: 320, ..SchedulerStats::default() }); metrics.launched(GraphKind::Restore); @@ -2337,10 +2337,10 @@ mod tests { ("free_kv_tokens", 1280), ("cached_kv_pages", 3), ("cached_kv_tokens", 384), - ("parked_requests", 2), ("host_cache_slots_in_use", 3), ("host_cache_slots_total", 8), ("host_cache_intake_slots", 2), + ("parked_requests", 2), ] { assert!(text.contains(&format!("# TYPE flare_{name} gauge\n"))); assert!(text.contains(&format!("\nflare_{name} {value}\n"))); From be487aa866603c5851737e865503334430dd2a6e Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 21:54:04 -0600 Subject: [PATCH 10/14] Reuse GraphKind::samples for model-step metrics and stamp scheduled time after packing The completion path spelled the seven sampling graph kinds inline to decide whether a completed step contributes to flare_model_step_tokens, duplicating GraphKind::samples() in helios/src/execution/manifest.rs, which the same file already uses to validate sampling admissions. A sampling kind added to samples() would update its other consumers but not this list, so the counter would silently stop counting it. In reserve_and_pack, the first_scheduled_ns stamp preceded pack_inputs/pack_vision, which can return Err, so a request whose packing failed kept a scheduled instant for a step that never executed. The completion path now tests kind.samples(). reserve_and_pack performs its single monotonic_ns() read and the per-lane get_or_insert after packing returns Ok, so a successful step stamps the same instant as before and a failed pack leaves first_scheduled_ns unset. flare_model_step_tokens counts the same steps: samples() lists exactly the seven variants the inline list named (Prefill, TerminalPrefill, ScoredPrefill, Decode, Speculative, Mixed, Resume), now from one source of truth. The queue-time and prefill/inference histograms no longer record a scheduled instant for a step whose packing failed. cargo check --locked --manifest-path helios/Cargo.toml --features server finished with four pre-existing warnings. cargo test --locked --manifest-path helios/Cargo.toml --features runtime-core,server --lib -- server:: scheduler:: cache:: passed 814 tests and failed one: server::protocol::decode::native_prompt_tests::messages_image_hints_end_after_expansion_for_text_and_segmented_templates, which requires FLARE_TEST_TEMPLATE_DIR and exercises no changed path. No GPU server run was performed, so the emitted metrics were not checked end to end. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: enterprise/deepseek-v4.1-flash (omp agent); design-review=2e5b --- helios/src/server/runtime.rs | 44 +++++++++++++++--------------------- 1 file changed, 18 insertions(+), 26 deletions(-) diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index 18ef633d6..c84226736 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -1831,16 +1831,7 @@ impl<'a> Worker<'a> { self.metrics .progress(prefill, generated.len(), accepted, draft_rounds, verification_drafts, verification_rounds); - if matches!( - kind, - GraphKind::Prefill - | GraphKind::TerminalPrefill - | GraphKind::ScoredPrefill - | GraphKind::Resume - | GraphKind::Decode - | GraphKind::Speculative - | GraphKind::Mixed - ) { + if kind.samples() { self.metrics.model_step(prefill + generated.len() as u64); } self.metrics.replay_completed(completed_at_ns, completion.timing, prefill); @@ -2557,22 +2548,6 @@ impl<'a> Worker<'a> { fn reserve_and_pack(&mut self, step: &ScheduledPlan, fence: crate::cache::Fence) -> Result<()> { self.scheduler.commit(step, fence)?; - // Stamp here rather than at submission so a request that reaches a model step - // has one, including requests driven through reserve_and_pack directly. - let scheduled_ns = super::observation::monotonic_ns(); - for lane in &step.lanes { - if let Some(active) = self.active[lane.request.slot as usize] - .as_mut() - .filter(|a| a.request == lane.request) - { - active - .incoming - .record - .times - .first_scheduled_ns - .get_or_insert(scheduled_ns); - } - } let inputs = self .inputs .as_mut() @@ -2618,6 +2593,23 @@ impl<'a> Worker<'a> { &self.admissions, )?; } + // Stamp after packing so the instant marks a step whose inputs were accepted, + // including requests driven through reserve_and_pack directly. A failed pack + // leaves first_scheduled_ns unset. + let scheduled_ns = super::observation::monotonic_ns(); + for lane in &step.lanes { + if let Some(active) = self.active[lane.request.slot as usize] + .as_mut() + .filter(|a| a.request == lane.request) + { + active + .incoming + .record + .times + .first_scheduled_ns + .get_or_insert(scheduled_ns); + } + } Ok(()) } From 5687ebb0e3918e42c08eec03595d0262fef3a5c4 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Sat, 28 Nov 2026 16:45:02 -0600 Subject: [PATCH 11/14] Render every observed histogram through Histogram The metrics module wrote histograms three ways. The request histograms used `Histogram` and `Buckets`, with `# HELP` and `_sum` before `_count`. The three host prefix-store lookup histograms (`flare_host_cache_missing_tokens`, `flare_host_cache_estimated_transfer_ns`, `flare_host_cache_estimated_prefill_ns`) used separate integer bound arrays, a sum array, and a hand-written render loop without `# HELP` that printed `_count` before `_sum`. `Buckets` held `f64` bounds in the exposed unit plus a `scale`, so every observation was divided before comparison. `flare_time_to_first_response_seconds` was a `Histogram` owned by the rolling first-response window and rendered through a separate hook in the `/metrics` handler. Folding all of them onto one type gives every scrape one histogram format and one bucket search. `Buckets` now holds `u64` bounds on the observation grid (nanoseconds or counts) ending at `u64::MAX`, and a `per_unit` divisor applied only when rendering `le` labels and `_sum`. The three host lookup histograms are `Histogram<8>` fields observed with `HOST_NANOSECONDS` and `HOST_TOKEN_COUNTS` and rendered by `Histogram::render`; `host_cost_sums`, `HOST_TIME_BUCKETS`, `HOST_TOKEN_BUCKETS`, and the custom loop are removed. `flare_time_to_first_response_seconds` is a `Metrics` field observed through `Metrics::first_response`, which `FirstResponse::output` calls through the metrics handle it receives when the observation starts; the window keeps only its rolling samples. A module doc names `Histogram` over `Buckets` as the form of every observed histogram, and comments at `Metrics::store` and the retirement render state that `flare_host_cache_retirement_seconds` copies counts owned by the selene store. Result: metric names, bucket bounds, and observed values are unchanged. The host lookup histograms gain `# HELP` lines and emit `_sum` before `_count`, and their nanosecond sums stay exact integers. Every `le` label renders the same text as before because each integer bound divided by 1e9 is the same double as the former decimal literal. Evidence: the host lookup test asserts the `# HELP` line, bucket boundaries, sums, counts, and `_sum` before `_count`; the first-response unit test asserts one `flare_time_to_first_response_seconds` observation after two `output` calls. Each nanosecond bound of `REQUEST_SECONDS` and `TOKEN_SECONDS` divided by 1e9 compares equal to its former literal in IEEE double arithmetic. Build and tests: on the tree with this commit and the two that follow it, `cargo check --locked --features server` succeeds and `cargo test --locked --features runtime-core,server --lib -- server:: scheduler:: cache::` reports 816 passed, 1 failed, 11 ignored. The failure is server::protocol::decode::native_prompt_tests::messages_image_hints_end_after_expansion_for_text_and_segmented_templates, which requires FLARE_TEST_TEMPLATE_DIR and exercises no changed path. No GPU server run was performed, so a live scrape was not compared. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: enterprise/deepseek-v4.1-flash (omp agent); design-review=2e5b --- helios/src/server.rs | 1 - helios/src/server/http.rs | 2 +- helios/src/server/latency.rs | 33 ++-- helios/src/server/metrics.rs | 214 +++++++++++++---------- helios/src/server/runtime/phase_tests.rs | 5 +- 5 files changed, 140 insertions(+), 115 deletions(-) diff --git a/helios/src/server.rs b/helios/src/server.rs index a8ce75298..8161fe701 100644 --- a/helios/src/server.rs +++ b/helios/src/server.rs @@ -668,7 +668,6 @@ async fn metrics(State(state): State>, uri: Uri, headers: HeaderM use std::fmt::Write; let _ = writeln!(text, "# HELP flare_first_response_median_seconds Server-side HTTP admission to first offered answer or reasoning text.\n# TYPE flare_first_response_median_seconds gauge\nflare_first_response_median_seconds {median}"); } - state.first_response.render_histogram(&mut text); for (name, kind, help, value) in input_metrics { metrics::metric(&mut text, name, kind, help, value); } diff --git a/helios/src/server/http.rs b/helios/src/server/http.rs index 69414e417..dacf6be5d 100644 --- a/helios/src/server/http.rs +++ b/helios/src/server/http.rs @@ -125,7 +125,7 @@ pub(super) async fn generate( request: Request, ) -> Response { let admitted_at = request.extensions().get::().map(|at| at.0).unwrap_or_else(Instant::now); - let mut first_response = state.first_response.observe(admitted_at); + let mut first_response = state.first_response.observe(admitted_at, state.model.metrics_handle()); let ingress_ns = observation::monotonic_ns(); let protocol = Protocol::from_path(request.uri().path()); let count = request.uri().path() == "/v1/messages/count_tokens"; diff --git a/helios/src/server/latency.rs b/helios/src/server/latency.rs index 760739281..c1ae89200 100644 --- a/helios/src/server/latency.rs +++ b/helios/src/server/latency.rs @@ -33,7 +33,6 @@ struct Samples { #[derive(Default)] pub(super) struct FirstResponseSamples { window: Mutex, - histogram: super::metrics::Histogram<21>, } impl Samples { fn expire(&mut self, now: Instant) { @@ -61,9 +60,16 @@ impl Samples { } } impl FirstResponseSamples { - pub(super) fn observe(self: &Arc, started: Instant) -> FirstResponse { + /// Starts one response's observation, which records into this window and the + /// all-time `flare_time_to_first_response_seconds` histogram of `metrics`. + pub(super) fn observe( + self: &Arc, + started: Instant, + metrics: Arc, + ) -> FirstResponse { FirstResponse { samples: self.clone(), + metrics, started, recorded: false, } @@ -98,17 +104,10 @@ impl FirstResponseSamples { truncated, } } - pub(super) fn render_histogram(&self, text: &mut String) { - self.histogram.render( - text, - "time_to_first_response_seconds", - "Server-side HTTP admission to the first offered answer or reasoning text.", - &super::metrics::REQUEST_SECONDS, - ); - } } pub(super) struct FirstResponse { samples: Arc, + metrics: Arc, started: Instant, recorded: bool, } @@ -118,10 +117,8 @@ impl FirstResponse { let now = Instant::now(); let mut samples = self.samples.window.lock().unwrap_or_else(|e| e.into_inner()); samples.record(self.started, now); - self.samples.histogram.observe( - &super::metrics::REQUEST_SECONDS, - now.saturating_duration_since(self.started).as_nanos() as u64, - ); + self.metrics + .first_response(now.saturating_duration_since(self.started).as_nanos() as u64); self.recorded = true; } } @@ -225,13 +222,17 @@ mod tests { #[test] fn first_response_records_once_and_excludes_unoffered_output() { let samples = Arc::new(FirstResponseSamples::default()); - drop(samples.observe(Instant::now())); + let metrics = Arc::new(super::super::metrics::Metrics::default()); + drop(samples.observe(Instant::now(), metrics.clone())); assert_eq!(samples.snapshot().samples, 0); - let mut response = samples.observe(Instant::now()); + let mut response = samples.observe(Instant::now(), metrics.clone()); response.output(); response.output(); assert_eq!(samples.snapshot().samples, 1); assert!(samples.snapshot().median_seconds.is_some()); + assert!(metrics + .render() + .contains("\nflare_time_to_first_response_seconds_count 1\n")); } #[test] diff --git a/helios/src/server/metrics.rs b/helios/src/server/metrics.rs index b09366da4..5f6b7d406 100644 --- a/helios/src/server/metrics.rs +++ b/helios/src/server/metrics.rs @@ -4,6 +4,10 @@ * SPDX-License-Identifier: Apache-2.0 */ +//! Serving metrics and their Prometheus text exposition. Every histogram observed +//! in this process is a [`Histogram`] over a [`Buckets`] preset, which renders +//! `# HELP`, cumulative buckets, `_sum`, then `_count`. + use std::{ fmt::Write, sync::atomic::{AtomicU64, Ordering}, @@ -196,64 +200,80 @@ impl Format { } } -const HOST_TIME_BUCKETS: [u64; 8] = [ - 100_000, - 1_000_000, - 10_000_000, - 100_000_000, - 1_000_000_000, - 10_000_000_000, - 100_000_000_000, - u64::MAX, -]; -const HOST_TOKEN_BUCKETS: [u64; 8] = [64, 256, 1024, 4096, 16384, 65536, 262144, u64::MAX]; - -/// Upper bucket bounds of a Prometheus histogram in its exposed unit, ending at -/// `f64::INFINITY`. Observations are integers of `1 / scale` exposed units. +const US: u64 = 1_000; +const MS: u64 = 1_000_000; +const S: u64 = 1_000_000_000; + +/// Upper bucket bounds of a Prometheus histogram on the integer grid of its +/// observations, ending at `u64::MAX`, which renders as `+Inf`. `per_unit` +/// observations make one exposed unit: nanoseconds per second, or 1 when the +/// exposed unit is the observed one. pub(super) struct Buckets { - bounds: [f64; N], - scale: f64, + bounds: [u64; N], + per_unit: u64, +} + +impl Buckets { + fn exposed(&self, value: u64) -> String { + if self.per_unit == 1 { + value.to_string() + } else { + (value as f64 / self.per_unit as f64).to_string() + } + } } pub(super) const REQUEST_SECONDS: Buckets<21> = Buckets { bounds: [ - 0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 20.0, 40.0, 80.0, - 160.0, 320.0, 640.0, 1280.0, 2560.0, f64::INFINITY, + MS, 5 * MS, 10 * MS, 25 * MS, 50 * MS, 100 * MS, 250 * MS, 500 * MS, S, 2500 * MS, + 5 * S, 10 * S, 20 * S, 40 * S, 80 * S, 160 * S, 320 * S, 640 * S, 1280 * S, 2560 * S, + u64::MAX, ], - scale: 1e9, + per_unit: S, }; pub(super) const TOKEN_SECONDS: Buckets<19> = Buckets { bounds: [ - 0.001, 0.0025, 0.005, 0.0075, 0.01, 0.015, 0.02, 0.03, 0.04, 0.05, 0.075, 0.1, 0.15, 0.2, - 0.3, 0.5, 1.0, 2.5, f64::INFINITY, + MS, 2500 * US, 5 * MS, 7500 * US, 10 * MS, 15 * MS, 20 * MS, 30 * MS, 40 * MS, 50 * MS, + 75 * MS, 100 * MS, 150 * MS, 200 * MS, 300 * MS, 500 * MS, S, 2500 * MS, u64::MAX, ], - scale: 1e9, + per_unit: S, }; pub(super) const TOKEN_COUNTS: Buckets<21> = Buckets { bounds: [ - 1.0, 8.0, 16.0, 32.0, 64.0, 128.0, 256.0, 512.0, 1024.0, 2048.0, 4096.0, 8192.0, 16384.0, - 32768.0, 65536.0, 131072.0, 262144.0, 524288.0, 1048576.0, 2097152.0, f64::INFINITY, + 1, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, + 262144, 524288, 1048576, 2097152, u64::MAX, ], - scale: 1.0, + per_unit: 1, }; /// vLLM's preemption-count bounds with a leading zero bound, so never-preempted /// requests stay separate from requests preempted once. pub(super) const PREEMPTION_COUNTS: Buckets<9> = Buckets { - bounds: [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 10.0, 20.0, f64::INFINITY], - scale: 1.0, + bounds: [0, 1, 2, 3, 4, 5, 10, 20, u64::MAX], + per_unit: 1, }; /// vLLM's bounds for the `n` request parameter. pub(super) const CHOICE_COUNTS: Buckets<6> = Buckets { - bounds: [1.0, 2.0, 5.0, 10.0, 20.0, f64::INFINITY], - scale: 1.0, + bounds: [1, 2, 5, 10, 20, u64::MAX], + per_unit: 1, +}; + +/// Host prefix-store cost estimates, exposed in nanoseconds. +const HOST_NANOSECONDS: Buckets<8> = Buckets { + bounds: [100 * US, MS, 10 * MS, 100 * MS, S, 10 * S, 100 * S, u64::MAX], + per_unit: 1, +}; + +const HOST_TOKEN_COUNTS: Buckets<8> = Buckets { + bounds: [64, 256, 1024, 4096, 16384, 65536, 262144, u64::MAX], + per_unit: 1, }; /// Fixed-bucket Prometheus histogram: per-bucket observations and the sum of the -/// observed values, both on the exposed unit's integer grid. +/// observed values, both in observation units. pub(super) struct Histogram { counts: [AtomicU64; N], sum: AtomicU64, @@ -270,13 +290,10 @@ impl Default for Histogram { impl Histogram { pub(super) fn observe(&self, buckets: &Buckets, value: u64) { - // Division is correctly rounded, so an integer grid point lands exactly on - // a bound written as the same decimal. - let exposed = value as f64 / buckets.scale; let index = buckets .bounds .iter() - .position(|bound| exposed <= *bound) + .position(|bound| value <= *bound) .unwrap_or(N - 1); self.counts[index].fetch_add(1, Ordering::Relaxed); self.sum.fetch_add(value, Ordering::Relaxed); @@ -300,12 +317,12 @@ impl Histogram { "# HELP flare_{name} {help}\n# TYPE flare_{name} histogram" ); let mut cumulative = 0; - for (index, bound) in buckets.bounds.iter().enumerate() { - cumulative += self.counts[index].load(Ordering::Relaxed); - let bound = if bound.is_infinite() { + for (count, &bound) in self.counts.iter().zip(&buckets.bounds) { + cumulative += count.load(Ordering::Relaxed); + let bound = if bound == u64::MAX { "+Inf".to_string() } else { - format!("{bound}") + buckets.exposed(bound) }; let _ = writeln!( text, @@ -315,7 +332,7 @@ impl Histogram { let _ = writeln!( text, "flare_{name}_sum {}", - self.sum.load(Ordering::Relaxed) as f64 / buckets.scale + buckets.exposed(self.sum.load(Ordering::Relaxed)) ); let _ = writeln!(text, "flare_{name}_count {cumulative}"); } @@ -410,6 +427,7 @@ pub(super) struct Metrics { request_decode: Histogram<21>, request_inference: Histogram<21>, time_to_first_token: Histogram<21>, + time_to_first_response: Histogram<21>, time_per_output_token: Histogram<19>, inter_token_latency: Histogram<19>, request_prompt_tokens: Histogram<21>, @@ -471,10 +489,9 @@ pub(super) struct Metrics { host_store_reasons: [AtomicU64; 6], pub(super) host_retry_success: AtomicU64, pub(super) host_retry_abandoned: [AtomicU64; 6], - host_cost_sums: [AtomicU64; 3], - host_missing_tokens: [AtomicU64; 8], - host_transfer_ns: [AtomicU64; 8], - host_prefill_ns: [AtomicU64; 8], + host_missing_tokens: Histogram<8>, + host_transfer_ns: Histogram<8>, + host_prefill_ns: Histogram<8>, host_store_skipped: AtomicU64, host_store_failed: AtomicU64, host_held: [AtomicU64; 2], @@ -618,6 +635,13 @@ impl Metrics { } } + /// Records the server-side interval from HTTP admission to the first answer + /// or reasoning text a response offers. + pub(super) fn first_response(&self, elapsed_ns: u64) { + self.time_to_first_response + .observe(&REQUEST_SECONDS, elapsed_ns); + } + pub fn persistent_worker_snapshot(&self) -> Option { self.persistent_worker .as_ref() @@ -817,26 +841,14 @@ impl Metrics { pub(super) fn host_lookup_cost(&self, hit: &flare_selene::HostHit, rate: f64) { let missing = hit.consumed_tokens - hit.resident_tokens; - for (index, (buckets, value, limits)) in [ - (&self.host_missing_tokens, missing, HOST_TOKEN_BUCKETS), - ( - &self.host_transfer_ns, - (hit.estimated_seconds * 1e9) as u64, - HOST_TIME_BUCKETS, - ), - ( - &self.host_prefill_ns, - (missing as f64 / rate.max(1.0) * 1e9) as u64, - HOST_TIME_BUCKETS, - ), - ] - .into_iter() - .enumerate() - { - self.host_cost_sums[index].fetch_add(value, Ordering::Relaxed); - let bucket = limits.iter().position(|limit| value <= *limit).unwrap(); - buckets[bucket].fetch_add(1, Ordering::Relaxed); - } + self.host_missing_tokens + .observe(&HOST_TOKEN_COUNTS, missing); + self.host_transfer_ns + .observe(&HOST_NANOSECONDS, (hit.estimated_seconds * 1e9) as u64); + self.host_prefill_ns.observe( + &HOST_NANOSECONDS, + (missing as f64 / rate.max(1.0) * 1e9) as u64, + ); } pub(super) fn codec_placement(&self, placement: crate::offload::KvCompression) { @@ -850,6 +862,8 @@ impl Metrics { if self.codec_state.get().is_some_and(|placement| *placement != crate::offload::KvCompression::Off) { *self.decode.lock().unwrap() = stats.decode; } + // The selene store owns the cumulative retirement-latency counts, so this + // histogram copies them instead of observing through `Histogram::observe`. for (gauge, value) in self .host_retirement_buckets .iter() @@ -996,6 +1010,7 @@ impl Metrics { count.load(Ordering::Relaxed) ); } + // Counts copied from the selene store in `store`; see the comment there. let _ = writeln!(text, "# TYPE flare_host_cache_retirement_seconds histogram"); for (ms, count) in flare_selene::RETIREMENT_LATENCY_MS .iter() @@ -1174,42 +1189,25 @@ impl Metrics { )); } } - for (index, (name, counters, limits)) in [ - ( - "host_cache_missing_tokens", - &self.host_missing_tokens, - HOST_TOKEN_BUCKETS, - ), + self.host_missing_tokens.render( + &mut text, + "host_cache_missing_tokens", + "Tokens each host prefix-store match evaluated at admission covers beyond the resident GPU checkpoint.", + &HOST_TOKEN_COUNTS, + ); + for (histogram, name, help) in [ ( - "host_cache_estimated_transfer_ns", &self.host_transfer_ns, - HOST_TIME_BUCKETS, + "host_cache_estimated_transfer_ns", + "Estimated nanoseconds to restore each host prefix-store match evaluated at admission.", ), ( - "host_cache_estimated_prefill_ns", &self.host_prefill_ns, - HOST_TIME_BUCKETS, + "host_cache_estimated_prefill_ns", + "Estimated prefill nanoseconds for the tokens each host prefix-store match evaluated at admission covers beyond the resident GPU checkpoint.", ), - ] - .into_iter() - .enumerate() - { - text.push_str(&format!("# TYPE flare_{name} histogram\n")); - let mut count = 0; - for (counter, limit) in counters.iter().zip(limits) { - count += counter.load(Ordering::Relaxed); - let bound = if limit == u64::MAX { - "+Inf".to_owned() - } else { - limit.to_string() - }; - text.push_str(&format!("flare_{name}_bucket{{le=\"{bound}\"}} {count}\n")); - } - text.push_str(&format!("flare_{name}_count {count}\n")); - text.push_str(&format!( - "flare_{name}_sum {}\n", - self.host_cost_sums[index].load(Ordering::Relaxed) - )); + ] { + histogram.render(&mut text, name, help, &HOST_NANOSECONDS); } for (name, help, counts) in [ @@ -1570,6 +1568,11 @@ impl Metrics { "time_to_first_token_seconds", "Model-scheduler arrival to the first committed generated token, for completed requests.", ), + ( + &self.time_to_first_response, + "time_to_first_response_seconds", + "Server-side HTTP admission to the first offered answer or reasoning text.", + ), ] { histogram.render(&mut text, name, help, &REQUEST_SECONDS); } @@ -2080,9 +2083,28 @@ mod tests { }); let text = metrics.render(); assert!(text.contains("flare_snapshot_capacity 256\n")); - assert!(text.contains("flare_host_cache_missing_tokens_sum 1024\n")); - assert!(text.contains("flare_host_cache_estimated_transfer_ns_sum 1000000\n")); - assert!(text.contains("flare_host_cache_estimated_prefill_ns_sum 1000000000\n")); + for line in [ + "# HELP flare_host_cache_missing_tokens Tokens each host prefix-store match evaluated at admission covers beyond the resident GPU checkpoint.", + "flare_host_cache_missing_tokens_bucket{le=\"256\"} 0", + "flare_host_cache_missing_tokens_bucket{le=\"1024\"} 1", + "flare_host_cache_missing_tokens_bucket{le=\"+Inf\"} 1", + "flare_host_cache_missing_tokens_sum 1024", + "flare_host_cache_missing_tokens_count 1", + "flare_host_cache_estimated_transfer_ns_bucket{le=\"100000\"} 0", + "flare_host_cache_estimated_transfer_ns_bucket{le=\"1000000\"} 1", + "flare_host_cache_estimated_transfer_ns_sum 1000000", + "flare_host_cache_estimated_transfer_ns_count 1", + "flare_host_cache_estimated_prefill_ns_bucket{le=\"100000000\"} 0", + "flare_host_cache_estimated_prefill_ns_bucket{le=\"1000000000\"} 1", + "flare_host_cache_estimated_prefill_ns_bucket{le=\"100000000000\"} 1", + "flare_host_cache_estimated_prefill_ns_sum 1000000000", + "flare_host_cache_estimated_prefill_ns_count 1", + ] { + assert!(text.lines().any(|value| value == line), "{line}"); + } + // Prometheus orders the sum before the count. + let sum = text.find("flare_host_cache_missing_tokens_sum").unwrap(); + assert!(sum < text.find("flare_host_cache_missing_tokens_count").unwrap()); assert_eq!( metrics .host_lookup_outcomes diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 4051562df..49ee31b93 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -5596,7 +5596,10 @@ async fn metrics_route_serves_prometheus_or_json_without_the_api_key() { (10, 3) ); } - state.first_response.observe(std::time::Instant::now()).output(); + state + .first_response + .observe(std::time::Instant::now(), state.model.metrics_handle()) + .output(); let (_, _, body) = get("/metrics?format=json", None).await.unwrap(); let value: serde_json::Value = serde_json::from_str(&body).unwrap(); assert_eq!(value["first_response"]["samples"], 1); From 6452595ac3eb134e32d3399ff3d473316ad29f4e Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Sat, 28 Nov 2026 16:45:30 -0600 Subject: [PATCH 12/14] Exclude only tool-limit-cancelled choices from HTTP response histograms One flag, `Encoder::tool_limit_reached`, gated the HTTP response histograms for a whole response. When any choice reached the parallel-tool-call limit, the response added no `flare_request_e2e_seconds`, `flare_request_choices`, or `flare_request_max_choice_generated_tokens` observation, although the runtime counts each choice as its own request and had already counted a sibling choice that finished on its own as completed. The runtime termination of each choice is what decides whether it counts as cancelled, so the HTTP gate records that termination per choice and excludes only the cancelled choices. Only `/v1/completions` accepts more than one choice and it rejects tools, so no public request reaches a multi-choice tool-limit response today. `Encoder::finish` records whether the runtime ended each choice as `Termination::Cancelled`, before the tool-limit override of the finish reason, and `Encoder::choice_generated_tokens` returns each choice's generated-token count, or `None` for a cancelled choice. The HTTP handler passes that list to `Metrics::response_completed` and no longer keeps its own per-choice count vector or the `!count` condition, which never held because token-count requests return before the delivery stream starts. `response_completed` observes `flare_request_e2e_seconds` once when at least one choice was delivered, and per prompt observes the delivered choice count and the largest delivered generated-token count, skipping a prompt with no delivered choice. The `# HELP` text of both choice histograms and the HTTP histogram paragraph and vLLM table row in docs/api.md state the per-choice rule. Result: a response whose only choices were cancelled is not observed, as before, and a choice the runtime completed enters the response histograms even when another choice of the same response reached the tool-call limit. Evidence: a unit test drives an `Encoder` with two choices and parallel tool calls disabled through two tool calls on choice 0, finishes choice 1 at EOS and choice 0 as cancelled, asserts `[None, Some(5)]`, and asserts one e2e observation, one choice, and a largest-choice sum of 5, with no observation for an all-cancelled response. The existing HTTP tool-limit test still asserts zero e2e observations for a single cancelled choice. Build and tests: on the tree with this commit and the one that follows it, `cargo check --locked --features server` succeeds and `cargo test --locked --features runtime-core,server --lib -- server:: scheduler:: cache::` reports 816 passed, 1 failed, 11 ignored. The failure is server::protocol::decode::native_prompt_tests::messages_image_hints_end_after_expansion_for_text_and_segmented_templates, which requires FLARE_TEST_TEMPLATE_DIR and exercises no changed path. No GPU server run was performed, so a live scrape was not compared. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: enterprise/deepseek-v4.1-flash (omp agent); design-review=2e5b --- docs/api.md | 34 +++++----- helios/src/server/http.rs | 19 +++--- helios/src/server/metrics.rs | 95 ++++++++++++++++++++++++---- helios/src/server/protocol/encode.rs | 12 ++++ 4 files changed, 121 insertions(+), 39 deletions(-) diff --git a/docs/api.md b/docs/api.md index d6a33551b..d4d1e4fea 100644 --- a/docs/api.md +++ b/docs/api.md @@ -308,22 +308,22 @@ start. Host prefix-store histograms report lookup cost and retirement: `flare_host_cache_estimated_prefill_ns`, and `flare_host_cache_retirement_seconds`. -The HTTP histograms observe delivery. `flare_request_e2e_seconds` observes each -successful generation response once, from admission to the completed response; -it excludes `/v1/messages/count_tokens` and responses the runtime records as -cancelled, such as a parallel tool-limit stop. It is observed once per delivered -response, while the runtime counts one completion per model request, so a -multi-choice response adds fewer observations than completions, and a stream the -client abandons before draining adds none. For a stream it is observed when -delivery completes, which requires the client to drain the body. -`flare_time_to_first_response_seconds` counts each response that offers answer or -reasoning text, from admission to that text, once the client reads it; a stream -that offers text before it fails still records this observation. -With `flare_request_e2e_seconds`, each response also adds one observation per -prompt to `flare_request_choices`, the requested choice count `n`, and to -`flare_request_max_choice_generated_tokens`, the largest generated-token count -among that prompt's choices. Only `/v1/completions` accepts `n` above one or a -list of prompts; Flare runs each choice as its own model request. +The HTTP histograms measure response delivery time and exclude +`/v1/messages/count_tokens`. `flare_request_e2e_seconds` observes once each +successful generation response that delivers at least one choice. A stream is +observed when the client drains its body, so a stream the client abandons adds +none; a non-streaming response is observed when its body is ready, before the +client reads it. Flare runs each choice as its own model request and counts one +completion per choice, so a multi-choice response adds fewer e2e observations +than completions. Only `/v1/completions` accepts `n` above one or a list of +prompts. Per prompt, `flare_request_choices` observes the number of delivered +choices and `flare_request_max_choice_generated_tokens` the largest +generated-token count among them. A choice the runtime cancels because another +choice reached the parallel-tool-call limit is not delivered: the runtime counts +it as cancelled, and it enters neither choice histogram. +`flare_time_to_first_response_seconds` observes each response that offers answer +or reasoning text once the client reads that text, including a stream that fails +after offering it. The runtime histograms observe requests whose model generation completes successfully. `flare_request_queue_seconds` spans model-scheduler arrival to the @@ -501,7 +501,7 @@ fails. | `request_success{finished_reason}` | `stop`: `flare_requests_completed_total` − `flare_requests_output_limited_total`; `length`: `flare_requests_output_limited_total`; `abort`: `flare_requests_cancelled_total`; `error`: `flare_requests_failed_total`; `repetition`: not provided | | `admission_rejections{reason}` | `flare_admission_rejections_total{reason}`, with Flare's queue limits as reasons | | `iteration_tokens_total` | `flare_model_step_tokens` | -| `e2e_request_latency_seconds` | `flare_request_e2e_seconds`, from HTTP admission, for successful delivered responses and excluding token counting and tool-limit cancellations | +| `e2e_request_latency_seconds` | `flare_request_e2e_seconds`, from HTTP admission, for successful responses that deliver at least one choice, excluding token counting | | `time_to_first_token_seconds` | `flare_time_to_first_token_seconds`, from model-scheduler arrival; `flare_time_to_first_response_seconds` from HTTP admission to visible text, also recorded when a stream that offered text later fails | | `inter_token_latency_seconds` | `flare_inter_token_latency_seconds` | | `request_queue_time_seconds`, `request_prefill_time_seconds`, `request_decode_time_seconds`, `request_inference_time_seconds` | `flare_request_queue_seconds`, `flare_request_prefill_seconds`, `flare_request_decode_seconds`, `flare_request_inference_seconds` | diff --git a/helios/src/server/http.rs b/helios/src/server/http.rs index dacf6be5d..13c1a492e 100644 --- a/helios/src/server/http.rs +++ b/helios/src/server/http.rs @@ -404,7 +404,6 @@ pub(super) async fn generate( let mut raw_tokens = Vec::new(); let mut timestamps = Vec::new(); let mut reused_total = 0; - let mut generated = vec![0u32; size]; if streaming && protocol == Protocol::Chat { // Chat has one choice and rejects streamed prompt logprobs, so no // output queue needs draining before the first raw token is ready. @@ -527,7 +526,6 @@ pub(super) async fn generate( .. } => { reused_total += reused_prompt_tokens; - generated[index] = generated_tokens; let result = decoders[index] .finish(if encoder.tool_limit_reached { crate::output::Termination::Cancelled } else { termination }) .and_then(|events| encoder.apply(index, events)) @@ -601,15 +599,14 @@ pub(super) async fn generate( false, ); } - // One observation per successful response: a tool-limit cancellation reaches - // this point but the runtime counts it as cancelled, so it is excluded. - if !count && !encoder.tool_limit_reached { - state.model.metrics().response_completed( - admitted_at.elapsed().as_nanos() as u64, - decoded.request.choices, - &generated, - ); - } + // Choices the runtime cancelled after another choice reached the + // parallel-tool-call limit are counted as cancelled there, so they enter no + // response histogram. + state.model.metrics().response_completed( + admitted_at.elapsed().as_nanos() as u64, + decoded.request.choices, + &encoder.choice_generated_tokens(), + ); yield Delivery::Complete(response); }; if streaming { diff --git a/helios/src/server/metrics.rs b/helios/src/server/metrics.rs index 5f6b7d406..d38fead5a 100644 --- a/helios/src/server/metrics.rs +++ b/helios/src/server/metrics.rs @@ -622,16 +622,24 @@ impl Metrics { /// Records one successful HTTP generation response delivered `elapsed_ns` /// after admission. `generated` holds each choice's generated-token count in - /// response order, `choices` consecutive choices per prompt. - pub(super) fn response_completed(&self, elapsed_ns: u64, choices: usize, generated: &[u32]) { + /// response order, `choices` consecutive choices per prompt, and `None` for a + /// choice the runtime cancelled, which happens when another choice reaches the + /// parallel-tool-call limit. Cancelled choices enter neither choice histogram, + /// and a response without a delivered choice is not observed. + pub(super) fn response_completed(&self, elapsed_ns: u64, choices: usize, generated: &[Option]) { + if generated.iter().all(Option::is_none) { + return; + } self.request_e2e.observe(&REQUEST_SECONDS, elapsed_ns); for prompt in generated.chunks(choices) { + let delivered = prompt.iter().flatten(); + let Some(&max) = delivered.clone().max() else { + continue; + }; self.request_choices - .observe(&CHOICE_COUNTS, choices as u64); - self.request_max_choice_generated_tokens.observe( - &TOKEN_COUNTS, - u64::from(prompt.iter().copied().max().unwrap_or(0)), - ); + .observe(&CHOICE_COUNTS, delivered.count() as u64); + self.request_max_choice_generated_tokens + .observe(&TOKEN_COUNTS, u64::from(max)); } } @@ -1614,7 +1622,7 @@ impl Metrics { ( &self.request_max_choice_generated_tokens, "request_max_choice_generated_tokens", - "Largest generated-token count among the choices of one prompt, for successful HTTP generation responses.", + "Largest generated-token count among the delivered choices of one prompt, for successful HTTP generation responses.", ), ] { histogram.render(&mut text, name, help, &TOKEN_COUNTS); @@ -1622,7 +1630,7 @@ impl Metrics { self.request_choices.render( &mut text, "request_choices", - "Requested choices (the n parameter) per prompt, for successful HTTP generation responses.", + "Choices (the n parameter) per prompt in successful HTTP generation responses, excluding choices cancelled by the parallel-tool-call limit.", &CHOICE_COUNTS, ); self.request_preemptions.render( @@ -1979,8 +1987,8 @@ mod tests { fn response_histograms_count_choices_and_largest_choice_per_prompt() { let metrics = Metrics::new(0, 0, 0, 16); // Two prompts with two choices each, as a completions batch orders them. - metrics.response_completed(300_000_000, 2, &[3, 9, 0, 4]); - metrics.response_completed(300_000_000, 1, &[7]); + metrics.response_completed(300_000_000, 2, &[Some(3), Some(9), Some(0), Some(4)]); + metrics.response_completed(300_000_000, 1, &[Some(7)]); let text = metrics.render(); for expected in [ "flare_request_e2e_seconds_count 2", @@ -1997,6 +2005,71 @@ mod tests { } } + #[test] + fn response_histograms_exclude_choices_cancelled_by_the_tool_call_limit() { + use crate::output::{Event, Termination}; + use crate::server::inference::{Tool, ToolChoice}; + use crate::server::protocol::{Encoder, PromptUsage, Protocol}; + let tool = Tool { + name: "lookup".into(), + namespace: None, + description: String::new(), + parameters: serde_json::json!({"type":"object"}), + declared_parameters: true, + strict: false, + custom: false, + grammar: None, + }; + // One prompt with two choices and parallel tool calls disabled. + let mut encoder = Encoder::new( + Protocol::Completions, + "test".into(), + "model".into(), + 1, + 2, + vec![PromptUsage { tokens: 17, image_tokens: 0 }], + vec![tool], + ToolChoice::Auto, + false, + true, + serde_json::json!({}), + ); + let call = |id: &str| { + [ + Event::ToolBegin { index: 0, name: "lookup".into(), id: Some(id.into()) }, + Event::ToolArguments { index: 0, text: "{}".into() }, + Event::ToolEnd { index: 0 }, + ] + }; + encoder + .apply(0, [call("call_1"), call("call_2")].concat()) + .unwrap(); + assert!(encoder.tool_limit_reached); + // The runtime completes choice 1 at EOS and cancels choice 0, whose second + // tool call reached the limit. + encoder.finish(1, Termination::Eos, 5, 0, None).unwrap(); + encoder.finish(0, Termination::Cancelled, 9, 0, None).unwrap(); + let generated = encoder.choice_generated_tokens(); + assert_eq!(generated, [None, Some(5)]); + let metrics = Metrics::new(0, 0, 0, 16); + metrics.response_completed(300_000_000, 2, &generated); + // A response whose only choice was cancelled delivers nothing. + metrics.response_completed(300_000_000, 1, &[None]); + let text = metrics.render(); + for expected in [ + "flare_request_e2e_seconds_count 1", + "flare_request_choices_bucket{le=\"1\"} 1", + "flare_request_choices_count 1", + "flare_request_max_choice_generated_tokens_count 1", + "flare_request_max_choice_generated_tokens_sum 5", + ] { + assert!( + text.contains(&format!("\n{expected}\n")), + "missing {expected}" + ); + } + } + #[test] fn checkpoint_metrics_report_capture_roles_rejection_reasons_work_and_reservations() { let metrics = Metrics::new(0, 0, 0, 16); diff --git a/helios/src/server/protocol/encode.rs b/helios/src/server/protocol/encode.rs index 2d1ddabcf..55754e4db 100644 --- a/helios/src/server/protocol/encode.rs +++ b/helios/src/server/protocol/encode.rs @@ -57,6 +57,8 @@ struct Usage { generated: u32, cached: u64, reasoning: u32, + /// The runtime ended the choice's generation as cancelled. + cancelled: bool, } #[derive(Clone, Copy, Default)] pub(crate) struct PromptUsage { @@ -595,6 +597,7 @@ impl Encoder { cached: u64, stop: Option, ) -> Result> { + let cancelled = cause == Termination::Cancelled; let cause = if self.tool_limit_reached { Termination::Cancelled } else { cause }; if let Some((_, name, _, _)) = self.pending_strict_calls[index].take() && cause == Termination::Eos @@ -631,6 +634,7 @@ impl Encoder { generated, cached, reasoning: self.usage[index].reasoning, + cancelled, }; self.stop = stop; if matches!(self.protocol, Protocol::Chat | Protocol::Completions) { @@ -679,6 +683,14 @@ impl Encoder { } Ok(frames) } + /// Generated-token count of each finished choice in response order, `None` + /// for a choice whose generation the runtime ended as cancelled. + pub fn choice_generated_tokens(&self) -> Vec> { + self.usage + .iter() + .map(|usage| (!usage.cancelled).then_some(usage.generated)) + .collect() + } pub fn usage_value(&self) -> Value { let prompt_tokens: usize = self.prompts.iter().map(|p| p.tokens).sum(); let image_tokens: usize = self.prompts.iter().map(|p| p.image_tokens).sum(); From ed663005d64063fd6d8a33c412da474c9a6d6551 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Sat, 28 Nov 2026 16:45:47 -0600 Subject: [PATCH 13/14] Skip idle model steps, bind admission labels to their enum, and trim metric docs Four review findings remained in the metrics and their documentation. `flare_model_step_tokens` observed a 0-token sample for a step in which every lane failed, lowering the mean without measuring work. The `flare_admission_rejections_total` labels were a literal array that had to track the declaration order of `AdmissionLimit` with nothing linking them. One test checked a full completion and then a zero-token completion on the same `Metrics`, so the zero-token assertions restated the first request's counts. docs/api.md restated `# HELP` text in prose, omitted that decode time includes a preemption stall and that the first model step of a request can be an initialization step, and named vLLM's metric list without a source or date. `Metrics::model_step` skips a step with zero tokens, which is a step in which no lane made progress. `AdmissionLimit` has an `ALL` array, which also sizes the counter array, and an exhaustive `reason` match that the render loop uses for labels. The zero-token completion has its own test on a fresh `Metrics` that asserts every interval histogram is empty and every token-count histogram holds one observation. docs/api.md keeps the population rules (which requests enter, the cancelled and failed exclusion, the two-token rule, the zero-token rule, and the tool-limit rule from the HTTP histogram paragraph) and drops the interval definitions the `# HELP` lines already carry. It states that decode time, time per output token, and the spanning inter-token interval include the wait for readmission; that the first model step can be an initialization or vision step, so prefill time includes initialization; that a step without progress is not observed; and that the vLLM table follows https://docs.vllm.ai/en/latest/usage/metrics/ as checked on 2026-11-27. Result: the model-step histogram counts only steps that did work, admission reason labels are bound to their enum variants, the zero-token population is tested in isolation, and the documentation describes each population without duplicating the scrape. Metric names, labels, bucket bounds, and the vLLM table rows are unchanged. Evidence: the scheduler metrics test calls `model_step(0)` beside the two nonzero steps and asserts `flare_model_step_tokens_count 2`, and still asserts the three admission reason labels and their counts. The zero-token test asserts zero counts for the queue, prefill, inference, time-to-first-token, decode, time-per-output-token, inter-token, and max-token histograms, and one observation in the prompt, computed-prompt, generated, and preemption histograms. Build and tests: on this commit's tree, `cargo check --locked --features server` succeeds and `cargo test --locked --features runtime-core,server --lib -- server:: scheduler:: cache::` reports 816 passed, 1 failed, 11 ignored. The failure is server::protocol::decode::native_prompt_tests::messages_image_hints_end_after_expansion_for_text_and_segmented_templates, which requires FLARE_TEST_TEMPLATE_DIR and exercises no changed path. No GPU server run was performed, so a live scrape was not compared. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: enterprise/deepseek-v4.1-flash (omp agent); design-review=2e5b --- docs/api.md | 79 ++++++++++++++++-------------------- helios/src/server/metrics.rs | 63 +++++++++++++++++++--------- 2 files changed, 77 insertions(+), 65 deletions(-) diff --git a/docs/api.md b/docs/api.md index d4d1e4fea..e034f2440 100644 --- a/docs/api.md +++ b/docs/api.md @@ -302,8 +302,9 @@ selects text regardless of `Accept`, and any other `format` value returns HTTP as zero, and `flare_helios::server::view` holds the rate history and plots of the serving terminal dashboard. -Histograms appear in the Prometheus format only and accumulate since server -start. Host prefix-store histograms report lookup cost and retirement: +Histograms appear in the Prometheus format only, accumulate since server start, +and define each interval or count in their `# HELP` text. Host prefix-store +histograms report lookup cost and retirement: `flare_host_cache_missing_tokens`, `flare_host_cache_estimated_transfer_ns`, `flare_host_cache_estimated_prefill_ns`, and `flare_host_cache_retirement_seconds`. @@ -325,43 +326,27 @@ it as cancelled, and it enters neither choice histogram. or reasoning text once the client reads that text, including a stream that fails after offering it. -The runtime histograms observe requests whose model generation completes -successfully. `flare_request_queue_seconds` spans model-scheduler arrival to the -first model step that includes the request, which can be a vision step; it is -recorded only if the request reached such a step. -`flare_request_prefill_seconds` spans that step to the request's first committed -generated token, and `flare_request_inference_seconds` spans it to the last -committed generated token. A completion that committed no generated token still -increments `flare_requests_completed_total` and enters the token histograms -below, but records no time-to-first-token, prefill, or inference observation. -`flare_time_to_first_token_seconds` spans model-scheduler arrival to the first -committed generated token; unlike `flare_time_to_first_response_seconds`, it -excludes HTTP preparation and counts tokens that produce no visible text. -`flare_request_decode_seconds` and `flare_time_per_output_token_seconds` are -recorded only for requests with at least two generated tokens. -`flare_inter_token_latency_seconds` observes, for every model step after the -first that commits generated tokens for a request, the time since the previous -such step: a speculative round committing several tokens is one observation, and -the interval that spans a preemption includes the wait for readmission. A -request's intervals enter the histogram when it completes. - -The runtime token histograms count per completed request. -`flare_request_prompt_tokens` counts prompt tokens including tokens reused from -the prefix cache, and `flare_request_prefill_computed_tokens` subtracts the -tokens that GPU or host prefix reuse supplied at the request's first admission; -recomputation after a preemption is not included. -`flare_request_generated_tokens` counts committed generated tokens, including -EOS, tokens withheld by text stops, and a forced reasoning close. -`flare_request_max_tokens` records the output limit at first admission: the -client's `max_tokens` or `max_completion_tokens`, else the server default capped -by the remaining context, including tokens a reasoning budget defers. -Prompt-scoring requests with a zero limit are not observed. -`flare_request_preemptions` counts how many times each request was preempted and -readmitted; its buckets are vLLM's preemption bounds with an added zero bound. -Cancelled and failed requests contribute no observation to the runtime histograms -here. Apart from counters, the only series that can observe them is -`flare_time_to_first_response_seconds`, and only when text was offered before the -failure. +The runtime histograms observe only requests whose model generation completes +successfully. Cancelled and failed requests enter none of them; apart from +counters, the only series that can observe such a request is +`flare_time_to_first_response_seconds`, and only when text was offered before +the failure. The first model step that includes a request, which ends the queue +interval and starts the prefill and inference intervals, can be an +initialization or vision step, so `flare_request_prefill_seconds` includes +initialization time; a request that reached no such step records no queue +observation. A completion that committed no generated token increments +`flare_requests_completed_total` and enters only the token-count and preemption +histograms. `flare_request_decode_seconds` and +`flare_time_per_output_token_seconds` require at least two generated tokens. +The decode time and time per output token of a preempted request, and its +inter-token interval that spans the preemption, include the wait for readmission. +A speculative round committing several tokens is one inter-token observation, +and a request's intervals enter the histogram when it completes. +`flare_request_prefill_computed_tokens` excludes recomputation after a +preemption, and `flare_request_generated_tokens` includes a forced reasoning +close. `flare_request_max_tokens` includes tokens a reasoning budget defers and +omits prompt-scoring requests with a zero limit. `flare_request_preemptions` uses +vLLM's preemption bounds with an added zero bound. `flare_requests_output_limited_total` counts completed requests that stopped at their output token limit; the rest of `flare_requests_completed_total` stopped at @@ -382,8 +367,10 @@ capacity or the channel into the model worker is full. Paused admission and an unavailable runtime return HTTP 503 and are not counted. `flare_model_step_tokens` observes, for every completed prefill, resume, decode, speculative, or mixed graph, the prompt tokens it computed plus the generated -tokens it committed; rejected draft positions and padding are excluded, and -initialization, restore, vision, and snapshot graphs are not observed. +tokens it committed; rejected draft positions and padding are excluded, +initialization, restore, vision, and snapshot graphs are not observed, and a step +in which no lane made progress, such as one whose every lane failed, is not +observed. The fields in the table are integers except `learned_drafter`. Totals count from server start; `active`, `pending`, the page fields, and the host record fields are @@ -479,10 +466,12 @@ failed lanes, and terminal rounds without progress do not enter this average. Flare exports no `vllm:` names. The table gives the Flare series that measure each metric in vLLM's production metric list, named here without the `vllm:` -prefix, and the metrics Flare does not provide. Flare's request histograms cover -successful completions, where vLLM's also observe failed and cancelled requests; -only `flare_time_to_first_response_seconds` can observe a response that later -fails. +prefix, and the metrics Flare does not provide. The list is the +[vLLM metrics documentation](https://docs.vllm.ai/en/latest/usage/metrics/) as +checked on 2026-11-27; later vLLM releases can add or rename metrics. Flare's +request histograms cover successful completions, where vLLM's also observe failed +and cancelled requests; only `flare_time_to_first_response_seconds` can observe a +response that later fails. | vLLM metric | Flare series | | --- | --- | diff --git a/helios/src/server/metrics.rs b/helios/src/server/metrics.rs index d38fead5a..ded7eb128 100644 --- a/helios/src/server/metrics.rs +++ b/helios/src/server/metrics.rs @@ -401,6 +401,18 @@ pub(super) enum AdmissionLimit { RequestQueue, } +impl AdmissionLimit { + const ALL: [Self; 3] = [Self::HttpSlots, Self::GenerationCapacity, Self::RequestQueue]; + + fn reason(self) -> &'static str { + match self { + Self::HttpSlots => "http_slots", + Self::GenerationCapacity => "generation_capacity", + Self::RequestQueue => "request_queue", + } + } +} + #[derive(Default)] pub(super) struct Metrics { pub scheduler_trace: scheduler::SchedulerMetrics, @@ -437,7 +449,7 @@ pub(super) struct Metrics { request_preemptions: Histogram<9>, model_step_tokens: Histogram<21>, output_limited: AtomicU64, - admission_rejections: [AtomicU64; 3], + admission_rejections: [AtomicU64; AdmissionLimit::ALL.len()], pub reasoning_budget_cuts: AtomicU64, pub cancelled: AtomicU64, pub failed: AtomicU64, @@ -709,9 +721,12 @@ impl Metrics { } /// Records one completed text-model step that computed `tokens` prompt tokens - /// and committed generated tokens in total. + /// and committed generated tokens in total. A step in which no lane made + /// progress, such as one whose every lane failed, is not observed. pub(super) fn model_step(&self, tokens: u64) { - self.model_step_tokens.observe(&TOKEN_COUNTS, tokens); + if tokens != 0 { + self.model_step_tokens.observe(&TOKEN_COUNTS, tokens); + } } pub(super) fn admission_rejected(&self, limit: AdmissionLimit) { @@ -1649,10 +1664,9 @@ impl Metrics { text, "# HELP flare_admission_rejections_total Generation requests rejected because a queue limit was full.\n# TYPE flare_admission_rejections_total counter" ); - for (reason, count) in ["http_slots", "generation_capacity", "request_queue"] - .into_iter() - .zip(&self.admission_rejections) - { + for limit in AdmissionLimit::ALL { + let reason = limit.reason(); + let count = &self.admission_rejections[limit as usize]; let _ = writeln!( text, "flare_admission_rejections_total{{reason=\"{reason}\"}} {}", @@ -1948,8 +1962,12 @@ mod tests { "missing {expected}" ); } - // A zero-token completion reaches no model step and commits no token, so it - // adds only token-count and preemption observations. + } + + #[test] + fn zero_token_completion_enters_only_token_count_and_preemption_histograms() { + let metrics = Metrics::new(0, 0, 0, 16); + // A zero-token completion reaches no model step and commits no token. metrics.request_completed( 1_000_000_000, &RequestRecord::default(), @@ -1962,19 +1980,21 @@ mod tests { ); let text = metrics.render(); for expected in [ - "flare_request_queue_seconds_count 1", - "flare_request_prefill_seconds_count 1", - "flare_request_inference_seconds_count 1", - "flare_time_to_first_token_seconds_count 1", - "flare_request_decode_seconds_count 1", - "flare_inter_token_latency_seconds_count 2", - "flare_request_max_tokens_count 1", - "flare_request_prompt_tokens_count 2", - "flare_request_prefill_computed_tokens_sum 5000", + "flare_request_queue_seconds_count 0", + "flare_request_prefill_seconds_count 0", + "flare_request_inference_seconds_count 0", + "flare_time_to_first_token_seconds_count 0", + "flare_request_decode_seconds_count 0", + "flare_time_per_output_token_seconds_count 0", + "flare_inter_token_latency_seconds_count 0", + "flare_request_max_tokens_count 0", + "flare_request_prompt_tokens_count 1", + "flare_request_prefill_computed_tokens_sum 3000", "flare_request_generated_tokens_bucket{le=\"1\"} 1", + "flare_request_generated_tokens_sum 0", "flare_request_preemptions_bucket{le=\"0\"} 1", - "flare_requests_completed_total 2", - "flare_requests_output_limited_total 1", + "flare_requests_completed_total 1", + "flare_requests_output_limited_total 0", ] { assert!( text.contains(&format!("\n{expected}\n")), @@ -2389,6 +2409,8 @@ mod tests { metrics.parked.store(2, Ordering::Relaxed); metrics.model_step(3); metrics.model_step(20); + // A step in which no lane made progress is not observed. + metrics.model_step(0); for limit in [ AdmissionLimit::HttpSlots, AdmissionLimit::HttpSlots, @@ -2519,6 +2541,7 @@ mod tests { for line in [ "flare_model_step_tokens_bucket{le=\"8\"} 1", "flare_model_step_tokens_bucket{le=\"32\"} 2", + "flare_model_step_tokens_count 2", "flare_model_step_tokens_sum 23", "flare_admission_rejections_total{reason=\"http_slots\"} 2", "flare_admission_rejections_total{reason=\"generation_capacity\"} 0", From 4fbb9d23d58736f065a77215b0697db00242b373 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Sun, 29 Nov 2026 17:26:49 -0600 Subject: [PATCH 14/14] Keep requeued waits in queue time and drop synthetic histogram samples `flare_request_queue_seconds` must end at the model step that schedules the request, not at a step that was discarded. When a late host-cache answer or a failed restore requeues a request that has generated no token, the discarded Init or Restore step had already stamped `first_scheduled_ns`, so the park and host-restore wait landed in `flare_request_prefill_seconds` and `flare_request_inference_seconds`. A host-forced reasoning close adds a generated token without running a model step, so a generated-token count above one also produced zero-second samples in `flare_request_decode_seconds` and `flare_time_per_output_token_seconds`. `RequestRecord` is worker-thread-owned until completion yet embedded an atomic `Histogram<19>`, paying atomic read-modify-writes on every committing step. docs/api.md also carried a dated table of vLLM metric names, which drifts independently of Flare's own documentation. The scheduled instant now clears on requeue, decode requires a committing step after the first token, per-request intervals use plain storage merged at completion, and the API documentation keeps only Flare's series. `Worker::requeue` sets `RequestRecord::times.first_scheduled_ns` to `None`; requeue runs only before token generation, so the next executed step stamps again and the intervening wait is queue time. `Metrics::request_completed` observes decode and time per output token only when `last_token_ns` is later than `first_token_ns`. `RequestRecord` holds `InterTokenIntervals`, a `[u32; 19]` bucket-count array and a `u64` nanosecond sum observed without atomics; `Histogram::absorb` merges it into `flare_inter_token_latency_seconds`. docs/api.md drops the vLLM correspondence section and table, describes a choice stopped at the `parallel_tool_calls: false` tool limit including a choice whose generation completed naturally before delivery stopped, lists the routes whose HTTP 429 counts as reason `http_slots`, states the requeue and decode rules, and updates the histogram `# HELP` lines that described a two-token threshold. Tests cover a requeued request whose queue observation spans the park and readmission, a forced reasoning close without a later committing step, and per-request bucket absorption against direct observation. Queue, prefill, and inference intervals now separate waiting from work across a requeue; decode and time per output token no longer gain zero-second samples when no decode step ran; the per-request interval store drops from a 160-byte atomic histogram to a plain bucket array and sum, removing atomic read-modify-writes from the committing path; and the API documentation describes only Flare's series. Focused release tests passed: `server::runtime::phase_tests::requeued_request_reports_queue_time_through_its_readmission`, `server::runtime::phase_tests::a_forced_reasoning_close_without_a_later_step_records_no_decode`, `server::metrics::tests::a_token_without_a_following_committing_step_records_no_decode`, and `server::metrics::tests::per_request_inter_token_buckets_match_direct_observation` (one test passed in each run). `cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --target-dir ~/tmp/mc6/548-target` reported `1731 passed; 17 failed; 46 ignored` in 12.45 s (2 m 48 s wall). All 17 failures are environmental and reproduce without these changes: 11 `engram` tests fail with `register Engram staging: Cannot allocate memory (os error 12)` because io_uring buffer registration exceeds the host's 8 MiB `RLIMIT_MEMLOCK` (`engram::tests::deferred_commit_populates_output_before_cache_insertion` fails the same way on upstream/main c146d7b), and 6 frontend tests require `FLARE_TEST_TEMPLATE_DIR` from `tests/frontend/prepare_templates.py`, whose pinned repository is gated (`frontend::templates::tests::compatibility_requires_exact_legacy_bytes` fails the same way on upstream/main). `python3 verification/helios-lifecycle/check.py --tlc-jar ~/tmp/tla/tla2tools.jar --target-dir ~/tmp/mc6/548-target -j 8` exited 0 in 4 m 30 s. No GPU server run or live scrape was compared. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: enterprise/deepseek-v4.1-flash (omp agent); design-review=2e5b --- docs/api.md | 86 +++++---------- helios/src/server/metrics.rs | 130 +++++++++++++++++++---- helios/src/server/runtime.rs | 3 + helios/src/server/runtime/phase_tests.rs | 119 +++++++++++++++++++++ 4 files changed, 260 insertions(+), 78 deletions(-) diff --git a/docs/api.md b/docs/api.md index e034f2440..f34405677 100644 --- a/docs/api.md +++ b/docs/api.md @@ -319,9 +319,10 @@ completion per choice, so a multi-choice response adds fewer e2e observations than completions. Only `/v1/completions` accepts `n` above one or a list of prompts. Per prompt, `flare_request_choices` observes the number of delivered choices and `flare_request_max_choice_generated_tokens` the largest -generated-token count among them. A choice the runtime cancels because another -choice reached the parallel-tool-call limit is not delivered: the runtime counts -it as cancelled, and it enters neither choice histogram. +generated-token count among them. A choice stopped at the +`parallel_tool_calls: false` tool limit is not delivered, including a choice +whose generation completed naturally before the limit stopped delivery: the +encoder counts it as cancelled, and it enters neither choice histogram. `flare_time_to_first_response_seconds` observes each response that offers answer or reasoning text once the client reads that text, including a stream that fails after offering it. @@ -330,14 +331,21 @@ The runtime histograms observe only requests whose model generation completes successfully. Cancelled and failed requests enter none of them; apart from counters, the only series that can observe such a request is `flare_time_to_first_response_seconds`, and only when text was offered before -the failure. The first model step that includes a request, which ends the queue -interval and starts the prefill and inference intervals, can be an -initialization or vision step, so `flare_request_prefill_seconds` includes -initialization time; a request that reached no such step records no queue -observation. A completion that committed no generated token increments +the failure. The first model step that includes a request ends the queue interval +and starts the prefill and inference intervals; it can be an initialization, +restore, or vision step, so `flare_request_prefill_seconds` includes +cache-initialization and host-restore time. A request that reached no such step +records no queue observation. A request requeued before it generated a token +clears that instant: the wait through its park and readmission counts as queue +time, and the next executing step stamps the intervals again. A late host-cache +answer that requeues a request before its initialization or restore step +therefore counts the wait for the restore as queue time rather than prefill +time. A completion that committed no generated token increments `flare_requests_completed_total` and enters only the token-count and preemption -histograms. `flare_request_decode_seconds` and -`flare_time_per_output_token_seconds` require at least two generated tokens. +histograms. +`flare_request_decode_seconds` and `flare_time_per_output_token_seconds` require +a committing step after the first token; a token that only a forced reasoning +close added, without such a step, records neither. The decode time and time per output token of a preempted request, and its inter-token interval that spans the preemption, include the wait for readmission. A speculative round committing several tokens is one inter-token observation, @@ -360,11 +368,15 @@ waiting there for readmission after a preemption, a reasoning budget cut, or a host-store restore that failed or was retried; neither includes admitted requests waiting for a host restore, which `flare_host_cache_inbound_waiting` counts among `flare_active_requests`. `flare_admission_rejections_total{reason}` -counts generation requests refused because a queue limit was full: `http_slots` -when the HTTP admission slots, one per generated choice, are all reserved (HTTP -429), and `generation_capacity` or `request_queue` when the runtime's generation -capacity or the channel into the model worker is full. Paused admission and an -unavailable runtime return HTTP 503 and are not counted. +counts HTTP requests refused because a queue limit was full. `http_slots` +counts requests refused with HTTP 429 because the HTTP admission slots, one per +generated choice, are all reserved; the admission middleware wraps +`/v1/chat/completions`, `/v1/completions`, `/v1/messages`, +`/v1/messages/count_tokens`, `/v1/responses`, `/v1/systemone`, and +`/v1/decisions`, so a 429 from any of those routes counts. +`generation_capacity` and `request_queue` count generation requests when the +runtime's generation capacity or the channel into the model worker is full. +Paused admission and an unavailable runtime return HTTP 503 and are not counted. `flare_model_step_tokens` observes, for every completed prefill, resume, decode, speculative, or mixed graph, the prompt tokens it computed plus the generated tokens it committed; rejected draft positions and padding are excluded, @@ -462,50 +474,6 @@ capacity. For packed speculation, completion records report the prefixes allocat on the GPU before target verification. Prefill, resume sampling, inactive padding, failed lanes, and terminal rounds without progress do not enter this average. -### Correspondence with vLLM metrics - -Flare exports no `vllm:` names. The table gives the Flare series that measure -each metric in vLLM's production metric list, named here without the `vllm:` -prefix, and the metrics Flare does not provide. The list is the -[vLLM metrics documentation](https://docs.vllm.ai/en/latest/usage/metrics/) as -checked on 2026-11-27; later vLLM releases can add or rename metrics. Flare's -request histograms cover successful completions, where vLLM's also observe failed -and cancelled requests; only `flare_time_to_first_response_seconds` can observe a -response that later fails. - -| vLLM metric | Flare series | -| --- | --- | -| `num_requests_running` | `flare_active_requests`, which includes admitted requests waiting for a host restore (`flare_host_cache_inbound_waiting`) | -| `num_requests_waiting` | `flare_pending_requests` + `flare_parked_requests` | -| `num_requests_waiting_by_reason` | No capacity or deferred split; `flare_pending_requests` (first admission) and `flare_parked_requests` (readmission) | -| `num_requests_kv_fetch_by_stage` | `flare_host_cache_inbound_waiting` and `flare_host_cache_inbound_in_flight` | -| `kv_cache_usage_perc` | Not provided as one ratio; `flare_free_kv_pages`, `flare_cached_kv_pages`, and `flare_total_kv_pages` bound it | -| `prompt_tokens`, `prompt_tokens_by_source` | `flare_prefill_tokens_total` (computed, including recomputation after preemption), `flare_cache_reused_tokens_total` (GPU), `flare_host_cache_reused_tokens_total` (host) | -| `prompt_tokens_cached`, `prompt_tokens_cached_by_source` | `flare_cache_reused_tokens_total` (device) + `flare_host_cache_reused_tokens_total` (host DRAM, disk, or shared pool) | -| `prefix_cache_queries`, `prefix_cache_hits` | `flare_cache_lookup_tokens_total`, `flare_cache_reused_tokens_total`; both include readmissions | -| `external_prefix_cache_queries`, `external_prefix_cache_hits` | `flare_host_cache_lookups_total` (lookups, not tokens), `flare_host_cache_reused_tokens_total` | -| `mm_cache_queries`, `mm_cache_hits` | `flare_input_cache_payload_hits_total` + `flare_input_cache_payload_misses_total`, `flare_input_cache_payload_hits_total` | -| `generation_tokens` | `flare_generated_tokens_total` | -| `num_preemptions` | `flare_preemptions_total` | -| `request_success{finished_reason}` | `stop`: `flare_requests_completed_total` − `flare_requests_output_limited_total`; `length`: `flare_requests_output_limited_total`; `abort`: `flare_requests_cancelled_total`; `error`: `flare_requests_failed_total`; `repetition`: not provided | -| `admission_rejections{reason}` | `flare_admission_rejections_total{reason}`, with Flare's queue limits as reasons | -| `iteration_tokens_total` | `flare_model_step_tokens` | -| `e2e_request_latency_seconds` | `flare_request_e2e_seconds`, from HTTP admission, for successful responses that deliver at least one choice, excluding token counting | -| `time_to_first_token_seconds` | `flare_time_to_first_token_seconds`, from model-scheduler arrival; `flare_time_to_first_response_seconds` from HTTP admission to visible text, also recorded when a stream that offered text later fails | -| `inter_token_latency_seconds` | `flare_inter_token_latency_seconds` | -| `request_queue_time_seconds`, `request_prefill_time_seconds`, `request_decode_time_seconds`, `request_inference_time_seconds` | `flare_request_queue_seconds`, `flare_request_prefill_seconds`, `flare_request_decode_seconds`, `flare_request_inference_seconds` | -| `request_time_per_output_token_seconds` | `flare_time_per_output_token_seconds` | -| `request_prompt_tokens`, `request_generation_tokens`, `request_prefill_kv_computed_tokens` | `flare_request_prompt_tokens`, `flare_request_generated_tokens`, `flare_request_prefill_computed_tokens` | -| `request_params_max_tokens`, `request_params_n`, `request_max_num_generation_tokens` | `flare_request_max_tokens`, `flare_request_choices`, `flare_request_max_choice_generated_tokens` | -| `request_num_preemptions` | `flare_request_preemptions` | -| `spec_decode_num_drafts`, `spec_decode_num_draft_tokens`, `spec_decode_num_accepted_tokens` | `flare_draft_request_rounds_total`, `flare_verification_draft_tokens_total`, `flare_accepted_draft_tokens_total` | -| `spec_decode_num_verified_tokens_per_pos`, `spec_decode_num_accepted_tokens_per_pos`, `spec_decode_num_verified_tokens` | `flare_speculative_drafts_total{depth,source,outcome}` with `outcome` `offered` or `accepted`, summed over `source` (and over `depth` for the total) | -| `corrupted_requests` | Not provided: Flare does not inspect logits for NaN values | -| `kv_block_lifetime_seconds`, `kv_block_idle_before_evict_seconds`, `kv_block_reuse_gap_seconds` | Not provided: Flare does not sample KV page residency | -| `estimated_flops_per_gpu_total`, `estimated_read_bytes_per_gpu_total`, `estimated_write_bytes_per_gpu_total` | Not provided; `flare_decode_weight_bytes` gives the weight bytes one decode step reads per request | -| `lora_requests_info`, `watermark_requests`, `engine_sleep_state` | Not provided: Flare has no LoRA adapters, output watermarking, or sleep mode | -| KV connector metrics (`nixl_*`, `hisparse_*`, `simple_kv_offload_*`) | Not provided: Flare has no KV connectors; `flare_host_cache_*` series report its host prefix store | - ## Conversation and tool semantics The neutral request representation in `helios/src/server/inference.rs` separates diff --git a/helios/src/server/metrics.rs b/helios/src/server/metrics.rs index ded7eb128..1e5c9aabe 100644 --- a/helios/src/server/metrics.rs +++ b/helios/src/server/metrics.rs @@ -299,16 +299,15 @@ impl Histogram { self.sum.fetch_add(value, Ordering::Relaxed); } - /// Adds the observations of `other`, which shares this histogram's buckets. - fn absorb(&self, other: &Self) { - for (count, added) in self.counts.iter().zip(&other.counts) { - let added = added.load(Ordering::Relaxed); - if added != 0 { - count.fetch_add(added, Ordering::Relaxed); + /// Adds a plain store of bucket counts and their sum, which shares this + /// histogram's buckets. + fn absorb(&self, counts: &[u32; N], sum: u64) { + for (count, added) in self.counts.iter().zip(counts) { + if *added != 0 { + count.fetch_add(u64::from(*added), Ordering::Relaxed); } } - self.sum - .fetch_add(other.sum.load(Ordering::Relaxed), Ordering::Relaxed); + self.sum.fetch_add(sum, Ordering::Relaxed); } pub(super) fn render(&self, text: &mut String, name: &str, help: &str, buckets: &Buckets) { @@ -346,6 +345,28 @@ pub(super) struct RequestTimes { pub last_token_ns: u64, } +/// Inter-token intervals accumulated for one request, in bucket counts and the +/// summed interval in nanoseconds. The worker thread owns the record until the +/// request completes, so this store uses no atomics; [`Metrics::request_completed`] +/// merges it into `inter_token_latency` through the same buckets. +#[derive(Default)] +struct InterTokenIntervals { + counts: [u32; 19], + sum: u64, +} + +impl InterTokenIntervals { + fn observe(&mut self, value: u64) { + let index = TOKEN_SECONDS + .bounds + .iter() + .position(|bound| value <= *bound) + .unwrap_or(self.counts.len() - 1); + self.counts[index] += 1; + self.sum += value; + } +} + /// Values a request accumulates for the completion histograms. The record moves /// with the request through preemption and readmission and is observed once, by /// [`Metrics::request_completed`], only if the request completes successfully. @@ -359,7 +380,7 @@ pub(super) struct RequestRecord { pub preemptions: u32, /// Intervals between successive model steps that committed generated tokens /// for the request, merged into the server histogram on completion. - inter_token: Histogram<19>, + inter_token: InterTokenIntervals, } impl RequestRecord { @@ -368,10 +389,8 @@ impl RequestRecord { /// one inter-token interval, however many tokens the step committed. pub(super) fn tokens_committed(&mut self, now_ns: u64) { if self.times.first_token_ns.is_some() { - self.inter_token.observe( - &TOKEN_SECONDS, - now_ns.saturating_sub(self.times.last_token_ns), - ); + self.inter_token + .observe(now_ns.saturating_sub(self.times.last_token_ns)); } else { self.times.first_token_ns = Some(now_ns); } @@ -603,7 +622,8 @@ impl Metrics { } self.request_preemptions .observe(&PREEMPTION_COUNTS, u64::from(record.preemptions)); - self.inter_token_latency.absorb(&record.inter_token); + self.inter_token_latency + .absorb(&record.inter_token.counts, record.inter_token.sum); if let Some(first) = times.first_token_ns { self.time_to_first_token .observe(&REQUEST_SECONDS, first.saturating_sub(arrival_ns)); @@ -620,10 +640,12 @@ impl Metrics { ); } } + // Decode time covers steps after the first committing one; a token that + // only a forced reasoning close added has no step and no decode interval. if let Some(first) = times.first_token_ns - && generated_tokens > 1 + && times.last_token_ns > first { - let decode = times.last_token_ns.saturating_sub(first); + let decode = times.last_token_ns - first; self.request_decode.observe(&REQUEST_SECONDS, decode); self.time_per_output_token.observe( &TOKEN_SECONDS, @@ -1569,7 +1591,7 @@ impl Metrics { ( &self.request_queue, "request_queue_seconds", - "Model-scheduler arrival to the first model step that includes the request, for completed requests.", + "Model-scheduler arrival to the first model step that includes the request after any requeue before token generation, for completed requests.", ), ( &self.request_prefill, @@ -1579,7 +1601,7 @@ impl Metrics { ( &self.request_decode, "request_decode_seconds", - "First to last committed generated token, for completed requests with at least two generated tokens.", + "First to last committed generated token, for completed requests whose first token was followed by another committing step.", ), ( &self.request_inference, @@ -1603,7 +1625,7 @@ impl Metrics { ( &self.time_per_output_token, "time_per_output_token_seconds", - "Decode time divided by generated tokens after the first, for completed requests with at least two generated tokens.", + "Decode time divided by generated tokens after the first, for completed requests whose first token was followed by another committing step.", ), ( &self.inter_token_latency, @@ -2003,6 +2025,76 @@ mod tests { } } + #[test] + fn a_token_without_a_following_committing_step_records_no_decode() { + let metrics = Metrics::new(0, 0, 0, 16); + let mut record = RequestRecord::default(); + record.times.first_scheduled_ns = Some(1_000_000_000); + // One model step commits the first token; a host-forced reasoning close + // then counts a second token without running a step. + record.tokens_committed(1_500_000_000); + metrics.request_completed( + 900_000_000, + &record, + CompletedRequest { + prompt_tokens: 10, + reused_prompt_tokens: 0, + generated_tokens: 2, + output_limit: false, + }, + ); + let text = metrics.render(); + for expected in [ + "flare_request_decode_seconds_count 0", + "flare_time_per_output_token_seconds_count 0", + "flare_inter_token_latency_seconds_count 0", + "flare_time_to_first_token_seconds_count 1", + "flare_request_inference_seconds_count 1", + ] { + assert!( + text.contains(&format!("\n{expected}\n")), + "missing {expected}" + ); + } + } + + #[test] + fn per_request_inter_token_buckets_match_direct_observation() { + let intervals = [750_000u64, 3_000_000, 60_000_000, 900_000_000, 5_000_000_000]; + let metrics = Metrics::new(0, 0, 0, 16); + let mut record = RequestRecord::default(); + let mut now = 1_000_000_000u64; + record.tokens_committed(now); + for interval in intervals { + now += interval; + record.tokens_committed(now); + } + metrics.request_completed( + 0, + &record, + CompletedRequest { + prompt_tokens: 1, + reused_prompt_tokens: 0, + generated_tokens: intervals.len() as u32 + 1, + output_limit: false, + }, + ); + let direct = Metrics::new(0, 0, 0, 16); + for interval in intervals { + direct.inter_token_latency.observe(&TOKEN_SECONDS, interval); + } + let section = |text: &str| { + text.lines() + .filter(|line| line.contains("flare_inter_token_latency_seconds")) + .map(str::to_owned) + .collect::>() + }; + let absorbed_text = metrics.render(); + assert_eq!(section(&absorbed_text), section(&direct.render())); + assert!(absorbed_text.contains("flare_inter_token_latency_seconds_count 5")); + assert!(absorbed_text.contains("flare_inter_token_latency_seconds_sum 5.96375")); + } + #[test] fn response_histograms_count_choices_and_largest_choice_per_prompt() { let metrics = Metrics::new(0, 0, 0, 16); diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index c84226736..075d99811 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -2987,6 +2987,9 @@ impl<'a> Worker<'a> { incoming.pool_plan = None; } incoming.readmitted = true; + // A requeued request has generated no token, so its wait through the park + // and readmission is queue time; the next executed step stamps again. + incoming.record.times.first_scheduled_ns = None; self.parked.push_front(( incoming, Parked { diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 49ee31b93..c90a5e544 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -610,6 +610,35 @@ fn reasoning_budget_cuts_when_ignored_eos_is_the_last_pass_token() { ); } +#[test] +fn a_forced_reasoning_close_without_a_later_step_records_no_decode() { + let fixture = Fixture::new(); + let (sender, receiver) = mpsc::channel(); + let (mut incoming, mut generation) = fixture.incoming(vec![0], 1); + incoming.prompt.reasoning_cut = Some(budget_cut(4, 1)); + sender.send(vec![incoming]).unwrap(); + let mut worker = fixture.worker(receiver); + let _ = worker.admit().unwrap(); + let mut sequence = 0; + // One prefill step commits the only generated token; the budget then forces + // the reasoning close, which counts a second token without running a step. + budget_pass(&mut worker, &mut sequence, &[1]); + assert_eq!( + budget_events(&mut generation), + (vec![1, 4], vec![(1, 2, "length")], vec![]) + ); + assert_eq!(fixture.metrics.snapshot(false).reasoning_budget_cuts, 1); + let text = fixture.metrics.render(); + for expected in [ + "\nflare_request_decode_seconds_count 0\n", + "\nflare_time_per_output_token_seconds_count 0\n", + "\nflare_inter_token_latency_seconds_count 0\n", + "\nflare_request_generated_tokens_sum 2\n", + ] { + assert!(text.contains(expected), "missing {expected}"); + } +} + #[test] fn reasoning_budget_cuts_after_a_multi_token_speculative_completion() { let mut fixture = Fixture::new(); @@ -3726,6 +3755,96 @@ fn an_idle_worker_holds_a_pending_pool_lookup_until_answer_or_deadline() { } } +#[test] +fn requeued_request_reports_queue_time_through_its_readmission() { + use std::time::{Duration, Instant}; + let fixture = Fixture::new(); + let (_sender, receiver) = mpsc::channel(); + let mut worker = fixture.worker(receiver); + let mut store = FakeStore::new(None); + store.pooled = true; + store.pending_tickets = true; + worker.attach_store(Some(Box::new(store))); + let (incoming, _generation) = fixture.incoming(vec![0; 70], 4); + worker.enqueue(vec![incoming]); + let hit = host_hit(worker.pending[0].pool_plan.as_ref().unwrap().history(), 70); + worker.pending[0].pool_lookup_started = Some(Instant::now() - Duration::from_secs(1)); + let _ = worker.admit().unwrap(); + + // The discarded Init step stamps the first scheduled instant for a request + // that generates no token; the late host answer then requeues it. + advance(&mut worker, GraphKind::Init, 1, None); + let discarded = worker.active[0] + .as_ref() + .unwrap() + .incoming + .record + .times + .first_scheduled_ns + .expect("a scheduled step stamps the first scheduled instant"); + complete_pool_answer(&mut worker, 0, hit.key); + fake_store(&mut worker).hit = Some(hit); + let (step, progress) = worker.plan().unwrap(); + assert!(step.is_none() && progress); + assert_eq!( + worker.parked.front().unwrap().0.record.times.first_scheduled_ns, + None, + "requeueing clears the discarded step's scheduled instant" + ); + + // Readmission waits for the host restore; the Restore step that consumes it + // stamps a new first scheduled instant, so the wait is queue time. + let _ = worker.admit().unwrap(); + let (_, ticket) = fake_store(&mut worker).fetched.pop().unwrap(); + fake_store(&mut worker) + .events + .push_back(flare_selene::StoreEvent::Fetched { + key: ticket.key, + result: Ok(1 << 20), + }); + worker.service_store().unwrap(); + std::thread::sleep(Duration::from_millis(1)); + advance(&mut worker, GraphKind::Restore, 2, None); + let handle = worker.active[0].as_ref().unwrap().request; + let restamped = worker.active[0] + .as_ref() + .unwrap() + .incoming + .record + .times + .first_scheduled_ns + .unwrap(); + assert!(restamped >= discarded + 1_000_000); + + advance(&mut worker, GraphKind::Resume, 3, Some(1)); + advance(&mut worker, GraphKind::Decode, 4, Some(2)); + let step = planned(&mut worker, GraphKind::Decode, 5); + let mut frame = completion(&worker, &step, 5, Some(fixture.config.eos_token_ids[0])); + frame.records[handle.slot as usize].status = 2; + worker.complete(GraphKind::Decode, frame).unwrap(); + worker.publish().unwrap(); + assert!(worker.scheduler.request(handle).is_err()); + + let text = fixture.metrics.render(); + for expected in [ + "\nflare_request_queue_seconds_count 1\n", + "\nflare_request_prefill_seconds_count 1\n", + "\nflare_request_inference_seconds_count 1\n", + ] { + assert!(text.contains(expected), "missing {expected}"); + } + let queue: f64 = text + .lines() + .find_map(|line| line.strip_prefix("flare_request_queue_seconds_sum ")) + .unwrap() + .parse() + .unwrap(); + assert!( + queue >= 0.001, + "queue time {queue}s must cover the wait after the discarded step" + ); +} + #[test] fn a_pending_pool_lookup_does_not_hold_other_requests() { let fixture = Fixture::new();