dynamo-llm 1.7.0

Dynamo LLM Library
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use std::sync::Arc;

use anyhow::Result;
use futures::StreamExt;
use tokio::sync::OwnedSemaphorePermit;

use dynamo_runtime::{
    pipeline::{AsyncEngineContextProvider, ManyOut},
    protocols::{annotated::Annotated, maybe_error::MaybeError},
};

use super::{PrefillCompletion, PrefillError, PrefillRouter, handoff::PrefillTask};
use crate::protocols::common::{
    llm_backend::{FinishReason, LLMEngineOutput},
    timing::RequestTracker,
};

impl PrefillRouter {
    pub(super) async fn consume_prefill_stream(
        mut prefill_response: ManyOut<Annotated<LLMEngineOutput>>,
        tracker: Option<Arc<RequestTracker>>,
        task_guard: Option<dynamo_runtime::engine::EngineContextGuard>,
    ) -> Result<PrefillCompletion, PrefillError> {
        let Some(first_output) = prefill_response.next().await else {
            // The egress ends the response stream as soon as the request context is
            // stopped, before the worker's final item can arrive. Once a decode
            // rejection has stopped this prefill, an empty stream is that cancellation.
            if prefill_response.context().is_stopped() {
                return Err(PrefillError::Cancelled);
            }
            return Err(PrefillError::PrefillError(
                "Prefill router returned no output (stream ended)".to_string(),
                None,
            ));
        };

        if let Some(error) = first_output.err() {
            // Include the worker's text. `to_pyerr` keeps only `Display`, so a
            // `#[source]` is lost. See `PrefillError::PrefillError`.
            let detail = format!("Prefill router returned error in output: {error}");
            return Err(PrefillError::PrefillError(detail, Some(Box::new(error))));
        }

        let mut prompt_tokens_details = first_output
            .data
            .as_ref()
            .and_then(|output| output.completion_usage.as_ref())
            .and_then(|usage| usage.prompt_tokens_details.clone());

        // For SGLang, check if the first output is a bootstrap message.
        let is_bootstrap = first_output
            .data
            .as_ref()
            .and_then(|o| o.disaggregated_params.as_ref())
            .and_then(|p| p.as_object())
            .is_some_and(|obj| {
                obj.contains_key("bootstrap_host")
                    && obj.contains_key("bootstrap_port")
                    && obj.contains_key("bootstrap_room")
            });

        let completion = if !is_bootstrap {
            if let Some(ref tracker) = tracker {
                tracker.record_prefill_complete();
            }
            while let Some(next) = prefill_response.next().await {
                if let Some(error) = next.err() {
                    let detail = format!("Prefill router returned error in output stream: {error}");
                    return Err(PrefillError::PrefillError(detail, Some(Box::new(error))));
                }
                if let Some(output) = next.data.as_ref()
                    && prompt_tokens_details.is_none()
                {
                    prompt_tokens_details = output
                        .completion_usage
                        .as_ref()
                        .and_then(|usage| usage.prompt_tokens_details.clone());
                }
            }
            None
        } else {
            let prefill_context = prefill_response.context();
            Some(PrefillTask::spawn(
                async move {
                    let _task_guard = task_guard;
                    let mut prefill_output = None;
                    while let Some(output) = prefill_response.next().await {
                        PrefillTask::check_output(&output)?;
                        if let Some(engine_data) = output.data.and_then(|data| data.engine_data) {
                            prefill_output = Some(engine_data);
                        }
                    }
                    // Bootstrap details unblock decode, but do not mean prefill is
                    // complete. Record completion only after its stream finishes.
                    if let Some(tracker) = tracker {
                        tracker.record_prefill_complete();
                    }
                    Ok(prefill_output)
                },
                prefill_context,
            ))
        };

        // A CTX request that reaches EOS/stop during its one-token prefill step
        // is already complete and does not establish a KV-cache handoff. The
        // prefill protocol carries this classification on the first output's
        // data; a data-less first output is rejected below. A missing finish
        // reason is equivalent to TRT-LLM's "not_finished", while Length still
        // requires the normal GEN handoff.
        let is_terminal = first_output
            .data
            .as_ref()
            .and_then(|output| output.finish_reason.as_ref())
            .is_some_and(|reason| !matches!(reason, FinishReason::Length));
        if is_terminal {
            return Ok(PrefillCompletion::Terminal {
                output: Box::new(first_output),
            });
        }

        let Some(output) = &first_output.data else {
            return Err(PrefillError::NoDisaggregatedParams(
                "Prefill router output has no data field".to_string(),
            ));
        };
        let Some(disaggregated_params) = output.disaggregated_params.clone() else {
            return Err(PrefillError::NoDisaggregatedParams(
                "Prefill router output missing disaggregated_params".to_string(),
            ));
        };
        // TRT-LLM serializes ctx_request_id as null for a terminal context
        // response. Terminal responses returned above do not need a handoff;
        // any non-terminal response that explicitly carries a null ID cannot
        // be decoded safely. Refuse it here instead of dispatching GEN and
        // failing later inside the backend. Other backends do not expose this
        // TRT-LLM-specific field and are unaffected.
        let ctx_request_id = disaggregated_params.get("ctx_request_id");
        let is_trtllm_context_handoff = disaggregated_params
            .get("request_type")
            .and_then(serde_json::Value::as_str)
            == Some("context_only");
        if ctx_request_id.is_some_and(serde_json::Value::is_null)
            || (is_trtllm_context_handoff && ctx_request_id.is_none())
        {
            return Err(PrefillError::NoDisaggregatedParams(
                "Prefill router output has no usable ctx_request_id for a non-terminal handoff"
                    .to_string(),
            ));
        }

        Ok(PrefillCompletion::Handoff {
            result: crate::protocols::common::preprocessor::PrefillResult {
                disaggregated_params,
                prompt_tokens_details,
            },
            worker_link: output.worker_trace_link.clone(),
            completion,
        })
    }

