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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use std::collections::HashSet;

use anyhow::Result;
use dynamo_kv_router::{
    protocols::{BlockExtraInfo, RoutingConstraints, WorkerId, WorkerWithDpRank},
    scheduling::queue::BookingHandle,
};

use super::{PrefillError, PrefillLifecycleState, PrefillRouter};

/// A prefill booking that owns cleanup of the exact scheduler attempt it admitted.
///
/// KV-routed bookings retain their exact scheduler booking descriptor, so
/// cleanup is independent of a later [`PrefillRouter`] binding change and
/// cannot release a newer booking that reused its request ID and worker.
/// Built-in router modes use an untracked, advisory booking whose release is a no-op.
#[must_use]
pub struct PrefillReservation {
    worker: WorkerWithDpRank,
    dp_rank: Option<u32>,
    booking: Option<BookingHandle>,
}

impl PrefillReservation {
    pub fn worker_id(&self) -> WorkerId {
        self.worker.worker_id
    }

    pub fn dp_rank(&self) -> Option<u32> {
        self.dp_rank
    }

    /// Release this booking and wait for the scheduler to acknowledge it.
    pub async fn release(mut self) -> Result<()> {
        if let Some(booking) = self.booking.take() {
            booking.release().await?;
        }
        Ok(())
    }
}

