From ebecef137a97bd04f78fcdab6a4de406f73317f6 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Thu, 26 Nov 2026 14:05:46 -0600 Subject: [PATCH 01/24] 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=eb2f --- 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 | 46 ++++- helios/src/server/runtime/phase_tests.rs | 35 ++++ 8 files changed, 545 insertions(+), 20 deletions(-) create mode 100644 helios/src/server/metrics/process.rs diff --git a/docs/api.md b/docs/api.md index b9d61f71b..8f05c4406 100644 --- a/docs/api.md +++ b/docs/api.md @@ -287,14 +287,36 @@ 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. `flare_history_drafts_enabled` reports whether shared decoded history augments learned proposals in the serving process. +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 d598bd19c..c77dc53bd 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, @@ -227,6 +324,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, @@ -344,6 +447,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() @@ -1251,6 +1386,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", @@ -1477,6 +1648,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 745cc0805..c32105ccc 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -190,6 +190,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. @@ -908,6 +910,7 @@ impl ModelRuntime { failure: failure.clone(), metrics: self.metrics.clone(), observation, + times: Default::default(), host_lookup: true, readmitted: false, blocked: None, @@ -1768,6 +1771,8 @@ impl<'a> Worker<'a> { .as_mut() .filter(|a| a.request == token.request) { + 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); if let Some(reasoning) = &mut request.reasoning { @@ -1829,17 +1834,21 @@ 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 prompt_tokens = + request.carried.prompt_tokens.unwrap_or(live.prompt_tokens); + let generated_tokens = request.carried.generated_tokens + live.generated_tokens; + 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, + prompt_tokens, + generated_tokens, reused_prompt_tokens: request .carried .reused_prompt_tokens @@ -1981,7 +1990,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 @@ -2172,6 +2186,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() @@ -3222,6 +3251,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 a324ad586..93cf408c4 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -248,6 +248,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, @@ -572,6 +573,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, @@ -4416,6 +4425,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")); } } @@ -4444,6 +4458,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) + ))); } } @@ -5352,6 +5377,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 d64c3ea37ebb977047c19babb838cfd6ce51ae13 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Thu, 26 Nov 2026 22:55:17 -0600 Subject: [PATCH 02/24] 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=eb2f --- 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 8f05c4406..8fc5b2c07 100644 --- a/docs/api.md +++ b/docs/api.md @@ -287,30 +287,33 @@ 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. `flare_history_drafts_enabled` reports whether shared decoded history augments learned proposals in the serving process. -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 037adcb4d..84f04959e 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -55,6 +55,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 300e7b913..d686a4d6e 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 93cf408c4..c5f871543 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -4601,6 +4601,16 @@ async fn disabled_parallel_calls_complete_http_and_stop_decoding() { assert!(worker.plan(0).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 a34c4d060f96553c490eceb44b2fcf09ed277098 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Thu, 26 Nov 2026 23:02:24 -0600 Subject: [PATCH 03/24] 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=eb2f --- 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 c77dc53bd..06ffac4aa 100644 --- a/helios/src/server/metrics.rs +++ b/helios/src/server/metrics.rs @@ -1678,18 +1678,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 c32105ccc..3361cf536 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -1990,11 +1990,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 @@ -2012,11 +2015,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 54e06b304b3aef1a6fc2d7dc3dd15be9a0faa443 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 14:56:42 -0600 Subject: [PATCH 04/24] 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=eb2f --- 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 8fc5b2c07..0a65b4cde 100644 --- a/docs/api.md +++ b/docs/api.md @@ -287,8 +287,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. `flare_history_drafts_enabled` reports whether shared decoded history @@ -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 84f04959e..037adcb4d 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -55,7 +55,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 d686a4d6e..300e7b913 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 06ffac4aa..cc0798f2f 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 c5f871543..b10c52019 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -5395,8 +5395,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 10c0b937834c951ba31553f7fcefe86063886fd3 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 15:17:55 -0600 Subject: [PATCH 05/24] 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=eb2f --- 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 0a65b4cde..553f5aa5c 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 cc0798f2f..89c84852e 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, @@ -323,12 +389,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, @@ -451,19 +526,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 @@ -478,6 +579,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() @@ -1406,20 +1522,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 [ ( @@ -1650,15 +1819,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 [ @@ -1666,10 +1845,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!( @@ -1678,14 +1874,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!( @@ -1695,6 +1906,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 3361cf536..61ad3bf4e 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -190,8 +190,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. @@ -910,7 +910,7 @@ impl ModelRuntime { failure: failure.clone(), metrics: self.metrics.clone(), observation, - times: Default::default(), + record: Default::default(), host_lookup: true, readmitted: false, blocked: None, @@ -1552,6 +1552,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); } self.scheduler.resume_decoded_sequence(handle, parked.carried.decoded_sequence)?; if !pending_pool_answer { @@ -1771,8 +1773,11 @@ impl<'a> Worker<'a> { .as_mut() .filter(|a| a.request == token.request) { - 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); if let Some(reasoning) = &mut request.reasoning { @@ -1838,21 +1843,25 @@ impl<'a> Worker<'a> { let prompt_tokens = request.carried.prompt_tokens.unwrap_or(live.prompt_tokens); let generated_tokens = request.carried.generated_tokens + live.generated_tokens; + 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 @@ -1993,11 +2002,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 @@ -2017,10 +2031,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 @@ -2067,13 +2078,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) } @@ -2196,6 +2203,7 @@ impl<'a> Worker<'a> { { active .incoming + .record .times .first_scheduled_ns .get_or_insert(scheduled_ns); @@ -3251,7 +3259,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 b10c52019..0bd871364 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -248,7 +248,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, @@ -682,6 +682,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}"); + } } fn prepared_budget_request( @@ -1479,6 +1494,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(); @@ -3861,6 +3905,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 @@ -3998,6 +4043,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 01f1e92bcfc766e34afb40a0d49f20b8198d457c Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 15:23:37 -0600 Subject: [PATCH 06/24] 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=eb2f --- 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 553f5aa5c..59b9fefaf 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 67edac493..9e9e2b29e 100644 --- a/helios/src/scheduler.rs +++ b/helios/src/scheduler.rs @@ -113,6 +113,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, @@ -1596,6 +1598,7 @@ impl RequestScheduler { let AdmissionPlan { history, lookup } = 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; @@ -1796,6 +1799,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 b553ac423..365509a51 100644 --- a/helios/src/scheduler/tests.rs +++ b/helios/src/scheduler/tests.rs @@ -882,6 +882,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, @@ -3425,11 +3427,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 89c84852e..0d41d0d13 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)] @@ -404,6 +418,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, @@ -418,6 +435,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, @@ -440,6 +458,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, @@ -533,9 +552,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( @@ -652,6 +675,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, @@ -735,6 +768,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), @@ -1349,6 +1383,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 submissions containing both grammar-constrained and unconstrained request lanes.", @@ -1364,6 +1403,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.", @@ -1590,6 +1634,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", @@ -1643,9 +1707,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.", @@ -1837,6 +1906,7 @@ mod tests { prompt_tokens: 3000, reused_prompt_tokens: 1000, generated_tokens: 101, + output_limit: true, }, ); let text = metrics.render(); @@ -1882,6 +1952,7 @@ mod tests { prompt_tokens: 3000, reused_prompt_tokens: 0, generated_tokens: 0, + output_limit: false, }, ); let text = metrics.render(); @@ -1898,6 +1969,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")), @@ -2224,6 +2296,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, @@ -2231,6 +2304,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 { @@ -2267,6 +2350,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), @@ -2349,6 +2433,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 61ad3bf4e..1a0de5ef2 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -747,6 +747,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; } @@ -864,6 +865,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", @@ -938,6 +941,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( @@ -1149,10 +1154,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}; @@ -1197,6 +1199,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 { let now = std::time::Instant::now(); if self @@ -1705,6 +1718,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); @@ -1854,6 +1879,7 @@ impl<'a> Worker<'a> { prompt_tokens, reused_prompt_tokens, generated_tokens, + output_limit: false, }, ); request @@ -2004,6 +2030,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, @@ -2011,6 +2042,7 @@ impl<'a> Worker<'a> { prompt_tokens, reused_prompt_tokens, generated_tokens, + output_limit: reason == "length", }, ); for token in request.stops.finish() { @@ -2021,11 +2053,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 0bd871364..ae8587408 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -940,6 +940,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")); } } @@ -1492,6 +1496,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] @@ -3796,6 +3810,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(); @@ -3906,6 +3954,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 @@ -5367,6 +5420,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 15018689879bafd4516132a05cbdca43abafebd3 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 15:24:39 -0600 Subject: [PATCH 07/24] 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=eb2f --- docs/api.md | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/docs/api.md b/docs/api.md index 59b9fefaf..28dd26965 100644 --- a/docs/api.md +++ b/docs/api.md @@ -460,6 +460,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 49373bc5673c2130ad7f8d645510365d45e85f06 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 15:44:48 -0600 Subject: [PATCH 08/24] 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=eb2f --- 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 28dd26965..6c73b0763 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 @@ -464,8 +476,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 | | --- | --- | @@ -473,7 +487,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 | @@ -484,8 +498,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 ae8587408..6a19b790e 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -4533,6 +4533,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() @@ -4571,12 +4572,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 055663a76f3cc9c7158fe514bb9a677f79fe279c Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 20:26:26 -0600 Subject: [PATCH 09/24] 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=eb2f --- 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 6c73b0763..bbdc78a23 100644 --- a/docs/api.md +++ b/docs/api.md @@ -293,6 +293,15 @@ launches by kind, embedding row-cache counters, HTTP admission gauges, and uptime. `flare_history_drafts_enabled` reports whether shared decoded history augments learned proposals in the serving process. +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 0d41d0d13..27d5773b1 100644 --- a/helios/src/server/metrics.rs +++ b/helios/src/server/metrics.rs @@ -2296,11 +2296,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); @@ -2350,10 +2350,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 66245920cd3b4cf84567e67d19821df70fedd29d Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 21:54:04 -0600 Subject: [PATCH 10/24] 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=eb2f --- 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 1a0de5ef2..de3b359ad 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -1718,16 +1718,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); @@ -2220,22 +2211,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() @@ -2281,6 +2256,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 fb50f07caf5a535e1a3aa1dbdadc854a06ffa17a Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Sat, 28 Nov 2026 16:45:02 -0600 Subject: [PATCH 11/24] 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=eb2f --- 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 27d5773b1..7e0367c7f 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}"); } @@ -411,6 +428,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>, @@ -472,10 +490,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], @@ -617,6 +634,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() @@ -818,26 +842,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) { @@ -851,6 +863,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() @@ -997,6 +1011,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() @@ -1175,42 +1190,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 [ @@ -1576,6 +1574,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); } @@ -2086,9 +2089,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 6a19b790e..14732de61 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -5524,7 +5524,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 ba1bc41a82c4103b1905df47ed0c5ee005b96204 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Sat, 28 Nov 2026 16:45:30 -0600 Subject: [PATCH 12/24] 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=eb2f --- 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 bbdc78a23..ee1addea5 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 @@ -498,7 +498,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 7e0367c7f..d7285cf8f 100644 --- a/helios/src/server/metrics.rs +++ b/helios/src/server/metrics.rs @@ -621,16 +621,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)); } } @@ -1620,7 +1628,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); @@ -1628,7 +1636,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( @@ -1985,8 +1993,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", @@ -2003,6 +2011,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 6b736d24d4c07e6671a02e349d626fcfe70a8a28 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Sat, 28 Nov 2026 16:45:47 -0600 Subject: [PATCH 13/24] 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=eb2f --- 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 ee1addea5..5b5cb71dd 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 @@ -476,10 +463,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 d7285cf8f..4ac8b5298 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, @@ -438,7 +450,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, @@ -708,9 +720,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) { @@ -1655,10 +1670,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}\"}} {}", @@ -1954,8 +1968,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(), @@ -1968,19 +1986,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")), @@ -2402,6 +2422,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, @@ -2532,6 +2554,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 3b1ebbf650048628fac382055ef34ad496aeab85 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 15:16:47 -0600 Subject: [PATCH 14/24] Report the first scheduled model step in Chat performance A Chat request that sets `return_token_ids` and `return_token_timestamps` receives a `performance` object with its HTTP ingress and model-queue enqueue instants, and a timestamp for every generated token, all on Flare's monotonic observation clock. It cannot separate the time spent waiting for the scheduler from the time spent in prefill, because no instant marks when the request first reached a model step. The worker already records that instant: it stamps `RequestTimes::first_scheduled_ns` when it reserves and packs the first step that includes the request, and preserves it across preemption, for the request queue histogram. Reporting it next to the existing instants lets a client derive queue time, time to first token, decode time, inter-token latency, and throughput from one timed response. `GenerationEvent::Finished` now carries the request's `RequestTimes`, and the Chat handler adds `first_scheduled_ns` to `performance`, on the terminal choice chunk of a stream and on the JSON body otherwise. The value is null when no model step included the request. `helios/model-contract.md` defines the field and the intervals it closes. Requests that do not ask for timestamps are unchanged; the terminal event copies three integers the worker already holds and reads no clock. Evidence: `server::runtime::phase_tests::performance_reports_the_first_scheduled_model_step` serves a timed two-token Chat request through `http::generate` and a worker driven step by step, streaming and not, pausing between steps. The reported `first_scheduled_ns` falls inside the first worker step, after `enqueue_ns` and before the first token timestamp, which falls inside the first generating step. `cargo test --locked --manifest-path helios/Cargo.toml --features runtime-core,server --lib -- server::` passed 325 tests; the one failure, `messages_image_hints_end_after_expansion_for_text_and_segmented_templates`, needs templates from `tests/frontend/prepare_templates.py` through `FLARE_TEST_TEMPLATE_DIR`, which this host does not have. No GPU or live server was used. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=eb2f --- helios/model-contract.md | 14 +- helios/src/server/http.rs | 8 +- helios/src/server/metrics.rs | 2 +- helios/src/server/observation.rs | 16 +- helios/src/server/runtime.rs | 5 + helios/src/server/runtime/phase_tests.rs | 145 +++++++++++++++++- .../runtime/response_lifecycle_tests.rs | 2 + 7 files changed, 169 insertions(+), 23 deletions(-) diff --git a/helios/model-contract.md b/helios/model-contract.md index 412b5493c..668ad289e 100644 --- a/helios/model-contract.md +++ b/helios/model-contract.md @@ -343,10 +343,16 @@ requests read no per-token clock and emit no observation events. Observed terminal responses include `reused_prompt_tokens` and ordinary token usage. Timed responses also include one top-level `performance` object with -`ingress_ns`, `enqueue_ns` and `reused_prompt_tokens`. Ingress is chat-handler -entry after HTTP JSON decoding, before waiting for frontend preparation; -enqueue is immediately before submitting the prepared request to the model -queue. Both timestamps use the token timestamp origin. +`ingress_ns`, `enqueue_ns`, `first_scheduled_ns` and `reused_prompt_tokens`. +Ingress is chat-handler entry after HTTP JSON decoding, before waiting for +frontend preparation; enqueue is immediately before submitting the prepared +request to the model queue. `first_scheduled_ns` marks the earliest model step +that included the request, when the worker reserves and packs that step before +submitting it; a preempted request keeps its original value. It is null when no +model step included the request. All three timestamps use the token timestamp +origin, so `first_scheduled_ns - enqueue_ns` is the time the request waited +for its first model step and `token_timestamps_ns[0] - first_scheduled_ns` is +its time to first token. `stream_options.include_usage=true` emits a final usage-only SSE chunk with `choices=[]` before `[DONE]`; preceding chunks have `usage=null`. Otherwise an diff --git a/helios/src/server/http.rs b/helios/src/server/http.rs index 13c1a492e..83da35fbe 100644 --- a/helios/src/server/http.rs +++ b/helios/src/server/http.rs @@ -404,6 +404,8 @@ pub(super) async fn generate( let mut raw_tokens = Vec::new(); let mut timestamps = Vec::new(); let mut reused_total = 0; + // `performance` is Chat-only, and Chat has one choice. + let mut first_scheduled_ns = None; 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. @@ -523,9 +525,11 @@ pub(super) async fn generate( reused_prompt_tokens, termination, stop_sequence, + times, .. } => { reused_total += reused_prompt_tokens; + first_scheduled_ns = times.first_scheduled_ns; let result = decoders[index] .finish(if encoder.tool_limit_reached { crate::output::Termination::Cancelled } else { termination }) .and_then(|events| encoder.apply(index, events)) @@ -550,7 +554,7 @@ pub(super) async fn generate( &mut frame.data, &encoder.usage_value(), reused_prompt_tokens, - (ingress_ns, enqueue_ns), + (ingress_ns, enqueue_ns, times.first_scheduled_ns), true, ); } @@ -595,7 +599,7 @@ pub(super) async fn generate( &mut response, &encoder.usage_value(), reused_total, - (ingress_ns, enqueue_ns), + (ingress_ns, enqueue_ns, first_scheduled_ns), false, ); } diff --git a/helios/src/server/metrics.rs b/helios/src/server/metrics.rs index 4ac8b5298..0fbd4e9e2 100644 --- a/helios/src/server/metrics.rs +++ b/helios/src/server/metrics.rs @@ -340,7 +340,7 @@ impl Histogram { /// Request lifecycle instants on the `observation::monotonic_ns` clock, kept across preemption. #[derive(Clone, Copy, Debug, Default)] -pub(super) struct RequestTimes { +pub struct RequestTimes { pub first_scheduled_ns: Option, pub first_token_ns: Option, pub last_token_ns: u64, diff --git a/helios/src/server/observation.rs b/helios/src/server/observation.rs index a3f21febd..675373e44 100644 --- a/helios/src/server/observation.rs +++ b/helios/src/server/observation.rs @@ -58,7 +58,7 @@ impl ObservationOptions { response: &mut Value, usage: &Value, reused: u64, - timing: (Option, Option), + timing: (Option, Option, Option), stream: bool, ) { if self.token_ids { @@ -68,9 +68,9 @@ impl ObservationOptions { } } if self.timestamps { - let (ingress_ns, enqueue_ns) = timing; + let (ingress_ns, enqueue_ns, first_scheduled_ns) = timing; response["performance"] = json!({"ingress_ns":ingress_ns,"enqueue_ns":enqueue_ns, - "reused_prompt_tokens":reused}); + "first_scheduled_ns":first_scheduled_ns,"reused_prompt_tokens":reused}); } } } @@ -132,7 +132,7 @@ mod tests { let usage = json!({"prompt_tokens":17,"completion_tokens":3,"total_tokens":20, "prompt_tokens_details":{"cached_tokens":16,"multimodal_tokens":{"image":8}}}); let mut value = original.clone(); - ObservationOptions::default().finish(&mut value, &usage, 16, (None, None), true); + ObservationOptions::default().finish(&mut value, &usage, 16, (None, None, None), true); assert_eq!(value, original); let options = ObservationOptions { token_ids: true, @@ -140,12 +140,12 @@ mod tests { include_usage: false, continuous_usage: false, }; - options.finish(&mut value, &usage, 16, (Some(10), Some(20)), true); + options.finish(&mut value, &usage, 16, (Some(10), Some(20), Some(30)), true); assert_eq!(value["choices"], original["choices"]); assert_eq!(value["usage"], usage); assert_eq!( value["performance"], - json!({"ingress_ns":10,"enqueue_ns":20,"reused_prompt_tokens":16}) + json!({"ingress_ns":10,"enqueue_ns":20,"first_scheduled_ns":30,"reused_prompt_tokens":16}) ); assert_eq!(value["reused_prompt_tokens"], 16); let mut separate = original.clone(); @@ -153,9 +153,9 @@ mod tests { include_usage: true, ..options } - .finish(&mut separate, &usage, 16, (Some(10), Some(20)), true); + .finish(&mut separate, &usage, 16, (Some(10), Some(20), Some(30)), true); assert!(separate.get("usage").is_none()); - options.finish(&mut value, &usage, 16, (Some(10), Some(20)), false); + options.finish(&mut value, &usage, 16, (Some(10), Some(20), Some(30)), false); assert_eq!(value["usage"], usage); } } diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index de3b359ad..2c91ebbc3 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -99,6 +99,8 @@ pub enum GenerationEvent { reason: &'static str, termination: crate::output::Termination, stop_sequence: Option, + /// The request's lifecycle instants, as its completion histograms record them. + times: super::metrics::RequestTimes, }, AdmissionRejected(Error), Error(Error), @@ -298,6 +300,7 @@ impl Incoming { reason: "stop", termination: crate::output::Termination::Cancelled, stop_sequence: None, + times: self.times, }); } @@ -1885,6 +1888,7 @@ impl<'a> Worker<'a> { .text_stops .as_ref() .and_then(|s| s.matched().map(str::to_owned)), + times: request.incoming.times, }); stopped.push(token.request); } @@ -2062,6 +2066,7 @@ impl<'a> Worker<'a> { } else { crate::output::Termination::OutputLimit }, + times: request.incoming.times, }); if user_stop { self.scheduler.cancel(request.request)?; diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 14732de61..5197ce5cd 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -55,8 +55,12 @@ impl Fixture { wrapping_newlines: 0, terminal_markers: vec![], }); - // Prepared text prompts have no image arrays or image graph inputs. - for graph in &mut fixture.config.contract.graphs { + fixture.text_inputs() + } + + /// Prepared text prompts have no image arrays or image graph inputs. + fn text_inputs(mut self) -> Self { + for graph in &mut self.config.contract.graphs { graph.inputs.retain(|binding| { !matches!( binding.source, @@ -65,7 +69,7 @@ impl Fixture { ) }); } - fixture + self } fn with_template(template: &[u8], special_tokens: &[&str], text_tokens: &[&str]) -> Self { @@ -4511,6 +4515,130 @@ async fn http_generation_request_observed( (response, incoming, state) } +/// The bounds of one worker step on the observation clock. +struct StepBounds { + start_ns: u64, + end_ns: u64, + generated: bool, +} + +/// Drive a single request like `budget_pass`, pausing after each step so that +/// instants recorded in different steps differ by at least the pause. +fn timed_pass(worker: &mut Worker<'_>, samples: &[u32]) -> Vec { + let mut bounds = Vec::new(); + let mut samples = samples.iter().copied(); + for sequence in 1..=samples.len() as u64 + 40 { + if worker.active.iter().all(Option::is_none) { + assert!(samples.next().is_none()); + return bounds; + } + let start_ns = super::super::observation::monotonic_ns(); + let step = worker.plan(0).unwrap().0.expect("timed pass must progress"); + worker.reserve_and_pack(&step, Fence(sequence)).unwrap(); + let lane = &step.lanes[0]; + let live = worker.scheduler.request(lane.request).unwrap(); + let generates = matches!(step.kind, GraphKind::Decode | GraphKind::Resume) + || (step.kind == GraphKind::Prefill + && lane.start_position + lane.tokens as u64 == live.prompt_tokens as u64); + let token = generates.then(|| samples.next().expect("unexpected generation")); + let mut frame = completion(worker, &step, sequence, token); + if token.is_some_and(|token| worker.config.eos_token_ids.contains(&token)) { + frame.records[lane.request.slot as usize].status = 2; + } + worker.complete(step.kind, frame).unwrap(); + worker.publish().unwrap(); + bounds.push(StepBounds { + start_ns, + end_ns: super::super::observation::monotonic_ns(), + generated: generates, + }); + thread::sleep(std::time::Duration::from_millis(3)); + } + panic!("timed pass did not finish"); +} + +/// Serve one HTTP request through a worker that `timed_pass` drives, returning the +/// step bounds and the JSON body, or the SSE `data` payloads of a stream. +async fn served_through_worker( + fixture: fn() -> Fixture, + path: &str, + body: serde_json::Value, + samples: &[u32], +) -> (Vec, Vec) { + use axum::{Extension, extract::State}; + let (sender, receiver) = mpsc::sync_channel(4); + let state = http_state_for(fixture(), sender, None, &[]); + let stream = body["stream"] == true; + let ingress = Arc::new(state.ingress_slots.clone().acquire_owned().await.unwrap()); + let request = axum::http::Request::builder() + .method("POST") + .uri(path) + .header("content-type", "application/json") + .body(axum::body::Body::from(body.to_string())) + .unwrap(); + let response = tokio::spawn(super::super::http::generate(State(state), Extension(ingress), request)); + let group = tokio::task::spawn_blocking(move || { + receiver.recv_timeout(std::time::Duration::from_secs(5)).unwrap() + }) + .await + .unwrap(); + let steps = { + let worker_fixture = fixture(); + let (queue, inbound) = mpsc::channel(); + queue.send(group).unwrap(); + let mut worker = worker_fixture.worker(inbound); + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); + timed_pass(&mut worker, samples) + }; + let bytes = axum::body::to_bytes(response.await.unwrap().into_body(), 1 << 20) + .await + .unwrap(); + let values = if stream { + std::str::from_utf8(&bytes) + .unwrap() + .lines() + .filter_map(|line| line.strip_prefix("data: ")) + .filter_map(|line| serde_json::from_str(line).ok()) + .collect() + } else { + vec![serde_json::from_slice(&bytes).unwrap()] + }; + (steps, values) +} + +#[tokio::test] +async fn performance_reports_the_first_scheduled_model_step() { + use serde_json::json; + for stream in [false, true] { + let (steps, values) = served_through_worker( + || Fixture::new().text_inputs(), + "/v1/chat/completions", + json!({"model":"qwen-worker-phases","messages":[{"role":"user","content":"a"}], + "max_tokens":2,"stream":stream,"return_token_ids":true,"return_token_timestamps":true}), + &[1, 2], + ) + .await; + let performance = &values + .iter() + .find(|value| value.get("performance").is_some()) + .expect("timed responses carry performance")["performance"]; + let timestamps: Vec = values + .iter() + .flat_map(|value| value["choices"][0]["token_timestamps_ns"].as_array().cloned().unwrap_or_default()) + .map(|value| value.as_u64().unwrap()) + .collect(); + let scheduled = performance["first_scheduled_ns"].as_u64().unwrap(); + // The request's first model step stamps the instant; HTTP rendering, which + // runs after every step, does not. + assert!((steps[0].start_ns..=steps[0].end_ns).contains(&scheduled), "{stream}"); + assert!(performance["enqueue_ns"].as_u64().unwrap() <= scheduled); + let first = steps.iter().find(|step| step.generated).unwrap(); + assert_eq!(timestamps.len(), 2); + assert!(scheduled <= timestamps[0]); + assert!((first.start_ns..=first.end_ns).contains(×tamps[0])); + } +} + #[tokio::test] async fn first_response_http_stream_excludes_pretext_failures_and_unpolled_bodies() { for (emit_text, poll_body) in [(false, true), (true, false), (true, true)] { @@ -4555,7 +4683,7 @@ async fn first_response_http_nonstream_records_only_when_completed_body_is_offer incoming[0].emit(GenerationEvent::Finished { prompt_tokens: incoming[0].prompt.tokens.len(), generated_tokens: 1, reused_prompt_tokens: 0, reason: "length", stop_sequence: None, - termination: crate::output::Termination::OutputLimit, + termination: crate::output::Termination::OutputLimit, times: Default::default(), }); let response = response.await.unwrap(); assert_eq!(state.first_response.snapshot().samples, 0); @@ -4599,7 +4727,7 @@ async fn unread_http_stream_preserves_all_tokens_and_its_terminal_event() { incoming[0].emit(GenerationEvent::Finished { prompt_tokens: incoming[0].prompt.tokens.len(), generated_tokens: 100, reused_prompt_tokens: 0, reason: "length", stop_sequence: None, - termination: crate::output::Termination::OutputLimit, + termination: crate::output::Termination::OutputLimit, times: Default::default(), }); } assert!(!incoming[0].cancelled.load(Ordering::Acquire)); @@ -4829,6 +4957,7 @@ async fn paused_http_bodies_preserve_output_and_completion_for_every_protocol() reason: "length", termination: crate::output::Termination::OutputLimit, stop_sequence: None, + times: Default::default(), }); assert!(!incoming.cancelled.load(Ordering::Acquire)); assert_eq!(incoming.publications.get(), 3000); @@ -5049,7 +5178,7 @@ async fn responses_carry_the_first_non_empty_served_name() { incoming[0].emit(GenerationEvent::Finished { prompt_tokens: incoming[0].prompt.tokens.len(), generated_tokens: 1, reused_prompt_tokens: 0, reason: "stop", stop_sequence: None, - termination: crate::output::Termination::OutputLimit, + termination: crate::output::Termination::OutputLimit, times: Default::default(), }); let bytes = axum::body::to_bytes(response.into_body(), 131072).await.unwrap(); let body = std::str::from_utf8(&bytes).unwrap(); @@ -5079,7 +5208,7 @@ async fn responses_carry_the_first_non_empty_served_name() { incoming[0].emit(GenerationEvent::Finished { prompt_tokens: incoming[0].prompt.tokens.len(), generated_tokens: 1, reused_prompt_tokens: 0, reason: "length", stop_sequence: None, - termination: crate::output::Termination::OutputLimit, + termination: crate::output::Termination::OutputLimit, times: Default::default(), }); let response = response.await.unwrap(); let bytes = axum::body::to_bytes(response.into_body(), 65536).await.unwrap(); @@ -5097,7 +5226,7 @@ async fn responses_carry_the_first_non_empty_served_name() { incoming[0].emit(GenerationEvent::Finished { prompt_tokens: incoming[0].prompt.tokens.len(), generated_tokens: 1, reused_prompt_tokens: 0, reason: "length", stop_sequence: None, - termination: crate::output::Termination::OutputLimit, + termination: crate::output::Termination::OutputLimit, times: Default::default(), }); let response = response.await.unwrap(); let bytes = axum::body::to_bytes(response.into_body(), 65536).await.unwrap(); diff --git a/helios/src/server/runtime/response_lifecycle_tests.rs b/helios/src/server/runtime/response_lifecycle_tests.rs index 5a0adf3c0..dba308cda 100644 --- a/helios/src/server/runtime/response_lifecycle_tests.rs +++ b/helios/src/server/runtime/response_lifecycle_tests.rs @@ -159,6 +159,7 @@ impl Responses { reason: "length", stop_sequence: None, termination: crate::output::Termination::OutputLimit, + times: Default::default(), }); row.sent += 1; row.terminal = 1; @@ -376,6 +377,7 @@ async fn terminal_stream_frames_retain_http_admission_after_native_retirement() reason: "length", stop_sequence: None, termination: crate::output::Termination::OutputLimit, + times: Default::default(), }); drop(incoming); let mut reader = response.into_body().into_data_stream(); From d277c1246fdf717827bda993911eccec8633be00 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 15:27:48 -0600 Subject: [PATCH 15/24] Report vLLM per-request metrics from runtime instants Gateways, billing, and SLA tooling that show per-request speed read vLLM's `metrics` object from the response body when the server runs with `--enable-per-request-metrics`. Flare reports aggregate latency histograms on `/metrics` but nothing per request in OpenAI output, so these consumers show no rates for Flare. The model worker already records each request's arrival, first scheduled step, first committed token, and last committed token for those histograms, on the same monotonic clock and preserved across preemption. vLLM derives its fields from the corresponding engine instants, so reading them from the worker measures what vLLM measures, independently of HTTP delivery and of stop-string matching, which the worker performs before publishing output. `GenerationEvent::Finished` now carries the request's model-queue arrival beside its `RequestTimes`. `flare run --enable-per-request-metrics` (forwarded to rank zero by `flare orbit run`, and passed to Helios as the server configuration key `per_request_metrics`) makes the encoder render `time_to_first_token_ms`, `time_to_first_content_token_ms`, `generation_time_ms`, `queue_time_ms`, `mean_itl_ms`, and `tokens_per_second` with vLLM's definitions. A JSON body carries the object at the top level; a Chat or Completions stream carries it on the final usage chunk, so it needs `stream_options.include_usage`; a Responses stream carries it in the `response` of `response.completed` or `response.incomplete`. `n` greater than one makes the object null, several Completions prompts omit it, and Messages never carries it, because vLLM defines it only for the three OpenAI APIs. Fields whose instants the request did not reach are null. The content field needs the instant of the model step whose output first produced answer text, which only the HTTP decoder can recognize. A stream that reports it asks the worker for a `Committed` event before each step's output, carrying the completion instant the worker already read for that step; the encoder keeps the latest one and records it when the first non-empty content event passes its tool-choice filtering, so reasoning, tool-call output, and text a named tool choice discards do not count. The response event budget grows by one event per generated token for such streams. With the option off, the encoder holds no metrics state, the worker sends no extra events, and nothing reads a clock; the option on reads no clock either. The encoder is now built before submission, because its placement rules decide whether the request asks for commit instants. The option has no `[server]` configuration-file key: like `--bypass-performance-check`, `--verify-weights`, and the scheduler policy flags, it is a serving flag that `docs/cli-design.md` lists without a configuration fallback. The claimed result is vLLM-compatible per-request timing in OpenAI output when the option is on, and unchanged responses and serving work when it is off. Evidence: `server::runtime::phase_tests::per_request_metrics_report_the_runtime_instants_of_a_stopped_reasoning_answer` serves a Chat request with a stop string through `http::generate` and a worker driven step by step with pauses, streaming and not. The model reasons, closes, answers, and generates the stop string. Combining `metrics` with `performance.first_scheduled_ns` places the first scheduled step, first token, first answer text, and last token inside the worker steps that produced them; the content instant is two steps after the first token in the stream and null in the JSON body; arrival lies between HTTP ingress and `enqueue_ns`; and the mean inter-token latency and token rate reconcile with those instants. `per_request_metrics_reach_completions_and_responses_where_vllm_places_them` checks the usage chunk, `response.incomplete`, and top-level placements through the worker. `per_request_metrics_are_absent_without_the_option_and_null_for_several_choices` checks that Completions output carries no key and requests no commit instants with the option off, and that two choices give `"metrics": null` in both modes. `server::protocol::tests::per_request_metrics_follow_vllm_placement_and_null_rules` and `content_instant_excludes_reasoning_tool_calls_and_suppressed_text` check the encoder's placement, values, and null rules for every protocol; `server::config` checks the configuration key, and `cli::tests::per_request_metrics_flag_is_off_by_default_and_reaches_rank_zero` checks the flag and its Orbit forwarding. `cargo test --locked --manifest-path helios/Cargo.toml --features runtime-core,server --lib -- server::` passed 330 tests; the one failure, `messages_image_hints_end_after_expansion_for_text_and_segmented_templates`, needs templates from `tests/frontend/prepare_templates.py` through `FLARE_TEST_TEMPLATE_DIR`, which this host does not have. `cargo test --locked --manifest-path flare-cli/Cargo.toml --bin flare -- cli::` passed 33 tests. No GPU, exported core, live server, or gateway was used, and the CPU cost of the option under load has not been measured. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=eb2f --- docs/api.md | 51 ++++ docs/cli-design.md | 3 +- flare-cli/src/cli.rs | 40 +++ flare-cli/src/main.rs | 3 + helios/model-contract.md | 6 +- helios/src/server.rs | 6 + helios/src/server/config.rs | 18 ++ helios/src/server/http.rs | 64 +++-- helios/src/server/protocol/encode.rs | 94 ++++++- helios/src/server/protocol/tests.rs | 174 ++++++++++++ helios/src/server/runtime.rs | 72 +++-- helios/src/server/runtime/phase_tests.rs | 257 +++++++++++++++++- .../runtime/response_lifecycle_tests.rs | 2 + 13 files changed, 727 insertions(+), 63 deletions(-) diff --git a/docs/api.md b/docs/api.md index 5b5cb71dd..96019532d 100644 --- a/docs/api.md +++ b/docs/api.md @@ -991,6 +991,57 @@ before the final usage chunk arrives. Each emitted chunk carries cumulative native token counts; text chunks can combine multiple tokens, so counting chunks does not measure generated tokens. The final usage chunk is also emitted. +## Per-request metrics + +`flare run --enable-per-request-metrics` adds vLLM's per-request `metrics` +object to OpenAI Chat Completions, Completions, and Responses output. The option +is off by default, and no response carries the key without it. Anthropic Messages +output never carries the object. The fields are milliseconds, except +`tokens_per_second`, and come from the instants the model worker records for the +runtime histograms under [Health and metrics](#health-and-metrics), so a stop +string, which the worker matches, does not change how they are measured: + +| Field | Definition | +| --- | --- | +| `queue_time_ms` | Model-scheduler arrival to the first model step that includes the request | +| `time_to_first_token_ms` | That first scheduled step to the completion of the step that committed the first generated token | +| `time_to_first_content_token_ms` | Streams only: the first scheduled step to the completion of the step whose output first produced non-empty answer text | +| `generation_time_ms` | First to last committed generated token | +| `mean_itl_ms` | `generation_time_ms` divided by the generated tokens after the first | +| `tokens_per_second` | Generated tokens, as `usage` counts them, over the first scheduled step to the last committed generated token | + +A step's completion instant is read once when the worker processes that step's +results, so tokens committed by one speculative step share it. Reasoning text, +tool-call output, and answer text that a named tool choice discards do not count +as content; text that stop-string matching holds back counts from the step whose +output releases it. `time_to_first_content_token_ms` equals +`time_to_first_token_ms` when the first generated step produces answer text. + +A JSON body carries `metrics` at the top level. A Chat or Completions stream +carries it only on the final usage chunk, whose `choices` is empty, so the stream +needs `"stream_options": {"include_usage": true}`; without that option no chunk +carries it. A Responses stream carries it in the `response` object of +`response.completed` or `response.incomplete`; earlier events do not. Responses +requests always run one generation, so every Responses output carries it. + +Every field is present and is null when the request did not reach the instants +it spans: `time_to_first_content_token_ms` is null in JSON bodies and in streams +that produced no answer text, `mean_itl_ms` is null for a single generated token, +the token fields are null when nothing was generated, and every field is null for +a choice that never reached a model step. With `n` greater than one, `metrics` is +null, because one choice's instants do not describe the response. Completions +with several prompts omit `metrics`. Failed requests return error bodies without +it. + +The option adds no clock reads. A stream that reports +`time_to_first_content_token_ms` receives one additional runtime event per model +step that generated a token for it, carrying that step's completion instant; +other requests receive only the instants on their terminal event. Chat token +observation reports the same first scheduled step as `performance.first_scheduled_ns`, +beside per-token timestamps; the +[prepared model contract](../helios/model-contract.md#token-and-timing-observation) +defines those fields. + ## Raw completions `prompt` accepts a string, an array of strings, a token-ID array, or an array of diff --git a/docs/cli-design.md b/docs/cli-design.md index d66b0c7a2..045aabd52 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -170,7 +170,7 @@ defaulting to `~/.config/flare/orbit.toml` and `~/.config/flare/orbit/controller.key`. `flare orbit run` takes the serving flags of `flare run` and applies them to every rank; `--host`, `--port`, `--served-model-name`, `--scheduler-policy`, `--scheduler-terminal-value`, -`--scheduler-terminal-age-price`, and `--api-key-file` apply to rank zero. `--api-key-file` names a file rank zero must be able to read; Orbit does +`--scheduler-terminal-age-price`, `--api-key-file`, and `--enable-per-request-metrics` apply to rank zero. `--api-key-file` names a file rank zero must be able to read; Orbit does not upload it. Core inputs are Hugging Face repositories `ORG/NAME[@REVISION]`, controller-local files, or `NODE:/absolute/path` on a paired node. Orbit downloads repository cores on a candidate node and @@ -733,6 +733,7 @@ Help exits with status 0; usage errors go to stderr with status 2. Its options a | `--port N` | Listener port | `[server] port`, otherwise `8000` | | `--served-model-name ALIAS` | Replace the core's serving aliases with this nonblank alias | Core aliases | | `--api-key-file PATH` | File containing the serving API key; an empty file disables authentication | `[server] api_key`, otherwise no authentication | +| `--enable-per-request-metrics` | Add vLLM's per-request `metrics` timing object to OpenAI Chat, Completions, and Responses output; see [per-request metrics](api.md#per-request-metrics) | off | | `--max-concurrency N` | Reduce concurrency within captured batch capacities | Model/default configuration, otherwise core default | | `--kv-cache-limit concurrency\|context\|memory` | Bound shared KV history by prepared context times selected concurrency, one prepared context, or available memory | `memory` | | `--memory-limit LIMIT` | Per-GPU occupied size (`30G`), free-memory reserve (`-30G`, including `-0G`), or fraction of total memory (`0.8`) | `[memory] reserve`, otherwise core serving reserve | diff --git a/flare-cli/src/cli.rs b/flare-cli/src/cli.rs index 02d81c76b..853173cb4 100644 --- a/flare-cli/src/cli.rs +++ b/flare-cli/src/cli.rs @@ -532,6 +532,7 @@ impl OrbitPush { scheduler_terminal_age_price: None, scheduler_checkpoint_extra_work_fraction: None, bypass_performance_check: false, + enable_per_request_metrics: false, serving: self.serving.clone(), } } @@ -642,6 +643,10 @@ pub struct OrbitRun { #[arg(long, value_name = "PATH", help_heading = "Serving options")] pub api_key_file: Option, + /// Report vLLM's per-request `metrics` timing object in rank zero's OpenAI responses. + #[arg(long, help_heading = "Serving options")] + pub enable_per_request_metrics: bool, + #[command(flatten)] pub serving: ServingOptions, } @@ -689,6 +694,9 @@ impl OrbitRun { if let Some(path) = &self.api_key_file { options.extend(["--api-key-file".into(), path.display().to_string()]); } + if self.enable_per_request_metrics { + options.push("--enable-per-request-metrics".into()); + } options } @@ -717,6 +725,7 @@ impl OrbitRun { scheduler_terminal_age_price: self.scheduler_terminal_age_price, scheduler_checkpoint_extra_work_fraction: self.scheduler_checkpoint_extra_work_fraction, bypass_performance_check: false, + enable_per_request_metrics: self.enable_per_request_metrics, serving: self.serving.clone(), } } @@ -847,6 +856,11 @@ pub struct Run { #[arg(long, help_heading = "Serving options")] pub bypass_performance_check: bool, + /// Report vLLM's per-request `metrics` timing object in OpenAI Chat, Completions, + /// and Responses output. + #[arg(long, help_heading = "Serving options")] + pub enable_per_request_metrics: bool, + #[command(flatten)] pub serving: ServingOptions, } @@ -1360,6 +1374,32 @@ mod tests { } } + #[test] + fn per_request_metrics_flag_is_off_by_default_and_reaches_rank_zero() { + assert!(!run(&["flare", "run", "model"]).enable_per_request_metrics); + assert!(run(&["flare", "run", "model", "--enable-per-request-metrics"]).enable_per_request_metrics); + for enabled in [false, true] { + let mut arguments = vec!["flare", "orbit", "run", "model"]; + if enabled { + arguments.push("--enable-per-request-metrics"); + } + let Command::Orbit(orbit) = Cli::try_parse_from(arguments).unwrap().command else { + panic!() + }; + let OrbitCommand::Run(orbit) = orbit.command else { + panic!() + }; + assert_eq!(orbit.run_args().enable_per_request_metrics, enabled); + // Rank zero parses the forwarded options as `flare run` options. + let mut forwarded = vec!["flare".to_string(), "run".into(), "model".into()]; + forwarded.extend(orbit.rank_zero_options()); + let Command::Run(rank_zero) = Cli::try_parse_from(forwarded).unwrap().command else { + panic!() + }; + assert_eq!(rank_zero.enable_per_request_metrics, enabled); + } + } + #[test] fn persistent_orbit_options_preserve_saved_values_and_allow_explicit_defaults() { use clap::{CommandFactory, FromArgMatches}; diff --git a/flare-cli/src/main.rs b/flare-cli/src/main.rs index c66489c99..c915e5e88 100644 --- a/flare-cli/src/main.rs +++ b/flare-cli/src/main.rs @@ -352,6 +352,9 @@ fn run() -> Result> { } config["api_key"] = key.into(); config["thinking_token_budget"] = serde_json::json!(configuration.thinking_token_budget()); + if args.enable_per_request_metrics { + config["per_request_metrics"] = true.into(); + } phase.finish(config["model_id"].as_str().unwrap_or_default()); serve(owner, config, progress, cluster, routing)?; #[cfg(unix)] diff --git a/helios/model-contract.md b/helios/model-contract.md index 668ad289e..f81db52da 100644 --- a/helios/model-contract.md +++ b/helios/model-contract.md @@ -359,8 +359,10 @@ its time to first token. observed stream includes usage on its terminal choice chunk. Observation flags and `include_usage` accept only booleans or null; null is equivalent to false. The response event budget includes one observation per generated token when -requested, in addition to presentation events. Observation changes no CUDA -graph, device allocation or replay ABI. +requested, in addition to presentation events, and one model-step completion +instant per generated token for a stream that reports +[per-request metrics](../docs/api.md#per-request-metrics) with a content instant. +Observation changes no CUDA graph, device allocation or replay ABI. `stop_token_ids` and `stop_token_sequences` accept explicit vocabulary IDs. At most sixteen sequences of at most 64 tokens are supported. Matching tokens diff --git a/helios/src/server.rs b/helios/src/server.rs index 8161fe701..6edd60766 100644 --- a/helios/src/server.rs +++ b/helios/src/server.rs @@ -124,6 +124,9 @@ pub struct ServerConfig { pub served_names: Vec, /// Default reasoning-token cap for conversational requests without a budget. pub thinking_token_budget: Option, + /// Report vLLM's per-request `metrics` object on OpenAI Chat, Completions, and + /// Responses output. + pub per_request_metrics: bool, /// Setting that raises the per-request context, appended to context rejections. pub context_hint: String, /// Setting that raises request or page capacity, appended to capacity rejections. @@ -142,6 +145,7 @@ impl Default for ServerConfig { api_key: None, served_names: Vec::new(), thinking_token_budget: None, + per_request_metrics: false, context_hint: String::new(), capacity_hint: String::new(), scheduling_policy: crate::scheduler::PolicyConfig::default(), @@ -167,6 +171,7 @@ struct HttpState { ids: AtomicU64, api_key: Option, thinking_token_budget: Option, + per_request_metrics: bool, context_hint: String, capacity_hint: String, response_model: String, @@ -325,6 +330,7 @@ impl Server { ids: AtomicU64::new(1), api_key: config.api_key.clone(), thinking_token_budget: config.thinking_token_budget, + per_request_metrics: config.per_request_metrics, context_hint: config.context_hint.clone(), capacity_hint: config.capacity_hint.clone(), response_model: models::response_name(model.config(), &config.served_names).to_owned(), diff --git a/helios/src/server/config.rs b/helios/src/server/config.rs index ffd22c6bc..517f05fad 100644 --- a/helios/src/server/config.rs +++ b/helios/src/server/config.rs @@ -350,6 +350,11 @@ impl Bootstrap { .filter(|&value| value > 0) .ok_or("server configuration thinking_token_budget must be a positive 32-bit integer")) .transpose()?, + per_request_metrics: match object.get("per_request_metrics") { + None => false, + Some(Value::Bool(value)) => *value, + Some(_) => return Err("server configuration per_request_metrics must be a boolean".into()), + }, api_key: Some(optional_text("api_key")?).filter(|key| !key.is_empty()), served_names, context_hint: optional_text("context_hint")?, @@ -719,6 +724,19 @@ mod tests { let loaded = Bootstrap::load(&legacy.to_string(), &manifest).unwrap(); assert_eq!(loaded.frontend.prompt_encoder(), PromptEncoder::Jinja); assert_eq!(loaded.server.scheduling_policy.adaptive_verification_alpha, 1.0); + assert!(!loaded.server.per_request_metrics); + for (value, expected) in [(json!(true), true), (json!(false), false)] { + let mut configured = legacy.clone(); + configured["per_request_metrics"] = value; + let loaded = Bootstrap::load(&configured.to_string(), &manifest).unwrap(); + assert_eq!(loaded.server.per_request_metrics, expected); + } + for invalid in [json!(1), json!("true"), json!(null)] { + let mut configured = legacy.clone(); + configured["per_request_metrics"] = invalid; + assert!(Bootstrap::load(&configured.to_string(), &manifest).err().unwrap() + .to_string().contains("per_request_metrics")); + } for preference in ["balanced", "throughput"] { let mut configured = legacy.clone(); configured["scheduler_policy"] = preference.into(); diff --git a/helios/src/server/http.rs b/helios/src/server/http.rs index 83da35fbe..7cf843241 100644 --- a/helios/src/server/http.rs +++ b/helios/src/server/http.rs @@ -329,32 +329,6 @@ pub(super) async fn generate( state.run, state.ids.fetch_add(1, Ordering::Relaxed) ); - let submitted = if prompts.is_empty() { - Ok(vec![]) - } else if continuous_usage { - state.model.generate_many_observed(prompts, observation.timestamps) - } else if observation.token_ids && size == 1 { - state - .model - .generate_observed(prompts.remove(0), observation.timestamps) - .map(|g| vec![g]) - } else { - state.model.generate_many(prompts) - }; - let mut generation = match submitted { - Ok(g) => g, - Err(e) => return rejection(&state, protocol, &id, "admission", e), - }; - if !decoded.stream - && let Err(e) = runtime::await_admission(&mut generation).await - { - return rejection(&state, protocol, &id, "admission", e); - } - let enqueue_ns = generation.first().and_then(|g| g.enqueue_ns); - let mut iter = generation.into_iter(); - let mut generations: Vec> = (0..size) - .map(|i| if zero.contains(&i) { None } else { iter.next() }) - .collect(); let created = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default() @@ -384,6 +358,35 @@ pub(super) async fn generate( encoder.set_tool_grammars(tool_grammars); encoder.set_strict_validators(strict_validators); encoder.set_continuous_usage(continuous_usage); + // The encoder decides where per-request metrics appear, and so whether the + // generation must report its model steps' completion instants. + let commits = state.per_request_metrics && encoder.enable_request_metrics(decoded.stream); + let submitted = if prompts.is_empty() { + Ok(vec![]) + } else if continuous_usage { + state.model.generate_many_observed(prompts, Some(observation.timestamps), commits) + } else if observation.token_ids && size == 1 { + state + .model + .generate_observed(prompts.remove(0), observation.timestamps, commits) + .map(|g| vec![g]) + } else { + state.model.generate_many_observed(prompts, None, commits) + }; + let mut generation = match submitted { + Ok(g) => g, + Err(e) => return rejection(&state, protocol, &id, "admission", e), + }; + if !decoded.stream + && let Err(e) = runtime::await_admission(&mut generation).await + { + return rejection(&state, protocol, &id, "admission", e); + } + let enqueue_ns = generation.first().and_then(|g| g.enqueue_ns); + let mut iter = generation.into_iter(); + let mut generations: Vec> = (0..size) + .map(|i| if zero.contains(&i) { None } else { iter.next() }) + .collect(); let streaming = decoded.stream; let stream_state = state.clone(); let stream_id = id.clone(); @@ -520,16 +523,22 @@ pub(super) async fn generate( } Ok(vec![]) } + GenerationEvent::Committed { at_ns } => { + encoder.record_commit(at_ns); + Ok(vec![]) + } GenerationEvent::Finished { generated_tokens, reused_prompt_tokens, termination, stop_sequence, + arrival_ns, times, .. } => { reused_total += reused_prompt_tokens; first_scheduled_ns = times.first_scheduled_ns; + encoder.record_times(arrival_ns, times, 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)) @@ -603,6 +612,9 @@ pub(super) async fn generate( false, ); } + if !streaming && let Some(metrics) = encoder.metrics_value() { + response["metrics"] = metrics; + } // Choices the runtime cancelled after another choice reached the // parallel-tool-call limit are counted as cancelled there, so they enter no // response histogram. diff --git a/helios/src/server/protocol/encode.rs b/helios/src/server/protocol/encode.rs index 55754e4db..0eaf2d8f9 100644 --- a/helios/src/server/protocol/encode.rs +++ b/helios/src/server/protocol/encode.rs @@ -10,6 +10,7 @@ use crate::{ output::{Event, Termination}, server::{ inference::{Tool, ToolChoice}, + metrics::RequestTimes, output::{Accumulator, Block, Change, ResponseOutput}, }, }; @@ -65,6 +66,25 @@ pub(crate) struct PromptUsage { pub tokens: usize, pub image_tokens: usize, } +/// vLLM's per-request `metrics` for one response. +enum RequestMetrics { + /// The response holds several sequences, whose separate times cannot describe it. + Suppressed, + Single(Timing), +} +/// Instants of a response's one generation, on the `observation::monotonic_ns` clock. +#[derive(Default)] +struct Timing { + arrival_ns: u64, + times: RequestTimes, + generated: u32, + /// Only a stream reports when text content first appeared. + streaming: bool, + /// Completion of the latest model step whose output the encoder received. + step_ns: Option, + /// Completion of the model step whose output first produced text content. + content_ns: Option, +} pub(crate) struct Encoder { logprob_format: Option<(crate::server::inference::LogprobOptions, std::sync::Arc)>, logprob_entries: Vec>, @@ -100,6 +120,7 @@ pub(crate) struct Encoder { sequence: u64, metadata: Value, incomplete_item: Option, + metrics: Option, } impl Encoder { pub fn new( @@ -153,6 +174,7 @@ impl Encoder { sequence: 0, metadata, incomplete_item: None, + metrics: None, } } pub fn set_tool_grammars( @@ -215,6 +237,64 @@ impl Encoder { self.continuous_usage = self.include_usage && enabled; } + /// Report vLLM's per-request `metrics` where it places them: on the final usage + /// chunk of a Chat or Completions stream, on the terminal `response` of a + /// Responses stream, and at the top level of a JSON body. Messages and + /// multi-prompt Completions omit the object; several choices make it null. + /// Returns whether the content instant applies, which needs the generation's + /// `Committed` events. + pub fn enable_request_metrics(&mut self, streaming: bool) -> bool { + let placed = !streaming || self.include_usage || self.protocol == Protocol::Responses; + self.metrics = match self.protocol { + Protocol::Messages => None, + _ if !placed || self.prompts.len() > 1 => None, + _ if self.choices_per_prompt > 1 => Some(RequestMetrics::Suppressed), + _ => Some(RequestMetrics::Single(Timing { streaming, ..Timing::default() })), + }; + streaming && matches!(self.metrics, Some(RequestMetrics::Single(_))) + } + /// Record the completion instant of the model step whose output follows. + pub fn record_commit(&mut self, at_ns: u64) { + if let Some(RequestMetrics::Single(timing)) = &mut self.metrics + && timing.streaming + { + timing.step_ns = Some(at_ns); + } + } + /// Record the terminal instants and generated-token count of the generation. + pub fn record_times(&mut self, arrival_ns: u64, times: RequestTimes, generated: u32) { + if let Some(RequestMetrics::Single(timing)) = &mut self.metrics { + (timing.arrival_ns, timing.times, timing.generated) = (arrival_ns, times, generated); + } + } + /// The `metrics` object, `null` when suppressed, or `None` when omitted. Each + /// interval is null when the generation did not reach its instants. + pub fn metrics_value(&self) -> Option { + let timing = match self.metrics.as_ref()? { + RequestMetrics::Suppressed => return Some(Value::Null), + RequestMetrics::Single(timing) => timing, + }; + let ms = |from: u64, to: u64| to.saturating_sub(from) as f64 / 1e6; + let scheduled = timing.times.first_scheduled_ns; + let first = timing.times.first_token_ns; + let last = first.map(|_| timing.times.last_token_ns); + let generation = first.zip(last).map(|(first, last)| ms(first, last)); + Some(json!({ + "time_to_first_token_ms": scheduled.zip(first).map(|(s, f)| ms(s, f)), + "time_to_first_content_token_ms": scheduled.zip(timing.content_ns).map(|(s, c)| ms(s, c)), + "generation_time_ms": generation, + "queue_time_ms": scheduled.map(|s| ms(timing.arrival_ns, s)), + "mean_itl_ms": generation + .filter(|_| timing.generated > 1) + .map(|g| g / f64::from(timing.generated - 1)), + "tokens_per_second": scheduled + .zip(last) + .map(|(s, l)| l.saturating_sub(s)) + .filter(|ns| *ns > 0) + .map(|ns| f64::from(timing.generated) * 1e9 / ns as f64), + })) + } + /// Count raw generated tokens before text decoding can merge or hide them. pub fn observe_generated_token(&mut self, index: usize) { self.usage[index].generated += 1; @@ -465,6 +545,12 @@ impl Encoder { { continue; } + if let Event::Content(text) = &event + && !text.is_empty() + && let Some(RequestMetrics::Single(timing)) = &mut self.metrics + { + timing.content_ns = timing.content_ns.or(timing.step_ns); + } match &event { Event::TokenLogprobs(entries) => { if self.protocol != Protocol::Responses { @@ -655,6 +741,9 @@ impl Encoder { let mut frame = self.chunk(0, Value::Null, Value::Null); frame.data["choices"] = json!([]); frame.data["usage"] = self.usage_value(); + if let Some(metrics) = self.metrics_value() { + frame.data["metrics"] = metrics; + } frames.push(frame); } frames.push(Frame { @@ -669,7 +758,10 @@ impl Encoder { frames.push(self.named("message_stop", json!({}))); } Protocol::Responses => { - let response = self.response(); + let mut response = self.response(); + if let Some(metrics) = self.metrics_value() { + response["metrics"] = metrics; + } frames.push(self.named( if reason == "length" { "response.incomplete" diff --git a/helios/src/server/protocol/tests.rs b/helios/src/server/protocol/tests.rs index ead6a6cfa..48dd41dd8 100644 --- a/helios/src/server/protocol/tests.rs +++ b/helios/src/server/protocol/tests.rs @@ -2314,3 +2314,177 @@ fn strict_tool_wires_reach_encoder_only_after_parser_completion() { ); } } + +fn metered(protocol: Protocol, prompts: usize, choices: usize, include_usage: bool) -> Encoder { + Encoder::new( + protocol, + "metered".into(), + "model".into(), + 1, + choices, + vec![PromptUsage { tokens: 5, image_tokens: 0 }; prompts], + vec![], + ToolChoice::Auto, + true, + include_usage, + json!({}), + ) +} + +/// Feed one generation that reasons in its first committed step and answers in +/// its second, then finish it, returning every frame. +fn metered_generation(encoder: &mut Encoder, times: crate::server::metrics::RequestTimes) -> Vec { + let mut frames = encoder.start(); + encoder.record_commit(10_000_000); + frames.extend(encoder.apply(0, vec![Event::Reasoning("think".into())]).unwrap()); + encoder.record_commit(25_000_000); + frames.extend(encoder.apply(0, vec![Event::Content(String::new()), Event::Content("answer".into())]).unwrap()); + encoder.record_commit(40_000_000); + frames.extend(encoder.apply(0, vec![Event::Content(" more".into())]).unwrap()); + encoder.record_times(1_000_000, times, 4); + frames.extend(encoder.finish(0, Termination::Eos, 4, 0, None).unwrap()); + frames +} + +#[test] +fn per_request_metrics_follow_vllm_placement_and_null_rules() { + use crate::server::metrics::RequestTimes; + let times = RequestTimes { + first_scheduled_ns: Some(3_000_000), + first_token_ns: Some(10_000_000), + last_token_ns: 40_000_000, + }; + let expected = |content: Value| { + json!({ + "time_to_first_token_ms": 7.0, + "time_to_first_content_token_ms": content, + "generation_time_ms": 30.0, + "queue_time_ms": 2.0, + "mean_itl_ms": 10.0, + "tokens_per_second": 4e9 / 37e6, + }) + }; + let carriers = |frames: &[crate::server::protocol::Frame]| { + frames + .iter() + .filter_map(|frame| { + frame.data.get("metrics").or_else(|| frame.data.get("response")?.get("metrics")) + .map(|metrics| (frame.data.clone(), metrics.clone())) + }) + .collect::>() + }; + for protocol in [Protocol::Chat, Protocol::Completions, Protocol::Responses] { + // A stream reports the step that first produced text, after the reasoning + // step and skipping empty content, on its final usage chunk or terminal response. + let mut encoder = metered(protocol, 1, 1, true); + assert!(encoder.enable_request_metrics(true)); + let frames = metered_generation(&mut encoder, times); + let carried = carriers(&frames); + assert_eq!(carried.len(), 1, "{protocol:?}"); + let (frame, metrics) = &carried[0]; + assert_eq!(metrics, &expected(json!(22.0)), "{protocol:?}"); + if protocol == Protocol::Responses { + assert_eq!(frame["type"], "response.completed"); + } else { + assert_eq!(frame["choices"], json!([])); + assert!(frame["usage"].is_object()); + } + + // A JSON body has no content instant; `http::generate` places the object at + // the top level of the body built from `response`. + let mut encoder = metered(protocol, 1, 1, false); + assert!(!encoder.enable_request_metrics(false)); + let _ = metered_generation(&mut encoder, times); + assert!(encoder.response().get("metrics").is_none()); + assert_eq!(encoder.metrics_value(), Some(expected(Value::Null))); + } + + // Without usage reporting a Chat or Completions stream has no chunk to carry it. + for protocol in [Protocol::Chat, Protocol::Completions] { + let mut encoder = metered(protocol, 1, 1, false); + assert!(!encoder.enable_request_metrics(true)); + assert!(carriers(&metered_generation(&mut encoder, times)).is_empty()); + assert_eq!(encoder.metrics_value(), None); + } + + // Messages has no vLLM metrics, in a stream or a body. + for streaming in [false, true] { + let mut encoder = metered(Protocol::Messages, 1, 1, true); + assert!(!encoder.enable_request_metrics(streaming)); + assert!(carriers(&metered_generation(&mut encoder, times)).is_empty()); + assert_eq!(encoder.metrics_value(), None); + } + + // Several choices of one prompt make the object null; several prompts omit it. + for (prompts, choices, metrics) in [(1, 2, Some(Value::Null)), (2, 1, None)] { + for streaming in [false, true] { + let mut encoder = metered(Protocol::Completions, prompts, choices, true); + assert!(!encoder.enable_request_metrics(streaming)); + let mut frames = Vec::new(); + for index in 0..prompts * choices { + encoder.record_times(1_000_000, times, 4); + frames.extend(encoder.finish(index, Termination::Eos, 4, 0, None).unwrap()); + } + let usage = frames.iter().find(|frame| frame.data["choices"] == json!([])).unwrap(); + assert_eq!(usage.data.get("metrics").cloned(), metrics.clone()); + assert_eq!(encoder.metrics_value(), metrics); + } + } + + // Instants the generation did not reach are null: a single token has no + // inter-token interval, and a choice that recorded no times has none at all. + let mut encoder = metered(Protocol::Chat, 1, 1, true); + encoder.enable_request_metrics(false); + encoder.record_times( + 1_000_000, + RequestTimes { last_token_ns: 10_000_000, ..times }, + 1, + ); + let single = encoder.metrics_value().unwrap(); + assert_eq!(single["mean_itl_ms"], Value::Null); + assert_eq!(single["generation_time_ms"], 0.0); + assert_eq!(single["tokens_per_second"], 1e9 / 7e6); + let mut encoder = metered(Protocol::Chat, 1, 1, true); + encoder.enable_request_metrics(false); + let _ = encoder.finish(0, Termination::OutputLimit, 0, 0, None).unwrap(); + let unrecorded = encoder.metrics_value().unwrap(); + assert_eq!(unrecorded.as_object().unwrap().len(), 6); + assert!(unrecorded.as_object().unwrap().values().all(Value::is_null)); +} + +#[test] +fn content_instant_excludes_reasoning_tool_calls_and_suppressed_text() { + // Reasoning and a tool call commit first; the first text arrives in a later step. + let mut encoder = metered(Protocol::Chat, 1, 1, true); + assert!(encoder.enable_request_metrics(true)); + encoder.record_commit(5_000_000); + encoder.apply(0, vec![Event::Reasoning("r".into())]).unwrap(); + encoder.record_commit(6_000_000); + let mut call = events(); + call.retain(|event| !matches!(event, Event::Reasoning(_) | Event::Content(_))); + encoder.apply(0, call).unwrap(); + encoder.record_commit(9_000_000); + encoder.apply(0, vec![Event::Content("text".into())]).unwrap(); + encoder.record_times(0, crate::server::metrics::RequestTimes { + first_scheduled_ns: Some(1_000_000), + first_token_ns: Some(5_000_000), + last_token_ns: 9_000_000, + }, 3); + let metrics = encoder.metrics_value().unwrap(); + assert_eq!(metrics["time_to_first_token_ms"], 4.0); + assert_eq!(metrics["time_to_first_content_token_ms"], 8.0); + + // A named tool choice drops answer text, so no text content is produced. + let mut encoder = Encoder::new(Protocol::Chat, "named".into(), "model".into(), 1, 1, + vec![PromptUsage { tokens: 5, image_tokens: 0 }], tools(), + ToolChoice::Named("lookup".into()), true, true, json!({})); + assert!(encoder.enable_request_metrics(true)); + encoder.record_commit(5_000_000); + encoder.apply(0, events()).unwrap(); + encoder.record_times(0, crate::server::metrics::RequestTimes { + first_scheduled_ns: Some(1_000_000), + first_token_ns: Some(5_000_000), + last_token_ns: 5_000_000, + }, 1); + assert_eq!(encoder.metrics_value().unwrap()["time_to_first_content_token_ms"], Value::Null); +} diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index 2c91ebbc3..b8aaba3d4 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -59,15 +59,17 @@ impl Prompt { !self.stop_sequences.is_empty() || !self.stop_strings.is_empty() } - fn output_event_capacity(&self, minimum: usize, observed: bool) -> Result { - // Each generated token produces at most one presentation event and one - // optional observation. A reasoning cut's forced token is part of `after`. + fn output_event_capacity(&self, minimum: usize, observed: bool, commits: bool) -> Result { + // Each generated token produces at most one presentation event, one + // optional observation, and one optional commit instant, because every + // step that reports a commit instant generated at least one token. + // A reasoning cut's forced token is part of `after`. // Prompt-score chunks cover disjoint, nonempty ranges of the original prompt. let tokens = u64::from(self.max_new_tokens) + u64::from(self.reasoning_cut.as_ref().map_or(0, |cut| cut.after)); let events = usize::try_from(tokens) .ok() - .and_then(|tokens| tokens.checked_mul(if observed { 2 } else { 1 })) + .and_then(|tokens| tokens.checked_mul(1 + usize::from(observed) + usize::from(commits))) .and_then(|events| { events.checked_add(if self.prompt_logprobs { self.tokens.len() } else { 0 }) }) @@ -99,9 +101,17 @@ pub enum GenerationEvent { reason: &'static str, termination: crate::output::Termination, stop_sequence: Option, + /// Model-queue arrival on the `observation::monotonic_ns` clock. + arrival_ns: u64, /// The request's lifecycle instants, as its completion histograms record them. times: super::metrics::RequestTimes, }, + /// The completion instant of the model step whose output events follow, on the + /// `observation::monotonic_ns` clock. Sent only to requests submitted with + /// `commits`, once per step that generated a token for the request. + Committed { + at_ns: u64, + }, AdmissionRejected(Error), Error(Error), } @@ -192,6 +202,8 @@ struct Incoming { failure: Arc>>, metrics: Arc, observation: Option, + /// Send `GenerationEvent::Committed` before each model step's output. + commits: bool, /// 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. @@ -300,7 +312,8 @@ impl Incoming { reason: "stop", termination: crate::output::Termination::Cancelled, stop_sequence: None, - times: self.times, + arrival_ns: self.arrival_ns, + times: self.record.times, }); } @@ -828,30 +841,38 @@ impl ModelRuntime { self.healthy() } pub fn generate(&self, prompt: Prompt) -> Result { - self.enqueue(prompt, None) + self.enqueue(prompt, None, false) } - pub(super) fn generate_observed(&self, prompt: Prompt, timestamps: bool) -> Result { - self.enqueue(prompt, Some(timestamps)) + pub(super) fn generate_observed(&self, prompt: Prompt, timestamps: bool, commits: bool) -> Result { + self.enqueue(prompt, Some(timestamps), commits) } - fn enqueue(&self, prompt: Prompt, observation: Option) -> Result { - self.enqueue_many(vec![prompt], observation) + fn enqueue(&self, prompt: Prompt, observation: Option, commits: bool) -> Result { + self.enqueue_many(vec![prompt], observation, commits) .map(|mut group| group.remove(0)) } pub fn generate_many(&self, prompts: Vec) -> Result> { - self.enqueue_many(prompts, None) + self.enqueue_many(prompts, None, false) } - pub(super) fn generate_many_observed(&self, prompts: Vec, timestamps: bool) -> Result> { - self.enqueue_many(prompts, Some(timestamps)) + /// `observation` adds an `ObservedToken` per committed token, timestamped when + /// `Some(true)`; `commits` adds a `Committed` event before each model step's output. + pub(super) fn generate_many_observed( + &self, + prompts: Vec, + observation: Option, + commits: bool, + ) -> Result> { + self.enqueue_many(prompts, observation, commits) } fn enqueue_many( &self, prompts: Vec, observation: Option, + commits: bool, ) -> Result> { if !self.healthy() { return Err(Error::admission( @@ -896,7 +917,7 @@ impl ModelRuntime { .map_err(|error| error.admission_context(AdmissionError::Invalid))?; // Tokio allocates queue blocks as events arrive, not at this capacity. let event_capacity = - prompt.output_event_capacity(self.event_capacity, observation.is_some())?; + prompt.output_event_capacity(self.event_capacity, observation.is_some(), commits)?; let (events, receiver) = async_mpsc::channel(event_capacity); let (admission, admitted) = oneshot::channel(); let (first_token, first_token_ready) = oneshot::channel(); @@ -916,6 +937,7 @@ impl ModelRuntime { failure: failure.clone(), metrics: self.metrics.clone(), observation, + commits, record: Default::default(), host_lookup: true, readmitted: false, @@ -1796,6 +1818,9 @@ impl<'a> Worker<'a> { // speculative round, adds one inter-token interval. if position == 0 { request.incoming.record.tokens_committed(completed_at_ns); + if request.incoming.commits { + request.incoming.emit(GenerationEvent::Committed { at_ns: completed_at_ns }); + } } request.incoming.observe_token(token.token); request.last_token = Some(token.token); @@ -1888,7 +1913,8 @@ impl<'a> Worker<'a> { .text_stops .as_ref() .and_then(|s| s.matched().map(str::to_owned)), - times: request.incoming.times, + arrival_ns: request.incoming.arrival_ns, + times: request.incoming.record.times, }); stopped.push(token.request); } @@ -2066,7 +2092,8 @@ impl<'a> Worker<'a> { } else { crate::output::Termination::OutputLimit }, - times: request.incoming.times, + arrival_ns: request.incoming.arrival_ns, + times: request.incoming.record.times, }); if user_stop { self.scheduler.cancel(request.request)?; @@ -3283,6 +3310,7 @@ mod tests { failure: failure.clone(), metrics: Arc::new(super::super::metrics::Metrics::new(0, 0, 0, 16)), observation: None, + commits: false, record: Default::default(), host_lookup: true, readmitted: false, @@ -3314,15 +3342,17 @@ mod tests { let (mut incoming, _generation) = stream(2); let prompt = &mut incoming.prompt; prompt.max_new_tokens = 1_000_000; - assert_eq!(prompt.output_event_capacity(128, false).unwrap(), 1_000_003); - assert_eq!(prompt.output_event_capacity(128, true).unwrap(), 2_000_003); + assert_eq!(prompt.output_event_capacity(128, false, false).unwrap(), 1_000_003); + assert_eq!(prompt.output_event_capacity(128, true, false).unwrap(), 2_000_003); + assert_eq!(prompt.output_event_capacity(128, false, true).unwrap(), 2_000_003); + assert_eq!(prompt.output_event_capacity(128, true, true).unwrap(), 3_000_003); prompt.reasoning_cut = Some(ReasoningCut { close: 8, after: 20, output: None }); prompt.prompt_logprobs = true; - assert_eq!(prompt.output_event_capacity(128, true).unwrap(), 2_000_044); + assert_eq!(prompt.output_event_capacity(128, true, false).unwrap(), 2_000_044); prompt.max_new_tokens = 0; prompt.reasoning_cut = None; - assert_eq!(prompt.output_event_capacity(128, false).unwrap(), 128); - assert!(prompt.output_event_capacity(usize::MAX, true).is_err()); + assert_eq!(prompt.output_event_capacity(128, false, false).unwrap(), 128); + assert!(prompt.output_event_capacity(usize::MAX, true, false).is_err()); } #[test] diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 5197ce5cd..6988c0e36 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -252,6 +252,7 @@ impl Fixture { failure: failure.clone(), metrics: self.metrics.clone(), observation: Some(false), + commits: false, record: Default::default(), host_lookup: true, readmitted: false, @@ -3745,7 +3746,7 @@ fn unread_responses_finish_and_release_model_resources_but_retain_admission_capa let mut slow_prompt = prompt(512); slow_prompt.logprobs = logprobs; slow_prompt.stop_sequences = vec![vec![2, 3]]; - let mut slow = runtime.generate_observed(slow_prompt, true).unwrap(); + let mut slow = runtime.generate_observed(slow_prompt, true, false).unwrap(); let mut worker = fixture.worker(receiver); assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); let mut tokens = vec![1; 512]; @@ -3799,7 +3800,7 @@ fn unread_response_keeps_its_budget_through_a_reasoning_continuation() { positions: vec![[0; 3]], vision_token_indices: vec![-1], ..Default::default() }); prompt.reasoning_cut = Some(budget_cut(4, 81)); - let mut generation = runtime.generate_observed(prompt, false).unwrap(); + let mut generation = runtime.generate_observed(prompt, false, false).unwrap(); let mut worker = fixture.worker(receiver); assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); let mut sequence = 0; @@ -4312,6 +4313,7 @@ fn http_state_for( ids: Default::default(), api_key, thinking_token_budget: None, + per_request_metrics: false, context_hint: String::new(), capacity_hint: String::new(), response_model, @@ -4558,16 +4560,19 @@ fn timed_pass(worker: &mut Worker<'_>, samples: &[u32]) -> Vec { } /// Serve one HTTP request through a worker that `timed_pass` drives, returning the -/// step bounds and the JSON body, or the SSE `data` payloads of a stream. +/// step bounds, the JSON body or the SSE `data` payloads of a stream, and whether +/// the request asked the worker for commit instants. async fn served_through_worker( fixture: fn() -> Fixture, + per_request_metrics: bool, path: &str, body: serde_json::Value, samples: &[u32], -) -> (Vec, Vec) { +) -> (Vec, Vec, bool) { use axum::{Extension, extract::State}; let (sender, receiver) = mpsc::sync_channel(4); - let state = http_state_for(fixture(), sender, None, &[]); + let mut state = http_state_for(fixture(), sender, None, &[]); + Arc::get_mut(&mut state).unwrap().per_request_metrics = per_request_metrics; let stream = body["stream"] == true; let ingress = Arc::new(state.ingress_slots.clone().acquire_owned().await.unwrap()); let request = axum::http::Request::builder() @@ -4582,6 +4587,7 @@ async fn served_through_worker( }) .await .unwrap(); + let commits = group[0].commits; let steps = { let worker_fixture = fixture(); let (queue, inbound) = mpsc::channel(); @@ -4603,15 +4609,16 @@ async fn served_through_worker( } else { vec![serde_json::from_slice(&bytes).unwrap()] }; - (steps, values) + (steps, values, commits) } #[tokio::test] async fn performance_reports_the_first_scheduled_model_step() { use serde_json::json; for stream in [false, true] { - let (steps, values) = served_through_worker( + let (steps, values, _) = served_through_worker( || Fixture::new().text_inputs(), + false, "/v1/chat/completions", json!({"model":"qwen-worker-phases","messages":[{"role":"user","content":"a"}], "max_tokens":2,"stream":stream,"return_token_ids":true,"return_token_timestamps":true}), @@ -4639,6 +4646,231 @@ async fn performance_reports_the_first_scheduled_model_step() { } } +/// Absolute instants of a served response: `performance` supplies the first +/// scheduled step and the `metrics` intervals the others. +struct Served { + arrival_ns: u64, + scheduled_ns: u64, + first_ns: u64, + content_ns: Option, + last_ns: u64, +} + +fn served_instants(values: &[serde_json::Value]) -> (serde_json::Value, Served) { + let metrics = values + .iter() + .find_map(|value| value.get("metrics")) + .expect("response carries metrics") + .clone(); + let performance = &values + .iter() + .find(|value| value.get("performance").is_some()) + .unwrap()["performance"]; + let scheduled_ns = performance["first_scheduled_ns"].as_u64().unwrap(); + let after = |field: &str| { + metrics[field].as_f64().map(|ms| scheduled_ns + (ms * 1e6).round() as u64) + }; + let first_ns = after("time_to_first_token_ms").unwrap(); + let served = Served { + arrival_ns: scheduled_ns - (metrics["queue_time_ms"].as_f64().unwrap() * 1e6).round() as u64, + scheduled_ns, + first_ns, + content_ns: after("time_to_first_content_token_ms"), + last_ns: first_ns + (metrics["generation_time_ms"].as_f64().unwrap() * 1e6).round() as u64, + }; + // The HTTP ingress precedes model-queue arrival, which precedes enqueue_ns. + assert!(performance["ingress_ns"].as_u64().unwrap() <= served.arrival_ns); + assert!(served.arrival_ns <= performance["enqueue_ns"].as_u64().unwrap() + 1); + (metrics, served) +} + +fn within(step: &StepBounds, instant: u64) -> bool { + // One nanosecond absorbs rounding through the millisecond fields. + step.start_ns <= instant + 1 && instant <= step.end_ns + 1 +} + +#[tokio::test] +async fn per_request_metrics_report_the_runtime_instants_of_a_stopped_reasoning_answer() { + use serde_json::{Value, json}; + let fixture = Fixture::reasoning(); + let token = |text| fixture.frontend.tokenizer().token_to_id(text).unwrap(); + // Reasoning, its close, the first answer text, then the stop string. + let samples = [token("b"), token(""), token("c"), token("d")]; + for stream in [true, false] { + let (steps, values, commits) = served_through_worker( + Fixture::reasoning, + true, + "/v1/chat/completions", + json!({"model":"qwen-worker-phases","messages":[{"role":"user","content":"a"}], + "add_generation_prompt":true,"max_tokens":8,"stop":["d"],"stream":stream, + "stream_options":if stream { json!({"include_usage":true}) } else { Value::Null }, + "return_token_ids":true,"return_token_timestamps":true}), + &samples, + ) + .await; + assert_eq!(commits, stream); + let carriers: Vec<_> = values.iter().filter(|value| value.get("metrics").is_some()).collect(); + assert_eq!(carriers.len(), 1); + if stream { + assert_eq!(carriers[0]["choices"], json!([])); + let content: String = values.iter() + .filter_map(|value| value["choices"][0]["delta"]["content"].as_str()).collect(); + assert_eq!(content, "c"); + } else { + assert_eq!(values[0]["choices"][0]["message"]["content"], "c"); + } + assert_eq!(carriers[0]["usage"]["completion_tokens"], 4); + let (metrics, served) = served_instants(&values); + let generating: Vec<_> = steps.iter().filter(|step| step.generated).collect(); + assert_eq!(generating.len(), 4); + // Every instant falls inside the worker step that produced it, not in HTTP + // rendering, which runs after the last step. + assert!(within(&steps[0], served.scheduled_ns)); + assert!(within(generating[0], served.first_ns)); + assert!(within(generating[3], served.last_ns)); + if stream { + // Reasoning and its close precede the first answer text by two steps. + assert!(within(generating[2], served.content_ns.unwrap())); + assert!(metrics["time_to_first_content_token_ms"].as_f64() > metrics["time_to_first_token_ms"].as_f64()); + } else { + assert_eq!(served.content_ns, None); + } + let ms = |ns: u64| ns as f64 / 1e6; + assert!((metrics["mean_itl_ms"].as_f64().unwrap() - ms(served.last_ns - served.first_ns) / 3.0).abs() < 1e-5); + assert!((metrics["tokens_per_second"].as_f64().unwrap() * ms(served.last_ns - served.scheduled_ns) / 1e3 - 4.0).abs() < 1e-6); + assert!(served.arrival_ns <= served.scheduled_ns); + } +} + +#[tokio::test] +async fn per_request_metrics_reach_completions_and_responses_where_vllm_places_them() { + use serde_json::{Value, json}; + for (path, mut body) in [ + ("/v1/completions", json!({"prompt":"a","max_tokens":2})), + ("/v1/responses", json!({"input":"a","max_output_tokens":2})), + ] { + for stream in [false, true] { + body["model"] = json!("qwen-worker-phases"); + body["stream"] = json!(stream); + if path == "/v1/completions" && stream { + body["stream_options"] = json!({"include_usage":true}); + } + let (steps, values, commits) = served_through_worker( + || Fixture::new().text_inputs(), + true, + path, + body.clone(), + &[1, 2], + ) + .await; + assert_eq!(commits, stream); + let carriers: Vec<(&Value, &Value)> = values + .iter() + .filter_map(|value| { + let metrics = value.get("metrics") + .or_else(|| value.get("response")?.get("metrics"))?; + Some((value, metrics)) + }) + .collect(); + assert_eq!(carriers.len(), 1, "{path} {stream}"); + let (carrier, metrics) = carriers[0]; + match (path, stream) { + ("/v1/completions", true) => assert_eq!(carrier["choices"], json!([])), + // Two tokens reach the output limit, so the stream ends incomplete. + ("/v1/responses", true) => assert_eq!(carrier["type"], "response.incomplete"), + _ => assert!(carrier.get("metrics").is_some()), + } + let generating: Vec<_> = steps.iter().filter(|step| step.generated).collect(); + let ttft = metrics["time_to_first_token_ms"].as_f64().unwrap(); + let generation = metrics["generation_time_ms"].as_f64().unwrap(); + // The two tokens commit in different steps, at least one pause apart. + assert!(generation >= 3.0 && generation * 1e6 <= (generating[1].end_ns - generating[0].start_ns) as f64); + assert!(ttft >= 0.0 && metrics["queue_time_ms"].as_f64().unwrap() >= 0.0); + assert_eq!(metrics["mean_itl_ms"], metrics["generation_time_ms"]); + // Plain text is content from the first token. + assert_eq!( + metrics["time_to_first_content_token_ms"], + if stream { metrics["time_to_first_token_ms"].clone() } else { Value::Null } + ); + } + } +} + +#[tokio::test] +async fn per_request_metrics_are_absent_without_the_option_and_null_for_several_choices() { + use serde_json::{Value, json}; + for stream in [false, true] { + let (_, values, commits) = served_through_worker( + || Fixture::new().text_inputs(), + false, + "/v1/completions", + json!({"model":"qwen-worker-phases","prompt":"a","max_tokens":2,"stream":stream, + "stream_options":if stream { json!({"include_usage":true}) } else { Value::Null }}), + &[1, 2], + ) + .await; + assert!(!commits); + assert!(values.iter().all(|value| value.get("metrics").is_none())); + assert!(values.iter().any(|value| value["usage"]["completion_tokens"] == 2)); + } + for stream in [false, true] { + let (sender, receiver) = mpsc::sync_channel(4); + let mut state = http_state_for(Fixture::new(), sender, None, &[]); + Arc::get_mut(&mut state).unwrap().per_request_metrics = true; + let ingress = Arc::new(state.ingress_slots.clone().acquire_owned().await.unwrap()); + let body = json!({"model":"qwen-worker-phases","prompt":"a","max_tokens":1,"n":2, + "stream":stream,"stream_options":if stream { json!({"include_usage":true}) } else { Value::Null }}); + let request = axum::http::Request::builder() + .method("POST") + .uri("/v1/completions") + .header("content-type", "application/json") + .body(axum::body::Body::from(body.to_string())) + .unwrap(); + let response = tokio::spawn(super::super::http::generate( + axum::extract::State(state), + axum::Extension(ingress), + request, + )); + let group = tokio::task::spawn_blocking(move || { + receiver.recv_timeout(std::time::Duration::from_secs(5)).unwrap() + }) + .await + .unwrap(); + assert!(group.iter().all(|incoming| !incoming.commits)); + for incoming in &group { + incoming.notify_admission(Ok(())); + incoming.observe_token(1); + incoming.emit_token(1); + incoming.emit(GenerationEvent::Finished { + prompt_tokens: incoming.prompt.tokens.len(), + generated_tokens: 1, + reused_prompt_tokens: 0, + reason: "length", + termination: crate::output::Termination::OutputLimit, + stop_sequence: None, + arrival_ns: 1, + times: crate::server::metrics::RequestTimes { + first_scheduled_ns: Some(2), + first_token_ns: Some(3), + last_token_ns: 3, + }, + }); + } + let bytes = axum::body::to_bytes(response.await.unwrap().into_body(), 1 << 20).await.unwrap(); + let carrier: serde_json::Value = if stream { + std::str::from_utf8(&bytes).unwrap().lines() + .filter_map(|line| line.strip_prefix("data: ")) + .filter_map(|line| serde_json::from_str::(line).ok()) + .find(|value| value["choices"] == json!([])) + .unwrap() + } else { + serde_json::from_slice(&bytes).unwrap() + }; + assert_eq!(carrier.get("metrics"), Some(&Value::Null)); + assert_eq!(carrier["usage"]["completion_tokens"], 2); + } +} + #[tokio::test] async fn first_response_http_stream_excludes_pretext_failures_and_unpolled_bodies() { for (emit_text, poll_body) in [(false, true), (true, false), (true, true)] { @@ -4683,7 +4915,7 @@ async fn first_response_http_nonstream_records_only_when_completed_body_is_offer incoming[0].emit(GenerationEvent::Finished { prompt_tokens: incoming[0].prompt.tokens.len(), generated_tokens: 1, reused_prompt_tokens: 0, reason: "length", stop_sequence: None, - termination: crate::output::Termination::OutputLimit, times: Default::default(), + termination: crate::output::Termination::OutputLimit, arrival_ns: 0, times: Default::default(), }); let response = response.await.unwrap(); assert_eq!(state.first_response.snapshot().samples, 0); @@ -4727,7 +4959,7 @@ async fn unread_http_stream_preserves_all_tokens_and_its_terminal_event() { incoming[0].emit(GenerationEvent::Finished { prompt_tokens: incoming[0].prompt.tokens.len(), generated_tokens: 100, reused_prompt_tokens: 0, reason: "length", stop_sequence: None, - termination: crate::output::Termination::OutputLimit, times: Default::default(), + termination: crate::output::Termination::OutputLimit, arrival_ns: 0, times: Default::default(), }); } assert!(!incoming[0].cancelled.load(Ordering::Acquire)); @@ -4957,6 +5189,7 @@ async fn paused_http_bodies_preserve_output_and_completion_for_every_protocol() reason: "length", termination: crate::output::Termination::OutputLimit, stop_sequence: None, + arrival_ns: 0, times: Default::default(), }); assert!(!incoming.cancelled.load(Ordering::Acquire)); @@ -5178,7 +5411,7 @@ async fn responses_carry_the_first_non_empty_served_name() { incoming[0].emit(GenerationEvent::Finished { prompt_tokens: incoming[0].prompt.tokens.len(), generated_tokens: 1, reused_prompt_tokens: 0, reason: "stop", stop_sequence: None, - termination: crate::output::Termination::OutputLimit, times: Default::default(), + termination: crate::output::Termination::OutputLimit, arrival_ns: 0, times: Default::default(), }); let bytes = axum::body::to_bytes(response.into_body(), 131072).await.unwrap(); let body = std::str::from_utf8(&bytes).unwrap(); @@ -5208,7 +5441,7 @@ async fn responses_carry_the_first_non_empty_served_name() { incoming[0].emit(GenerationEvent::Finished { prompt_tokens: incoming[0].prompt.tokens.len(), generated_tokens: 1, reused_prompt_tokens: 0, reason: "length", stop_sequence: None, - termination: crate::output::Termination::OutputLimit, times: Default::default(), + termination: crate::output::Termination::OutputLimit, arrival_ns: 0, times: Default::default(), }); let response = response.await.unwrap(); let bytes = axum::body::to_bytes(response.into_body(), 65536).await.unwrap(); @@ -5226,7 +5459,7 @@ async fn responses_carry_the_first_non_empty_served_name() { incoming[0].emit(GenerationEvent::Finished { prompt_tokens: incoming[0].prompt.tokens.len(), generated_tokens: 1, reused_prompt_tokens: 0, reason: "length", stop_sequence: None, - termination: crate::output::Termination::OutputLimit, times: Default::default(), + termination: crate::output::Termination::OutputLimit, arrival_ns: 0, times: Default::default(), }); let response = response.await.unwrap(); let bytes = axum::body::to_bytes(response.into_body(), 65536).await.unwrap(); diff --git a/helios/src/server/runtime/response_lifecycle_tests.rs b/helios/src/server/runtime/response_lifecycle_tests.rs index dba308cda..932712aa2 100644 --- a/helios/src/server/runtime/response_lifecycle_tests.rs +++ b/helios/src/server/runtime/response_lifecycle_tests.rs @@ -159,6 +159,7 @@ impl Responses { reason: "length", stop_sequence: None, termination: crate::output::Termination::OutputLimit, + arrival_ns: 0, times: Default::default(), }); row.sent += 1; @@ -377,6 +378,7 @@ async fn terminal_stream_frames_retain_http_admission_after_native_retirement() reason: "length", stop_sequence: None, termination: crate::output::Termination::OutputLimit, + arrival_ns: 0, times: Default::default(), }); drop(incoming); From 65116f5f4b7d228056343613fd90ef0c2e030445 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 21:54:15 -0600 Subject: [PATCH 16/24] Report the content-token instant of per-request metrics as null vLLM's per-request `metrics` object includes `time_to_first_content_token_ms`, the time from the first scheduled step to the step whose output first produced answer text. Only the HTTP decoder can recognize answer text, so measuring it needs the worker to send the completion instant of every generating model step to the stream, adding one runtime event per step and a third term to the response event budget. The other five fields come from instants the worker already places on each request's terminal event. vLLM documents the field as null when a server cannot provide it, so the object stays complete without the per-step events. `time_to_first_content_token_ms` is always null. `GenerationEvent::Committed`, the `commits` admission flag, the commit term of `output_event_capacity`, and the encoder's step and content instants are removed; the admission entry points and the HTTP handler's submission order are those the server had without per-request metrics. `docs/api.md` defines the field as always null, and `helios/model-contract.md` states the event budget without a commit term. With `--enable-per-request-metrics`, OpenAI output carries the same `metrics` object as before except that the content field is null in streams as well as JSON bodies; the worker sends no event beyond the terminal one for metrics. Evidence: `server::protocol::tests::per_request_metrics_follow_vllm_placement_and_null_rules` checks the placement and the null content field for every protocol, and `per_request_metrics_report_the_runtime_instants_of_a_stopped_reasoning_answer` and `per_request_metrics_reach_completions_and_responses_where_vllm_places_them` check through a worker driven step by step that streams and JSON bodies report a null content field while the other instants fall inside the steps that produced them. `cargo test --locked --manifest-path helios/Cargo.toml --features runtime-core,server --lib -- server:: scheduler:: cache::` passed 819 tests at the head of the series this commit belongs to; the one failure, `messages_image_hints_end_after_expansion_for_text_and_segmented_templates`, needs templates from `tests/frontend/prepare_templates.py` through `FLARE_TEST_TEMPLATE_DIR`, which this host does not have. No GPU or live server was used. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=eb2f --- docs/api.md | 28 +++----- helios/model-contract.md | 6 +- helios/src/server/http.rs | 60 ++++++++--------- helios/src/server/protocol/encode.rs | 32 ++------- helios/src/server/protocol/tests.rs | 83 ++++++------------------ helios/src/server/runtime.rs | 61 +++++------------ helios/src/server/runtime/phase_tests.rs | 46 ++++--------- 7 files changed, 95 insertions(+), 221 deletions(-) diff --git a/docs/api.md b/docs/api.md index 96019532d..15a111083 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1005,17 +1005,13 @@ string, which the worker matches, does not change how they are measured: | --- | --- | | `queue_time_ms` | Model-scheduler arrival to the first model step that includes the request | | `time_to_first_token_ms` | That first scheduled step to the completion of the step that committed the first generated token | -| `time_to_first_content_token_ms` | Streams only: the first scheduled step to the completion of the step whose output first produced non-empty answer text | +| `time_to_first_content_token_ms` | Always null: Flare does not report when answer text first appeared, as vLLM permits for a value it cannot provide | | `generation_time_ms` | First to last committed generated token | | `mean_itl_ms` | `generation_time_ms` divided by the generated tokens after the first | | `tokens_per_second` | Generated tokens, as `usage` counts them, over the first scheduled step to the last committed generated token | A step's completion instant is read once when the worker processes that step's -results, so tokens committed by one speculative step share it. Reasoning text, -tool-call output, and answer text that a named tool choice discards do not count -as content; text that stop-string matching holds back counts from the step whose -output releases it. `time_to_first_content_token_ms` equals -`time_to_first_token_ms` when the first generated step produces answer text. +results, so tokens committed by one speculative step share it. A JSON body carries `metrics` at the top level. A Chat or Completions stream carries it only on the final usage chunk, whose `choices` is empty, so the stream @@ -1025,18 +1021,14 @@ carries it. A Responses stream carries it in the `response` object of requests always run one generation, so every Responses output carries it. Every field is present and is null when the request did not reach the instants -it spans: `time_to_first_content_token_ms` is null in JSON bodies and in streams -that produced no answer text, `mean_itl_ms` is null for a single generated token, -the token fields are null when nothing was generated, and every field is null for -a choice that never reached a model step. With `n` greater than one, `metrics` is -null, because one choice's instants do not describe the response. Completions -with several prompts omit `metrics`. Failed requests return error bodies without -it. - -The option adds no clock reads. A stream that reports -`time_to_first_content_token_ms` receives one additional runtime event per model -step that generated a token for it, carrying that step's completion instant; -other requests receive only the instants on their terminal event. Chat token +it spans: `mean_itl_ms` is null for a single generated token, the token fields +are null when nothing was generated, and every field is null for a choice that +never reached a model step. With `n` greater than one, `metrics` is null, +because one choice's instants do not describe the response. Completions with +several prompts omit `metrics`. Failed requests return error bodies without it. + +The option adds no clock reads: the encoder reads the instants on each +request's terminal event. Chat token observation reports the same first scheduled step as `performance.first_scheduled_ns`, beside per-token timestamps; the [prepared model contract](../helios/model-contract.md#token-and-timing-observation) diff --git a/helios/model-contract.md b/helios/model-contract.md index f81db52da..668ad289e 100644 --- a/helios/model-contract.md +++ b/helios/model-contract.md @@ -359,10 +359,8 @@ its time to first token. observed stream includes usage on its terminal choice chunk. Observation flags and `include_usage` accept only booleans or null; null is equivalent to false. The response event budget includes one observation per generated token when -requested, in addition to presentation events, and one model-step completion -instant per generated token for a stream that reports -[per-request metrics](../docs/api.md#per-request-metrics) with a content instant. -Observation changes no CUDA graph, device allocation or replay ABI. +requested, in addition to presentation events. Observation changes no CUDA +graph, device allocation or replay ABI. `stop_token_ids` and `stop_token_sequences` accept explicit vocabulary IDs. At most sixteen sequences of at most 64 tokens are supported. Matching tokens diff --git a/helios/src/server/http.rs b/helios/src/server/http.rs index 7cf843241..1dfcfbe12 100644 --- a/helios/src/server/http.rs +++ b/helios/src/server/http.rs @@ -329,6 +329,32 @@ pub(super) async fn generate( state.run, state.ids.fetch_add(1, Ordering::Relaxed) ); + let submitted = if prompts.is_empty() { + Ok(vec![]) + } else if continuous_usage { + state.model.generate_many_observed(prompts, observation.timestamps) + } else if observation.token_ids && size == 1 { + state + .model + .generate_observed(prompts.remove(0), observation.timestamps) + .map(|g| vec![g]) + } else { + state.model.generate_many(prompts) + }; + let mut generation = match submitted { + Ok(g) => g, + Err(e) => return rejection(&state, protocol, &id, "admission", e), + }; + if !decoded.stream + && let Err(e) = runtime::await_admission(&mut generation).await + { + return rejection(&state, protocol, &id, "admission", e); + } + let enqueue_ns = generation.first().and_then(|g| g.enqueue_ns); + let mut iter = generation.into_iter(); + let mut generations: Vec> = (0..size) + .map(|i| if zero.contains(&i) { None } else { iter.next() }) + .collect(); let created = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default() @@ -358,35 +384,9 @@ pub(super) async fn generate( encoder.set_tool_grammars(tool_grammars); encoder.set_strict_validators(strict_validators); encoder.set_continuous_usage(continuous_usage); - // The encoder decides where per-request metrics appear, and so whether the - // generation must report its model steps' completion instants. - let commits = state.per_request_metrics && encoder.enable_request_metrics(decoded.stream); - let submitted = if prompts.is_empty() { - Ok(vec![]) - } else if continuous_usage { - state.model.generate_many_observed(prompts, Some(observation.timestamps), commits) - } else if observation.token_ids && size == 1 { - state - .model - .generate_observed(prompts.remove(0), observation.timestamps, commits) - .map(|g| vec![g]) - } else { - state.model.generate_many_observed(prompts, None, commits) - }; - let mut generation = match submitted { - Ok(g) => g, - Err(e) => return rejection(&state, protocol, &id, "admission", e), - }; - if !decoded.stream - && let Err(e) = runtime::await_admission(&mut generation).await - { - return rejection(&state, protocol, &id, "admission", e); + if state.per_request_metrics { + encoder.enable_request_metrics(decoded.stream); } - let enqueue_ns = generation.first().and_then(|g| g.enqueue_ns); - let mut iter = generation.into_iter(); - let mut generations: Vec> = (0..size) - .map(|i| if zero.contains(&i) { None } else { iter.next() }) - .collect(); let streaming = decoded.stream; let stream_state = state.clone(); let stream_id = id.clone(); @@ -523,10 +523,6 @@ pub(super) async fn generate( } Ok(vec![]) } - GenerationEvent::Committed { at_ns } => { - encoder.record_commit(at_ns); - Ok(vec![]) - } GenerationEvent::Finished { generated_tokens, reused_prompt_tokens, diff --git a/helios/src/server/protocol/encode.rs b/helios/src/server/protocol/encode.rs index 0eaf2d8f9..3dbf350a8 100644 --- a/helios/src/server/protocol/encode.rs +++ b/helios/src/server/protocol/encode.rs @@ -78,12 +78,6 @@ struct Timing { arrival_ns: u64, times: RequestTimes, generated: u32, - /// Only a stream reports when text content first appeared. - streaming: bool, - /// Completion of the latest model step whose output the encoder received. - step_ns: Option, - /// Completion of the model step whose output first produced text content. - content_ns: Option, } pub(crate) struct Encoder { logprob_format: Option<(crate::server::inference::LogprobOptions, std::sync::Arc)>, @@ -241,25 +235,14 @@ impl Encoder { /// chunk of a Chat or Completions stream, on the terminal `response` of a /// Responses stream, and at the top level of a JSON body. Messages and /// multi-prompt Completions omit the object; several choices make it null. - /// Returns whether the content instant applies, which needs the generation's - /// `Committed` events. - pub fn enable_request_metrics(&mut self, streaming: bool) -> bool { + pub fn enable_request_metrics(&mut self, streaming: bool) { let placed = !streaming || self.include_usage || self.protocol == Protocol::Responses; self.metrics = match self.protocol { Protocol::Messages => None, _ if !placed || self.prompts.len() > 1 => None, _ if self.choices_per_prompt > 1 => Some(RequestMetrics::Suppressed), - _ => Some(RequestMetrics::Single(Timing { streaming, ..Timing::default() })), + _ => Some(RequestMetrics::Single(Timing::default())), }; - streaming && matches!(self.metrics, Some(RequestMetrics::Single(_))) - } - /// Record the completion instant of the model step whose output follows. - pub fn record_commit(&mut self, at_ns: u64) { - if let Some(RequestMetrics::Single(timing)) = &mut self.metrics - && timing.streaming - { - timing.step_ns = Some(at_ns); - } } /// Record the terminal instants and generated-token count of the generation. pub fn record_times(&mut self, arrival_ns: u64, times: RequestTimes, generated: u32) { @@ -268,7 +251,8 @@ impl Encoder { } } /// The `metrics` object, `null` when suppressed, or `None` when omitted. Each - /// interval is null when the generation did not reach its instants. + /// interval is null when the generation did not reach its instants; Flare does + /// not report the content instant. pub fn metrics_value(&self) -> Option { let timing = match self.metrics.as_ref()? { RequestMetrics::Suppressed => return Some(Value::Null), @@ -281,7 +265,7 @@ impl Encoder { let generation = first.zip(last).map(|(first, last)| ms(first, last)); Some(json!({ "time_to_first_token_ms": scheduled.zip(first).map(|(s, f)| ms(s, f)), - "time_to_first_content_token_ms": scheduled.zip(timing.content_ns).map(|(s, c)| ms(s, c)), + "time_to_first_content_token_ms": Value::Null, "generation_time_ms": generation, "queue_time_ms": scheduled.map(|s| ms(timing.arrival_ns, s)), "mean_itl_ms": generation @@ -545,12 +529,6 @@ impl Encoder { { continue; } - if let Event::Content(text) = &event - && !text.is_empty() - && let Some(RequestMetrics::Single(timing)) = &mut self.metrics - { - timing.content_ns = timing.content_ns.or(timing.step_ns); - } match &event { Event::TokenLogprobs(entries) => { if self.protocol != Protocol::Responses { diff --git a/helios/src/server/protocol/tests.rs b/helios/src/server/protocol/tests.rs index 48dd41dd8..d4f58ad2f 100644 --- a/helios/src/server/protocol/tests.rs +++ b/helios/src/server/protocol/tests.rs @@ -2331,15 +2331,12 @@ fn metered(protocol: Protocol, prompts: usize, choices: usize, include_usage: bo ) } -/// Feed one generation that reasons in its first committed step and answers in -/// its second, then finish it, returning every frame. +/// Feed one generation that reasons and then answers, then finish it, returning +/// every frame. fn metered_generation(encoder: &mut Encoder, times: crate::server::metrics::RequestTimes) -> Vec { let mut frames = encoder.start(); - encoder.record_commit(10_000_000); frames.extend(encoder.apply(0, vec![Event::Reasoning("think".into())]).unwrap()); - encoder.record_commit(25_000_000); frames.extend(encoder.apply(0, vec![Event::Content(String::new()), Event::Content("answer".into())]).unwrap()); - encoder.record_commit(40_000_000); frames.extend(encoder.apply(0, vec![Event::Content(" more".into())]).unwrap()); encoder.record_times(1_000_000, times, 4); frames.extend(encoder.finish(0, Termination::Eos, 4, 0, None).unwrap()); @@ -2354,16 +2351,14 @@ fn per_request_metrics_follow_vllm_placement_and_null_rules() { first_token_ns: Some(10_000_000), last_token_ns: 40_000_000, }; - let expected = |content: Value| { - json!({ - "time_to_first_token_ms": 7.0, - "time_to_first_content_token_ms": content, - "generation_time_ms": 30.0, - "queue_time_ms": 2.0, - "mean_itl_ms": 10.0, - "tokens_per_second": 4e9 / 37e6, - }) - }; + let expected = json!({ + "time_to_first_token_ms": 7.0, + "time_to_first_content_token_ms": null, + "generation_time_ms": 30.0, + "queue_time_ms": 2.0, + "mean_itl_ms": 10.0, + "tokens_per_second": 4e9 / 37e6, + }); let carriers = |frames: &[crate::server::protocol::Frame]| { frames .iter() @@ -2374,15 +2369,14 @@ fn per_request_metrics_follow_vllm_placement_and_null_rules() { .collect::>() }; for protocol in [Protocol::Chat, Protocol::Completions, Protocol::Responses] { - // A stream reports the step that first produced text, after the reasoning - // step and skipping empty content, on its final usage chunk or terminal response. + // A stream carries the object on its final usage chunk or terminal response. let mut encoder = metered(protocol, 1, 1, true); - assert!(encoder.enable_request_metrics(true)); + encoder.enable_request_metrics(true); let frames = metered_generation(&mut encoder, times); let carried = carriers(&frames); assert_eq!(carried.len(), 1, "{protocol:?}"); let (frame, metrics) = &carried[0]; - assert_eq!(metrics, &expected(json!(22.0)), "{protocol:?}"); + assert_eq!(metrics, &expected, "{protocol:?}"); if protocol == Protocol::Responses { assert_eq!(frame["type"], "response.completed"); } else { @@ -2390,19 +2384,19 @@ fn per_request_metrics_follow_vllm_placement_and_null_rules() { assert!(frame["usage"].is_object()); } - // A JSON body has no content instant; `http::generate` places the object at - // the top level of the body built from `response`. + // `http::generate` places a JSON body's object at the top level of the body + // built from `response`. let mut encoder = metered(protocol, 1, 1, false); - assert!(!encoder.enable_request_metrics(false)); + encoder.enable_request_metrics(false); let _ = metered_generation(&mut encoder, times); assert!(encoder.response().get("metrics").is_none()); - assert_eq!(encoder.metrics_value(), Some(expected(Value::Null))); + assert_eq!(encoder.metrics_value(), Some(expected.clone())); } // Without usage reporting a Chat or Completions stream has no chunk to carry it. for protocol in [Protocol::Chat, Protocol::Completions] { let mut encoder = metered(protocol, 1, 1, false); - assert!(!encoder.enable_request_metrics(true)); + encoder.enable_request_metrics(true); assert!(carriers(&metered_generation(&mut encoder, times)).is_empty()); assert_eq!(encoder.metrics_value(), None); } @@ -2410,7 +2404,7 @@ fn per_request_metrics_follow_vllm_placement_and_null_rules() { // Messages has no vLLM metrics, in a stream or a body. for streaming in [false, true] { let mut encoder = metered(Protocol::Messages, 1, 1, true); - assert!(!encoder.enable_request_metrics(streaming)); + encoder.enable_request_metrics(streaming); assert!(carriers(&metered_generation(&mut encoder, times)).is_empty()); assert_eq!(encoder.metrics_value(), None); } @@ -2419,7 +2413,7 @@ fn per_request_metrics_follow_vllm_placement_and_null_rules() { for (prompts, choices, metrics) in [(1, 2, Some(Value::Null)), (2, 1, None)] { for streaming in [false, true] { let mut encoder = metered(Protocol::Completions, prompts, choices, true); - assert!(!encoder.enable_request_metrics(streaming)); + encoder.enable_request_metrics(streaming); let mut frames = Vec::new(); for index in 0..prompts * choices { encoder.record_times(1_000_000, times, 4); @@ -2451,40 +2445,3 @@ fn per_request_metrics_follow_vllm_placement_and_null_rules() { assert_eq!(unrecorded.as_object().unwrap().len(), 6); assert!(unrecorded.as_object().unwrap().values().all(Value::is_null)); } - -#[test] -fn content_instant_excludes_reasoning_tool_calls_and_suppressed_text() { - // Reasoning and a tool call commit first; the first text arrives in a later step. - let mut encoder = metered(Protocol::Chat, 1, 1, true); - assert!(encoder.enable_request_metrics(true)); - encoder.record_commit(5_000_000); - encoder.apply(0, vec![Event::Reasoning("r".into())]).unwrap(); - encoder.record_commit(6_000_000); - let mut call = events(); - call.retain(|event| !matches!(event, Event::Reasoning(_) | Event::Content(_))); - encoder.apply(0, call).unwrap(); - encoder.record_commit(9_000_000); - encoder.apply(0, vec![Event::Content("text".into())]).unwrap(); - encoder.record_times(0, crate::server::metrics::RequestTimes { - first_scheduled_ns: Some(1_000_000), - first_token_ns: Some(5_000_000), - last_token_ns: 9_000_000, - }, 3); - let metrics = encoder.metrics_value().unwrap(); - assert_eq!(metrics["time_to_first_token_ms"], 4.0); - assert_eq!(metrics["time_to_first_content_token_ms"], 8.0); - - // A named tool choice drops answer text, so no text content is produced. - let mut encoder = Encoder::new(Protocol::Chat, "named".into(), "model".into(), 1, 1, - vec![PromptUsage { tokens: 5, image_tokens: 0 }], tools(), - ToolChoice::Named("lookup".into()), true, true, json!({})); - assert!(encoder.enable_request_metrics(true)); - encoder.record_commit(5_000_000); - encoder.apply(0, events()).unwrap(); - encoder.record_times(0, crate::server::metrics::RequestTimes { - first_scheduled_ns: Some(1_000_000), - first_token_ns: Some(5_000_000), - last_token_ns: 5_000_000, - }, 1); - assert_eq!(encoder.metrics_value().unwrap()["time_to_first_content_token_ms"], Value::Null); -} diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index b8aaba3d4..dd3e8b4fe 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -59,17 +59,15 @@ impl Prompt { !self.stop_sequences.is_empty() || !self.stop_strings.is_empty() } - fn output_event_capacity(&self, minimum: usize, observed: bool, commits: bool) -> Result { - // Each generated token produces at most one presentation event, one - // optional observation, and one optional commit instant, because every - // step that reports a commit instant generated at least one token. - // A reasoning cut's forced token is part of `after`. + fn output_event_capacity(&self, minimum: usize, observed: bool) -> Result { + // Each generated token produces at most one presentation event and one + // optional observation. A reasoning cut's forced token is part of `after`. // Prompt-score chunks cover disjoint, nonempty ranges of the original prompt. let tokens = u64::from(self.max_new_tokens) + u64::from(self.reasoning_cut.as_ref().map_or(0, |cut| cut.after)); let events = usize::try_from(tokens) .ok() - .and_then(|tokens| tokens.checked_mul(1 + usize::from(observed) + usize::from(commits))) + .and_then(|tokens| tokens.checked_mul(if observed { 2 } else { 1 })) .and_then(|events| { events.checked_add(if self.prompt_logprobs { self.tokens.len() } else { 0 }) }) @@ -106,12 +104,6 @@ pub enum GenerationEvent { /// The request's lifecycle instants, as its completion histograms record them. times: super::metrics::RequestTimes, }, - /// The completion instant of the model step whose output events follow, on the - /// `observation::monotonic_ns` clock. Sent only to requests submitted with - /// `commits`, once per step that generated a token for the request. - Committed { - at_ns: u64, - }, AdmissionRejected(Error), Error(Error), } @@ -202,8 +194,6 @@ struct Incoming { failure: Arc>>, metrics: Arc, observation: Option, - /// Send `GenerationEvent::Committed` before each model step's output. - commits: bool, /// 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. @@ -841,38 +831,30 @@ impl ModelRuntime { self.healthy() } pub fn generate(&self, prompt: Prompt) -> Result { - self.enqueue(prompt, None, false) + self.enqueue(prompt, None) } - pub(super) fn generate_observed(&self, prompt: Prompt, timestamps: bool, commits: bool) -> Result { - self.enqueue(prompt, Some(timestamps), commits) + pub(super) fn generate_observed(&self, prompt: Prompt, timestamps: bool) -> Result { + self.enqueue(prompt, Some(timestamps)) } - fn enqueue(&self, prompt: Prompt, observation: Option, commits: bool) -> Result { - self.enqueue_many(vec![prompt], observation, commits) + fn enqueue(&self, prompt: Prompt, observation: Option) -> Result { + self.enqueue_many(vec![prompt], observation) .map(|mut group| group.remove(0)) } pub fn generate_many(&self, prompts: Vec) -> Result> { - self.enqueue_many(prompts, None, false) + self.enqueue_many(prompts, None) } - /// `observation` adds an `ObservedToken` per committed token, timestamped when - /// `Some(true)`; `commits` adds a `Committed` event before each model step's output. - pub(super) fn generate_many_observed( - &self, - prompts: Vec, - observation: Option, - commits: bool, - ) -> Result> { - self.enqueue_many(prompts, observation, commits) + pub(super) fn generate_many_observed(&self, prompts: Vec, timestamps: bool) -> Result> { + self.enqueue_many(prompts, Some(timestamps)) } fn enqueue_many( &self, prompts: Vec, observation: Option, - commits: bool, ) -> Result> { if !self.healthy() { return Err(Error::admission( @@ -917,7 +899,7 @@ impl ModelRuntime { .map_err(|error| error.admission_context(AdmissionError::Invalid))?; // Tokio allocates queue blocks as events arrive, not at this capacity. let event_capacity = - prompt.output_event_capacity(self.event_capacity, observation.is_some(), commits)?; + prompt.output_event_capacity(self.event_capacity, observation.is_some())?; let (events, receiver) = async_mpsc::channel(event_capacity); let (admission, admitted) = oneshot::channel(); let (first_token, first_token_ready) = oneshot::channel(); @@ -937,7 +919,6 @@ impl ModelRuntime { failure: failure.clone(), metrics: self.metrics.clone(), observation, - commits, record: Default::default(), host_lookup: true, readmitted: false, @@ -1818,9 +1799,6 @@ impl<'a> Worker<'a> { // speculative round, adds one inter-token interval. if position == 0 { request.incoming.record.tokens_committed(completed_at_ns); - if request.incoming.commits { - request.incoming.emit(GenerationEvent::Committed { at_ns: completed_at_ns }); - } } request.incoming.observe_token(token.token); request.last_token = Some(token.token); @@ -3310,7 +3288,6 @@ mod tests { failure: failure.clone(), metrics: Arc::new(super::super::metrics::Metrics::new(0, 0, 0, 16)), observation: None, - commits: false, record: Default::default(), host_lookup: true, readmitted: false, @@ -3342,17 +3319,15 @@ mod tests { let (mut incoming, _generation) = stream(2); let prompt = &mut incoming.prompt; prompt.max_new_tokens = 1_000_000; - assert_eq!(prompt.output_event_capacity(128, false, false).unwrap(), 1_000_003); - assert_eq!(prompt.output_event_capacity(128, true, false).unwrap(), 2_000_003); - assert_eq!(prompt.output_event_capacity(128, false, true).unwrap(), 2_000_003); - assert_eq!(prompt.output_event_capacity(128, true, true).unwrap(), 3_000_003); + assert_eq!(prompt.output_event_capacity(128, false).unwrap(), 1_000_003); + assert_eq!(prompt.output_event_capacity(128, true).unwrap(), 2_000_003); prompt.reasoning_cut = Some(ReasoningCut { close: 8, after: 20, output: None }); prompt.prompt_logprobs = true; - assert_eq!(prompt.output_event_capacity(128, true, false).unwrap(), 2_000_044); + assert_eq!(prompt.output_event_capacity(128, true).unwrap(), 2_000_044); prompt.max_new_tokens = 0; prompt.reasoning_cut = None; - assert_eq!(prompt.output_event_capacity(128, false, false).unwrap(), 128); - assert!(prompt.output_event_capacity(usize::MAX, true, false).is_err()); + assert_eq!(prompt.output_event_capacity(128, false).unwrap(), 128); + assert!(prompt.output_event_capacity(usize::MAX, true).is_err()); } #[test] diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 6988c0e36..b848d2d1a 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -252,7 +252,6 @@ impl Fixture { failure: failure.clone(), metrics: self.metrics.clone(), observation: Some(false), - commits: false, record: Default::default(), host_lookup: true, readmitted: false, @@ -3746,7 +3745,7 @@ fn unread_responses_finish_and_release_model_resources_but_retain_admission_capa let mut slow_prompt = prompt(512); slow_prompt.logprobs = logprobs; slow_prompt.stop_sequences = vec![vec![2, 3]]; - let mut slow = runtime.generate_observed(slow_prompt, true, false).unwrap(); + let mut slow = runtime.generate_observed(slow_prompt, true).unwrap(); let mut worker = fixture.worker(receiver); assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); let mut tokens = vec![1; 512]; @@ -3800,7 +3799,7 @@ fn unread_response_keeps_its_budget_through_a_reasoning_continuation() { positions: vec![[0; 3]], vision_token_indices: vec![-1], ..Default::default() }); prompt.reasoning_cut = Some(budget_cut(4, 81)); - let mut generation = runtime.generate_observed(prompt, false, false).unwrap(); + let mut generation = runtime.generate_observed(prompt, false).unwrap(); let mut worker = fixture.worker(receiver); assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); let mut sequence = 0; @@ -4560,15 +4559,14 @@ fn timed_pass(worker: &mut Worker<'_>, samples: &[u32]) -> Vec { } /// Serve one HTTP request through a worker that `timed_pass` drives, returning the -/// step bounds, the JSON body or the SSE `data` payloads of a stream, and whether -/// the request asked the worker for commit instants. +/// step bounds and the JSON body or the SSE `data` payloads of a stream. async fn served_through_worker( fixture: fn() -> Fixture, per_request_metrics: bool, path: &str, body: serde_json::Value, samples: &[u32], -) -> (Vec, Vec, bool) { +) -> (Vec, Vec) { use axum::{Extension, extract::State}; let (sender, receiver) = mpsc::sync_channel(4); let mut state = http_state_for(fixture(), sender, None, &[]); @@ -4587,7 +4585,6 @@ async fn served_through_worker( }) .await .unwrap(); - let commits = group[0].commits; let steps = { let worker_fixture = fixture(); let (queue, inbound) = mpsc::channel(); @@ -4609,14 +4606,14 @@ async fn served_through_worker( } else { vec![serde_json::from_slice(&bytes).unwrap()] }; - (steps, values, commits) + (steps, values) } #[tokio::test] async fn performance_reports_the_first_scheduled_model_step() { use serde_json::json; for stream in [false, true] { - let (steps, values, _) = served_through_worker( + let (steps, values) = served_through_worker( || Fixture::new().text_inputs(), false, "/v1/chat/completions", @@ -4652,7 +4649,6 @@ struct Served { arrival_ns: u64, scheduled_ns: u64, first_ns: u64, - content_ns: Option, last_ns: u64, } @@ -4667,15 +4663,11 @@ fn served_instants(values: &[serde_json::Value]) -> (serde_json::Value, Served) .find(|value| value.get("performance").is_some()) .unwrap()["performance"]; let scheduled_ns = performance["first_scheduled_ns"].as_u64().unwrap(); - let after = |field: &str| { - metrics[field].as_f64().map(|ms| scheduled_ns + (ms * 1e6).round() as u64) - }; - let first_ns = after("time_to_first_token_ms").unwrap(); + let first_ns = scheduled_ns + (metrics["time_to_first_token_ms"].as_f64().unwrap() * 1e6).round() as u64; let served = Served { arrival_ns: scheduled_ns - (metrics["queue_time_ms"].as_f64().unwrap() * 1e6).round() as u64, scheduled_ns, first_ns, - content_ns: after("time_to_first_content_token_ms"), last_ns: first_ns + (metrics["generation_time_ms"].as_f64().unwrap() * 1e6).round() as u64, }; // The HTTP ingress precedes model-queue arrival, which precedes enqueue_ns. @@ -4697,7 +4689,7 @@ async fn per_request_metrics_report_the_runtime_instants_of_a_stopped_reasoning_ // Reasoning, its close, the first answer text, then the stop string. let samples = [token("b"), token(""), token("c"), token("d")]; for stream in [true, false] { - let (steps, values, commits) = served_through_worker( + let (steps, values) = served_through_worker( Fixture::reasoning, true, "/v1/chat/completions", @@ -4708,7 +4700,6 @@ async fn per_request_metrics_report_the_runtime_instants_of_a_stopped_reasoning_ &samples, ) .await; - assert_eq!(commits, stream); let carriers: Vec<_> = values.iter().filter(|value| value.get("metrics").is_some()).collect(); assert_eq!(carriers.len(), 1); if stream { @@ -4728,13 +4719,7 @@ async fn per_request_metrics_report_the_runtime_instants_of_a_stopped_reasoning_ assert!(within(&steps[0], served.scheduled_ns)); assert!(within(generating[0], served.first_ns)); assert!(within(generating[3], served.last_ns)); - if stream { - // Reasoning and its close precede the first answer text by two steps. - assert!(within(generating[2], served.content_ns.unwrap())); - assert!(metrics["time_to_first_content_token_ms"].as_f64() > metrics["time_to_first_token_ms"].as_f64()); - } else { - assert_eq!(served.content_ns, None); - } + assert_eq!(metrics["time_to_first_content_token_ms"], Value::Null); let ms = |ns: u64| ns as f64 / 1e6; assert!((metrics["mean_itl_ms"].as_f64().unwrap() - ms(served.last_ns - served.first_ns) / 3.0).abs() < 1e-5); assert!((metrics["tokens_per_second"].as_f64().unwrap() * ms(served.last_ns - served.scheduled_ns) / 1e3 - 4.0).abs() < 1e-6); @@ -4755,7 +4740,7 @@ async fn per_request_metrics_reach_completions_and_responses_where_vllm_places_t if path == "/v1/completions" && stream { body["stream_options"] = json!({"include_usage":true}); } - let (steps, values, commits) = served_through_worker( + let (steps, values) = served_through_worker( || Fixture::new().text_inputs(), true, path, @@ -4763,7 +4748,6 @@ async fn per_request_metrics_reach_completions_and_responses_where_vllm_places_t &[1, 2], ) .await; - assert_eq!(commits, stream); let carriers: Vec<(&Value, &Value)> = values .iter() .filter_map(|value| { @@ -4787,11 +4771,7 @@ async fn per_request_metrics_reach_completions_and_responses_where_vllm_places_t assert!(generation >= 3.0 && generation * 1e6 <= (generating[1].end_ns - generating[0].start_ns) as f64); assert!(ttft >= 0.0 && metrics["queue_time_ms"].as_f64().unwrap() >= 0.0); assert_eq!(metrics["mean_itl_ms"], metrics["generation_time_ms"]); - // Plain text is content from the first token. - assert_eq!( - metrics["time_to_first_content_token_ms"], - if stream { metrics["time_to_first_token_ms"].clone() } else { Value::Null } - ); + assert_eq!(metrics["time_to_first_content_token_ms"], Value::Null); } } } @@ -4800,7 +4780,7 @@ async fn per_request_metrics_reach_completions_and_responses_where_vllm_places_t async fn per_request_metrics_are_absent_without_the_option_and_null_for_several_choices() { use serde_json::{Value, json}; for stream in [false, true] { - let (_, values, commits) = served_through_worker( + let (_, values) = served_through_worker( || Fixture::new().text_inputs(), false, "/v1/completions", @@ -4809,7 +4789,6 @@ async fn per_request_metrics_are_absent_without_the_option_and_null_for_several_ &[1, 2], ) .await; - assert!(!commits); assert!(values.iter().all(|value| value.get("metrics").is_none())); assert!(values.iter().any(|value| value["usage"]["completion_tokens"] == 2)); } @@ -4836,7 +4815,6 @@ async fn per_request_metrics_are_absent_without_the_option_and_null_for_several_ }) .await .unwrap(); - assert!(group.iter().all(|incoming| !incoming.commits)); for incoming in &group { incoming.notify_admission(Ok(())); incoming.observe_token(1); From 3320a726472de1c415212d862b80308d74ba2fc7 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 21:54:49 -0600 Subject: [PATCH 17/24] Export RequestTimes and report the earliest first scheduled step `GenerationEvent` is public, and its `Finished` variant carries a `RequestTimes` with the request's lifecycle instants, but that type lived in the private `server::metrics` module, so a caller outside the crate could neither read the instants nor build a `Finished` event. The HTTP handler also assigned `performance.first_scheduled_ns` from whichever generation finished last, rather than the earliest step of the response, which is the instant the field defines. `flare_helios::server` re-exports `RequestTimes` beside `Snapshot`; its fields are already public. The handler keeps the minimum of the first scheduled instants across `Finished` events, ignoring generations that never reached a model step. The doc comment on `Encoder::enable_request_metrics` refers to `docs/api.md` for placement instead of restating it, and the encoder test builds its expected `metrics` objects, including the all-null one, from one key list, so the field set is spelled once. Out-of-crate code can name and construct the instants carried by `GenerationEvent::Finished`. Responses are unchanged today, because Chat, the only protocol that reports `performance`, runs one generation per response. Evidence: `per_request_metrics_follow_vllm_placement_and_null_rules` compares whole `metrics` objects built from one key list, including the all-null object, and `performance_reports_the_first_scheduled_model_step` checks the reported instant through a worker. `cargo test --locked --manifest-path helios/Cargo.toml --features runtime-core,server --lib -- server:: scheduler:: cache::` passed 819 tests at the head of the series this commit belongs to; the one failure, `messages_image_hints_end_after_expansion_for_text_and_segmented_templates`, needs templates from `tests/frontend/prepare_templates.py` through `FLARE_TEST_TEMPLATE_DIR`, which this host does not have. No test serves a Chat response with several generations, because Chat accepts only one choice. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=eb2f --- helios/src/server.rs | 2 +- helios/src/server/http.rs | 4 ++-- helios/src/server/protocol/encode.rs | 5 +---- helios/src/server/protocol/tests.rs | 24 +++++++++++++----------- 4 files changed, 17 insertions(+), 18 deletions(-) diff --git a/helios/src/server.rs b/helios/src/server.rs index 6edd60766..56b38d8c9 100644 --- a/helios/src/server.rs +++ b/helios/src/server.rs @@ -30,7 +30,7 @@ pub use session::{LoadedSession, ServingSession}; pub(crate) mod token_spans; pub use config::Bootstrap; pub use dashboard::view; -pub use metrics::Snapshot; +pub use metrics::{RequestTimes, Snapshot}; pub use runtime::{Generation, GenerationEvent, ModelRuntime, Prompt}; pub use crate::execution::{PersistentWorkerSnapshot, WorkerState}; diff --git a/helios/src/server/http.rs b/helios/src/server/http.rs index 1dfcfbe12..6ed2ddc0d 100644 --- a/helios/src/server/http.rs +++ b/helios/src/server/http.rs @@ -407,7 +407,7 @@ pub(super) async fn generate( let mut raw_tokens = Vec::new(); let mut timestamps = Vec::new(); let mut reused_total = 0; - // `performance` is Chat-only, and Chat has one choice. + // The earliest model step that included any of the response's generations. let mut first_scheduled_ns = None; if streaming && protocol == Protocol::Chat { // Chat has one choice and rejects streamed prompt logprobs, so no @@ -533,7 +533,7 @@ pub(super) async fn generate( .. } => { reused_total += reused_prompt_tokens; - first_scheduled_ns = times.first_scheduled_ns; + first_scheduled_ns = first_scheduled_ns.into_iter().chain(times.first_scheduled_ns).min(); encoder.record_times(arrival_ns, times, generated_tokens); let result = decoders[index] .finish(if encoder.tool_limit_reached { crate::output::Termination::Cancelled } else { termination }) diff --git a/helios/src/server/protocol/encode.rs b/helios/src/server/protocol/encode.rs index 3dbf350a8..652d8cc72 100644 --- a/helios/src/server/protocol/encode.rs +++ b/helios/src/server/protocol/encode.rs @@ -231,10 +231,7 @@ impl Encoder { self.continuous_usage = self.include_usage && enabled; } - /// Report vLLM's per-request `metrics` where it places them: on the final usage - /// chunk of a Chat or Completions stream, on the terminal `response` of a - /// Responses stream, and at the top level of a JSON body. Messages and - /// multi-prompt Completions omit the object; several choices make it null. + /// Report vLLM's per-request `metrics`, placed as `docs/api.md` describes. pub fn enable_request_metrics(&mut self, streaming: bool) { let placed = !streaming || self.include_usage || self.protocol == Protocol::Responses; self.metrics = match self.protocol { diff --git a/helios/src/server/protocol/tests.rs b/helios/src/server/protocol/tests.rs index d4f58ad2f..db0ebe713 100644 --- a/helios/src/server/protocol/tests.rs +++ b/helios/src/server/protocol/tests.rs @@ -2351,14 +2351,18 @@ fn per_request_metrics_follow_vllm_placement_and_null_rules() { first_token_ns: Some(10_000_000), last_token_ns: 40_000_000, }; - let expected = json!({ - "time_to_first_token_ms": 7.0, - "time_to_first_content_token_ms": null, - "generation_time_ms": 30.0, - "queue_time_ms": 2.0, - "mean_itl_ms": 10.0, - "tokens_per_second": 4e9 / 37e6, - }); + let object = |values: [Value; 6]| { + let keys = [ + "time_to_first_token_ms", + "time_to_first_content_token_ms", + "generation_time_ms", + "queue_time_ms", + "mean_itl_ms", + "tokens_per_second", + ]; + Value::Object(keys.into_iter().map(String::from).zip(values).collect()) + }; + let expected = object([json!(7.0), Value::Null, json!(30.0), json!(2.0), json!(10.0), json!(4e9 / 37e6)]); let carriers = |frames: &[crate::server::protocol::Frame]| { frames .iter() @@ -2441,7 +2445,5 @@ fn per_request_metrics_follow_vllm_placement_and_null_rules() { let mut encoder = metered(Protocol::Chat, 1, 1, true); encoder.enable_request_metrics(false); let _ = encoder.finish(0, Termination::OutputLimit, 0, 0, None).unwrap(); - let unrecorded = encoder.metrics_value().unwrap(); - assert_eq!(unrecorded.as_object().unwrap().len(), 6); - assert!(unrecorded.as_object().unwrap().values().all(Value::is_null)); + assert_eq!(encoder.metrics_value(), Some(object(std::array::from_fn(|_| Value::Null)))); } From 8be24e2f98781f193e0b309af9f2340d4a68e1b8 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 21:55:40 -0600 Subject: [PATCH 18/24] Read per-request metrics from the [server] configuration Native `flare run` takes its serving defaults from the `[server]` section of the host configuration, and the desktop controller in the `flare` library reads only that file. Per-request metrics could be enabled only by the `--enable-per-request-metrics` flag, so the desktop controller could not enable them, and a `[server] per_request_metrics` key was accepted and ignored because `[server]` tolerates unknown keys. A configuration key, applied the way `scheduler_checkpoint_extra_work_fraction` is, gives both front ends one home for the setting. `flare::configuration::Server` has an optional boolean `per_request_metrics`. `Settings` resolves it to a boolean, defaulting to off, and the controller passes it to Helios as the server configuration key of the same name. Native `flare run` enables the option when the key is true or the flag is given, so the flag still enables it over `per_request_metrics = false`. `flare run --help` and `flare orbit run --help` describe the flag with the same sentence, and `docs/cli-design.md` lists the key among the `[server]` keys native `flare run` applies, shows it in the sample configuration, and names it as the flag's default; `docs/api.md` names both switches. `[server] per_request_metrics = true` enables vLLM's per-request `metrics` in native `flare run` and in the desktop controller; a non-boolean value is a configuration error. Evidence: `flare::settings::tests::per_request_metrics_reach_application_settings` checks the absent, true, and false keys and rejects a string value; `config::tests::per_request_metrics_configuration_and_flag_precedence` in `flare-cli` checks that the key enables the option and that the flag enables it over a false key. `cargo test --locked --manifest-path flare-cli/Cargo.toml --bin flare -- cli:: config::` passed 50 tests and `cargo test --locked --manifest-path flare/Cargo.toml --lib -- settings:: configuration::` passed 11. The desktop controller was not run. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=eb2f --- docs/api.md | 5 +++-- docs/cli-design.md | 5 +++-- flare-cli/src/cli.rs | 5 +++-- flare-cli/src/config.rs | 17 +++++++++++++++++ flare/src/configuration.rs | 1 + flare/src/controller.rs | 1 + flare/src/settings.rs | 15 +++++++++++++++ 7 files changed, 43 insertions(+), 6 deletions(-) diff --git a/docs/api.md b/docs/api.md index 15a111083..390faacfd 100644 --- a/docs/api.md +++ b/docs/api.md @@ -993,8 +993,9 @@ chunks does not measure generated tokens. The final usage chunk is also emitted. ## Per-request metrics -`flare run --enable-per-request-metrics` adds vLLM's per-request `metrics` -object to OpenAI Chat Completions, Completions, and Responses output. The option +`flare run --enable-per-request-metrics`, or `[server] per_request_metrics = true` +in the host configuration, adds vLLM's per-request `metrics` object to OpenAI +Chat Completions, Completions, and Responses output. The option is off by default, and no response carries the key without it. Anthropic Messages output never carries the object. The fields are milliseconds, except `tokens_per_second`, and come from the instants the model worker records for the diff --git a/docs/cli-design.md b/docs/cli-design.md index 045aabd52..f786539c7 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -733,7 +733,7 @@ Help exits with status 0; usage errors go to stderr with status 2. Its options a | `--port N` | Listener port | `[server] port`, otherwise `8000` | | `--served-model-name ALIAS` | Replace the core's serving aliases with this nonblank alias | Core aliases | | `--api-key-file PATH` | File containing the serving API key; an empty file disables authentication | `[server] api_key`, otherwise no authentication | -| `--enable-per-request-metrics` | Add vLLM's per-request `metrics` timing object to OpenAI Chat, Completions, and Responses output; see [per-request metrics](api.md#per-request-metrics) | off | +| `--enable-per-request-metrics` | Add vLLM's per-request `metrics` timing object to OpenAI Chat, Completions, and Responses output; see [per-request metrics](api.md#per-request-metrics) | `[server] per_request_metrics`, otherwise off | | `--max-concurrency N` | Reduce concurrency within captured batch capacities | Model/default configuration, otherwise core default | | `--kv-cache-limit concurrency\|context\|memory` | Bound shared KV history by prepared context times selected concurrency, one prepared context, or available memory | `memory` | | `--memory-limit LIMIT` | Per-GPU occupied size (`30G`), free-memory reserve (`-30G`, including `-0G`), or fraction of total memory (`0.8`) | `[memory] reserve`, otherwise core serving reserve | @@ -1315,7 +1315,7 @@ An absent default file supplies no overrides; an explicitly selected missing file or an invalid runtime setting is an error. Help does not read the file. Native `flare run` applies `[server] host`, `port`, `api_key`, `thinking_token_budget`, -and `scheduler_checkpoint_extra_work_fraction`, +`scheduler_checkpoint_extra_work_fraction`, and `per_request_metrics`, `[memory] reserve`, `[defaults] max_concurrency`, `[models.] max_concurrency`, all `[prefix_cache]` settings, and `[paths] prefix_cache`. Prepared-model acquisition and cache commands use `[paths] core_cache`. Flags override these defaults, including explicit @@ -1346,6 +1346,7 @@ port = 8000 api_key = "" # Empty: no authentication. # thinking_token_budget = 1536 # Optional default reasoning-token cap. # scheduler_checkpoint_extra_work_fraction = 0.05 # Fraction of productive work for extra captures. +# per_request_metrics = false # Add vLLM's per-request `metrics` to OpenAI output. [defaults] model = "qwen3.8-flash" diff --git a/flare-cli/src/cli.rs b/flare-cli/src/cli.rs index 853173cb4..12f68f929 100644 --- a/flare-cli/src/cli.rs +++ b/flare-cli/src/cli.rs @@ -643,7 +643,8 @@ pub struct OrbitRun { #[arg(long, value_name = "PATH", help_heading = "Serving options")] pub api_key_file: Option, - /// Report vLLM's per-request `metrics` timing object in rank zero's OpenAI responses. + /// Add vLLM's per-request `metrics` timing object to OpenAI Chat, Completions, + /// and Responses output. #[arg(long, help_heading = "Serving options")] pub enable_per_request_metrics: bool, @@ -856,7 +857,7 @@ pub struct Run { #[arg(long, help_heading = "Serving options")] pub bypass_performance_check: bool, - /// Report vLLM's per-request `metrics` timing object in OpenAI Chat, Completions, + /// Add vLLM's per-request `metrics` timing object to OpenAI Chat, Completions, /// and Responses output. #[arg(long, help_heading = "Serving options")] pub enable_per_request_metrics: bool, diff --git a/flare-cli/src/config.rs b/flare-cli/src/config.rs index 40b0167da..3d7536da8 100644 --- a/flare-cli/src/config.rs +++ b/flare-cli/src/config.rs @@ -70,6 +70,9 @@ impl Configuration { if run.scheduler_checkpoint_extra_work_fraction.is_none() { run.scheduler_checkpoint_extra_work_fraction = self.server.scheduler_checkpoint_extra_work_fraction; } + if !run.enable_per_request_metrics { + run.enable_per_request_metrics = self.server.per_request_metrics.unwrap_or(false); + } let serving = &mut run.serving; if serving.memory_limit.is_none() { serving.memory_limit = size(self.memory.reserve.as_deref(), "memory.reserve")? @@ -216,6 +219,20 @@ mod tests { } } + #[test] + fn per_request_metrics_configuration_and_flag_precedence() { + let args = ["flare", "run", "model.safetensors"]; + let flag = ["flare", "run", "model.safetensors", "--enable-per-request-metrics"]; + for (text, configured_only) in [ + ("", false), + ("[server]\nper_request_metrics=true", true), + ("[server]\nper_request_metrics=false", false), + ] { + assert_eq!(configured(text, &args, &[]).1.enable_per_request_metrics, configured_only, "{text}"); + assert!(configured(text, &flag, &[]).1.enable_per_request_metrics, "{text}"); + } + } + #[test] fn prefix_cache_drain_on_shutdown_defaults_and_flag_precedence() { let args = ["flare", "run", "model.safetensors"]; diff --git a/flare/src/configuration.rs b/flare/src/configuration.rs index e4420dbb8..ffc552ff3 100644 --- a/flare/src/configuration.rs +++ b/flare/src/configuration.rs @@ -31,6 +31,7 @@ pub struct Server { pub api_key: Option, pub thinking_token_budget: Option, pub scheduler_checkpoint_extra_work_fraction: Option, + pub per_request_metrics: Option, } #[derive(Default, Deserialize)] diff --git a/flare/src/controller.rs b/flare/src/controller.rs index 67bb49076..93c2caf83 100644 --- a/flare/src/controller.rs +++ b/flare/src/controller.rs @@ -2563,6 +2563,7 @@ impl Worker { if let Some(fraction) = self.settings.scheduler_checkpoint_extra_work_fraction { config["scheduler_checkpoint_extra_work_fraction"] = fraction.into(); } + config["per_request_metrics"] = self.settings.per_request_metrics.into(); let mut loaded = match LoadedSession::new(owner, config) { Ok(loaded) => loaded, Err(error) => { diff --git a/flare/src/settings.rs b/flare/src/settings.rs index f6d055a8e..5c9206ed3 100644 --- a/flare/src/settings.rs +++ b/flare/src/settings.rs @@ -29,6 +29,7 @@ pub struct Settings { pub publisher_keys: Vec, pub thinking_token_budget: Option, pub scheduler_checkpoint_extra_work_fraction: Option, + pub per_request_metrics: bool, pub prefix_cache: PrefixCacheOffload, pub model_concurrency: std::collections::HashMap, } @@ -71,6 +72,19 @@ mod tests { assert_eq!(settings.scheduler_checkpoint_extra_work_fraction, fraction); } } + #[test] + fn per_request_metrics_reach_application_settings() { + for (text, expected) in [ + ("", false), + ("[server]\nper_request_metrics=true", true), + ("[server]\nper_request_metrics=false", false), + ] { + let configuration = Configuration::parse(text).unwrap(); + let settings = Settings::resolve(configuration, Path::new("user"), Path::new("config.toml")).unwrap(); + assert_eq!(settings.per_request_metrics, expected, "{text}"); + } + assert!(Configuration::parse("[server]\nper_request_metrics='true'").is_err()); + } #[test] fn conflicting_alias_defaults_are_rejected() { @@ -207,6 +221,7 @@ impl Settings { publisher_keys: Vec::new(), thinking_token_budget, scheduler_checkpoint_extra_work_fraction: configuration.server.scheduler_checkpoint_extra_work_fraction, + per_request_metrics: configuration.server.per_request_metrics.unwrap_or(false), prefix_cache, model_concurrency, }) From cad6bf0434ec8b6435044b5d40e1fdf857e048ce Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 21:56:08 -0600 Subject: [PATCH 19/24] State the per-request metrics boundaries and the include_usage gap The per-request metrics section of `docs/api.md` placed model-queue arrival at the worker side of the request queue, and it did not say that a Chat or Completions stream without `stream_options.include_usage` carries no `metrics`, which is why gateways that read rates from the response body show none for such streams. It referred to `performance.first_scheduled_ns` without defining the `performance` object anywhere in the file, and it restated null rules the field table already implies. The section states that `ModelRuntime::enqueue_many` reads arrival while building the request group, before publishing it to the worker channel, so `queue_time_ms` includes the channel send and worker pickup and starts later than vLLM's engine-core scheduler queue. It states that streams without `include_usage` receive no `metrics`, that vLLM closes this with `--enable-force-include-usage`, and that Flare has no equivalent option. The null rules are two sentences, and one sentence defines the Chat `performance` object: its fields and their shared process-local origin with `choices[0].token_timestamps_ns`, with the model-contract link kept. A reader of the HTTP API reference can tell where `queue_time_ms` starts, why a stream may carry no metrics, and what `performance` holds. No behavior changes. Evidence: Documentation only. The arrival boundary matches `ModelRuntime::enqueue_many` in `helios/src/server/runtime.rs`, which reads `arrival_ns` while building each `Incoming` and sends the group with `try_send` after the loop. `cargo test --locked --manifest-path helios/Cargo.toml --features runtime-core,server --lib -- server:: scheduler:: cache::` passed 819 tests at the head of the series this commit belongs to; the one failure, `messages_image_hints_end_after_expansion_for_text_and_segmented_templates`, needs templates from `tests/frontend/prepare_templates.py` through `FLARE_TEST_TEMPLATE_DIR`, which this host does not have. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=eb2f --- docs/api.md | 45 ++++++++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/docs/api.md b/docs/api.md index 390faacfd..22c388d7b 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1004,7 +1004,7 @@ string, which the worker matches, does not change how they are measured: | Field | Definition | | --- | --- | -| `queue_time_ms` | Model-scheduler arrival to the first model step that includes the request | +| `queue_time_ms` | Model-queue arrival to the first model step that includes the request | | `time_to_first_token_ms` | That first scheduled step to the completion of the step that committed the first generated token | | `time_to_first_content_token_ms` | Always null: Flare does not report when answer text first appeared, as vLLM permits for a value it cannot provide | | `generation_time_ms` | First to last committed generated token | @@ -1012,26 +1012,29 @@ string, which the worker matches, does not change how they are measured: | `tokens_per_second` | Generated tokens, as `usage` counts them, over the first scheduled step to the last committed generated token | A step's completion instant is read once when the worker processes that step's -results, so tokens committed by one speculative step share it. - -A JSON body carries `metrics` at the top level. A Chat or Completions stream -carries it only on the final usage chunk, whose `choices` is empty, so the stream -needs `"stream_options": {"include_usage": true}`; without that option no chunk -carries it. A Responses stream carries it in the `response` object of -`response.completed` or `response.incomplete`; earlier events do not. Responses -requests always run one generation, so every Responses output carries it. - -Every field is present and is null when the request did not reach the instants -it spans: `mean_itl_ms` is null for a single generated token, the token fields -are null when nothing was generated, and every field is null for a choice that -never reached a model step. With `n` greater than one, `metrics` is null, -because one choice's instants do not describe the response. Completions with -several prompts omit `metrics`. Failed requests return error bodies without it. - -The option adds no clock reads: the encoder reads the instants on each -request's terminal event. Chat token -observation reports the same first scheduled step as `performance.first_scheduled_ns`, -beside per-token timestamps; the +results, so tokens committed by one speculative step share it. The runtime reads +model-queue arrival when it builds the request group, before publishing the group +to the worker channel, so `queue_time_ms` includes the channel send and worker +pickup and starts later than vLLM's engine-core scheduler queue. + +A JSON body carries `metrics` at the top level, and a Responses stream carries it +in the `response` object of `response.completed` or `response.incomplete`. A Chat +or Completions stream carries it only on the final usage chunk, so a client that +does not send `"stream_options": {"include_usage": true}` receives none, and +gateways that read rates from the response body, such as llama-swap, show none +for those streams. Flare has no equivalent of vLLM's +`--enable-force-include-usage` server option, which forces the usage chunk and +would close this gap. + +All six fields are always present, and a field is null when the request did not +reach the instants it spans, such as `mean_itl_ms` for a single generated token. +With `n` greater than one `metrics` is null, and Completions with several prompts +omit it. + +A Chat request with `return_token_timestamps: true` also receives a top-level +`performance` object holding `ingress_ns`, `enqueue_ns`, `first_scheduled_ns` and +`reused_prompt_tokens`; the three instants are absolute nanoseconds on the same +process-local origin as `choices[0].token_timestamps_ns`. The [prepared model contract](../helios/model-contract.md#token-and-timing-observation) defines those fields. From 80b4cfb0f38e5d55dc27da2d0bf6bbe992b1cecc Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Sat, 28 Nov 2026 16:45:48 -0600 Subject: [PATCH 20/24] Accept [server] per_request_metrics in the Ignition configuration `docs/api.md` and `docs/cli-design.md` enable per-request metrics with `[server] per_request_metrics = true` in `~/.config/flare/config.toml`, the file Ignition and native Flare share. The Ignition schema lacked the key, so every Ignition command that loads the file failed with `unknown key per_request_metrics in [server]`. The key joins the schema as a boolean, the way `thinking_token_budget` and `scheduler_checkpoint_extra_work_fraction` do. `ignition/cli/config.py` lists `per_request_metrics: bool` under `[server]`, defaults it to false, and writes it as a comment in the initial configuration file. `ignition debug-serve` passes it to the Helios bootstrap options beside the two other `[server]` serving keys. `docs/cli-design.md` states that `debug-serve` applies these three keys as native `flare run` does. A configuration with `per_request_metrics = true` loads in every Ignition command, a non-boolean value is a usage error, and `ignition debug-serve` enables vLLM's per-request `metrics` when the key is true. Evidence: `tests/cli/test_config.py` adds `test_per_request_metrics_configuration` (absent, true, false) and two rejection rows (integer, string); `uv run --with pytest python -m pytest tests/cli/test_config.py -q` passed 77 tests. `ignition debug-serve` was not run; it needs a GPU and a cached checkpoint. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: enterprise/deepseek-v4.1-flash (omp agent); design-review=eb2f --- docs/cli-design.md | 4 +++- ignition/cli/config.py | 4 +++- ignition/cli/serve.py | 1 + tests/cli/test_config.py | 11 +++++++++++ 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/docs/cli-design.md b/docs/cli-design.md index f786539c7..6c4365f4d 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -1382,7 +1382,9 @@ export_staging = "" # Rank files an export assembles from; empty: cuda = "/opt/cuda" # Explicit CUDA toolkit directory for native builds. ``` -Ignition rejects any section or key outside its schema. Native Flare ignores +Ignition rejects any section or key outside its schema. `ignition debug-serve` +applies `[server] thinking_token_budget`, `scheduler_checkpoint_extra_work_fraction`, +and `per_request_metrics` as native `flare run` does. Native Flare ignores keys it does not use, except in `[prefix_cache]`, where it accepts only `memory`, `disk_limit`, `drain_on_shutdown`, `max_age`, and `compression`. diff --git a/ignition/cli/config.py b/ignition/cli/config.py index 8760d12d6..0d979b775 100644 --- a/ignition/cli/config.py +++ b/ignition/cli/config.py @@ -21,7 +21,7 @@ _SECTIONS = { "publishing": {"signing_key": str, "namespace": str, "official_source": str}, "server": {"host": str, "port": int, "api_key": str, "thinking_token_budget": int, - "scheduler_checkpoint_extra_work_fraction": (int, float)}, + "scheduler_checkpoint_extra_work_fraction": (int, float), "per_request_metrics": bool}, "defaults": {"model": str, "max_concurrency": int, "image_concurrency": int, "speculative_token_capacity": int, "speculative_graph_budget": int, "speculative_method": str}, "memory": {"reserve": str}, @@ -38,6 +38,7 @@ "server.host": "127.0.0.1", "server.port": 8000, "server.api_key": "", "server.thinking_token_budget": None, "server.scheduler_checkpoint_extra_work_fraction": 0.05, + "server.per_request_metrics": False, "memory.reserve": "0", "preparation.force_moe_decode_a16": False, "preparation.compile_workers": 0, @@ -190,6 +191,7 @@ def write_initial(self, model: str, max_concurrency: int) -> None: f'# port = {self.get("server.port").value}', '# api_key = "" # empty: no authentication', '# thinking_token_budget = 1536 # omitted: no default reasoning cap', + "# per_request_metrics = false # add vLLM's per-request `metrics` to OpenAI output", "", "[defaults]", f'# model = "{model}"', f"# max_concurrency = {max_concurrency}", diff --git a/ignition/cli/serve.py b/ignition/cli/serve.py index c30ab26c1..23ac9bf48 100644 --- a/ignition/cli/serve.py +++ b/ignition/cli/serve.py @@ -485,6 +485,7 @@ def debug_serve(args) -> int: options = _server_options(configuration, model, plan) options["thinking_token_budget"] = configuration.get("server.thinking_token_budget").value options["scheduler_checkpoint_extra_work_fraction"] = configuration.get("server.scheduler_checkpoint_extra_work_fraction").value + options["per_request_metrics"] = configuration.get("server.per_request_metrics").value print(json.dumps({"plan": plan.to_dict()}), file=sys.stderr, flush=True) if args.history_drafts is not None: if args.history_drafts and (plan.speculation is None or plan.speculation.draft_tokens == 0): diff --git a/tests/cli/test_config.py b/tests/cli/test_config.py index e07dbc70b..9a24fbd35 100644 --- a/tests/cli/test_config.py +++ b/tests/cli/test_config.py @@ -159,6 +159,8 @@ def test_compiler_worker_flag_overrides_configured_host_budget(tmp_path): ("[server]\nthinking_token_budget = 1.5\n", "must be int"), ("[server]\nthinking_token_budget = true\n", "must be int"), ("[server]\nthinking_token_budget = \"1536\"\n", "must be int"), + ("[server]\nper_request_metrics = 1\n", "per_request_metrics in .* must be bool"), + ("[server]\nper_request_metrics = \"true\"\n", "per_request_metrics in .* must be bool"), ("[defaults]\nmax_concurrency = true\n", "must be int"), ("[defaults]\nmax_concurrency = 0\n", "at least 1"), ("[defaults]\nspeculative_token_capacity = 0\n", "at least 1"), @@ -177,6 +179,15 @@ def test_invalid_files_are_usage_errors(tmp_path, text, message): load(tmp_path, text) +@pytest.mark.parametrize("text, expected, source", [ + ("", False, "default"), + ("[server]\nper_request_metrics = true\n", True, "[server]"), + ("[server]\nper_request_metrics = false\n", False, "[server]"), +]) +def test_per_request_metrics_configuration(tmp_path, text, expected, source): + assert load(tmp_path, text).get("server.per_request_metrics") == Setting(expected, source) + + @pytest.mark.parametrize("text, expected", [ ("0", 0), ("4096", 4096), ("16G", 16 << 30), ("16g", 16 << 30), ("1.5G", 3 << 29), ("512M", 512 << 20), ("8 GiB", 8 << 30), ("2T", 2 << 40), ("64K", 64 << 10), From 696082b8e143e122f78aee8e196565f7fd660ff6 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Sat, 28 Nov 2026 16:46:06 -0600 Subject: [PATCH 21/24] Document where Orbit reads per_request_metrics and that the flag only enables `docs/cli-design.md` gave `[server] per_request_metrics` as the configuration default of `--enable-per-request-metrics` without saying which node's file applies under `flare orbit run`, and did not say that the flag cannot turn the option off. The Orbit agent starts rank zero as `flare run`, and `Configuration::apply` applies the key from rank zero's node configuration, so Orbit already honors it there; a test pins that path instead of adding a second configuration read on the controller. The flag stays enable-only; the configuration key is the per-host setting. `flare-cli/src/config.rs` adds `orbit_rank_zero_reads_per_request_metrics_from_its_node_configuration`, which parses `flare orbit run`, forwards its rank-zero options as `flare run` arguments, and applies a node configuration. The `--help` text of `flare run` and `flare orbit run` names `[server].per_request_metrics` (rank zero's, for Orbit). The `docs/cli-design.md` flag row states that the flag can only enable the option, that the key sets it per host, and that Orbit reads rank zero's file. The documentation and `--help` text describe the configuration source Orbit uses; serving behavior does not change. Evidence: `cargo test --locked --manifest-path flare-cli/Cargo.toml --bin flare -- cli:: config::` passed 51 tests, including the Orbit test for an absent key, a true key, and the flag over a false key. `cargo check --locked --manifest-path flare-cli/Cargo.toml` passed. No Orbit group was run. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: enterprise/deepseek-v4.1-flash (omp agent); design-review=eb2f --- docs/cli-design.md | 2 +- flare-cli/src/cli.rs | 4 ++-- flare-cli/src/config.rs | 26 ++++++++++++++++++++++++++ 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/docs/cli-design.md b/docs/cli-design.md index 6c4365f4d..e5b04bd38 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -733,7 +733,7 @@ Help exits with status 0; usage errors go to stderr with status 2. Its options a | `--port N` | Listener port | `[server] port`, otherwise `8000` | | `--served-model-name ALIAS` | Replace the core's serving aliases with this nonblank alias | Core aliases | | `--api-key-file PATH` | File containing the serving API key; an empty file disables authentication | `[server] api_key`, otherwise no authentication | -| `--enable-per-request-metrics` | Add vLLM's per-request `metrics` timing object to OpenAI Chat, Completions, and Responses output; see [per-request metrics](api.md#per-request-metrics) | `[server] per_request_metrics`, otherwise off | +| `--enable-per-request-metrics` | Add vLLM's per-request `metrics` timing object to OpenAI Chat, Completions, and Responses output; see [per-request metrics](api.md#per-request-metrics). The flag can only enable the option; `[server] per_request_metrics` sets it per host | `[server] per_request_metrics`, read on rank zero's node under `flare orbit run`, otherwise off | | `--max-concurrency N` | Reduce concurrency within captured batch capacities | Model/default configuration, otherwise core default | | `--kv-cache-limit concurrency\|context\|memory` | Bound shared KV history by prepared context times selected concurrency, one prepared context, or available memory | `memory` | | `--memory-limit LIMIT` | Per-GPU occupied size (`30G`), free-memory reserve (`-30G`, including `-0G`), or fraction of total memory (`0.8`) | `[memory] reserve`, otherwise core serving reserve | diff --git a/flare-cli/src/cli.rs b/flare-cli/src/cli.rs index 12f68f929..d04c7e7bd 100644 --- a/flare-cli/src/cli.rs +++ b/flare-cli/src/cli.rs @@ -644,7 +644,7 @@ pub struct OrbitRun { pub api_key_file: Option, /// Add vLLM's per-request `metrics` timing object to OpenAI Chat, Completions, - /// and Responses output. + /// and Responses output; rank zero's [server].per_request_metrics also enables it. #[arg(long, help_heading = "Serving options")] pub enable_per_request_metrics: bool, @@ -858,7 +858,7 @@ pub struct Run { pub bypass_performance_check: bool, /// Add vLLM's per-request `metrics` timing object to OpenAI Chat, Completions, - /// and Responses output. + /// and Responses output; [server].per_request_metrics also enables it. #[arg(long, help_heading = "Serving options")] pub enable_per_request_metrics: bool, diff --git a/flare-cli/src/config.rs b/flare-cli/src/config.rs index 3d7536da8..a94a8101c 100644 --- a/flare-cli/src/config.rs +++ b/flare-cli/src/config.rs @@ -233,6 +233,32 @@ mod tests { } } + #[test] + fn orbit_rank_zero_reads_per_request_metrics_from_its_node_configuration() { + for (text, flag, expected) in [ + ("", false, false), + ("[server]\nper_request_metrics=true", false, true), + ("[server]\nper_request_metrics=false", true, true), + ] { + let mut arguments = vec!["flare", "orbit", "run", "model"]; + if flag { + arguments.push("--enable-per-request-metrics"); + } + let cli::Command::Orbit(orbit) = cli::Cli::try_parse_from(arguments).unwrap().command else { + panic!() + }; + let cli::OrbitCommand::Run(orbit) = orbit.command else { + panic!() + }; + // The Orbit agent starts rank zero as `flare run`, which applies the + // configuration file on rank zero's node. + let mut rank_zero = vec!["flare".to_string(), "run".into(), "model".into()]; + rank_zero.extend(orbit.rank_zero_options()); + let rank_zero: Vec<&str> = rank_zero.iter().map(String::as_str).collect(); + assert_eq!(configured(text, &rank_zero, &[]).1.enable_per_request_metrics, expected, "{text}"); + } + } + #[test] fn prefix_cache_drain_on_shutdown_defaults_and_flag_precedence() { let args = ["flare", "run", "model.safetensors"]; From 0f6cd4f73d97a23e9d88f6390ae812139884be77 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Sat, 28 Nov 2026 16:46:06 -0600 Subject: [PATCH 22/24] Define the per-request metrics null cases and token timestamps in the API reference The per-request metrics section of `docs/api.md` described `time_to_first_content_token_ms` as a field null only when an instant was not reached, although the encoder always writes null; applied the `n > 1` null to every protocol, although only Completions accepts `n > 1`; omitted the shape of a response with no generated token; and compared the instants to `choices[0].token_timestamps_ns`, which the file never defined. The section now states what `Encoder::metrics_value` produces. The null paragraph says `time_to_first_content_token_ms` is always null, limits the `n > 1` null to Completions, and states that a response with no generated token has every field null except `queue_time_ms`, which is null too when no model step included the request. The timestamp paragraph defines `return_token_timestamps` (requires `return_token_ids`), the aligned `choices[0].token_timestamps_ns` array, and the `performance` object, and points to the prepared model contract for field definitions. The `mean_itl_ms` row states that tokens one speculative step commits count as zero-length intervals, and the boundary paragraph states that the first scheduled instant is read after the worker packs the step's inputs, including vision inputs, and before submission. A client reading `docs/api.md` alone learns which `metrics` fields can carry a value and what the timestamp extension returns. Evidence: each statement was checked against `helios/src/server/protocol/encode.rs` (`enable_request_metrics`, `metrics_value`), `helios/src/server/observation.rs` (`ObservationOptions::parse`), `helios/src/server/runtime.rs` (the `first_scheduled_ns` stamp after packing), and `helios/model-contract.md`. The request-histogram section is unchanged. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: enterprise/deepseek-v4.1-flash (omp agent); design-review=eb2f --- docs/api.md | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/docs/api.md b/docs/api.md index 22c388d7b..3cc83edcf 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1008,11 +1008,13 @@ string, which the worker matches, does not change how they are measured: | `time_to_first_token_ms` | That first scheduled step to the completion of the step that committed the first generated token | | `time_to_first_content_token_ms` | Always null: Flare does not report when answer text first appeared, as vLLM permits for a value it cannot provide | | `generation_time_ms` | First to last committed generated token | -| `mean_itl_ms` | `generation_time_ms` divided by the generated tokens after the first | +| `mean_itl_ms` | `generation_time_ms` divided by the generated tokens after the first; tokens one speculative step commits share a completion instant, so each extra token counts as a zero-length interval | | `tokens_per_second` | Generated tokens, as `usage` counts them, over the first scheduled step to the last committed generated token | A step's completion instant is read once when the worker processes that step's -results, so tokens committed by one speculative step share it. The runtime reads +results, so tokens committed by one speculative step share it. The worker reads +the first scheduled step's instant after packing that step's inputs, including +an image's vision inputs, and before submitting the step. The runtime reads model-queue arrival when it builds the request group, before publishing the group to the worker channel, so `queue_time_ms` includes the channel send and worker pickup and starts later than vLLM's engine-core scheduler queue. @@ -1026,17 +1028,19 @@ for those streams. Flare has no equivalent of vLLM's `--enable-force-include-usage` server option, which forces the usage chunk and would close this gap. -All six fields are always present, and a field is null when the request did not -reach the instants it spans, such as `mean_itl_ms` for a single generated token. -With `n` greater than one `metrics` is null, and Completions with several prompts -omit it. - -A Chat request with `return_token_timestamps: true` also receives a top-level -`performance` object holding `ingress_ns`, `enqueue_ns`, `first_scheduled_ns` and -`reused_prompt_tokens`; the three instants are absolute nanoseconds on the same -process-local origin as `choices[0].token_timestamps_ns`. The -[prepared model contract](../helios/model-contract.md#token-and-timing-observation) -defines those fields. +`time_to_first_content_token_ms` is always null; the key is present so the object +has vLLM's six keys. Another field is null when the request did not reach the +instants it spans: `mean_itl_ms` for a single generated token, and, for a response +with no generated token, every field except `queue_time_ms`, which is also null +when no model step included the request. In Completions, `n` greater than one +makes `metrics` null, and several prompts omit it. + +A Chat request that sets `return_token_timestamps: true`, which requires +`return_token_ids: true`, receives the host instant of each generated token in +`choices[0].token_timestamps_ns`, aligned with `choices[0].token_ids`, and a +top-level `performance` object of request instants on the same process-local +origin; the [prepared model contract](../helios/model-contract.md#token-and-timing-observation) +defines both. ## Raw completions From e3829e62854767870783eeb69ee94b2f368a25de Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Sat, 28 Nov 2026 16:46:06 -0600 Subject: [PATCH 23/24] Share the step-generates test predicate and trim encoder metrics comments Three worker test drivers in `helios/src/server/runtime/phase_tests.rs` copied the predicate that decides whether a step samples a token, the per-request metrics encoder test fed reasoning and empty content events that no assertion reads, and `encode.rs` restated the placement and null rules that `docs/api.md#per-request-metrics` states. One helper, one answer event, and pointer comments keep each rule in one place. `phase_tests.rs` adds `generates`, used by `budget_pass`, `timed_pass`, and the tool-limit cancellation test. `metered_generation` in `helios/src/server/protocol/tests.rs` feeds one content event and records four generated tokens; `carriers` is a function returning borrowed frame and metrics values. `enable_request_metrics` and `metrics_value` carry one pointer comment each to `docs/api.md#per-request-metrics`. Every assertion of the metrics encoder test and the worker phase tests is unchanged; behavior is unchanged. Evidence: `cargo check --locked --manifest-path helios/Cargo.toml --features server` passed. `cargo test --locked --manifest-path helios/Cargo.toml --features runtime-core,server --lib -- server:: scheduler:: cache::` reported 819 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 does not involve these files. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: enterprise/deepseek-v4.1-flash (omp agent); design-review=eb2f --- helios/src/server/protocol/encode.rs | 7 ++----- helios/src/server/protocol/tests.rs | 21 ++++++++----------- helios/src/server/runtime/phase_tests.rs | 26 ++++++++++++------------ 3 files changed, 24 insertions(+), 30 deletions(-) diff --git a/helios/src/server/protocol/encode.rs b/helios/src/server/protocol/encode.rs index 652d8cc72..c612373d4 100644 --- a/helios/src/server/protocol/encode.rs +++ b/helios/src/server/protocol/encode.rs @@ -231,7 +231,7 @@ impl Encoder { self.continuous_usage = self.include_usage && enabled; } - /// Report vLLM's per-request `metrics`, placed as `docs/api.md` describes. + /// The `metrics` object or its omission, per `docs/api.md#per-request-metrics`. pub fn enable_request_metrics(&mut self, streaming: bool) { let placed = !streaming || self.include_usage || self.protocol == Protocol::Responses; self.metrics = match self.protocol { @@ -241,15 +241,12 @@ impl Encoder { _ => Some(RequestMetrics::Single(Timing::default())), }; } - /// Record the terminal instants and generated-token count of the generation. pub fn record_times(&mut self, arrival_ns: u64, times: RequestTimes, generated: u32) { if let Some(RequestMetrics::Single(timing)) = &mut self.metrics { (timing.arrival_ns, timing.times, timing.generated) = (arrival_ns, times, generated); } } - /// The `metrics` object, `null` when suppressed, or `None` when omitted. Each - /// interval is null when the generation did not reach its instants; Flare does - /// not report the content instant. + /// The `metrics` value, or `None` when omitted, per `docs/api.md#per-request-metrics`. pub fn metrics_value(&self) -> Option { let timing = match self.metrics.as_ref()? { RequestMetrics::Suppressed => return Some(Value::Null), diff --git a/helios/src/server/protocol/tests.rs b/helios/src/server/protocol/tests.rs index db0ebe713..dde84da66 100644 --- a/helios/src/server/protocol/tests.rs +++ b/helios/src/server/protocol/tests.rs @@ -2331,13 +2331,10 @@ fn metered(protocol: Protocol, prompts: usize, choices: usize, include_usage: bo ) } -/// Feed one generation that reasons and then answers, then finish it, returning -/// every frame. +/// Feed one answer of four generated tokens, then finish it, returning every frame. fn metered_generation(encoder: &mut Encoder, times: crate::server::metrics::RequestTimes) -> Vec { let mut frames = encoder.start(); - frames.extend(encoder.apply(0, vec![Event::Reasoning("think".into())]).unwrap()); - frames.extend(encoder.apply(0, vec![Event::Content(String::new()), Event::Content("answer".into())]).unwrap()); - frames.extend(encoder.apply(0, vec![Event::Content(" more".into())]).unwrap()); + frames.extend(encoder.apply(0, vec![Event::Content("answer".into())]).unwrap()); encoder.record_times(1_000_000, times, 4); frames.extend(encoder.finish(0, Termination::Eos, 4, 0, None).unwrap()); frames @@ -2363,15 +2360,15 @@ fn per_request_metrics_follow_vllm_placement_and_null_rules() { Value::Object(keys.into_iter().map(String::from).zip(values).collect()) }; let expected = object([json!(7.0), Value::Null, json!(30.0), json!(2.0), json!(10.0), json!(4e9 / 37e6)]); - let carriers = |frames: &[crate::server::protocol::Frame]| { + fn carriers(frames: &[crate::server::protocol::Frame]) -> Vec<(&Value, &Value)> { frames .iter() .filter_map(|frame| { - frame.data.get("metrics").or_else(|| frame.data.get("response")?.get("metrics")) - .map(|metrics| (frame.data.clone(), metrics.clone())) + let metrics = frame.data.get("metrics").or_else(|| frame.data.get("response")?.get("metrics"))?; + Some((&frame.data, metrics)) }) - .collect::>() - }; + .collect() + } for protocol in [Protocol::Chat, Protocol::Completions, Protocol::Responses] { // A stream carries the object on its final usage chunk or terminal response. let mut encoder = metered(protocol, 1, 1, true); @@ -2379,8 +2376,8 @@ fn per_request_metrics_follow_vllm_placement_and_null_rules() { let frames = metered_generation(&mut encoder, times); let carried = carriers(&frames); assert_eq!(carried.len(), 1, "{protocol:?}"); - let (frame, metrics) = &carried[0]; - assert_eq!(metrics, &expected, "{protocol:?}"); + let (frame, metrics) = carried[0]; + assert_eq!(*metrics, expected, "{protocol:?}"); if protocol == Protocol::Responses { assert_eq!(frame["type"], "response.completed"); } else { diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index b848d2d1a..4085bb555 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -369,6 +369,16 @@ fn planned(worker: &mut Worker<'_>, kind: GraphKind, sequence: u64) -> Scheduled step } +/// Whether the step samples a token for its first lane: decode and resume steps +/// do, and so does the prefill step that consumes the last prompt token. +fn generates(worker: &Worker<'_>, step: &ScheduledStep) -> bool { + let lane = &step.lanes[0]; + let live = worker.scheduler.request(lane.request).unwrap(); + matches!(step.kind, GraphKind::Decode | GraphKind::Resume) + || (step.kind == GraphKind::Prefill + && lane.start_position + lane.tokens as u64 == live.prompt_tokens as u64) +} + fn completion( worker: &Worker<'_>, step: &ScheduledStep, @@ -448,10 +458,7 @@ fn budget_pass(worker: &mut Worker<'_>, sequence: &mut u64, samples: &[u32]) { *sequence += 1; worker.reserve_and_pack(&step, Fence(*sequence)).unwrap(); let lane = &step.lanes[0]; - let live = worker.scheduler.request(lane.request).unwrap(); - let generates = matches!(step.kind, GraphKind::Decode | GraphKind::Resume) - || (step.kind == GraphKind::Prefill - && lane.start_position + lane.tokens as u64 == live.prompt_tokens as u64); + let generates = generates(worker, &step); let token = generates.then(|| samples.next().expect("unexpected generation")); let mut frame = completion(worker, &step, *sequence, token); if token.is_some_and(|token| worker.config.eos_token_ids.contains(&token)) @@ -4537,10 +4544,7 @@ fn timed_pass(worker: &mut Worker<'_>, samples: &[u32]) -> Vec { let step = worker.plan(0).unwrap().0.expect("timed pass must progress"); worker.reserve_and_pack(&step, Fence(sequence)).unwrap(); let lane = &step.lanes[0]; - let live = worker.scheduler.request(lane.request).unwrap(); - let generates = matches!(step.kind, GraphKind::Decode | GraphKind::Resume) - || (step.kind == GraphKind::Prefill - && lane.start_position + lane.tokens as u64 == live.prompt_tokens as u64); + let generates = generates(worker, &step); let token = generates.then(|| samples.next().expect("unexpected generation")); let mut frame = completion(worker, &step, sequence, token); if token.is_some_and(|token| worker.config.eos_token_ids.contains(&token)) { @@ -5023,11 +5027,7 @@ async fn disabled_parallel_calls_complete_http_and_stop_decoding() { if generated == samples.len() { break; } let step = worker.plan(0).unwrap().0.unwrap(); worker.reserve_and_pack(&step, Fence(sequence)).unwrap(); - let lane = &step.lanes[0]; - let live = worker.scheduler.request(lane.request).unwrap(); - let generates = matches!(step.kind, GraphKind::Decode | GraphKind::Resume) - || (step.kind == GraphKind::Prefill - && lane.start_position + lane.tokens as u64 == live.prompt_tokens as u64); + let generates = generates(&worker, &step); let token = generates.then(|| { let token = samples[generated]; generated += 1; token }); let frame = completion(&worker, &step, sequence, token); worker.complete(step.kind, frame).unwrap(); From 3e8fd2883745d80054958ab2185e8de9aebb5bd0 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Fri, 27 Nov 2026 22:00:43 -0600 Subject: [PATCH 24/24] Report the first content token of per-request metrics in streams vLLM's per-request `metrics` object includes `time_to_first_content_token_ms`, the time from the first scheduled step to the step whose output first produced answer text, and Flare reports that field as null. Clients that read the object for parity with vLLM's fields need the value. Only the HTTP decoder can recognize answer text, because reasoning, tool-call output, and text a named tool choice discards are separated after the worker publishes tokens, while only the worker knows when each model step completed. The worker already reads that completion instant once per step for the request histograms, so passing it to the stream before the step's output lets the encoder latch the instant at the first answer text without reading a clock. A stream that reports per-request metrics with a content instant asks the worker for `GenerationEvent::Committed { at_ns }` before each generating step's output; the `commits` admission flag reaches the worker through `generate_many_observed`, which the HTTP handler now uses for every submission, and `generate`, the only other single-prompt entry, calls `enqueue_many` directly. `output_event_capacity` adds one event per generated token for such requests. The encoder keeps the latest step instant and records it when the first non-empty content event passes tool-choice filtering. The HTTP handler builds the encoder before submission, because its placement rules decide whether a request needs commit instants. `docs/api.md` defines the field for streams, and `helios/model-contract.md` states the larger event budget. With `--enable-per-request-metrics`, a Chat, Completions, or Responses stream that carries `metrics` reports `time_to_first_content_token_ms`; JSON bodies and streams without answer text report null. The cost is one runtime event per generating model step for those streams; other requests and the option off are unchanged. Evidence: `server::protocol::tests::content_instant_excludes_reasoning_tool_calls_and_suppressed_text` checks that reasoning, tool calls, and text a named tool choice drops do not set the instant; `per_request_metrics_follow_vllm_placement_and_null_rules` checks the stream value and the null JSON-body value for every protocol; `per_request_metrics_report_the_runtime_instants_of_a_stopped_reasoning_answer` places the content instant inside the third generating worker step, after reasoning and its close; `per_request_metrics_reach_completions_and_responses_where_vllm_places_them` checks that plain text equals the first token instant; and `per_request_metrics_are_absent_without_the_option_and_null_for_several_choices` checks that no commit instants are requested with the option off or with several choices. `cargo test --locked --manifest-path helios/Cargo.toml --features runtime-core,server --lib -- server:: scheduler:: cache::` passed 820 tests; the one failure, `messages_image_hints_end_after_expansion_for_text_and_segmented_templates`, needs templates through `FLARE_TEST_TEMPLATE_DIR`, which this host does not have. No GPU or live server was used, and the cost of the extra events under load has not been measured. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=eb2f --- docs/api.md | 27 +++++---- helios/model-contract.md | 6 +- helios/src/server/http.rs | 55 +++++++++--------- helios/src/server/protocol/encode.rs | 30 ++++++++-- helios/src/server/protocol/tests.rs | 72 +++++++++++++++++++----- helios/src/server/runtime.rs | 61 ++++++++++++-------- helios/src/server/runtime/phase_tests.rs | 46 +++++++++++---- 7 files changed, 205 insertions(+), 92 deletions(-) diff --git a/docs/api.md b/docs/api.md index 3cc83edcf..19a5f81b5 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1006,7 +1006,7 @@ string, which the worker matches, does not change how they are measured: | --- | --- | | `queue_time_ms` | Model-queue arrival to the first model step that includes the request | | `time_to_first_token_ms` | That first scheduled step to the completion of the step that committed the first generated token | -| `time_to_first_content_token_ms` | Always null: Flare does not report when answer text first appeared, as vLLM permits for a value it cannot provide | +| `time_to_first_content_token_ms` | Streams only: the first scheduled step to the completion of the step whose output first produced non-empty answer text | | `generation_time_ms` | First to last committed generated token | | `mean_itl_ms` | `generation_time_ms` divided by the generated tokens after the first; tokens one speculative step commits share a completion instant, so each extra token counts as a zero-length interval | | `tokens_per_second` | Generated tokens, as `usage` counts them, over the first scheduled step to the last committed generated token | @@ -1014,10 +1014,15 @@ string, which the worker matches, does not change how they are measured: A step's completion instant is read once when the worker processes that step's results, so tokens committed by one speculative step share it. The worker reads the first scheduled step's instant after packing that step's inputs, including -an image's vision inputs, and before submitting the step. The runtime reads -model-queue arrival when it builds the request group, before publishing the group -to the worker channel, so `queue_time_ms` includes the channel send and worker -pickup and starts later than vLLM's engine-core scheduler queue. +an image's vision inputs, and before submitting the step. Reasoning text, +tool-call output, and answer text that a named tool choice discards do not count +as content; text that stop-string matching holds back counts from the step whose +output releases it. `time_to_first_content_token_ms` equals +`time_to_first_token_ms` when the first generated step produces answer text. The +runtime reads model-queue arrival when it builds the request group, before +publishing the group to the worker channel, so `queue_time_ms` includes the +channel send and worker pickup and starts later than vLLM's engine-core +scheduler queue. A JSON body carries `metrics` at the top level, and a Responses stream carries it in the `response` object of `response.completed` or `response.incomplete`. A Chat @@ -1028,12 +1033,12 @@ for those streams. Flare has no equivalent of vLLM's `--enable-force-include-usage` server option, which forces the usage chunk and would close this gap. -`time_to_first_content_token_ms` is always null; the key is present so the object -has vLLM's six keys. Another field is null when the request did not reach the -instants it spans: `mean_itl_ms` for a single generated token, and, for a response -with no generated token, every field except `queue_time_ms`, which is also null -when no model step included the request. In Completions, `n` greater than one -makes `metrics` null, and several prompts omit it. +All six fields are always present. A field is null when the request did not +reach the instants it spans: `mean_itl_ms` for a single generated token, +`time_to_first_content_token_ms` in a JSON body or a stream without answer text, +and, for a response with no generated token, every field except `queue_time_ms`, +which is also null when no model step included the request. In Completions, `n` +greater than one makes `metrics` null, and several prompts omit it. A Chat request that sets `return_token_timestamps: true`, which requires `return_token_ids: true`, receives the host instant of each generated token in diff --git a/helios/model-contract.md b/helios/model-contract.md index 668ad289e..f81db52da 100644 --- a/helios/model-contract.md +++ b/helios/model-contract.md @@ -359,8 +359,10 @@ its time to first token. observed stream includes usage on its terminal choice chunk. Observation flags and `include_usage` accept only booleans or null; null is equivalent to false. The response event budget includes one observation per generated token when -requested, in addition to presentation events. Observation changes no CUDA -graph, device allocation or replay ABI. +requested, in addition to presentation events, and one model-step completion +instant per generated token for a stream that reports +[per-request metrics](../docs/api.md#per-request-metrics) with a content instant. +Observation changes no CUDA graph, device allocation or replay ABI. `stop_token_ids` and `stop_token_sequences` accept explicit vocabulary IDs. At most sixteen sequences of at most 64 tokens are supported. Matching tokens diff --git a/helios/src/server/http.rs b/helios/src/server/http.rs index 6ed2ddc0d..3a72aad38 100644 --- a/helios/src/server/http.rs +++ b/helios/src/server/http.rs @@ -329,32 +329,6 @@ pub(super) async fn generate( state.run, state.ids.fetch_add(1, Ordering::Relaxed) ); - let submitted = if prompts.is_empty() { - Ok(vec![]) - } else if continuous_usage { - state.model.generate_many_observed(prompts, observation.timestamps) - } else if observation.token_ids && size == 1 { - state - .model - .generate_observed(prompts.remove(0), observation.timestamps) - .map(|g| vec![g]) - } else { - state.model.generate_many(prompts) - }; - let mut generation = match submitted { - Ok(g) => g, - Err(e) => return rejection(&state, protocol, &id, "admission", e), - }; - if !decoded.stream - && let Err(e) = runtime::await_admission(&mut generation).await - { - return rejection(&state, protocol, &id, "admission", e); - } - let enqueue_ns = generation.first().and_then(|g| g.enqueue_ns); - let mut iter = generation.into_iter(); - let mut generations: Vec> = (0..size) - .map(|i| if zero.contains(&i) { None } else { iter.next() }) - .collect(); let created = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default() @@ -384,9 +358,30 @@ pub(super) async fn generate( encoder.set_tool_grammars(tool_grammars); encoder.set_strict_validators(strict_validators); encoder.set_continuous_usage(continuous_usage); - if state.per_request_metrics { - encoder.enable_request_metrics(decoded.stream); + // The encoder decides where per-request metrics appear, and so whether the + // generation must report its model steps' completion instants. + let commits = state.per_request_metrics && encoder.enable_request_metrics(decoded.stream); + let submitted = if prompts.is_empty() { + Ok(vec![]) + } else { + let observed = (continuous_usage || observation.token_ids && size == 1) + .then_some(observation.timestamps); + state.model.generate_many_observed(prompts, observed, commits) + }; + let mut generation = match submitted { + Ok(g) => g, + Err(e) => return rejection(&state, protocol, &id, "admission", e), + }; + if !decoded.stream + && let Err(e) = runtime::await_admission(&mut generation).await + { + return rejection(&state, protocol, &id, "admission", e); } + let enqueue_ns = generation.first().and_then(|g| g.enqueue_ns); + let mut iter = generation.into_iter(); + let mut generations: Vec> = (0..size) + .map(|i| if zero.contains(&i) { None } else { iter.next() }) + .collect(); let streaming = decoded.stream; let stream_state = state.clone(); let stream_id = id.clone(); @@ -523,6 +518,10 @@ pub(super) async fn generate( } Ok(vec![]) } + GenerationEvent::Committed { at_ns } => { + encoder.record_commit(at_ns); + Ok(vec![]) + } GenerationEvent::Finished { generated_tokens, reused_prompt_tokens, diff --git a/helios/src/server/protocol/encode.rs b/helios/src/server/protocol/encode.rs index c612373d4..39a5ec822 100644 --- a/helios/src/server/protocol/encode.rs +++ b/helios/src/server/protocol/encode.rs @@ -78,6 +78,12 @@ struct Timing { arrival_ns: u64, times: RequestTimes, generated: u32, + /// Only a stream reports when text content first appeared. + streaming: bool, + /// Completion of the latest model step whose output the encoder received. + step_ns: Option, + /// Completion of the model step whose output first produced text content. + content_ns: Option, } pub(crate) struct Encoder { logprob_format: Option<(crate::server::inference::LogprobOptions, std::sync::Arc)>, @@ -231,15 +237,25 @@ impl Encoder { self.continuous_usage = self.include_usage && enabled; } - /// The `metrics` object or its omission, per `docs/api.md#per-request-metrics`. - pub fn enable_request_metrics(&mut self, streaming: bool) { + /// The `metrics` object or its omission, per `docs/api.md#per-request-metrics`; + /// returns whether the content instant applies, so the worker must send `Committed`. + pub fn enable_request_metrics(&mut self, streaming: bool) -> bool { let placed = !streaming || self.include_usage || self.protocol == Protocol::Responses; self.metrics = match self.protocol { Protocol::Messages => None, _ if !placed || self.prompts.len() > 1 => None, _ if self.choices_per_prompt > 1 => Some(RequestMetrics::Suppressed), - _ => Some(RequestMetrics::Single(Timing::default())), + _ => Some(RequestMetrics::Single(Timing { streaming, ..Timing::default() })), }; + streaming && matches!(self.metrics, Some(RequestMetrics::Single(_))) + } + /// Record the completion instant of the model step whose output follows. + pub fn record_commit(&mut self, at_ns: u64) { + if let Some(RequestMetrics::Single(timing)) = &mut self.metrics + && timing.streaming + { + timing.step_ns = Some(at_ns); + } } pub fn record_times(&mut self, arrival_ns: u64, times: RequestTimes, generated: u32) { if let Some(RequestMetrics::Single(timing)) = &mut self.metrics { @@ -259,7 +275,7 @@ impl Encoder { let generation = first.zip(last).map(|(first, last)| ms(first, last)); Some(json!({ "time_to_first_token_ms": scheduled.zip(first).map(|(s, f)| ms(s, f)), - "time_to_first_content_token_ms": Value::Null, + "time_to_first_content_token_ms": scheduled.zip(timing.content_ns).map(|(s, c)| ms(s, c)), "generation_time_ms": generation, "queue_time_ms": scheduled.map(|s| ms(timing.arrival_ns, s)), "mean_itl_ms": generation @@ -523,6 +539,12 @@ impl Encoder { { continue; } + if let Event::Content(text) = &event + && !text.is_empty() + && let Some(RequestMetrics::Single(timing)) = &mut self.metrics + { + timing.content_ns = timing.content_ns.or(timing.step_ns); + } match &event { Event::TokenLogprobs(entries) => { if self.protocol != Protocol::Responses { diff --git a/helios/src/server/protocol/tests.rs b/helios/src/server/protocol/tests.rs index dde84da66..74987e1e4 100644 --- a/helios/src/server/protocol/tests.rs +++ b/helios/src/server/protocol/tests.rs @@ -2331,10 +2331,16 @@ fn metered(protocol: Protocol, prompts: usize, choices: usize, include_usage: bo ) } -/// Feed one answer of four generated tokens, then finish it, returning every frame. +/// Feed one generation that reasons in its first committed step and answers in +/// its second, then finish it, returning every frame. fn metered_generation(encoder: &mut Encoder, times: crate::server::metrics::RequestTimes) -> Vec { let mut frames = encoder.start(); - frames.extend(encoder.apply(0, vec![Event::Content("answer".into())]).unwrap()); + encoder.record_commit(10_000_000); + frames.extend(encoder.apply(0, vec![Event::Reasoning("think".into())]).unwrap()); + encoder.record_commit(25_000_000); + frames.extend(encoder.apply(0, vec![Event::Content(String::new()), Event::Content("answer".into())]).unwrap()); + encoder.record_commit(40_000_000); + frames.extend(encoder.apply(0, vec![Event::Content(" more".into())]).unwrap()); encoder.record_times(1_000_000, times, 4); frames.extend(encoder.finish(0, Termination::Eos, 4, 0, None).unwrap()); frames @@ -2359,7 +2365,9 @@ fn per_request_metrics_follow_vllm_placement_and_null_rules() { ]; Value::Object(keys.into_iter().map(String::from).zip(values).collect()) }; - let expected = object([json!(7.0), Value::Null, json!(30.0), json!(2.0), json!(10.0), json!(4e9 / 37e6)]); + let expected = |content: Value| { + object([json!(7.0), content, json!(30.0), json!(2.0), json!(10.0), json!(4e9 / 37e6)]) + }; fn carriers(frames: &[crate::server::protocol::Frame]) -> Vec<(&Value, &Value)> { frames .iter() @@ -2370,14 +2378,15 @@ fn per_request_metrics_follow_vllm_placement_and_null_rules() { .collect() } for protocol in [Protocol::Chat, Protocol::Completions, Protocol::Responses] { - // A stream carries the object on its final usage chunk or terminal response. + // A stream reports the step that first produced text, after the reasoning + // step and skipping empty content, on its final usage chunk or terminal response. let mut encoder = metered(protocol, 1, 1, true); - encoder.enable_request_metrics(true); + assert!(encoder.enable_request_metrics(true)); let frames = metered_generation(&mut encoder, times); let carried = carriers(&frames); assert_eq!(carried.len(), 1, "{protocol:?}"); let (frame, metrics) = carried[0]; - assert_eq!(*metrics, expected, "{protocol:?}"); + assert_eq!(*metrics, expected(json!(22.0)), "{protocol:?}"); if protocol == Protocol::Responses { assert_eq!(frame["type"], "response.completed"); } else { @@ -2385,19 +2394,19 @@ fn per_request_metrics_follow_vllm_placement_and_null_rules() { assert!(frame["usage"].is_object()); } - // `http::generate` places a JSON body's object at the top level of the body - // built from `response`. + // A JSON body has no content instant; `http::generate` places the object at + // the top level of the body built from `response`. let mut encoder = metered(protocol, 1, 1, false); - encoder.enable_request_metrics(false); + assert!(!encoder.enable_request_metrics(false)); let _ = metered_generation(&mut encoder, times); assert!(encoder.response().get("metrics").is_none()); - assert_eq!(encoder.metrics_value(), Some(expected.clone())); + assert_eq!(encoder.metrics_value(), Some(expected(Value::Null))); } // Without usage reporting a Chat or Completions stream has no chunk to carry it. for protocol in [Protocol::Chat, Protocol::Completions] { let mut encoder = metered(protocol, 1, 1, false); - encoder.enable_request_metrics(true); + assert!(!encoder.enable_request_metrics(true)); assert!(carriers(&metered_generation(&mut encoder, times)).is_empty()); assert_eq!(encoder.metrics_value(), None); } @@ -2405,7 +2414,7 @@ fn per_request_metrics_follow_vllm_placement_and_null_rules() { // Messages has no vLLM metrics, in a stream or a body. for streaming in [false, true] { let mut encoder = metered(Protocol::Messages, 1, 1, true); - encoder.enable_request_metrics(streaming); + assert!(!encoder.enable_request_metrics(streaming)); assert!(carriers(&metered_generation(&mut encoder, times)).is_empty()); assert_eq!(encoder.metrics_value(), None); } @@ -2414,7 +2423,7 @@ fn per_request_metrics_follow_vllm_placement_and_null_rules() { for (prompts, choices, metrics) in [(1, 2, Some(Value::Null)), (2, 1, None)] { for streaming in [false, true] { let mut encoder = metered(Protocol::Completions, prompts, choices, true); - encoder.enable_request_metrics(streaming); + assert!(!encoder.enable_request_metrics(streaming)); let mut frames = Vec::new(); for index in 0..prompts * choices { encoder.record_times(1_000_000, times, 4); @@ -2444,3 +2453,40 @@ fn per_request_metrics_follow_vllm_placement_and_null_rules() { let _ = encoder.finish(0, Termination::OutputLimit, 0, 0, None).unwrap(); assert_eq!(encoder.metrics_value(), Some(object(std::array::from_fn(|_| Value::Null)))); } + +#[test] +fn content_instant_excludes_reasoning_tool_calls_and_suppressed_text() { + // Reasoning and a tool call commit first; the first text arrives in a later step. + let mut encoder = metered(Protocol::Chat, 1, 1, true); + assert!(encoder.enable_request_metrics(true)); + encoder.record_commit(5_000_000); + encoder.apply(0, vec![Event::Reasoning("r".into())]).unwrap(); + encoder.record_commit(6_000_000); + let mut call = events(); + call.retain(|event| !matches!(event, Event::Reasoning(_) | Event::Content(_))); + encoder.apply(0, call).unwrap(); + encoder.record_commit(9_000_000); + encoder.apply(0, vec![Event::Content("text".into())]).unwrap(); + encoder.record_times(0, crate::server::metrics::RequestTimes { + first_scheduled_ns: Some(1_000_000), + first_token_ns: Some(5_000_000), + last_token_ns: 9_000_000, + }, 3); + let metrics = encoder.metrics_value().unwrap(); + assert_eq!(metrics["time_to_first_token_ms"], 4.0); + assert_eq!(metrics["time_to_first_content_token_ms"], 8.0); + + // A named tool choice drops answer text, so no text content is produced. + let mut encoder = Encoder::new(Protocol::Chat, "named".into(), "model".into(), 1, 1, + vec![PromptUsage { tokens: 5, image_tokens: 0 }], tools(), + ToolChoice::Named("lookup".into()), true, true, json!({})); + assert!(encoder.enable_request_metrics(true)); + encoder.record_commit(5_000_000); + encoder.apply(0, events()).unwrap(); + encoder.record_times(0, crate::server::metrics::RequestTimes { + first_scheduled_ns: Some(1_000_000), + first_token_ns: Some(5_000_000), + last_token_ns: 5_000_000, + }, 1); + assert_eq!(encoder.metrics_value().unwrap()["time_to_first_content_token_ms"], Value::Null); +} diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index dd3e8b4fe..5e176eb13 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -59,15 +59,17 @@ impl Prompt { !self.stop_sequences.is_empty() || !self.stop_strings.is_empty() } - fn output_event_capacity(&self, minimum: usize, observed: bool) -> Result { - // Each generated token produces at most one presentation event and one - // optional observation. A reasoning cut's forced token is part of `after`. + fn output_event_capacity(&self, minimum: usize, observed: bool, commits: bool) -> Result { + // Each generated token produces at most one presentation event, one + // optional observation, and one optional commit instant, because every + // step that reports a commit instant generated at least one token. + // A reasoning cut's forced token is part of `after`. // Prompt-score chunks cover disjoint, nonempty ranges of the original prompt. let tokens = u64::from(self.max_new_tokens) + u64::from(self.reasoning_cut.as_ref().map_or(0, |cut| cut.after)); let events = usize::try_from(tokens) .ok() - .and_then(|tokens| tokens.checked_mul(if observed { 2 } else { 1 })) + .and_then(|tokens| tokens.checked_mul(1 + usize::from(observed) + usize::from(commits))) .and_then(|events| { events.checked_add(if self.prompt_logprobs { self.tokens.len() } else { 0 }) }) @@ -104,6 +106,12 @@ pub enum GenerationEvent { /// The request's lifecycle instants, as its completion histograms record them. times: super::metrics::RequestTimes, }, + /// The completion instant of the model step whose output events follow, on the + /// `observation::monotonic_ns` clock. Sent only to requests submitted with + /// `commits`, once per step that generated a token for the request. + Committed { + at_ns: u64, + }, AdmissionRejected(Error), Error(Error), } @@ -194,6 +202,8 @@ struct Incoming { failure: Arc>>, metrics: Arc, observation: Option, + /// Send `GenerationEvent::Committed` before each model step's output. + commits: bool, /// 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. @@ -831,30 +841,30 @@ impl ModelRuntime { self.healthy() } pub fn generate(&self, prompt: Prompt) -> Result { - self.enqueue(prompt, None) - } - - pub(super) fn generate_observed(&self, prompt: Prompt, timestamps: bool) -> Result { - self.enqueue(prompt, Some(timestamps)) - } - - fn enqueue(&self, prompt: Prompt, observation: Option) -> Result { - self.enqueue_many(vec![prompt], observation) + self.enqueue_many(vec![prompt], None, false) .map(|mut group| group.remove(0)) } pub fn generate_many(&self, prompts: Vec) -> Result> { - self.enqueue_many(prompts, None) + self.enqueue_many(prompts, None, false) } - pub(super) fn generate_many_observed(&self, prompts: Vec, timestamps: bool) -> Result> { - self.enqueue_many(prompts, Some(timestamps)) + /// `observation` adds an `ObservedToken` per committed token, timestamped when + /// `Some(true)`; `commits` adds a `Committed` event before each model step's output. + pub(super) fn generate_many_observed( + &self, + prompts: Vec, + observation: Option, + commits: bool, + ) -> Result> { + self.enqueue_many(prompts, observation, commits) } fn enqueue_many( &self, prompts: Vec, observation: Option, + commits: bool, ) -> Result> { if !self.healthy() { return Err(Error::admission( @@ -899,7 +909,7 @@ impl ModelRuntime { .map_err(|error| error.admission_context(AdmissionError::Invalid))?; // Tokio allocates queue blocks as events arrive, not at this capacity. let event_capacity = - prompt.output_event_capacity(self.event_capacity, observation.is_some())?; + prompt.output_event_capacity(self.event_capacity, observation.is_some(), commits)?; let (events, receiver) = async_mpsc::channel(event_capacity); let (admission, admitted) = oneshot::channel(); let (first_token, first_token_ready) = oneshot::channel(); @@ -919,6 +929,7 @@ impl ModelRuntime { failure: failure.clone(), metrics: self.metrics.clone(), observation, + commits, record: Default::default(), host_lookup: true, readmitted: false, @@ -1799,6 +1810,9 @@ impl<'a> Worker<'a> { // speculative round, adds one inter-token interval. if position == 0 { request.incoming.record.tokens_committed(completed_at_ns); + if request.incoming.commits { + request.incoming.emit(GenerationEvent::Committed { at_ns: completed_at_ns }); + } } request.incoming.observe_token(token.token); request.last_token = Some(token.token); @@ -3288,6 +3302,7 @@ mod tests { failure: failure.clone(), metrics: Arc::new(super::super::metrics::Metrics::new(0, 0, 0, 16)), observation: None, + commits: false, record: Default::default(), host_lookup: true, readmitted: false, @@ -3319,15 +3334,17 @@ mod tests { let (mut incoming, _generation) = stream(2); let prompt = &mut incoming.prompt; prompt.max_new_tokens = 1_000_000; - assert_eq!(prompt.output_event_capacity(128, false).unwrap(), 1_000_003); - assert_eq!(prompt.output_event_capacity(128, true).unwrap(), 2_000_003); + assert_eq!(prompt.output_event_capacity(128, false, false).unwrap(), 1_000_003); + assert_eq!(prompt.output_event_capacity(128, true, false).unwrap(), 2_000_003); + assert_eq!(prompt.output_event_capacity(128, false, true).unwrap(), 2_000_003); + assert_eq!(prompt.output_event_capacity(128, true, true).unwrap(), 3_000_003); prompt.reasoning_cut = Some(ReasoningCut { close: 8, after: 20, output: None }); prompt.prompt_logprobs = true; - assert_eq!(prompt.output_event_capacity(128, true).unwrap(), 2_000_044); + assert_eq!(prompt.output_event_capacity(128, true, false).unwrap(), 2_000_044); prompt.max_new_tokens = 0; prompt.reasoning_cut = None; - assert_eq!(prompt.output_event_capacity(128, false).unwrap(), 128); - assert!(prompt.output_event_capacity(usize::MAX, true).is_err()); + assert_eq!(prompt.output_event_capacity(128, false, false).unwrap(), 128); + assert!(prompt.output_event_capacity(usize::MAX, true, false).is_err()); } #[test] diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 4085bb555..a0683d261 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -252,6 +252,7 @@ impl Fixture { failure: failure.clone(), metrics: self.metrics.clone(), observation: Some(false), + commits: false, record: Default::default(), host_lookup: true, readmitted: false, @@ -3752,7 +3753,7 @@ fn unread_responses_finish_and_release_model_resources_but_retain_admission_capa let mut slow_prompt = prompt(512); slow_prompt.logprobs = logprobs; slow_prompt.stop_sequences = vec![vec![2, 3]]; - let mut slow = runtime.generate_observed(slow_prompt, true).unwrap(); + let mut slow = runtime.generate_many_observed(vec![slow_prompt], Some(true), false).unwrap().remove(0); let mut worker = fixture.worker(receiver); assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); let mut tokens = vec![1; 512]; @@ -3806,7 +3807,7 @@ fn unread_response_keeps_its_budget_through_a_reasoning_continuation() { positions: vec![[0; 3]], vision_token_indices: vec![-1], ..Default::default() }); prompt.reasoning_cut = Some(budget_cut(4, 81)); - let mut generation = runtime.generate_observed(prompt, false).unwrap(); + let mut generation = runtime.generate_many_observed(vec![prompt], Some(false), false).unwrap().remove(0); let mut worker = fixture.worker(receiver); assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); let mut sequence = 0; @@ -4563,14 +4564,15 @@ fn timed_pass(worker: &mut Worker<'_>, samples: &[u32]) -> Vec { } /// Serve one HTTP request through a worker that `timed_pass` drives, returning the -/// step bounds and the JSON body or the SSE `data` payloads of a stream. +/// step bounds, the JSON body or the SSE `data` payloads of a stream, and whether +/// the request asked the worker for commit instants. async fn served_through_worker( fixture: fn() -> Fixture, per_request_metrics: bool, path: &str, body: serde_json::Value, samples: &[u32], -) -> (Vec, Vec) { +) -> (Vec, Vec, bool) { use axum::{Extension, extract::State}; let (sender, receiver) = mpsc::sync_channel(4); let mut state = http_state_for(fixture(), sender, None, &[]); @@ -4589,6 +4591,7 @@ async fn served_through_worker( }) .await .unwrap(); + let commits = group[0].commits; let steps = { let worker_fixture = fixture(); let (queue, inbound) = mpsc::channel(); @@ -4610,14 +4613,14 @@ async fn served_through_worker( } else { vec![serde_json::from_slice(&bytes).unwrap()] }; - (steps, values) + (steps, values, commits) } #[tokio::test] async fn performance_reports_the_first_scheduled_model_step() { use serde_json::json; for stream in [false, true] { - let (steps, values) = served_through_worker( + let (steps, values, _) = served_through_worker( || Fixture::new().text_inputs(), false, "/v1/chat/completions", @@ -4653,6 +4656,7 @@ struct Served { arrival_ns: u64, scheduled_ns: u64, first_ns: u64, + content_ns: Option, last_ns: u64, } @@ -4667,11 +4671,15 @@ fn served_instants(values: &[serde_json::Value]) -> (serde_json::Value, Served) .find(|value| value.get("performance").is_some()) .unwrap()["performance"]; let scheduled_ns = performance["first_scheduled_ns"].as_u64().unwrap(); - let first_ns = scheduled_ns + (metrics["time_to_first_token_ms"].as_f64().unwrap() * 1e6).round() as u64; + let after = |field: &str| { + metrics[field].as_f64().map(|ms| scheduled_ns + (ms * 1e6).round() as u64) + }; + let first_ns = after("time_to_first_token_ms").unwrap(); let served = Served { arrival_ns: scheduled_ns - (metrics["queue_time_ms"].as_f64().unwrap() * 1e6).round() as u64, scheduled_ns, first_ns, + content_ns: after("time_to_first_content_token_ms"), last_ns: first_ns + (metrics["generation_time_ms"].as_f64().unwrap() * 1e6).round() as u64, }; // The HTTP ingress precedes model-queue arrival, which precedes enqueue_ns. @@ -4693,7 +4701,7 @@ async fn per_request_metrics_report_the_runtime_instants_of_a_stopped_reasoning_ // Reasoning, its close, the first answer text, then the stop string. let samples = [token("b"), token(""), token("c"), token("d")]; for stream in [true, false] { - let (steps, values) = served_through_worker( + let (steps, values, commits) = served_through_worker( Fixture::reasoning, true, "/v1/chat/completions", @@ -4704,6 +4712,7 @@ async fn per_request_metrics_report_the_runtime_instants_of_a_stopped_reasoning_ &samples, ) .await; + assert_eq!(commits, stream); let carriers: Vec<_> = values.iter().filter(|value| value.get("metrics").is_some()).collect(); assert_eq!(carriers.len(), 1); if stream { @@ -4723,7 +4732,13 @@ async fn per_request_metrics_report_the_runtime_instants_of_a_stopped_reasoning_ assert!(within(&steps[0], served.scheduled_ns)); assert!(within(generating[0], served.first_ns)); assert!(within(generating[3], served.last_ns)); - assert_eq!(metrics["time_to_first_content_token_ms"], Value::Null); + if stream { + // Reasoning and its close precede the first answer text by two steps. + assert!(within(generating[2], served.content_ns.unwrap())); + assert!(metrics["time_to_first_content_token_ms"].as_f64() > metrics["time_to_first_token_ms"].as_f64()); + } else { + assert_eq!(served.content_ns, None); + } let ms = |ns: u64| ns as f64 / 1e6; assert!((metrics["mean_itl_ms"].as_f64().unwrap() - ms(served.last_ns - served.first_ns) / 3.0).abs() < 1e-5); assert!((metrics["tokens_per_second"].as_f64().unwrap() * ms(served.last_ns - served.scheduled_ns) / 1e3 - 4.0).abs() < 1e-6); @@ -4744,7 +4759,7 @@ async fn per_request_metrics_reach_completions_and_responses_where_vllm_places_t if path == "/v1/completions" && stream { body["stream_options"] = json!({"include_usage":true}); } - let (steps, values) = served_through_worker( + let (steps, values, commits) = served_through_worker( || Fixture::new().text_inputs(), true, path, @@ -4752,6 +4767,7 @@ async fn per_request_metrics_reach_completions_and_responses_where_vllm_places_t &[1, 2], ) .await; + assert_eq!(commits, stream); let carriers: Vec<(&Value, &Value)> = values .iter() .filter_map(|value| { @@ -4775,7 +4791,11 @@ async fn per_request_metrics_reach_completions_and_responses_where_vllm_places_t assert!(generation >= 3.0 && generation * 1e6 <= (generating[1].end_ns - generating[0].start_ns) as f64); assert!(ttft >= 0.0 && metrics["queue_time_ms"].as_f64().unwrap() >= 0.0); assert_eq!(metrics["mean_itl_ms"], metrics["generation_time_ms"]); - assert_eq!(metrics["time_to_first_content_token_ms"], Value::Null); + // Plain text is content from the first token. + assert_eq!( + metrics["time_to_first_content_token_ms"], + if stream { metrics["time_to_first_token_ms"].clone() } else { Value::Null } + ); } } } @@ -4784,7 +4804,7 @@ async fn per_request_metrics_reach_completions_and_responses_where_vllm_places_t async fn per_request_metrics_are_absent_without_the_option_and_null_for_several_choices() { use serde_json::{Value, json}; for stream in [false, true] { - let (_, values) = served_through_worker( + let (_, values, commits) = served_through_worker( || Fixture::new().text_inputs(), false, "/v1/completions", @@ -4793,6 +4813,7 @@ async fn per_request_metrics_are_absent_without_the_option_and_null_for_several_ &[1, 2], ) .await; + assert!(!commits); assert!(values.iter().all(|value| value.get("metrics").is_none())); assert!(values.iter().any(|value| value["usage"]["completion_tokens"] == 2)); } @@ -4819,6 +4840,7 @@ async fn per_request_metrics_are_absent_without_the_option_and_null_for_several_ }) .await .unwrap(); + assert!(group.iter().all(|incoming| !incoming.commits)); for incoming in &group { incoming.notify_admission(Ok(())); incoming.observe_token(1);