    pub(super) fn spawn_prefill_task(
        &self,
        prefill_stream: ManyOut<Annotated<LLMEngineOutput>>,
        tracker: Option<Arc<RequestTracker>>,
        phase_transition_permit: OwnedSemaphorePermit,
    ) -> PrefillTask {
        let task_guard = self.task_guard.clone();
        let prefill_context = prefill_stream.context();
        PrefillTask::spawn_unlogged(async move {
            drop(phase_transition_permit);
            let result =
                match Self::consume_prefill_stream(prefill_stream, tracker, task_guard).await {
                    Ok(PrefillCompletion::Handoff {
                        completion: Some(task),
                        ..
                    }) => {
                        // The inner observer already logs its own failures.
                        return task.wait().await;
                    }
                    Ok(PrefillCompletion::Terminal { output }) => {
                        PrefillTask::check_output(&output).map(|()| None)
                    }
                    Ok(_) => Ok(None),
                    Err(error) => Err(error),
                };
            result.inspect_err(|error| PrefillTask::log_failure(error, prefill_context.as_ref()))
        })
    }
}

#[cfg(test)]
mod tests {
    use crate::protocols::response_merge::PrefillNeed;
    use futures::stream;
    use serde_json::json;

    use dynamo_runtime::pipeline::{
        AsyncEngineContext, AsyncEngineContextProvider, Context, ResponseStream,
        context::Controller,
    };

    use super::*;
    use crate::kv_router::prefill_router::cancellation::arm_for;

    fn prefill_stream(
        items: Vec<Annotated<LLMEngineOutput>>,
    ) -> ManyOut<Annotated<LLMEngineOutput>> {
        ResponseStream::new(
            Box::pin(stream::iter(items)),
            Arc::new(Controller::default()),
        )
    }

    fn valid_prefill_output() -> Annotated<LLMEngineOutput> {
        Annotated::from_data(LLMEngineOutput {
            disaggregated_params: Some(json!({})),
            ..Default::default()
        })
    }

