From 8ffcc72462acfd8f4c2a0dd45496eb9942d8bd52 Mon Sep 17 00:00:00 2001 From: Wynn Drahorad Date: Thu, 26 Nov 2026 22:45:27 -0600 Subject: [PATCH] Add vLLM-compatible per-request metrics OpenAI clients and proxy gateways that display per-request speed read timings from the response body. Flare reports aggregates on `/metrics` but no per-request timing, so a gateway cannot show prompt or decode tokens per second, and billing or SLA tooling has to time the HTTP round trip itself, which mixes queueing and client transfer into the number. vLLM answers this with a `metrics` object on the response, enabled by `--enable-per-request-metrics`, and consumers already read it. Matching its object and placement lets those consumers read Flare responses unchanged. The HTTP layer already sees every offered token, so the timings are recorded there without changing the runtime or prepared core. The option is `--enable-per-request-metrics`, or `[server] per_request_metrics = true` in the configuration file; both default to off. `generate` records the instant of the first and last output token, the first non-empty answer or reasoning frame on a stream, and the committed output-token count. A non-streaming OpenAI Chat or Completions response carries a top-level `metrics` object; a streaming response carries it only on the final usage chunk, so the stream needs `"stream_options": {"include_usage": true}`, as vLLM requires. With `n` choices the object is null, again as vLLM does, because one sequence's timing cannot describe the whole response. The object uses vLLM's field names: `time_to_first_token_ms`, `time_to_first_content_token_ms` (streaming only), `generation_time_ms`, `queue_time_ms`, `mean_itl_ms`, and `tokens_per_second`. Measurement contract: every interval starts at HTTP admission. vLLM measures from scheduler admission, which the HTTP layer cannot observe, so `time_to_first_token_ms` here includes admission-to-scheduler time and `queue_time_ms` is null rather than a scheduler-queue value; `tokens_per_second` covers admission to the last output token. Any interval the request did not produce is null, and Anthropic Messages and OpenAI Responses are unchanged. The cost is one clock read per output token while the option is on, and none while it is off. The claimed result is opt-in per-request timing in OpenAI response bodies, with no change to serving behavior, the runtime, or the wire format when the option is off. Evidence: `cargo test --locked --release --manifest-path helios/Cargo.toml --target-dir ~/.cache/hyperflare-target --features runtime-core,server --lib -- per_request_metrics` passes three tests. `per_request_metrics_report_vllm_timings_when_enabled` checks a two-token non-streaming chat: positive first-token, generation, and throughput values, a finite mean inter-token latency, null content-token and queue fields, and no `metrics` key when the option is off. `per_request_metrics_ride_the_final_usage_chunk` checks that the object arrives on the usage chunk with an empty `choices` array and the content-token interval present, and that a stream without usage reporting carries no object. `per_request_metrics_suppress_multi_choice_responses` checks that two choices return a null object with both choices present. The whole `server::` filter ran 326 tests with one failure, `messages_image_hints_end_after_expansion_for_text_and_segmented_templates`, which needs `FLARE_TEST_TEMPLATE_DIR` from `tests/frontend/prepare_templates.py` and has no prepared templates on this host. `cargo test --locked --release --manifest-path flare/Cargo.toml --lib -- per_request_metrics` passes the settings test over the absent, true, and false `[server] per_request_metrics` values, and `cargo test --locked --release --manifest-path flare-cli/Cargo.toml --bin flare -- per_request_metrics` passes the flag test. Windows builds and live gateway verification are left to CI and to the caller. Signed-off-by: Wynn Drahorad Design-Signed-Off-By: Claude Opus 5.5 (omp agent); design-review=eb2f --- docs/api.md | 24 ++++ docs/cli-design.md | 3 +- flare-cli/src/cli.rs | 20 +++ flare-cli/src/main.rs | 2 + flare/src/configuration.rs | 5 + flare/src/controller.rs | 1 + flare/src/settings.rs | 20 +++ helios/src/server.rs | 6 + helios/src/server/config.rs | 5 + helios/src/server/http.rs | 133 ++++++++++++++++++-- helios/src/server/runtime/phase_tests.rs | 154 ++++++++++++++++++++++- 11 files changed, 364 insertions(+), 9 deletions(-) diff --git a/docs/api.md b/docs/api.md index b9d61f71b..61c86ab43 100644 --- a/docs/api.md +++ b/docs/api.md @@ -879,6 +879,30 @@ 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 + +`--enable-per-request-metrics`, or `[server] per_request_metrics = true`, makes +OpenAI Chat and Completions responses carry a `metrics` object with the timing +of that request, matching vLLM's per-request metrics. The option is off by +default. A non-streaming response carries the object at the top level; a +streaming response carries it only on the final usage chunk, so a stream needs +`"stream_options": {"include_usage": true}` to receive it. With `n` choices the +object is null, because one sequence's timing cannot describe the whole +response. Anthropic Messages and OpenAI Responses responses do not include it. + +| Field | Meaning | +| --- | --- | +| `time_to_first_token_ms` | HTTP admission to the first output token; vLLM measures from scheduler admission, which the HTTP layer cannot observe | +| `time_to_first_content_token_ms` | HTTP admission to the first non-empty answer or reasoning text; streaming only, and null for non-streaming requests | +| `generation_time_ms` | First output token to the last output token | +| `queue_time_ms` | Always null: the HTTP layer does not separate queueing from prefill | +| `mean_itl_ms` | `generation_time_ms` divided by output tokens after the first; null for a single-token response | +| `tokens_per_second` | Output tokens over the interval from HTTP admission to the last output token | + +Fields are null when the request produced no such interval. Enabling the option +makes the serving process read the clock once per output token and keep the +first and last instants; disabling it reads no clock for timing. + ## 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 b7fc582f5..08dbae276 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -735,6 +735,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 a `metrics` timing object to OpenAI Chat and Completions responses | `[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 | @@ -1316,7 +1317,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`, +`per_request_metrics`, and `scheduler_checkpoint_extra_work_fraction`, `[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 diff --git a/flare-cli/src/cli.rs b/flare-cli/src/cli.rs index 02d81c76b..79ce8a627 100644 --- a/flare-cli/src/cli.rs +++ b/flare-cli/src/cli.rs @@ -517,6 +517,7 @@ impl OrbitPush { host: "127.0.0.1".parse().unwrap(), port: 8000, served_model_name: None, + enable_per_request_metrics: false, roce_ring: self.roce_ring, roce_chain: self.roce_chain, rendezvous: None, @@ -620,6 +621,10 @@ pub struct OrbitRun { #[arg(long, value_name = "ALIAS", value_parser = served_model_name, help_heading = "Serving options")] pub served_model_name: Option, + /// Include per-request timing metrics in OpenAI chat and completion responses. + #[arg(long, help_heading = "Serving options")] + pub enable_per_request_metrics: bool, + /// Favor throughput or output cadence [default: saved group or balanced]. #[arg(long, value_name = "MODE", value_parser = ["balanced", "throughput"], help_heading = "Serving options")] @@ -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 } @@ -699,6 +707,7 @@ impl OrbitRun { host: self.host.unwrap_or_else(|| "127.0.0.1".parse().unwrap()), port: self.port.unwrap_or(8000), served_model_name: self.served_model_name.clone(), + enable_per_request_metrics: self.enable_per_request_metrics, roce_ring: self.roce_ring, roce_chain: self.roce_chain, rendezvous: None, @@ -764,6 +773,10 @@ pub struct Run { #[arg(long, value_name = "ALIAS", value_parser = served_model_name, help_heading = "Serving options")] pub served_model_name: Option, + /// Include per-request timing metrics in OpenAI chat and completion responses. + #[arg(long, help_heading = "Serving options")] + pub enable_per_request_metrics: bool, + /// Experimental ring in rank order: only neighbor RoCE QPs connect; /// native CPU relays forward non-neighbor traffic. Also emulates a ring on a switch. #[arg(long, help_heading = "Multi-host options")] @@ -1502,6 +1515,13 @@ mod tests { } } + #[test] + fn per_request_metrics_flag_is_off_by_default_and_forwards_to_rank_zero() { + assert!(!run(&["flare", "run", "model"]).enable_per_request_metrics); + assert!(run(&["flare", "run", "model", "--enable-per-request-metrics"]) + .enable_per_request_metrics); + } + fn run(arguments: &[&str]) -> Run { let Command::Run(args) = Cli::try_parse_from(arguments).unwrap().command else { panic!("expected run") diff --git a/flare-cli/src/main.rs b/flare-cli/src/main.rs index c66489c99..fd96048af 100644 --- a/flare-cli/src/main.rs +++ b/flare-cli/src/main.rs @@ -352,6 +352,8 @@ fn run() -> Result> { } config["api_key"] = key.into(); config["thinking_token_budget"] = serde_json::json!(configuration.thinking_token_budget()); + config["per_request_metrics"] = + (args.enable_per_request_metrics || configuration.per_request_metrics()).into(); phase.finish(config["model_id"].as_str().unwrap_or_default()); serve(owner, config, progress, cluster, routing)?; #[cfg(unix)] diff --git a/flare/src/configuration.rs b/flare/src/configuration.rs index e4420dbb8..f5ca0ae0b 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)] @@ -131,6 +132,10 @@ impl Configuration { .thinking_token_budget .map(std::num::NonZeroU32::get) } + + pub fn per_request_metrics(&self) -> bool { + self.server.per_request_metrics.unwrap_or(false) + } } pub fn nonempty(value: Option<&str>) -> Option<&str> { diff --git a/flare/src/controller.rs b/flare/src/controller.rs index 67bb49076..3fbf0bfd0 100644 --- a/flare/src/controller.rs +++ b/flare/src/controller.rs @@ -2560,6 +2560,7 @@ impl Worker { let phase = progress.phase("Load tokenizer", None); let mut config = owner.server_config().clone(); config["thinking_token_budget"] = serde_json::json!(self.settings.thinking_token_budget); + config["per_request_metrics"] = self.settings.per_request_metrics.into(); if let Some(fraction) = self.settings.scheduler_checkpoint_extra_work_fraction { config["scheduler_checkpoint_extra_work_fraction"] = fraction.into(); } diff --git a/flare/src/settings.rs b/flare/src/settings.rs index f6d055a8e..04235995b 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, } @@ -155,6 +156,7 @@ impl Settings { pool: None, }; let thinking_token_budget = configuration.thinking_token_budget(); + let per_request_metrics = configuration.per_request_metrics(); let model_concurrency = configuration .models .into_iter() @@ -207,6 +209,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, prefix_cache, model_concurrency, }) @@ -277,6 +280,23 @@ mod runtime_tests { assert_eq!(desired.api_key.as_deref(),Some("unchanged-secret")); assert!(!serde_json::to_string(&desired.runtime).unwrap().contains("secret")); } + #[test] + fn per_request_metrics_default_to_off_and_follow_the_server_section() { + for (text, expected) in [ + ("", false), + ("[server]\nper_request_metrics=true\n", true), + ("[server]\nper_request_metrics=false\n", false), + ] { + let settings = Settings::resolve( + Configuration::parse(text).unwrap(), + Path::new("user"), + Path::new("config.toml"), + ) + .unwrap(); + assert_eq!(settings.per_request_metrics, expected, "{text}"); + } + } + #[test] fn explicit_desktop_concurrency_wins_over_conflicting_model_aliases() { let config=Configuration::parse("[models.first]\nmax_concurrency=2\n[models.second]\nmax_concurrency=3\n").unwrap(); diff --git a/helios/src/server.rs b/helios/src/server.rs index 1adeeaf03..4ce40ace4 100644 --- a/helios/src/server.rs +++ b/helios/src/server.rs @@ -128,6 +128,9 @@ pub struct ServerConfig { pub context_hint: String, /// Setting that raises request or page capacity, appended to capacity rejections. pub capacity_hint: String, + /// Include vLLM-compatible per-request timing metrics in OpenAI chat and + /// completion responses. + pub per_request_metrics: bool, pub scheduling_policy: crate::scheduler::PolicyConfig, } impl Default for ServerConfig { @@ -144,6 +147,7 @@ impl Default for ServerConfig { thinking_token_budget: None, context_hint: String::new(), capacity_hint: String::new(), + per_request_metrics: false, scheduling_policy: crate::scheduler::PolicyConfig::default(), } } @@ -169,6 +173,7 @@ struct HttpState { thinking_token_budget: Option, context_hint: String, capacity_hint: String, + per_request_metrics: bool, response_model: String, started: Instant, generated: Mutex>, @@ -327,6 +332,7 @@ impl Server { thinking_token_budget: config.thinking_token_budget, context_hint: config.context_hint.clone(), capacity_hint: config.capacity_hint.clone(), + per_request_metrics: config.per_request_metrics, response_model: models::response_name(model.config(), &config.served_names).to_owned(), started: Instant::now(), generated: Mutex::new(VecDeque::new()), diff --git a/helios/src/server/config.rs b/helios/src/server/config.rs index ffd22c6bc..393b7da24 100644 --- a/helios/src/server/config.rs +++ b/helios/src/server/config.rs @@ -354,6 +354,11 @@ impl Bootstrap { served_names, context_hint: optional_text("context_hint")?, capacity_hint: optional_text("capacity_hint")?, + per_request_metrics: match object.get("per_request_metrics") { + None => false, + Some(Value::Bool(value)) => *value, + _ => return Err("per_request_metrics must be a boolean".into()), + }, bind: object .get("bind") .and_then(Value::as_str) diff --git a/helios/src/server/http.rs b/helios/src/server/http.rs index af1728abf..4d1cf7f20 100644 --- a/helios/src/server/http.rs +++ b/helios/src/server/http.rs @@ -119,6 +119,80 @@ enum Delivery { Failed(Error, Frame), } +/// Per-request instants for the `metrics` response object. Field names follow +/// vLLM's per-request metrics; the interval starts at HTTP admission because the +/// HTTP layer has no earlier scheduler boundary. +struct RequestTiming { + started: Instant, + first_token: Option, + last_token: Option, + first_content: Option, + seen_tokens: u64, + committed_tokens: u64, + streaming: bool, +} + +impl RequestTiming { + fn new(started: Instant, streaming: bool) -> Self { + Self { + started, + first_token: None, + last_token: None, + first_content: None, + seen_tokens: 0, + committed_tokens: 0, + streaming, + } + } + + fn token(&mut self) { + let now = Instant::now(); + self.first_token.get_or_insert(now); + self.last_token = Some(now); + self.seen_tokens += 1; + } + + fn content(&mut self) { + self.first_content.get_or_insert_with(Instant::now); + } + + /// Elapsed milliseconds between two instants. + fn millis(start: Instant, end: Instant) -> f64 { + end.saturating_duration_since(start).as_secs_f64() * 1000.0 + } + + fn value(&self) -> Value { + let first = self.first_token; + let last = self.last_token; + let generation = first + .zip(last) + .filter(|(first, last)| last > first) + .map(|(first, last)| Self::millis(first, last)); + let mean_itl = match (first, last) { + (Some(first), Some(last)) if self.seen_tokens > 1 => { + Some(Self::millis(first, last) / (self.seen_tokens - 1) as f64) + } + _ => None, + }; + let throughput = last.map(|last| { + let seconds = last.saturating_duration_since(self.started).as_secs_f64(); + self.committed_tokens as f64 / seconds.max(f64::MIN_POSITIVE) + }); + json!({ + "time_to_first_token_ms": first.map(|first| Self::millis(self.started, first)), + "time_to_first_content_token_ms": if self.streaming { + self.first_content.map(|content| Self::millis(self.started, content)) + } else { + None + }, + "generation_time_ms": generation, + "queue_time_ms": Value::Null, + "mean_itl_ms": mean_itl, + "tokens_per_second": throughput, + }) + } +} + pub(super) async fn generate( State(state): State>, Extension(ingress): Extension>, @@ -381,6 +455,11 @@ pub(super) async fn generate( encoder.set_strict_validators(strict_validators); encoder.set_continuous_usage(continuous_usage); let streaming = decoded.stream; + let per_request_metrics = + state.per_request_metrics && matches!(protocol, Protocol::Chat | Protocol::Completions); + // vLLM suppresses the object for n > 1: one sequence's timing cannot describe + // the whole response. + let single_choice = decoded.request.choices == 1; let stream_state = state.clone(); let stream_id = id.clone(); let delivery = async_stream::stream! { @@ -400,6 +479,7 @@ pub(super) async fn generate( let mut raw_tokens = Vec::new(); let mut timestamps = Vec::new(); let mut reused_total = 0; + let mut timing = RequestTiming::new(admitted_at, streaming); 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. @@ -422,6 +502,12 @@ pub(super) async fn generate( match encoder.apply(i, vec![crate::output::Event::Content(echo)]) { Ok(frames) => { for frame in frames { + if per_request_metrics + && streaming + && super::latency::stream_text(&frame.data) + { + timing.content(); + } yield Delivery::Frame(frame) } } @@ -476,12 +562,18 @@ pub(super) async fn generate( } let result = match event { GenerationEvent::PromptLogprobs { start, tokens, values } => encoder.prompt_logprobs(index, start, &tokens, &values), - GenerationEvent::LogprobToken(value) => decoders[index] - .push_logprob(value) - .and_then(|events| encoder.apply(index, events)), - GenerationEvent::Token(token) => decoders[index] - .push(token) - .and_then(|events| encoder.apply(index, events)), + GenerationEvent::LogprobToken(value) => { + timing.token(); + decoders[index] + .push_logprob(value) + .and_then(|events| encoder.apply(index, events)) + } + GenerationEvent::Token(token) => { + timing.token(); + decoders[index] + .push(token) + .and_then(|events| encoder.apply(index, events)) + } GenerationEvent::Protocol(pieces) => decoders[index] .push_protocol(pieces) .and_then(|events| encoder.apply(index, events)), @@ -522,6 +614,7 @@ pub(super) async fn generate( .. } => { reused_total += reused_prompt_tokens; + timing.committed_tokens += u64::from(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)) @@ -566,7 +659,26 @@ pub(super) async fn generate( } } match result { - Ok(frames) => { + Ok(mut frames) => { + if per_request_metrics && streaming { + for frame in &frames { + if super::latency::stream_text(&frame.data) { + timing.content(); + } + } + // vLLM attaches metrics to the final usage chunk, which a + // stream carries only when usage reporting is enabled. + if observation.include_usage + && let Some(done) = frames.iter().position(|frame| frame.done) + && let Some(target) = frames[..done].last_mut() + { + target.data["metrics"] = if single_choice { + timing.value() + } else { + Value::Null + }; + } + } for frame in frames { yield Delivery::Frame(frame) } @@ -579,6 +691,13 @@ pub(super) async fn generate( } } let mut response = encoder.response(); + if per_request_metrics && !streaming { + response["metrics"] = if single_choice { + timing.value() + } else { + Value::Null + }; + } if protocol == Protocol::Chat { if let Some(ids) = prompt_ids { response["prompt_token_ids"] = json!(ids); diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 5aa313c40..27c7b8fcc 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -4139,10 +4139,20 @@ fn http_state( } fn http_state_for( + fixture: Fixture, + sender: mpsc::SyncSender>, + api_key: Option, + served_names: &[String], +) -> Arc { + http_state_with(fixture, sender, api_key, served_names, false) +} + +fn http_state_with( mut fixture: Fixture, sender: mpsc::SyncSender>, api_key: Option, served_names: &[String], + per_request_metrics: bool, ) -> Arc { use super::super::HttpState; use tokio::sync::Semaphore; @@ -4193,6 +4203,7 @@ fn http_state_for( thinking_token_budget: None, context_hint: String::new(), capacity_hint: String::new(), + per_request_metrics, response_model, started: std::time::Instant::now(), generated: Default::default(), @@ -4371,11 +4382,24 @@ async fn http_generation_request_observed( tokio::task::JoinHandle, Vec, Arc, +) { + http_generation_request_with(path, body, served_names, false).await +} + +async fn http_generation_request_with( + path: &str, + body: serde_json::Value, + served_names: &[String], + per_request_metrics: bool, +) -> ( + tokio::task::JoinHandle, + Vec, + Arc, ) { use super::super::http; use axum::{Extension, extract::State}; let (sender, receiver) = mpsc::sync_channel(4); - let state = http_state_for(Fixture::new(), sender, None, served_names); + let state = http_state_with(Fixture::new(), sender, None, served_names, per_request_metrics); let ingress = Arc::new(state.ingress_slots.clone().acquire_owned().await.unwrap()); let request = axum::http::Request::builder() .method("POST") @@ -4447,6 +4471,134 @@ async fn first_response_http_nonstream_records_only_when_completed_body_is_offer } } +#[tokio::test] +async fn per_request_metrics_report_vllm_timings_when_enabled() { + let request = serde_json::json!({ + "messages": [{"role": "user", "content": "a"}], + "max_tokens": 2, "stream": false, + }); + let (response, incoming, _state) = + http_generation_request_with("/v1/chat/completions", request, &[], true).await; + incoming[0].notify_admission(Ok(())); + incoming[0].emit_token(1); + incoming[0].emit_token(2); + incoming[0].emit(GenerationEvent::Finished { + prompt_tokens: 1, generated_tokens: 2, reused_prompt_tokens: 0, + reason: "length", stop_sequence: None, + termination: crate::output::Termination::OutputLimit, + }); + let bytes = axum::body::to_bytes(response.await.unwrap().into_body(), 65536).await.unwrap(); + let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + let metrics = &body["metrics"]; + assert!(metrics["time_to_first_token_ms"].as_f64().is_some_and(|v| v > 0.0), "{body}"); + assert!(metrics["generation_time_ms"].as_f64().is_some_and(|v| v >= 0.0), "{body}"); + assert!(metrics["mean_itl_ms"].as_f64().is_some(), "{body}"); + assert!(metrics["tokens_per_second"].as_f64().is_some_and(|v| v > 0.0), "{body}"); + assert!(metrics["time_to_first_content_token_ms"].is_null(), "{body}"); + assert!(metrics["queue_time_ms"].is_null(), "{body}"); + + // The same response without the option carries no metrics object. + let request = serde_json::json!({ + "messages": [{"role": "user", "content": "a"}], + "max_tokens": 1, "stream": false, + }); + let (response, incoming, _state) = + http_generation_request_observed("/v1/chat/completions", request, &[]).await; + incoming[0].notify_admission(Ok(())); + incoming[0].emit_token(1); + incoming[0].emit(GenerationEvent::Finished { + prompt_tokens: 1, generated_tokens: 1, reused_prompt_tokens: 0, + reason: "length", stop_sequence: None, + termination: crate::output::Termination::OutputLimit, + }); + let bytes = axum::body::to_bytes(response.await.unwrap().into_body(), 65536).await.unwrap(); + let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert!(body.get("metrics").is_none(), "{body}"); +} + +#[tokio::test] +async fn per_request_metrics_ride_the_final_usage_chunk() { + let request = serde_json::json!({ + "messages": [{"role": "user", "content": "a"}], + "max_tokens": 2, "stream": true, + "stream_options": {"include_usage": true}, + }); + let (response, incoming, _state) = + http_generation_request_with("/v1/chat/completions", request, &[], true).await; + let response = response.await.unwrap(); + incoming[0].notify_admission(Ok(())); + for token in [1, 2] { + incoming[0].observe_token(token); + incoming[0].emit_token(token); + } + incoming[0].emit(GenerationEvent::Finished { + prompt_tokens: 1, generated_tokens: 2, reused_prompt_tokens: 0, + reason: "length", stop_sequence: None, + termination: crate::output::Termination::OutputLimit, + }); + let bytes = axum::body::to_bytes(response.into_body(), 65536).await.unwrap(); + let text = std::str::from_utf8(&bytes).unwrap(); + let line = text + .lines() + .find(|line| line.contains("\"metrics\"")) + .unwrap_or_else(|| panic!("no metrics chunk in {text}")); + let value: serde_json::Value = + serde_json::from_str(line.trim_start_matches("data: ")).unwrap(); + assert_eq!(value["choices"], serde_json::json!([]), "metrics ride the usage chunk"); + let metrics = &value["metrics"]; + assert!( + metrics["time_to_first_content_token_ms"].as_f64().is_some_and(|v| v >= 0.0), + "{value}" + ); + assert!(metrics["mean_itl_ms"].as_f64().is_some(), "{value}"); + + // Without usage reporting there is no final usage chunk to carry the object. + let request = serde_json::json!({ + "messages": [{"role": "user", "content": "a"}], + "max_tokens": 2, "stream": true, + }); + let (response, incoming, _state) = + http_generation_request_with("/v1/chat/completions", request, &[], true).await; + let response = response.await.unwrap(); + incoming[0].notify_admission(Ok(())); + for token in [1, 2] { + incoming[0].observe_token(token); + incoming[0].emit_token(token); + } + incoming[0].emit(GenerationEvent::Finished { + prompt_tokens: 1, generated_tokens: 2, reused_prompt_tokens: 0, + reason: "length", stop_sequence: None, + termination: crate::output::Termination::OutputLimit, + }); + let bytes = axum::body::to_bytes(response.into_body(), 65536).await.unwrap(); + let text = std::str::from_utf8(&bytes).unwrap(); + assert!(!text.contains("\"metrics\""), "{text}"); +} + +#[tokio::test] +async fn per_request_metrics_suppress_multi_choice_responses() { + let request = serde_json::json!({ + "prompt": "a", "max_tokens": 1, "n": 2, "stream": false, + }); + let (response, incoming, _state) = + http_generation_request_with("/v1/completions", request, &[], true).await; + for handle in &incoming { + handle.notify_admission(Ok(())); + } + for handle in &incoming { + handle.emit_token(1); + handle.emit(GenerationEvent::Finished { + prompt_tokens: 1, generated_tokens: 1, reused_prompt_tokens: 0, + reason: "length", stop_sequence: None, + termination: crate::output::Termination::OutputLimit, + }); + } + let bytes = axum::body::to_bytes(response.await.unwrap().into_body(), 65536).await.unwrap(); + let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(body["choices"].as_array().map(Vec::len), Some(2), "{body}"); + assert!(body["metrics"].is_null(), "{body}"); +} + #[tokio::test] async fn unread_http_stream_preserves_all_tokens_and_its_terminal_event() { for fail in [false, true] {