From 9c53ab0f1c24d2b2fc636e1c872ddcb3ab2ea61e Mon Sep 17 00:00:00 2001 From: spa5k <79936503+spa5k@users.noreply.github.com> Date: Thu, 29 Oct 2026 05:11:18 +0530 Subject: [PATCH 1/4] fix(frontend): observe completions metrics before dropping empty chunks Streaming /v1/completions dropped empty chunks before it observed their metrics, so output tokens were undercounted and TTFT moved to the first non-empty chunk. Observe first, then drop, as chat does. Signed-off-by: spa5k <79936503+spa5k@users.noreply.github.com> --- lib/llm/src/http/service/openai.rs | 44 ++++--- lib/llm/tests/http_metrics.rs | 205 +++++++++++++++++++++++++++++ 2 files changed, 233 insertions(+), 16 deletions(-) diff --git a/lib/llm/src/http/service/openai.rs b/lib/llm/src/http/service/openai.rs index ba05cf7b58f7..076a069d5e84 100644 --- a/lib/llm/src/http/service/openai.rs +++ b/lib/llm/src/http/service/openai.rs @@ -1521,15 +1521,21 @@ async fn completions_single( let error_signal = StreamErrorSignal::default(); let producer_error_signal = error_signal.clone(); let stream = stream - .filter(|r| { - // Drop empty chunks from multi-byte token assembly - futures::future::ready( - !r.data - .as_ref() - .is_some_and(is_empty_completion_stream_response), - ) - }) .map(move |mut response| { + // Drop empty chunks from multi-byte token assembly, but observe + // their metrics first: the engine generated these tokens. + if response + .data + .as_ref() + .is_some_and(is_empty_completion_stream_response) + { + process_response_and_observe_metrics( + &response, + &mut response_collector, + &mut http_queue_guard, + ); + return Ok(None); + } // Frontend-side SSE conversion for one chunk. The gaps between // consecutive ranges cover both worker time and the frontend's // own unannotated receive/decode path. @@ -1901,15 +1907,21 @@ async fn completions_batch( let error_signal = StreamErrorSignal::default(); let producer_error_signal = error_signal.clone(); let stream = merged_stream - .filter(|r| { - // Drop empty chunks from multi-byte token assembly - futures::future::ready( - !r.data - .as_ref() - .is_some_and(is_empty_completion_stream_response), - ) - }) .map(move |mut response| { + // Drop empty chunks from multi-byte token assembly, but observe + // their metrics first: the engine generated these tokens. + if response + .data + .as_ref() + .is_some_and(is_empty_completion_stream_response) + { + process_response_and_observe_metrics( + &response, + &mut response_collector, + &mut http_queue_guard, + ); + return Ok(None); + } // Frontend-side SSE conversion for one chunk of the merged stream. let _nvtx_chunk = dynamo_nvtx_range!("frontend.http.completions.sse_chunk"); // `echo` rides the chunk as typed metadata up to this boundary. diff --git a/lib/llm/tests/http_metrics.rs b/lib/llm/tests/http_metrics.rs index 7ff123614917..d7fce85801c2 100644 --- a/lib/llm/tests/http_metrics.rs +++ b/lib/llm/tests/http_metrics.rs @@ -286,6 +286,72 @@ impl } } +/// Completions engine whose first chunk renders as nothing, as multi-byte token +/// assembly produces, but still carries the metrics of the token it generated. +/// The next chunk waits until the test opens `gate`. +struct MockEmptyChunkCompletionsEngine { + gate: Arc, +} + +fn with_completion_metrics( + response: NvCreateCompletionResponse, + output_tokens: usize, +) -> Annotated { + let metrics = LLMMetricAnnotation { + input_tokens: 5, + output_tokens, + chunk_tokens: 1, + ..Default::default() + } + .to_annotation::() + .expect("metrics serialize"); + let mut annotated = Annotated::from_data(response); + annotated.event = metrics.event; + annotated.comment = metrics.comment; + annotated +} + +#[async_trait] +impl + AsyncEngine< + SingleIn, + ManyOut>, + Error, + > for MockEmptyChunkCompletionsEngine +{ + async fn generate( + &self, + request: SingleIn, + ) -> Result>, Error> { + let (request, context) = request.transfer(()); + let ctx = context.context(); + let generator = request.response_generator(ctx.id().to_string()); + let gate = Arc::clone(&self.gate); + + let stream = stream! { + yield with_completion_metrics( + generator.create_choice(0, Some(String::new()), None, None), + 1, + ); + + // The permit goes back on drop, so one permit releases every prompt. + drop(gate.acquire().await.expect("gate is never closed")); + + yield with_completion_metrics( + generator.create_choice( + 0, + Some("gated".to_string()), + Some(dynamo_protocols::types::CompletionFinishReason::Stop), + None, + ), + 2, + ); + }; + + Ok(ResponseStream::new(Box::pin(stream), ctx)) + } +} + #[tokio::test] async fn test_metrics_prefix_default() { // Test default prefix when no env var is set @@ -931,6 +997,145 @@ async fn test_responses_non_streaming_observes_metrics_before_backend_error_pref .await; } +/// Poll `/metrics` until it contains every needle. +async fn wait_for_metric_lines( + client: &reqwest::Client, + url: &str, + needles: &[&str], + context: &str, +) -> String { + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + loop { + let body = client.get(url).send().await.unwrap().text().await.unwrap(); + if needles.iter().all(|needle| body.contains(needle)) { + return body; + } + assert!( + tokio::time::Instant::now() < deadline, + "{context}: expected {needles:?} in metrics; got:\n{body}" + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } +} + +/// Streaming `/v1/completions` drops empty chunks from multi-byte token +/// assembly. It must observe their metrics first, as the chat handler does, +/// because the engine generated those tokens. Each prompt starts with an empty +/// chunk and holds its next chunk behind a gate: TTFT must be exposed while the +/// gate is closed, the output-token counter must count every chunk, and the +/// client must still receive only the non-empty chunks. +async fn assert_streaming_completions_observe_empty_chunk_metrics( + prompt: serde_json::Value, + prompts: usize, +) { + temp_env::async_with_vars([(METRICS_PREFIX_ENV, None::<&str>)], async { + let (listener, port) = bind_random_port().await; + let service = HttpService::builder() + .port(port) + .enable_cmpl_endpoints(true) + .build() + .unwrap(); + + let state = service.state_clone(); + let manager = state.manager(); + + let token = CancellationToken::new(); + let cancel_token = token.clone(); + let task = + tokio::spawn(async move { service.run_with_listener(token.clone(), listener).await }); + + let gate = Arc::new(tokio::sync::Semaphore::new(0)); + let card = ModelDeploymentCard::with_name_only("emptychunkmodel"); + manager + .add_completions_model( + "emptychunkmodel", + card.mdcsum(), + Arc::new(MockEmptyChunkCompletionsEngine { + gate: Arc::clone(&gate), + }), + ) + .unwrap(); + + wait_for_metrics_ready(port).await; + + let client = reqwest::Client::new(); + let metrics_url = format!("http://localhost:{port}/metrics"); + let request_task = { + let client = client.clone(); + let url = format!("http://localhost:{port}/v1/completions"); + let request = serde_json::json!({ + "model": "emptychunkmodel", + "stream": true, + "max_tokens": 8, + "prompt": prompt, + }); + tokio::spawn(async move { client.post(url).json(&request).send().await?.text().await }) + }; + + // While the gate is closed, the handler has received only empty chunks. + let ttft_line = + "dynamo_frontend_time_to_first_token_seconds_count{model=\"emptychunkmodel\"} 1\n"; + wait_for_metric_lines( + &client, + &metrics_url, + &[ttft_line], + "TTFT must be observed on the first generated chunk, even when it is empty", + ) + .await; + + gate.add_permits(1); + let body = request_task.await.unwrap().unwrap(); + let texts: Vec = body + .lines() + .filter_map(|line| line.strip_prefix("data: ")) + .filter(|data| *data != "[DONE]") + .flat_map(|data| { + let chunk: serde_json::Value = serde_json::from_str(data).unwrap(); + chunk["choices"] + .as_array() + .into_iter() + .flatten() + .map(|choice| choice["text"].as_str().unwrap().to_string()) + .collect::>() + }) + .collect(); + assert_eq!( + texts, + vec!["gated"; prompts], + "empty chunks must not reach the client; body:\n{body}" + ); + + let output_tokens_line = format!( + "dynamo_frontend_output_tokens_total{{model=\"emptychunkmodel\"}} {}\n", + 2 * prompts + ); + wait_for_metric_lines( + &client, + &metrics_url, + &[ttft_line, &output_tokens_line], + "tokens on empty chunks must be counted", + ) + .await; + + cancel_token.cancel(); + task.await.unwrap().unwrap(); + }) + .await; +} + +/// Streaming `/v1/completions` with one prompt (`completions_single`). +#[tokio::test] +async fn test_streaming_completions_observes_empty_chunk_metrics() { + assert_streaming_completions_observe_empty_chunk_metrics(serde_json::json!("hi"), 1).await; +} + +/// Streaming `/v1/completions` with a prompt batch (`completions_batch`). +#[tokio::test] +async fn test_streaming_completions_batch_observes_empty_chunk_metrics() { + assert_streaming_completions_observe_empty_chunk_metrics(serde_json::json!(["hi", "hi"]), 2) + .await; +} + // Integration tests that require distributed runtime with etcd #[cfg(feature = "integration")] mod integration_tests { From d9e47e3019bc3e6ef4fdc9087ca41be113ea013b Mon Sep 17 00:00:00 2001 From: spa5k <79936503+spa5k@users.noreply.github.com> Date: Thu, 29 Oct 2026 07:58:51 +0530 Subject: [PATCH 2/4] test(frontend): bound waits in completions empty-chunk metrics tests Signed-off-by: spa5k <79936503+spa5k@users.noreply.github.com> --- lib/llm/tests/http_metrics.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/llm/tests/http_metrics.rs b/lib/llm/tests/http_metrics.rs index d7fce85801c2..500296add0d8 100644 --- a/lib/llm/tests/http_metrics.rs +++ b/lib/llm/tests/http_metrics.rs @@ -1058,7 +1058,10 @@ async fn assert_streaming_completions_observe_empty_chunk_metrics( wait_for_metrics_ready(port).await; - let client = reqwest::Client::new(); + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(10)) + .build() + .unwrap(); let metrics_url = format!("http://localhost:{port}/metrics"); let request_task = { let client = client.clone(); @@ -1084,7 +1087,11 @@ async fn assert_streaming_completions_observe_empty_chunk_metrics( .await; gate.add_permits(1); - let body = request_task.await.unwrap().unwrap(); + let body = tokio::time::timeout(Duration::from_secs(10), request_task) + .await + .expect("completions request timed out") + .unwrap() + .unwrap(); let texts: Vec = body .lines() .filter_map(|line| line.strip_prefix("data: ")) From 11d978a42036609056251d5cc5dc5a3cec062df5 Mon Sep 17 00:00:00 2001 From: spa5k <79936503+spa5k@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:42:46 +0530 Subject: [PATCH 3/4] test(frontend): drop redundant helper comment Signed-off-by: spa5k <79936503+spa5k@users.noreply.github.com> --- lib/llm/tests/http_metrics.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/llm/tests/http_metrics.rs b/lib/llm/tests/http_metrics.rs index 500296add0d8..b20b4b42a917 100644 --- a/lib/llm/tests/http_metrics.rs +++ b/lib/llm/tests/http_metrics.rs @@ -997,7 +997,6 @@ async fn test_responses_non_streaming_observes_metrics_before_backend_error_pref .await; } -/// Poll `/metrics` until it contains every needle. async fn wait_for_metric_lines( client: &reqwest::Client, url: &str, From 89b761537147aec13101847cbf99024fd2b19972 Mon Sep 17 00:00:00 2001 From: spa5k <79936503+spa5k@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:59:25 +0530 Subject: [PATCH 4/4] test(frontend): drop redundant test comments --- lib/llm/tests/http_metrics.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/lib/llm/tests/http_metrics.rs b/lib/llm/tests/http_metrics.rs index b20b4b42a917..b9813a94a0c8 100644 --- a/lib/llm/tests/http_metrics.rs +++ b/lib/llm/tests/http_metrics.rs @@ -1129,13 +1129,11 @@ async fn assert_streaming_completions_observe_empty_chunk_metrics( .await; } -/// Streaming `/v1/completions` with one prompt (`completions_single`). #[tokio::test] async fn test_streaming_completions_observes_empty_chunk_metrics() { assert_streaming_completions_observe_empty_chunk_metrics(serde_json::json!("hi"), 1).await; } -/// Streaming `/v1/completions` with a prompt batch (`completions_batch`). #[tokio::test] async fn test_streaming_completions_batch_observes_empty_chunk_metrics() { assert_streaming_completions_observe_empty_chunk_metrics(serde_json::json!(["hi", "hi"]), 2)