    /// Intentional prefill aborts must be quiet without hiding real tail failures.
    #[test]
    fn bootstrap_cancellation_logging_distinguishes_expected_abort() {
        use std::sync::Mutex;
        use tracing_subscriber::{Layer, layer::SubscriberExt};

        struct Levels(Arc<Mutex<Vec<tracing::Level>>>);
        impl<S: tracing::Subscriber> Layer<S> for Levels {
            fn on_event(
                &self,
                event: &tracing::Event<'_>,
                _: tracing_subscriber::layer::Context<'_, S>,
            ) {
                if event
                    .metadata()
                    .target()
                    .ends_with("prefill_router::handoff")
                {
                    self.0.lock().unwrap().push(*event.metadata().level());
                }
            }
        }
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        for wrapped in [false, true] {
            for bootstrap in [true, false] {
                if !wrapped && !bootstrap {
                    continue;
                }
                for stopped in [true, false] {
                    // `None` ends the stream without a tail item, as the egress does
                    // once the context is stopped; it only reaches the observer when
                    // no bootstrap item arrived first.
                    let mut tails = vec![
                        Some(Annotated::from_data(LLMEngineOutput::cancelled())),
                        Some(Annotated::from_data(LLMEngineOutput::error(
                            "prefill failed".to_string(),
                        ))),
                        Some(Annotated::from_error("prefill transport failed")),
                    ];
                    if !bootstrap {
                        tails.push(None);
                    }
                    for tail in tails {
                        let ended = tail.is_none();
                        let cancelled = tail.as_ref().is_some_and(|tail| {
                            tail.data.as_ref().is_some_and(|data| {
                                data.finish_reason == Some(FinishReason::Cancelled)
                            })
                        });
                        let levels = Arc::new(Mutex::new(Vec::new()));
                        let _interest_guard = crate::test_utils::tracing_interest_guard();
                        let subscriber =
                            tracing_subscriber::registry().with(Levels(levels.clone()));
                        let run = async {
                            let context = Arc::new(Controller::default());
                            let first = Annotated::from_data(LLMEngineOutput {
                                disaggregated_params: Some(json!({
                                    "bootstrap_host": "prefill", "bootstrap_port": 1, "bootstrap_room": 7,
                                })),
                                ..Default::default()
                            });
                            let (tx, rx) = tokio::sync::oneshot::channel();
                            let stream = stream::iter(bootstrap.then_some(first)).chain(
                                stream::once(async move { rx.await.unwrap() })
                                    .filter_map(|tail| async move { tail }),
                            );
                            let response = ResponseStream::new(Box::pin(stream), context.clone());
                            let task = if wrapped {
                                let router = super::super::tests::active_conditional_router();
                                let tracker = Arc::new(RequestTracker::new());
                                let permit = tracker
                                    .set_phase(
                                        crate::protocols::common::timing::RequestPhase::Prefill,
                                    )
                                    .await;
                                router.spawn_prefill_task(response, Some(tracker), permit)
                            } else {
                                let result =
                                    PrefillRouter::consume_prefill_stream(response, None, None)
                                        .await
                                        .unwrap();
                                let PrefillCompletion::Handoff {
                                    completion: Some(task),
                                    ..
                                } = result
                                else {
                                    panic!("expected bootstrap completion observer");
                                };
                                task
                            };
                            if stopped {
                                context.stop_generating();
                            }
                            tx.send(tail).unwrap();
                            assert!(
                                tokio::time::timeout(
                                    std::time::Duration::from_secs(1),
                                    task.wait()
                                )
                                .await
                                .unwrap()
                                .is_err()
                            );
                        };
                        tracing::subscriber::with_default(subscriber, || runtime.block_on(run));
                        let expected = if stopped && (cancelled || ended) {
                            tracing::Level::DEBUG
                        } else {
                            tracing::Level::WARN
                        };
                        assert_eq!(
                            *levels.lock().unwrap(),
                            vec![expected],
                            "wrapped={wrapped}, bootstrap={bootstrap}, stopped={stopped}, cancelled={cancelled}, ended={ended}"
                        );
                    }
                }
            }
        }
    }

