diff --git a/docs/api.md b/docs/api.md index b9d61f71b..843e80712 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` @@ -879,6 +901,26 @@ 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. +Final output from Chat Completions, Completions, Messages, and Responses also +carries a llama.cpp-compatible `timings` object. `prompt_ms` spans from the first +model step that included the request to the earliest committed generated token, +and `prompt_n` counts the prompt tokens that step had to prefill, which is +`cache_n` fewer than the prompt total. `predicted_ms` spans the earliest to the +latest committed generated token, and `predicted_n` is the generated-token count +usage reports. `predicted_per_token_ms` and `predicted_per_second` divide that +span by the token intervals after each choice's first token, so one choice +reports its decode rate over its remaining tokens. `draft_n` and +`draft_n_accepted` count speculative drafts offered for verification and accepted; +both keys appear only when drafts were offered. `prompt_per_token_ms`, +`prompt_per_second`, `predicted_per_token_ms`, and `predicted_per_second` report +zero rather than an undefined value when their interval or token count is zero. + +Streams carry `timings` on the usage chunk when `stream_options.include_usage` is +set, otherwise on the chunk that completes the last choice. Messages reports it on +the `message_delta` event, and Responses reports it beside `response` on +`response.completed` or `response.incomplete`. The `[DONE]` sentinel, cancelled +requests, and failed requests carry no `timings`. + ## Raw completions `prompt` accepts a string, an array of strings, a token-ID array, or an array of 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..2296df3b9 100644 --- a/helios/src/server/http.rs +++ b/helios/src/server/http.rs @@ -519,9 +519,12 @@ pub(super) async fn generate( reused_prompt_tokens, termination, stop_sequence, + times, + drafts, .. } => { reused_total += reused_prompt_tokens; + encoder.record_timing(index, times, drafts); let result = decoders[index] .finish(if encoder.tool_limit_reached { crate::output::Termination::Cancelled } else { termination }) .and_then(|events| encoder.apply(index, events)) @@ -579,6 +582,9 @@ pub(super) async fn generate( } } let mut response = encoder.response(); + if let Some(timings) = encoder.timings_value() { + response["timings"] = timings; + } if protocol == Protocol::Chat { if let Some(ids) = prompt_ids { response["prompt_token_ids"] = json!(ids); @@ -600,6 +606,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 +617,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 +635,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..04a92f5c0 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 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/protocol/encode.rs b/helios/src/server/protocol/encode.rs index 2d1ddabcf..8da77e65a 100644 --- a/helios/src/server/protocol/encode.rs +++ b/helios/src/server/protocol/encode.rs @@ -94,6 +94,7 @@ pub(crate) struct Encoder { choices_per_prompt: usize, usage: Vec, reasons: Vec>, + timings: Vec>, stop: Option, sequence: u64, metadata: Value, @@ -133,6 +134,7 @@ impl Encoder { outputs: (0..choices).map(|_| ResponseOutput::default()).collect(), usage: vec![Usage::default(); choices], reasons: vec![None; choices], + timings: vec![None; choices], id, model, created, @@ -223,6 +225,16 @@ impl Encoder { pub fn report_reasoning_tokens(&mut self, index: usize, tokens: u32) { self.usage[index].reasoning = tokens; } + /// Record one choice's lifecycle instants and draft counts. `finish` renders + /// them as the `timings` object of the request's final output. + pub fn record_timing( + &mut self, + index: usize, + times: crate::server::metrics::RequestTimes, + drafts: crate::server::runtime::DraftCounts, + ) { + self.timings[index] = Some((times, drafts)); + } fn named(&mut self, name: &str, mut data: Value) -> Frame { data["type"] = json!(name); if self.protocol == Protocol::Responses { @@ -645,13 +657,22 @@ impl Encoder { )); } if self.reasons.iter().all(Option::is_some) { + let timings = self.timings_value(); match self.protocol { Protocol::Chat | Protocol::Completions => { if self.include_usage { let mut frame = self.chunk(0, Value::Null, Value::Null); frame.data["choices"] = json!([]); frame.data["usage"] = self.usage_value(); + if let Some(timings) = timings { + frame.data["timings"] = timings; + } frames.push(frame); + } else if let Some(timings) = timings + && let Some(last) = frames.last_mut() + { + // The chunk pushed above completes the last choice. + last.data["timings"] = timings; } frames.push(Frame { event: None, @@ -661,29 +682,36 @@ impl Encoder { } Protocol::Messages => { let response = self.response(); - frames.push(self.named("message_delta",json!({"delta":{"stop_reason":response["stop_reason"],"stop_sequence":response["stop_sequence"]},"usage":self.usage_value()}))); + let mut data = json!({"delta":{"stop_reason":response["stop_reason"],"stop_sequence":response["stop_sequence"]},"usage":self.usage_value()}); + if let Some(timings) = timings { + data["timings"] = timings; + } + frames.push(self.named("message_delta", data)); frames.push(self.named("message_stop", json!({}))); } Protocol::Responses => { let response = self.response(); + let mut data = json!({"response":response}); + if let Some(timings) = timings { + data["timings"] = timings; + } frames.push(self.named( if reason == "length" { "response.incomplete" } else { "response.completed" }, - json!({"response":response}), + data, )); } } } Ok(frames) } - pub fn usage_value(&self) -> Value { + /// Prompt, cached prompt, and generated token counts shared by usage and timings. + fn totals(&self) -> (usize, u64, u64) { 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(); let generated: u64 = self.usage.iter().map(|u| u.generated as u64).sum(); - let reasoning: u64 = self.usage.iter().map(|u| u.reasoning as u64).sum(); // Prompt usage counts each input once even with n > 1. Use its first // choice's admission lookup, independent of completion order or reuse // by later siblings after that choice has published a checkpoint. @@ -693,6 +721,68 @@ impl Encoder { .step_by(self.choices_per_prompt) .map(|u| u.cached) .sum(); + (prompt_tokens, cached, generated) + } + /// llama.cpp-compatible request timing: prefill from the earliest scheduled + /// model step that included the request to the earliest committed generated + /// token, decode from the earliest to the latest committed token. `None` + /// until a choice records its times. + pub fn timings_value(&self) -> Option { + let recorded: Vec<&(crate::server::metrics::RequestTimes, crate::server::runtime::DraftCounts)> = + self.timings.iter().flatten().collect(); + if recorded.is_empty() { + return None; + } + let (prompt_tokens, cached, generated) = self.totals(); + let first_scheduled = recorded + .iter() + .filter_map(|(times, _)| times.first_scheduled_ns) + .min(); + let first_token = recorded + .iter() + .filter_map(|(times, _)| times.first_token_ns) + .min(); + let last_token = recorded.iter().map(|(times, _)| times.last_token_ns).max(); + let prompt_n = (prompt_tokens as u64).saturating_sub(cached); + let prompt_ms = match (first_scheduled, first_token) { + (Some(scheduled), Some(first)) => first.saturating_sub(scheduled) as f64 / 1e6, + _ => 0.0, + }; + let predicted_n = generated; + let predicted_ms = match (first_token, last_token) { + (Some(first), Some(last)) => last.saturating_sub(first) as f64 / 1e6, + _ => 0.0, + }; + // Each recorded choice's first token is counted in `predicted_n` but starts + // decode rather than advancing it, so its interval count is one less. + let first_tokens = recorded + .iter() + .filter(|(times, _)| times.first_token_ns.is_some()) + .count() as u64; + let intervals = predicted_n.saturating_sub(first_tokens); + let mut timings = json!({ + "cache_n": cached, + "prompt_n": prompt_n, + "prompt_ms": prompt_ms, + "prompt_per_token_ms": if prompt_n == 0 { 0.0 } else { prompt_ms / prompt_n as f64 }, + "prompt_per_second": if prompt_ms == 0.0 { 0.0 } else { prompt_n as f64 * 1000.0 / prompt_ms }, + "predicted_n": predicted_n, + "predicted_ms": predicted_ms, + "predicted_per_token_ms": if intervals == 0 { 0.0 } else { predicted_ms / intervals as f64 }, + "predicted_per_second": if predicted_ms == 0.0 { 0.0 } else { intervals as f64 * 1000.0 / predicted_ms }, + }); + let offered: u64 = recorded.iter().map(|(_, drafts)| drafts.offered).sum(); + if offered > 0 { + timings["draft_n"] = json!(offered); + timings["draft_n_accepted"] = + json!(recorded.iter().map(|(_, drafts)| drafts.accepted).sum::()); + } + Some(timings) + } + pub fn usage_value(&self) -> Value { + let (prompt_tokens, cached, generated) = self.totals(); + let image_tokens: usize = self.prompts.iter().map(|p| p.image_tokens).sum(); + let reasoning: u64 = self.usage.iter().map(|u| u.reasoning as u64).sum(); match self.protocol { Protocol::Chat | Protocol::Completions => { let mut details = json!({"cached_tokens":cached}); diff --git a/helios/src/server/protocol/tests.rs b/helios/src/server/protocol/tests.rs index ead6a6cfa..1bf3400c7 100644 --- a/helios/src/server/protocol/tests.rs +++ b/helios/src/server/protocol/tests.rs @@ -1361,6 +1361,101 @@ fn image_usage_is_a_prompt_subset_and_stream_usage_remains_opt_in() { } } +#[test] +fn timings_report_prefill_decode_and_drafts_on_final_output() { + let times = crate::server::metrics::RequestTimes { + first_scheduled_ns: Some(1_000_000_000), + first_token_ns: Some(1_500_000_000), + last_token_ns: 2_500_000_000, + }; + let drafts = crate::server::runtime::DraftCounts { + offered: 6, + accepted: 4, + }; + let expected = json!({"cache_n":9,"prompt_n":8,"prompt_ms":500.0, + "prompt_per_token_ms":62.5,"prompt_per_second":16.0, + "predicted_n":5,"predicted_ms":1000.0, + "predicted_per_token_ms":250.0,"predicted_per_second":4.0, + "draft_n":6,"draft_n_accepted":4}); + for protocol in [ + Protocol::Chat, + Protocol::Completions, + Protocol::Messages, + Protocol::Responses, + ] { + let mut enc = encoder(protocol); + let mut frames = enc.start(); + enc.record_timing(0, times, drafts); + frames.extend(enc.finish(0, Termination::OutputLimit, 5, 9, None).unwrap()); + assert_eq!(enc.timings_value().unwrap(), expected, "value for {protocol:?}"); + let carrying: Vec<_> = frames + .iter() + .filter(|frame| frame.data.get("timings").is_some()) + .collect(); + assert_eq!(carrying.len(), 1, "one frame carries timings for {protocol:?}"); + assert_eq!(carrying[0].data["timings"], expected, "frame for {protocol:?}"); + let placed = match protocol { + Protocol::Chat | Protocol::Completions => &frames[frames.len() - 2], + Protocol::Messages => frames + .iter() + .find(|frame| frame.data["type"] == "message_delta") + .unwrap(), + Protocol::Responses => frames + .iter() + .find(|frame| frame.data["type"] == "response.incomplete") + .unwrap(), + }; + assert_eq!(placed.data["timings"], expected, "placement for {protocol:?}"); + } + // Without recorded times every protocol omits the object. + let mut enc = encoder(Protocol::Chat); + let mut frames = enc.start(); + frames.extend(enc.finish(0, Termination::Eos, 5, 9, None).unwrap()); + assert!(enc.timings_value().is_none()); + assert!(frames.iter().all(|frame| frame.data.get("timings").is_none())); + // A Chat stream without stream usage carries timings on the finish chunk. + let mut enc = Encoder::new( + Protocol::Chat, + "c".into(), + "m".into(), + 1, + 1, + vec![PromptUsage { + tokens: 17, + image_tokens: 0, + }], + vec![], + ToolChoice::Auto, + true, + false, + json!({}), + ); + let mut frames = enc.start(); + enc.record_timing(0, times, drafts); + frames.extend(enc.finish(0, Termination::OutputLimit, 5, 9, None).unwrap()); + let finish = frames + .iter() + .find(|frame| frame.data["choices"][0]["finish_reason"].is_string()) + .unwrap(); + assert_eq!(finish.data["timings"], expected); + assert_eq!( + frames + .iter() + .filter(|frame| frame.data.get("timings").is_some()) + .count(), + 1 + ); + // Draft keys appear only when drafts were offered. + let mut enc = encoder(Protocol::Chat); + let mut frames = enc.start(); + enc.record_timing(0, times, crate::server::runtime::DraftCounts::default()); + frames.extend(enc.finish(0, Termination::OutputLimit, 5, 9, None).unwrap()); + let timings = enc.timings_value().unwrap(); + assert!(timings.get("draft_n").is_none()); + assert!(timings.get("draft_n_accepted").is_none()); + assert_eq!(timings["predicted_per_second"], 4.0); +} + #[test] fn continuous_usage_counts_hidden_and_merged_tokens_without_extra_text_frames() { for protocol in [Protocol::Chat, Protocol::Completions] { diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index 745cc0805..963e7835d 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, + times: super::metrics::RequestTimes, + drafts: DraftCounts, }, AdmissionRejected(Error), Error(Error), @@ -190,6 +192,11 @@ struct Incoming { failure: Arc>>, metrics: Arc, observation: Option, + /// Lifecycle instants for completion histograms; preserved when a preempted request is parked. + times: super::metrics::RequestTimes, + /// Drafts offered and accepted by this request's rounds; preserved when a preempted + /// request is parked, like `times`. + drafts: DraftCounts, /// 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. @@ -296,6 +303,8 @@ impl Incoming { reason: "stop", termination: crate::output::Termination::Cancelled, stop_sequence: None, + times: self.times, + drafts: self.drafts, }); } @@ -398,6 +407,13 @@ struct Carried { seed: Option, } +/// Speculative drafts offered for verification and accepted, summed over a request's lifetime. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct DraftCounts { + pub offered: u64, + pub accepted: u64, +} + /// The sampling seed of a preempted request's continuation after `generated` tokens. /// Readmission restarts the device's random streams, so the continuation draws from /// a stream that depends on the seed and the preemption point instead of repeating @@ -908,6 +924,8 @@ impl ModelRuntime { failure: failure.clone(), metrics: self.metrics.clone(), observation, + times: Default::default(), + drafts: Default::default(), host_lookup: true, readmitted: false, blocked: None, @@ -1648,6 +1666,8 @@ impl<'a> Worker<'a> { let mut draft_rounds = 0; let mut verification_drafts = 0; let mut verification_rounds = 0; + // Per-request drafts, applied once the scheduler accepts the completion. + let mut drafts = Vec::new(); if matches!( kind, GraphKind::Prefill @@ -1676,11 +1696,14 @@ impl<'a> Worker<'a> { if let Some(vector) = record.vector.as_ref() { let offered = (vector.offered_drafts as usize).min(lane.tokens.saturating_sub(1)); + let accepted_drafts = + (vector.accepted_drafts as usize).min(offered) as u64; verification_drafts += offered as u64; if offered > 0 { - accepted += (vector.accepted_drafts as usize).min(offered) as u64; + accepted += accepted_drafts; draft_rounds += 1; } + drafts.push((lane.request, offered as u64, accepted_drafts)); } } } @@ -1700,6 +1723,15 @@ impl<'a> Worker<'a> { self.metrics .progress(prefill, generated.len(), accepted, draft_rounds, verification_drafts, verification_rounds); + for (request, offered, accepted_drafts) in drafts { + if let Some(active) = self.active[request.slot as usize] + .as_mut() + .filter(|active| active.request == request) + { + active.incoming.drafts.offered += offered; + active.incoming.drafts.accepted += accepted_drafts; + } + } self.metrics.replay_completed(completed_at_ns, completion.timing, prefill); if prefill > 0 && self.store.is_some() { self.observe_prefill_rate(completion.fence, prefill); @@ -1768,6 +1800,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 +1863,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 @@ -1850,6 +1888,8 @@ impl<'a> Worker<'a> { .text_stops .as_ref() .and_then(|s| s.matched().map(str::to_owned)), + times: request.incoming.times, + drafts: request.incoming.drafts, }); stopped.push(token.request); } @@ -1981,7 +2021,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 @@ -2019,6 +2064,8 @@ impl<'a> Worker<'a> { } else { crate::output::Termination::OutputLimit }, + times: request.incoming.times, + drafts: request.incoming.drafts, }); if user_stop { self.scheduler.cancel(request.request)?; @@ -2172,6 +2219,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 +3284,8 @@ mod tests { failure: failure.clone(), metrics: Arc::new(super::super::metrics::Metrics::new(0, 0, 0, 16)), observation: None, + times: Default::default(), + drafts: 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..9348c1a92 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -248,6 +248,8 @@ impl Fixture { failure: failure.clone(), metrics: self.metrics.clone(), observation: Some(false), + times: Default::default(), + drafts: Default::default(), host_lookup: true, readmitted: false, prompt_score_end: 0, @@ -507,8 +509,13 @@ fn budget_events( prompt_tokens, generated_tokens, reason, + times, .. } => { + // A completed generation reports the instants its histograms record. + assert!(times.first_scheduled_ns.is_some()); + assert!(times.first_token_ns.is_some()); + assert!(times.last_token_ns >= times.first_token_ns.unwrap()); finished.push((prompt_tokens, generated_tokens, reason)); } GenerationEvent::Error(error) | GenerationEvent::AdmissionRejected(error) => { @@ -572,6 +579,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, @@ -1655,6 +1670,20 @@ fn speculative_dashboard_counts_live_rounds_and_batched_forward_passes() { let metrics = fixture.metrics.snapshot(!copy); assert_eq!((metrics.prefill_tokens, metrics.generated_tokens), (13, 4)); assert_eq!((metrics.accepted_drafts, metrics.draft_rounds), (2, 1)); + assert_eq!( + worker + .active + .iter() + .flatten() + .next() + .unwrap() + .incoming + .drafts, + DraftCounts { + offered: 3, + accepted: 2 + } + ); assert_eq!( (metrics.verification_drafts, metrics.verification_rounds), (3, 1) @@ -4416,6 +4445,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")); } } @@ -4433,6 +4467,7 @@ async fn first_response_http_nonstream_records_only_when_completed_body_is_offer 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(), drafts: Default::default(), }); let response = response.await.unwrap(); assert_eq!(state.first_response.snapshot().samples, 0); @@ -4444,6 +4479,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) + ))); } } @@ -4472,6 +4518,7 @@ async fn unread_http_stream_preserves_all_tokens_and_its_terminal_event() { 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(), drafts: Default::default(), }); } assert!(!incoming[0].cancelled.load(Ordering::Acquire)); @@ -4691,6 +4738,8 @@ 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(), + drafts: Default::default(), }); assert!(!incoming.cancelled.load(Ordering::Acquire)); assert_eq!(incoming.publications.get(), 3000); @@ -4728,6 +4777,108 @@ async fn paused_http_bodies_preserve_output_and_completion_for_every_protocol() } } +#[tokio::test] +async fn http_final_output_reports_timings_for_every_protocol() { + use axum::{Extension, extract::State}; + use serde_json::json; + let times = crate::server::metrics::RequestTimes { + first_scheduled_ns: Some(1_000_000_000), + first_token_ns: Some(1_500_000_000), + last_token_ns: 2_500_000_000, + }; + for (path, mut body) in [ + ( + "/v1/chat/completions", + json!({"messages":[{"role":"user","content":"a"}], "max_tokens":2}), + ), + ( + "/v1/completions", + json!({"prompt":"a", "max_tokens":2}), + ), + ( + "/v1/messages", + json!({"messages":[{"role":"user","content":"a"}], "max_tokens":2}), + ), + ( + "/v1/responses", + json!({"input":"a", "max_output_tokens":2}), + ), + ] { + for stream in [false, true] { + let (sender, receiver) = mpsc::sync_channel(4); + let state = http_state_for(Fixture::new(), sender, None, &[]); + body["model"] = json!("qwen-worker-phases"); + body["stream"] = json!(stream); + 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") + .header("anthropic-version", "2023-06-01") + .body(axum::body::Body::from(body.to_string())) + .unwrap(); + let response = tokio::spawn(super::super::http::generate( + State(state.clone()), + Extension(ingress), + request, + )); + let incoming = tokio::task::spawn_blocking(move || { + receiver + .recv_timeout(std::time::Duration::from_secs(5)) + .unwrap() + }) + .await + .unwrap(); + let incoming = incoming.into_iter().next().unwrap(); + let prompt_tokens = incoming.prompt.tokens.len(); + incoming.notify_admission(Ok(())); + for _ in 0..2 { + incoming.observe_token(1); + incoming.emit_token(1); + } + incoming.emit(GenerationEvent::Finished { + prompt_tokens, + generated_tokens: 2, + reused_prompt_tokens: 0, + reason: "length", + termination: crate::output::Termination::OutputLimit, + stop_sequence: None, + times, + drafts: DraftCounts { + offered: 6, + accepted: 4, + }, + }); + let response = response.await.unwrap(); + let bytes = axum::body::to_bytes(response.into_body(), 131072).await.unwrap(); + let text = std::str::from_utf8(&bytes).unwrap(); + let events: Vec = if stream { + text.lines() + .filter_map(|line| line.strip_prefix("data: ")) + .filter_map(|line| serde_json::from_str(line).ok()) + .collect() + } else { + vec![serde_json::from_str(text).unwrap()] + }; + let carrying: Vec<_> = events + .iter() + .filter(|event| event.get("timings").is_some()) + .collect(); + assert_eq!(carrying.len(), 1, "{path} stream={stream}"); + let timings = &carrying[0]["timings"]; + assert_eq!(timings["prompt_ms"], 500.0, "{path} stream={stream}"); + assert_eq!(timings["predicted_ms"], 1000.0, "{path} stream={stream}"); + assert_eq!( + timings["predicted_per_second"], 1.0, + "{path} stream={stream}" + ); + assert_eq!(timings["prompt_n"], prompt_tokens, "{path} stream={stream}"); + assert_eq!(timings["draft_n"], 6, "{path} stream={stream}"); + assert_eq!(timings["draft_n_accepted"], 4, "{path} stream={stream}"); + } + } +} + #[tokio::test] async fn http_operator_thinking_budget_defaults_and_request_overrides() { use super::super::http; @@ -4912,6 +5063,7 @@ async fn responses_carry_the_first_non_empty_served_name() { 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(), drafts: Default::default(), }); let bytes = axum::body::to_bytes(response.into_body(), 131072).await.unwrap(); let body = std::str::from_utf8(&bytes).unwrap(); @@ -4942,6 +5094,7 @@ async fn responses_carry_the_first_non_empty_served_name() { 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(), drafts: Default::default(), }); let response = response.await.unwrap(); let bytes = axum::body::to_bytes(response.into_body(), 65536).await.unwrap(); @@ -4960,6 +5113,7 @@ async fn responses_carry_the_first_non_empty_served_name() { 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(), drafts: Default::default(), }); let response = response.await.unwrap(); let bytes = axum::body::to_bytes(response.into_body(), 65536).await.unwrap(); @@ -5352,6 +5506,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); diff --git a/helios/src/server/runtime/response_lifecycle_tests.rs b/helios/src/server/runtime/response_lifecycle_tests.rs index 5a0adf3c0..9ec9fb60c 100644 --- a/helios/src/server/runtime/response_lifecycle_tests.rs +++ b/helios/src/server/runtime/response_lifecycle_tests.rs @@ -159,6 +159,8 @@ impl Responses { reason: "length", stop_sequence: None, termination: crate::output::Termination::OutputLimit, + times: Default::default(), + drafts: Default::default(), }); row.sent += 1; row.terminal = 1; @@ -376,6 +378,8 @@ async fn terminal_stream_frames_retain_http_admission_after_native_retirement() reason: "length", stop_sequence: None, termination: crate::output::Termination::OutputLimit, + times: Default::default(), + drafts: Default::default(), }); drop(incoming); let mut reader = response.into_body().into_data_stream();