impl PrefillRouter {
    /// Select a prefill worker and reserve it when KV routing is enabled.
    ///
    /// If this future is dropped while queued, the scheduler retracts its
    /// pending admission. After success, the returned reservation owns the
    /// exact scheduler booking and enqueues cleanup when dropped; explicit
    /// release waits for that cleanup to be acknowledged. Built-in modes retain
    /// their existing advisory selection semantics and return an untracked
    /// reservation.
    #[expect(clippy::too_many_arguments)]
    pub async fn reserve_prefill_worker(
        &self,
        reservation_id: &str,
        token_ids: &[u32],
        block_mm_infos: Option<&[Option<BlockExtraInfo>]>,
        lora_name: Option<String>,
        cache_namespace: Option<String>,
        priority_jump: f64,
        strict_priority: u32,
        policy_class: Option<String>,
        allowed_worker_ids: Option<HashSet<WorkerId>>,
        routing_constraints: RoutingConstraints,
    ) -> Result<PrefillReservation> {
        if reservation_id.is_empty() {
            anyhow::bail!("prefill reservation ID must not be empty");
        }
        if self.lifecycle_state() != PrefillLifecycleState::Active {
            return Err(anyhow::anyhow!(PrefillError::NotActivated));
        }
        let binding = self
            .binding
            .load_full()
            .ok_or_else(|| anyhow::anyhow!(PrefillError::NotActivated))?;
        let router = &binding.router;
        let Some(chooser) = router.kv_router_if_enabled() else {
            let worker_id = router
                .peek_next_worker()
                .ok_or_else(|| anyhow::anyhow!("No workers available for prefill"))?;
            return Ok(PrefillReservation {
                worker: WorkerWithDpRank::new(worker_id, 0),
                dp_rank: None,
                booking: None,
            });
        };
        let admitted = chooser
            .find_best_match_details_with_policy_class_admitted(
                Some(reservation_id),
                token_ids,
                block_mm_infos,
                None,
                true,
                false,
                lora_name,
                cache_namespace,
                priority_jump,
                strict_priority,
                policy_class,
                None,
                None,
                None,
                allowed_worker_ids,
                routing_constraints,
            )
            .await?;
        let (outcome, booking) = admitted.into_parts();
        match outcome {
            crate::kv_router::FindBestMatchOutcome::Routed { worker, .. } => {
                let Some(booking) = booking else {
                    anyhow::bail!("prefill reservation admission did not return a booking");
                };
                Ok(PrefillReservation {
                    worker,
                    dp_rank: Some(worker.dp_rank),
                    booking: Some(booking),
                })
            }
            crate::kv_router::FindBestMatchOutcome::QueueRejected { rejection } => {
                anyhow::bail!(
                    "prefill router policy-class queue rejection: policy_class={}, limit_kind={}, current={}, limit={}",
                    rejection.policy_class,
                    rejection.limit_kind,
                    rejection.current,
                    rejection.limit,
                )
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{
        collections::HashMap,
        sync::{Arc, Mutex},
        time::Duration,
    };

    use crate::local_model::runtime_config::ModelRuntimeConfig;
    use async_trait::async_trait;
    use dynamo_kv_router::config::KvRouterConfig;
    use dynamo_runtime::{
        DistributedRuntime, Runtime,
        component::Instance,
        discovery::{EndpointInstanceId, EventTransportKind},
        distributed::{DiscoveryBackend, DistributedConfig, RequestPlaneMode},
        engine::{AsyncEngine, AsyncEngineContext},
        pipeline::{
            AddressedRequest, Context, Error, ManyIn, ManyOut, ResponseStream, RouterMode,
            SingleIn, StreamingDispatch, context::Controller,
        },
        storage::kv,
        traits::DistributedRuntimeProvider,
    };
    use futures::StreamExt;
    use tokio::sync::watch;

    use super::*;
    use crate::{
        discovery::ModelManager,
        kv_router::prefill_router::PrefillBinding,
        kv_router::{KvRouter, RouterLoadSource, RoutingHost, RoutingLoadContext},
        protocols::common::{
            FinishReason, llm_backend::LLMEngineOutput, preprocessor::PreprocessedRequest,
        },
        worker_type::WorkerType,
    };

    type LlmResponse = dynamo_runtime::protocols::annotated::Annotated<LLMEngineOutput>;

    struct RecordingDispatch {
        worker_ids: Mutex<Vec<u64>>,
        pending_responses: bool,
    }

    impl RecordingDispatch {
        fn completed() -> Self {
            Self {
                worker_ids: Mutex::new(Vec::new()),
                pending_responses: false,
            }
        }

        fn pending() -> Self {
            Self {
                worker_ids: Mutex::new(Vec::new()),
                pending_responses: true,
            }
        }

        fn response_stream(&self) -> ManyOut<LlmResponse> {
            let context: Arc<dyn AsyncEngineContext> = Arc::new(Controller::default());
            if self.pending_responses {
                return ResponseStream::new(Box::pin(futures::stream::pending()), context);
            }
            ResponseStream::new(
                Box::pin(tokio_stream::iter(vec![LlmResponse::from_data(
                    LLMEngineOutput {
                        finish_reason: Some(FinishReason::EoS),
                        ..Default::default()
                    },
                )])),
                context,
            )
        }
    }

    #[async_trait]
    impl StreamingDispatch<PreprocessedRequest, LlmResponse> for RecordingDispatch {
        async fn generate(
            &self,
            request: SingleIn<AddressedRequest<PreprocessedRequest>>,
        ) -> Result<ManyOut<LlmResponse>, Error> {
            let (addressed, _) = request.transfer(());
            let (_, _, instance) = addressed.into_parts();
            self.worker_ids
                .lock()
                .unwrap()
                .push(instance.expect("selected instance").id());
            Ok(self.response_stream())
        }

        async fn generate_bidirectional(
            &self,
            _instance: Instance,
            _address: String,
            _input: ManyIn<PreprocessedRequest>,
        ) -> Result<ManyOut<LlmResponse>, Error> {
            anyhow::bail!("bidirectional dispatch is unused in this test")
        }

        async fn on_instance_removed(&self, _id: &EndpointInstanceId) {}
    }

    fn distributed_config(root: &std::path::Path) -> DistributedConfig {
        DistributedConfig {
            discovery_backend: DiscoveryBackend::KvStore(kv::Selector::File(root.to_path_buf())),
            nats_config: None,
            request_plane: RequestPlaneMode::Tcp,
            response_plane: None,
            event_transport_kind: EventTransportKind::Zmq,
        }
    }

    fn request() -> PreprocessedRequest {
        PreprocessedRequest::builder()
            .model("test".to_string())
            .token_ids(vec![1, 2, 3])
            .stop_conditions(Default::default())
            .sampling_options(Default::default())
            .output_options(Default::default())
            .build()
            .unwrap()
    }

    /// The advisory builtin-host peek used by `reserve_prefill_worker`'s non-KV arm.
    fn query_worker(router: &PrefillRouter) -> u64 {
        router
            .binding
            .load_full()
            .unwrap()
            .router
            .peek_next_worker()
            .expect("RR query cannot fail")
    }

    async fn shared_router(
        runtime: &Runtime,
        discovery_root: &std::path::Path,
        namespace: &str,
        mode: RouterMode,
        dispatch: Arc<RecordingDispatch>,
    ) -> (
        Arc<RoutingHost>,
        Arc<PrefillRouter>,
        Vec<DistributedRuntime>,
        Vec<u64>,
    ) {
        let component = "workers";
        let endpoint_name = "generate";
        let mut worker_runtimes = Vec::new();
        for _ in 0..4 {
            let worker_runtime =
                DistributedRuntime::new(runtime.clone(), distributed_config(discovery_root))
                    .await
                    .unwrap();
            worker_runtime
                .namespace(namespace.to_string())
                .unwrap()
                .component(component.to_string())
                .unwrap()
                .endpoint(endpoint_name)
                .register_endpoint_instance()
                .await
                .unwrap();
            worker_runtimes.push(worker_runtime);
        }

        let router_runtime =
            DistributedRuntime::new(runtime.clone(), distributed_config(discovery_root))
                .await
                .unwrap();
        let client = router_runtime
            .namespace(namespace.to_string())
            .unwrap()
            .component(component.to_string())
            .unwrap()
            .endpoint(endpoint_name)
            .client()
            .await
            .unwrap();
        let instances = tokio::time::timeout(Duration::from_secs(5), async {
            let mut source = client.instance_source.as_ref().clone();
            loop {
                let instances = source.borrow_and_update().clone();
                if instances.len() == 4 {
                    return instances;
                }
                source
                    .changed()
                    .await
                    .expect("discovery source must remain open");
            }
        })
        .await
        .expect("all four workers must be discovered");
        let mut workers = instances.iter().map(Instance::id).collect::<Vec<_>>();
        workers.sort_unstable();
        let load_context = RoutingLoadContext::start(
            client.clone(),
            RouterLoadSource::Prefill,
            crate::discovery::LoadThresholdHandle::new(Default::default()),
            &client.endpoint.drt().child_token(),
            None,
        )
        .await
        .unwrap();
        let shared = Arc::new(
            RoutingHost::builder(client, mode)
                .load_context(load_context)
                .dispatch(dispatch as crate::kv_router::LlmDispatch)
                .build()
                .await
                .unwrap(),
        );
        let prefill = PrefillRouter::disabled(Arc::new(ModelManager::new()), mode, None);
        prefill.binding.store(Some(Arc::new(
            crate::kv_router::prefill_router::PrefillBinding {
                target_id: crate::discovery::WorkerSetTargetId::Legacy(
                    dynamo_runtime::protocols::EndpointId {
                        namespace: namespace.to_string(),
                        component: component.to_string(),
                        name: endpoint_name.to_string(),
                    },
                ),
                endpoint_id: dynamo_runtime::protocols::EndpointId {
                    namespace: namespace.to_string(),
                    component: component.to_string(),
                    name: endpoint_name.to_string(),
                },
                router: shared.clone(),
                prefill_router_mode: mode,
            },
        )));
        prefill.lifecycle.store(
            PrefillLifecycleState::Active as u8,
            std::sync::atomic::Ordering::Release,
        );
        worker_runtimes.push(router_runtime);
        (shared, prefill, worker_runtimes, workers)
    }

    async fn tracked_binding(label: &str) -> (Arc<PrefillBinding>, Arc<KvRouter>) {
        let runtime = Runtime::from_current().unwrap();
        let distributed = DistributedRuntime::new(runtime, DistributedConfig::process_local())
            .await
            .unwrap();
        let component = distributed
            .namespace(format!(
                "prefill-reservation-{label}-{}",
                uuid::Uuid::new_v4()
            ))
            .unwrap()
            .component("workers".to_string())
            .unwrap();
        let endpoint = component.endpoint("generate");
        let endpoint_id = endpoint.id();
        let client = endpoint.client().await.unwrap();
        let (_workers_tx, workers_rx) = watch::channel(HashMap::from([
            (7, ModelRuntimeConfig::default()),
            (8, ModelRuntimeConfig::default()),
        ]));
        let config = KvRouterConfig {
            overlap_score_credit: 0.0,
            router_temperature: 0.0,
            use_kv_events: false,
            router_track_active_blocks: false,
            router_track_prefill_tokens: true,
            skip_initial_worker_wait: true,
            ..Default::default()
        };
        let chooser = Arc::new(
            KvRouter::new_with_worker_role(
                endpoint,
                client.clone(),
                workers_rx,
                None,
                16,
                crate::kv_router::SelectionPolicySource::Registry,
                Some(config),
                None,
                Some(WorkerType::Prefill),
                "prefill",
                Some(format!("prefill-reservation-{label}")),
                false,
                None,
                None,
            )
            .await
            .unwrap(),
        );
        let router = RoutingHost::builder(client, RouterMode::KV)
            .kv_router(chooser.clone())
            .build()
            .await
            .unwrap();
        let binding = Arc::new(PrefillBinding {
            target_id: crate::discovery::WorkerSetTargetId::Legacy(endpoint_id.clone()),
            endpoint_id,
            router: Arc::new(router),
            prefill_router_mode: RouterMode::KV,
        });
        (binding, chooser)
    }

    async fn tracked_prefill_router() -> (Arc<PrefillRouter>, Arc<KvRouter>) {
        let (binding, chooser) = tracked_binding("primary").await;
        let router = PrefillRouter::disabled(Arc::new(ModelManager::new()), RouterMode::KV, None);
        router.binding.store(Some(binding));
        router.lifecycle.store(
            PrefillLifecycleState::Active as u8,
            std::sync::atomic::Ordering::Release,
        );
        (router, chooser)
    }

    #[tokio::test]
    async fn binding_availability_tracks_local_inhibition_and_cancellation() {
        use crate::kv_router::prefill_router::PrefillRouterLifecycle;

        let (router, chooser) = tracked_prefill_router().await;
        let endpoint = chooser.client().endpoint.id();
        chooser.client().override_discovered_instances(vec![7, 8]);
        assert_eq!(
            router.available_worker_ids_for("legacy", &endpoint),
            Some(HashSet::from([7, 8]))
        );
        chooser.client().report_instance_down(7);
        assert_eq!(
            router.available_worker_ids_for("legacy", &endpoint),
            Some(HashSet::from([8]))
        );
        let mut other = endpoint.clone();
        other.name = "other".into();
        assert!(router.available_worker_ids_for("legacy", &other).is_none());
        router.lifecycle.store(
            PrefillLifecycleState::Unavailable as u8,
            std::sync::atomic::Ordering::Release,
        );
        assert_eq!(
            router.available_worker_ids_for("legacy", &endpoint),
            Some(HashSet::new())
        );
        router.lifecycle.store(
            PrefillLifecycleState::Active as u8,
            std::sync::atomic::Ordering::Release,
        );
        router.cancel_token.cancel();
        assert_eq!(
            router.available_worker_ids_for("legacy", &endpoint),
            Some(HashSet::new())
        );
    }

    #[tokio::test]
    async fn binding_availability_waits_for_rebind_publication() {
        use crate::kv_router::prefill_router::PrefillRouterLifecycle;
        use std::sync::mpsc;

        let (router, chooser) = tracked_prefill_router().await;
        let original = chooser.client().endpoint.id();
        chooser.client().override_discovered_instances(vec![7]);
        let (replacement, _) = tracked_binding("availability-replacement").await;
        let mut target = router.target.lock();
        *target = Some(crate::discovery::WorkerSetTargetId::Legacy(
            original.clone(),
        ));
        let (started_tx, started_rx) = mpsc::channel();
        let (result_tx, result_rx) = mpsc::channel();
        let reader_router = router.clone();
        let reader = std::thread::spawn(move || {
            started_tx.send(()).unwrap();
            result_tx
                .send(reader_router.available_worker_ids_for("legacy", &original))
                .unwrap();
        });
        started_rx.recv_timeout(Duration::from_secs(5)).unwrap();
        assert!(matches!(
            result_rx.recv_timeout(Duration::from_millis(100)),
            Err(mpsc::RecvTimeoutError::Timeout)
        ));
        *target = Some(replacement.target_id.clone());
        router.binding.store(Some(replacement));
        router.lifecycle.store(
            PrefillLifecycleState::Active as u8,
            std::sync::atomic::Ordering::Release,
        );
        drop(target);
        assert_eq!(
            result_rx.recv_timeout(Duration::from_secs(5)).unwrap(),
            None
        );
        reader.join().unwrap();
    }

    #[tokio::test]
    async fn prefill_reservation_cleans_exact_bookings_after_rebind() {
        let (router, original_chooser) = tracked_prefill_router().await;
        let reservation = router
            .reserve_prefill_worker(
                "epp-prefill/rebind",
                &[1u32; 64],
                None,
                None,
                None,
                0.0,
                0,
                None,
                None,
                RoutingConstraints::default(),
            )
            .await
            .unwrap();

        assert!(reservation.dp_rank().is_some());
        let dropped_reservation = router
            .reserve_prefill_worker(
                "epp-prefill/drop",
                &[1u32; 64],
                None,
                None,
                None,
                0.0,
                0,
                None,
                None,
                RoutingConstraints::default(),
            )
            .await
            .unwrap();

        let loads = original_chooser
            .get_potential_loads(&[], None, None, None, None)
            .await
            .unwrap();
        assert!(
            loads.iter().any(|load| load.potential_prefill_tokens > 0),
            "reservation did not add prefill load: {loads:?}"
        );

        let (replacement, _) = tracked_binding("replacement").await;
        router.binding.store(Some(replacement));
        reservation.release().await.unwrap();

        drop(dropped_reservation);
        tokio::time::timeout(Duration::from_secs(1), async {
            loop {
                let loads = original_chooser
                    .get_potential_loads(&[], None, None, None, None)
                    .await
                    .unwrap();
                if loads.iter().all(|load| load.potential_prefill_tokens == 0) {
                    return;
                }
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("dropped reservation must release its admitted booking");
    }

    #[tokio::test]
    async fn prefill_reservation_keeps_the_unknown_class_error() {
        use dynamo_runtime::error::{DynamoError, ErrorType};

        // The tracked prefill router has no policy file, so its synthetic profile has no `priority`.
        let (router, chooser) = tracked_prefill_router().await;
        let error = router
            .reserve_prefill_worker(
                "epp-prefill/unknown-class",
                &[1u32; 64],
                None,
                None,
                None,
                0.0,
                0,
                Some("priority".to_string()),
                None,
                RoutingConstraints::default(),
            )
            .await
            .err()
            .expect("prefill class entry must reject an unknown class");
        let error = error
            .downcast_ref::<DynamoError>()
            .expect("the class error must stay a top-level DynamoError");
        assert_eq!(error.error_type(), ErrorType::InvalidArgument);
        assert_eq!(error.message(), "unknown policy class \"priority\"");
        let loads = chooser
            .get_potential_loads(&[], None, None, None, None)
            .await
            .unwrap();
        assert!(
            loads.iter().all(|load| load.potential_prefill_tokens == 0),
            "a rejected class must not book prefill load: {loads:?}"
        );
    }

    #[tokio::test]
    async fn unknown_class_decode_refusal_stops_pending_prefill() {
        use super::super::handoff::PrefillTask;
        use crate::protocols::response_merge::PrefillNeed;
        use dynamo_runtime::engine::AsyncEngineContextProvider;
        use dynamo_runtime::error::{DynamoError, ErrorType};
        use dynamo_runtime::pipeline::context::Controller;

        // This KV routing host stands in for decode: its synthetic profile has no `priority`,
        // so decode refuses that class when the request enters it, before any dispatch.
        let (decode, _chooser) = tracked_binding("decode-refusal").await;
        for output in [
            PrefillNeed::None,
            PrefillNeed::BeforeLast,
            PrefillNeed::BeforeFirst,
        ] {
            // Prefill accepted the class and is still running under its own controller.
            let prefill_context = Arc::new(Controller::default());
            let task_context = prefill_context.clone();
            let (cleaned_tx, cleaned_rx) = tokio::sync::oneshot::channel();
            let prefill = PrefillTask::spawn(
                async move {
                    task_context.stopped().await;
                    let _ = cleaned_tx.send(());
                    Ok(None)
                },
                prefill_context.clone(),
            );
            let request = Context::with_id_and_metadata(
                request(),
                format!("decode-refusal-{output:?}"),
                std::collections::BTreeMap::from([(
                    "policy-class".to_string(),
                    "priority".to_string(),
                )]),
            );
            let request_context = request.context();
            let error = prefill
                .forward_decode(
                    decode.router.generate(request),
                    request_context,
                    output,
                    prefill_context.clone(),
                )
                .await
                .expect_err("decode routing must refuse the unknown class");
            let refusal = error
                .downcast_ref::<DynamoError>()
                .expect("the refusal keeps its DynamoError");
            assert_eq!(refusal.error_type(), ErrorType::InvalidArgument);
            assert_eq!(refusal.message(), "unknown policy class \"priority\"");
            assert!(
                prefill_context.is_stopped(),
                "decode's class refusal left prefill running: {output:?}"
            );
            tokio::time::timeout(Duration::from_secs(1), cleaned_rx)
                .await
                .expect("stopped prefill must finish its cleanup")
                .unwrap();
        }
    }

    #[tokio::test]
    async fn rr_prefill_queries_and_reservations_do_not_advance_dispatch_cursor() {
        let runtime = Runtime::from_current().unwrap();
        let discovery_root = tempfile::tempdir().unwrap();
        let namespace = "prefill-query-rr";
        let dispatch = Arc::new(RecordingDispatch::completed());
        let (shared_router, prefill_router, worker_runtimes, expected_workers) = shared_router(
            &runtime,
            discovery_root.path(),
            namespace,
            RouterMode::RoundRobin,
            dispatch.clone(),
        )
        .await;

        let reservation = prefill_router
            .reserve_prefill_worker(
                "non-kv-reservation",
                &[1, 2, 3],
                None,
                None,
                None,
                0.0,
                0,
                None,
                None,
                RoutingConstraints::default(),
            )
            .await
            .unwrap();
        assert_eq!(reservation.worker_id(), expected_workers[0]);
        assert_eq!(reservation.dp_rank(), None);
        reservation.release().await.unwrap();

        let concurrent_peeks = (0..16)
            .map(|_| query_worker(&prefill_router))
            .collect::<Vec<_>>();
        assert!(
            concurrent_peeks
                .iter()
                .all(|worker_id| *worker_id == expected_workers[0])
        );

        for expected_worker in &expected_workers {
            assert_eq!(query_worker(&prefill_router), *expected_worker);
            assert_eq!(query_worker(&prefill_router), *expected_worker);
            let mut stream = shared_router
                .generate(Context::new(request()))
                .await
                .unwrap();
            while stream.next().await.is_some() {}
        }

        assert_eq!(*dispatch.worker_ids.lock().unwrap(), expected_workers);
        drop(worker_runtimes);
        runtime.shutdown();
    }

    #[tokio::test]
    async fn advisory_prefill_query_never_acquires_local_occupancy() {
        let runtime = Runtime::from_current().unwrap();
        let discovery_root = tempfile::tempdir().unwrap();

        for (index, mode) in [RouterMode::LeastLoaded, RouterMode::DeviceAwareWeighted]
            .into_iter()
            .enumerate()
        {
            let dispatch = Arc::new(RecordingDispatch::pending());
            let (shared, prefill, runtimes, workers) = shared_router(
                &runtime,
                discovery_root.path(),
                &format!("prefill-query-occupancy-{index}"),
                mode,
                dispatch,
            )
            .await;

            for _ in 0..16 {
                query_worker(&prefill);
            }
            assert_eq!(
                workers
                    .iter()
                    .map(|worker| shared.occupancy_for_test(*worker))
                    .sum::<u64>(),
                0,
                "{mode:?} advisory queries must not acquire occupancy"
            );

            let stream = shared.generate(Context::new(request())).await.unwrap();
            assert_eq!(
                workers
                    .iter()
                    .map(|worker| shared.occupancy_for_test(*worker))
                    .sum::<u64>(),
                1,
                "{mode:?} committed dispatch must retain exactly one lease"
            );
            drop(stream);
            assert_eq!(
                workers
                    .iter()
                    .map(|worker| shared.occupancy_for_test(*worker))
                    .sum::<u64>(),
                0,
                "{mode:?} dropping the response stream must release the lease"
            );
            drop(runtimes);
        }

        runtime.shutdown();
    }
}