    #[tokio::test]
    async fn bootstrap_tail_failures_reach_completion_observer() {
        for failure in [
            Annotated::from_error("connection closed during prefill"),
            Annotated::from_data(LLMEngineOutput::error("backend prefill failed".to_string())),
            Annotated::from_data(LLMEngineOutput::cancelled()),
        ] {
            let first = Annotated::from_data(LLMEngineOutput {
                disaggregated_params: Some(json!({
                    "bootstrap_host": "prefill", "bootstrap_port": 1, "bootstrap_room": 7,
                })),
                ..Default::default()
            });
            let (release_tx, release_rx) = tokio::sync::oneshot::channel();
            let stream = stream::iter([first]).chain(stream::once(async move {
                release_rx.await.unwrap();
                failure
            }));
            let response = ResponseStream::new(Box::pin(stream), Arc::new(Controller::default()));
            let result = PrefillRouter::consume_prefill_stream(response, None, None)
                .await
                .unwrap();
            let PrefillCompletion::Handoff {
                completion: Some(completion),
                ..
            } = result
            else {
                panic!("expected an early handoff with a completion observer");
            };
            release_tx.send(()).unwrap();
            let context = Arc::new(Controller::default());
            let decode: ManyOut<Annotated<LLMEngineOutput>> =
                ResponseStream::new(Box::pin(stream::pending()), context.clone());
            match completion
                .forward_decode(
                    async { Ok(decode) },
                    context,
                    PrefillNeed::None,
                    Arc::new(Controller::default()),
                )
                .await
            {
                Err(error) => assert!(error.to_string().contains("Prefill")),
                Ok(mut response) => {
                    let output =
                        tokio::time::timeout(std::time::Duration::from_secs(1), response.next())
                            .await
                            .unwrap()
                            .unwrap();
                    assert!(output.err().is_some());
                    assert!(response.next().await.is_none());
                }
            }
        }
    }

    #[tokio::test]
    async fn bootstrap_drain_retains_teardown_guard_until_stream_finishes() {
        let first = Annotated::from_data(LLMEngineOutput {
            disaggregated_params: Some(json!({
                "bootstrap_host": "127.0.0.1",
                "bootstrap_port": 1,
                "bootstrap_room": "test",
                "ctx_request_id": 42,
            })),
            ..Default::default()
        });
        let (release_tx, release_rx) = tokio::sync::oneshot::channel();
        let stream = stream::iter([first]).chain(stream::once(async move {
            let _ = release_rx.await;
            Annotated::from_data(LLMEngineOutput::default())
        }));
        let teardown = Arc::new(());
        let teardown_weak = Arc::downgrade(&teardown);
        let task_guard: dynamo_runtime::engine::EngineContextGuard = teardown.clone();
        let client_context = Context::new(());
        let prefill_context = Context::new(());
        let client = client_context.context();
        let prefill = prefill_context.context();
        let response = ResponseStream::new(Box::pin(stream), prefill.clone());
        let cancel_guard = arm_for(true, true, client.clone(), Arc::downgrade(&prefill)).unwrap();
        prefill.retain(cancel_guard);
        drop(teardown);

        PrefillRouter::consume_prefill_stream(response, None, Some(task_guard))
            .await
            .unwrap();
        assert!(teardown_weak.upgrade().is_some());

        client.stop_generating();
        tokio::time::timeout(std::time::Duration::from_secs(1), prefill.stopped())
            .await
            .expect("bootstrap drain did not retain cancellation propagation");

        release_tx.send(()).unwrap();
        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            while teardown_weak.upgrade().is_some() {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("bootstrap drain did not release its teardown guard");
    }

    #[tokio::test]
    async fn first_output_error_does_not_record_prefill_complete() {
        let tracker = Arc::new(RequestTracker::new());
        let result = PrefillRouter::consume_prefill_stream(
            prefill_stream(vec![Annotated::from_error("prefill failed")]),
            Some(tracker.clone()),
            None,
        )
        .await;

        // The text must survive: `to_pyerr` only keeps `Display`.
        let Err(err) = result else {
            panic!("expected a first output error");
        };
        assert!(err.to_string().contains("prefill failed"), "{err}");
        assert!(tracker.record_prefill_complete());
    }

    #[tokio::test]
    async fn later_output_error_is_propagated_after_prefill_arrival() {
        let tracker = Arc::new(RequestTracker::new());
        let result = PrefillRouter::consume_prefill_stream(
            prefill_stream(vec![
                valid_prefill_output(),
                Annotated::from_error("prefill stream failed"),
            ]),
            Some(tracker.clone()),
            None,
        )
        .await;

        let Err(err) = result else {
            panic!("expected a later output error");
        };
        assert!(err.to_string().contains("prefill stream failed"), "{err}");
        assert!(!tracker.record_prefill_complete());
    }

    #[tokio::test]
    async fn terminal_finish_reasons_without_handoff_are_returned_to_caller() {
        for finish_reason in [
            FinishReason::EoS,
            FinishReason::Stop,
            FinishReason::Cancelled,
            FinishReason::Error("prefill failed".to_string()),
            FinishReason::ContentFilter,
        ] {
            let output = LLMEngineOutput {
                token_ids: vec![2],
                finish_reason: Some(finish_reason.clone()),
                ..Default::default()
            };
            let result = PrefillRouter::consume_prefill_stream(
                prefill_stream(vec![Annotated::from_data(output)]),
                None,
                None,
            )
            .await
            .unwrap();

            let PrefillCompletion::Terminal { output } = result else {
                panic!("expected terminal prefill completion for {finish_reason:?}");
            };
            let output = *output;
            assert_eq!(
                output.data.and_then(|data| data.finish_reason),
                Some(finish_reason)
            );
        }
    }

    #[tokio::test]
    async fn length_limited_prefill_still_requires_handoff() {
        let output = LLMEngineOutput {
            finish_reason: Some(FinishReason::Length),
            disaggregated_params: Some(json!({"ctx_request_id": 42})),
            ..Default::default()
        };
        let result = PrefillRouter::consume_prefill_stream(
            prefill_stream(vec![Annotated::from_data(output)]),
            None,
            None,
        )
        .await
        .unwrap();

        let PrefillCompletion::Handoff { result, .. } = result else {
            panic!("expected prefill handoff");
        };
        assert_eq!(result.disaggregated_params, json!({"ctx_request_id": 42}));
    }

    #[tokio::test]
    async fn unfinished_prefill_still_requires_handoff() {
        let output = LLMEngineOutput {
            finish_reason: None,
            disaggregated_params: Some(json!({"ctx_request_id": 42})),
            ..Default::default()
        };
        let result = PrefillRouter::consume_prefill_stream(
            prefill_stream(vec![Annotated::from_data(output)]),
            None,
            None,
        )
        .await
        .unwrap();

        let PrefillCompletion::Handoff { result, .. } = result else {
            panic!("expected prefill handoff");
        };
        assert_eq!(result.disaggregated_params, json!({"ctx_request_id": 42}));
    }

    #[tokio::test]
    async fn non_terminal_prefill_without_usable_ctx_request_id_fails_before_decode() {
        for disaggregated_params in [
            json!({"ctx_request_id": null}),
            json!({"request_type": "context_only"}),
        ] {
            let output = LLMEngineOutput {
                finish_reason: None,
                disaggregated_params: Some(disaggregated_params),
                ..Default::default()
            };
            let result = PrefillRouter::consume_prefill_stream(
                prefill_stream(vec![Annotated::from_data(output)]),
                None,
                None,
            )
            .await;
            let Err(error) = result else {
                panic!("expected a missing ctx_request_id to reject the handoff");
            };

            assert!(matches!(
                error,
                PrefillError::NoDisaggregatedParams(message)
                    if message.contains("no usable ctx_request_id")
            ));
        }
    }
}