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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use std::sync::Arc;
use std::sync::atomic::Ordering;

use anyhow::{Context as _, Result};
use tokio::sync::{oneshot, watch};

use dynamo_kv_router::{
    PrefillLoadEstimator, conditional_disagg::make_conditional_disagg_policy,
    config::KvRouterConfig,
};
use dynamo_runtime::{
    component::Endpoint, discovery::DiscoveryQuery, pipeline::RouterMode,
    prelude::DistributedRuntimeProvider,
};

use super::{PrefillBinding, PrefillBuildContext, PrefillLifecycleState, PrefillRouter};

/// Routing state of a prefill hop, resolved atomically by [`PrefillRouter::activation_snapshot`].
pub(super) enum ActivationSnapshot {
    Active(Arc<PrefillBinding>),
    /// A target is set but its binding is not published yet: fail closed.
    Pending,
    /// No prefill target (never set, or cleared): passthrough to decode is safe.
    Untargeted,
}
use crate::{
    discovery::{LoadThresholdHandle, ModelManager, WorkerSetTarget},
    kv_router::{RouterLoadSource, RoutingHost, RoutingLoadContext, SelectionPolicySource},
    model_card::ModelDeploymentCard,
    protocols::common::timing::WORKER_TYPE_PREFILL,
    session_affinity::{SessionAffinityMode, create_affinity_coordinator},
};

/// How the prefill worker set wants to be routed to, resolved from its cards.
#[derive(Debug)]
struct PrefillAdvertisement {
    router_mode: RouterMode,
    /// `None` when the card declared nothing, so the decode set's tuning applies.
    kv_router_config: Option<KvRouterConfig>,
    /// Taken from an advertised `router_config` whole, `None` included -- an
    /// advertisement replaces the decode set's configuration rather than
    /// merging with it. `None` here when nothing was advertised at all.
    session_affinity_ttl: Option<Option<std::time::Duration>>,
    is_eagle: bool,
    /// The prefill workers' own block size, which is what their KV events are
    /// keyed on. The decode set's value would index this pool at the wrong
    /// granularity if the two ever differ.
    kv_cache_block_size: u32,
}

/// A prefill worker that declares its own `router_config` governs this hop;
/// one that declares nothing inherits `decode_router_mode`. That is what lets a
/// deployment run KV-routed prefill in front of round-robin decode.
fn resolve_advertisement_from_cards(
    cards: &[ModelDeploymentCard],
    decode_router_mode: RouterMode,
) -> Result<PrefillAdvertisement> {
    let mode_of = |card: &ModelDeploymentCard| {
        card.router_config
            .as_ref()
            .map_or(decode_router_mode, |config| config.router_mode)
    };

    let Some(first) = cards.first() else {
        anyhow::bail!("no readable prefill model card; cannot resolve prefill routing");
    };

    let advertisement = PrefillAdvertisement {
        router_mode: mode_of(first),
        kv_router_config: first
            .router_config
            .as_ref()
            .map(|config| config.kv_router_config.clone()),
        session_affinity_ttl: first.router_config.as_ref().map(|config| {
            config
                .session_affinity_ttl_secs
                .map(std::time::Duration::from_secs)
        }),
        is_eagle: first.runtime_config.enable_eagle,
        kv_cache_block_size: first.kv_cache_block_size,
    };

    // Only legacy explicit endpoints can supply multiple cards here; managed
    // topology supplies the selected card and filters incompatible workers.
    let disagreeing = cards
        .iter()
        .skip(1)
        .filter(|card| mode_of(card) != advertisement.router_mode)
        .count();
    if disagreeing > 0 {
        tracing::warn!(
            resolved_mode = ?advertisement.router_mode,
            disagreeing,
            total = cards.len(),
            "Prefill workers advertise conflicting router modes; using the first"
        );
    }

    Ok(advertisement)
}

impl PrefillRouter {
    /// Create a disabled prefill router that will never activate (passthrough only)
    pub fn disabled(
        model_manager: Arc<ModelManager>,
        decode_router_mode: RouterMode,
        session_affinity_ttl_secs: Option<u64>,
    ) -> Arc<Self> {
        Self::disabled_with_session_affinity_mode(
            model_manager,
            decode_router_mode,
            session_affinity_ttl_secs,
            SessionAffinityMode::Hard,
        )
    }

    /// `decode_router_mode` is the owning decode worker set's mode. It governs
    /// decode-side decisions and is the fallback for the prefill hop; a prefill
    /// worker that advertises its own `router_config` overrides the latter.
    #[expect(clippy::too_many_arguments)]
    pub fn new(
        activation_rx: oneshot::Receiver<Endpoint>,
        model_manager: Arc<ModelManager>,
        decode_router_mode: RouterMode,
        kv_cache_block_size: u32,
        kv_router_config: Option<KvRouterConfig>,
        prefill_load_estimator: Option<Arc<dyn PrefillLoadEstimator>>,
        session_affinity_ttl_secs: Option<u64>,
        session_affinity_mode: SessionAffinityMode,
        model_name: String,
        namespace: String,
        load_thresholds: LoadThresholdHandle,
        parent_token: tokio_util::sync::CancellationToken,
    ) -> Arc<Self> {
        Self::new_with_selection_policy(
            Some(activation_rx),
            model_manager,
            decode_router_mode,
            false,
            kv_cache_block_size,
            kv_router_config,
            SelectionPolicySource::Registry,
            prefill_load_estimator,
            session_affinity_ttl_secs,
            session_affinity_mode,
            model_name,
            namespace,
            load_thresholds,
            parent_token,
            None,
        )
    }
}

impl PrefillRouter {
    pub(crate) fn disabled_with_session_affinity_mode(
        model_manager: Arc<ModelManager>,
        decode_router_mode: RouterMode,
        session_affinity_ttl_secs: Option<u64>,
        session_affinity_mode: SessionAffinityMode,
    ) -> Arc<Self> {
        Arc::new(Self {
            binding: arc_swap::ArcSwapOption::empty(),
            target: parking_lot::Mutex::new(None),
            target_tx: None,
            decode_routing_host: std::sync::OnceLock::new(),
            selection_policy: None,
            model_manager,
            cancel_token: tokio_util::sync::CancellationToken::new(),
            decode_router_mode,
            decode_supports_prefill_cancellation: false,
            session_affinity_ttl: session_affinity_ttl_secs.map(std::time::Duration::from_secs),
            session_affinity_mode,
            conditional_disagg_policy: make_conditional_disagg_policy(None),
            conditional_disagg_prefill_busy_threshold: None,
            conditional_disagg_decode_busy_threshold: None,
            prefill_load_estimator: None,
            model_name: String::new(), // Not used for disabled router
            namespace: String::new(),  // Not used for disabled router
            task_guard: None,
            lifecycle: std::sync::atomic::AtomicU8::new(PrefillLifecycleState::Pending as u8),
            #[cfg(test)]
            activation_task_state: Arc::new(()),
        })
    }

    #[expect(clippy::too_many_arguments)]
    pub(crate) fn new_with_selection_policy(
        activation_rx: Option<oneshot::Receiver<Endpoint>>,
        model_manager: Arc<ModelManager>,
        decode_router_mode: RouterMode,
        decode_supports_prefill_cancellation: bool,
        kv_cache_block_size: u32,
        kv_router_config: Option<KvRouterConfig>,
        selection_policy: SelectionPolicySource,
        prefill_load_estimator: Option<Arc<dyn PrefillLoadEstimator>>,
        session_affinity_ttl_secs: Option<u64>,
        session_affinity_mode: SessionAffinityMode,
        model_name: String,
        namespace: String,
        load_thresholds: LoadThresholdHandle,
        parent_token: tokio_util::sync::CancellationToken,
        task_guard: Option<dynamo_runtime::engine::EngineContextGuard>,
    ) -> Arc<Self> {
        let cancel_token = parent_token.child_token();
        let (target_tx, target_rx) = watch::channel(None);
        let conditional_disagg_policy = make_conditional_disagg_policy(kv_router_config.as_ref());
        let conditional_disagg_prefill_busy_threshold = kv_router_config.as_ref().and_then(|c| {
            c.conditional_disagg_prefill_busy_threshold
                .or(c.router_queue_threshold)
        });
        let conditional_disagg_decode_busy_threshold = kv_router_config
            .as_ref()
            .and_then(|c| c.conditional_disagg_decode_busy_threshold);

        let router = Arc::new(Self {
            binding: arc_swap::ArcSwapOption::empty(),
            target: parking_lot::Mutex::new(None),
            target_tx: Some(target_tx),
            decode_routing_host: std::sync::OnceLock::new(),
            selection_policy: Some(selection_policy),
            model_manager: model_manager.clone(),
            cancel_token: cancel_token.clone(),
            decode_router_mode,
            decode_supports_prefill_cancellation,
            session_affinity_ttl: session_affinity_ttl_secs.map(std::time::Duration::from_secs),
            session_affinity_mode,
            conditional_disagg_policy,
            conditional_disagg_prefill_busy_threshold,
            conditional_disagg_decode_busy_threshold,
            prefill_load_estimator,
            model_name,
            namespace,
            task_guard: task_guard.clone(),
            lifecycle: std::sync::atomic::AtomicU8::new(PrefillLifecycleState::Pending as u8),
            #[cfg(test)]
            activation_task_state: Arc::new(()),
        });

        let router_weak = Arc::downgrade(&router);
        let drive_cancel_token = cancel_token.clone();
        let drive_task_guard = task_guard.clone();
        #[cfg(test)]
        let drive_task_state = router.activation_task_state.clone();
        tokio::spawn(async move {
            let _drive_task_guard = drive_task_guard;
            #[cfg(test)]
            let _drive_task_state = drive_task_state;
            Self::drive_target(
                router_weak,
                target_rx,
                drive_cancel_token,
                kv_cache_block_size,
                kv_router_config,
                load_thresholds,
            )
            .await;
        });
        if let Some(activation_rx) = activation_rx {
            let router = Arc::downgrade(&router);
            let activation_task_guard = task_guard;
            #[cfg(test)]
            let activation_task_state = router
                .upgrade()
                .expect("prefill router exists during construction")
                .activation_task_state
                .clone();
            tokio::spawn(async move {
                let _activation_task_guard = activation_task_guard;
                #[cfg(test)]
                let _activation_task_state = activation_task_state;
                tokio::select! {
                    result = activation_rx => {
                        if let (Ok(endpoint), Some(router)) = (result, router.upgrade()) {
                            router.set_target(Some(WorkerSetTarget::Legacy(endpoint)));
                        }
                    }
                    _ = cancel_token.cancelled() => {}
                }
            });
        }

        router
    }

    async fn build_binding(
        context: &PrefillBuildContext,
        target: WorkerSetTarget,
        kv_cache_block_size: u32,
        kv_router_config: Option<KvRouterConfig>,
    ) -> Result<PrefillBinding> {
        let target_id = target.id();
        let endpoint = target.endpoint();
        let endpoint_id = endpoint.id();
        let client = target.client(context.parent_token.clone()).await?;

        // Start runtime config watcher for this endpoint (needed for get_disaggregated_endpoint)
        // This must be done before creating the router so bootstrap info is available
        context
            .model_manager
            .get_or_create_runtime_config_watcher(endpoint)
            .await?;

        let advertisement = match &target {
            WorkerSetTarget::Committed(target) => resolve_advertisement_from_cards(
                std::slice::from_ref(target.card.as_ref()),
                context.decode_router_mode,
            )?,
            WorkerSetTarget::Legacy(endpoint) => {
                Self::resolve_prefill_advertisement(context, endpoint).await?
            }
        };
        let prefill_router_mode = advertisement.router_mode;

        // Everything the hop uses comes from the prefill card when it says so,
        // falling back to the decode set. A block size of 0 means the card never
        // declared one, so it cannot be trusted over the decode set's.
        let prefill_block_size = match advertisement.kv_cache_block_size {
            0 => kv_cache_block_size,
            advertised => advertised,
        };
        let prefill_session_affinity_ttl = advertisement
            .session_affinity_ttl
            .unwrap_or(context.session_affinity_ttl);
        let load_context = RoutingLoadContext::start(
            client.clone(),
            RouterLoadSource::Prefill,
            context.load_thresholds.clone(),
            &context.parent_token,
            context.task_guard.clone(),
        )
        .await?;

        // A prefill card that declares a mode may declare KV tuning alongside it;
        // honoring only half of its `RouterConfig` would be a trap. Whichever
        // config wins, `router_track_active_blocks` stays off: prefill routing is
        // prompt-side, and crediting decode blocks here would double-count load.
        let advertised_kv_tuning = advertisement.kv_router_config.is_some();
        let prefill_kv_config = match advertisement.kv_router_config {
            Some(mut advertised) => {
                advertised.router_track_active_blocks = false;
                Some(advertised)
            }
            None => kv_router_config,
        };

        // Logged once per activation, and deliberately the *resolved* values
        // rather than what the card asked for. An advertisement replaces the
        // decode set's configuration rather than merging with it, so a worker
        // that names a mode without restating tuning silently gets defaults --
        // this line is what makes that answerable without a rebuild.
        tracing::info!(
            ?prefill_router_mode,
            decode_router_mode = ?context.decode_router_mode,
            advertised = advertised_kv_tuning,
            is_eagle = advertisement.is_eagle,
            block_size = prefill_block_size,
            session_affinity_ttl = ?prefill_session_affinity_ttl,
            kv_tuning = ?prefill_kv_config,
            "Activating prefill router"
        );

        let router = if prefill_router_mode.is_kv_routing() {
            // Create KV chooser using the endpoint (this is a prefill router)
            let kv_chooser = context
                .model_manager
                .kv_chooser_for_with_policy_and_client(
                    client.clone(),
                    prefill_block_size,
                    context.selection_policy.clone(),
                    prefill_kv_config,
                    context.prefill_load_estimator.clone(),
                    Some(crate::worker_type::WorkerType::Prefill),
                    WORKER_TYPE_PREFILL,
                    Some(context.model_name.clone()),
                    advertisement.is_eagle,
                    load_context.scheduler_load_sender(),
                    load_context.cancellation_token(),
                )
                .await?;

            let affinity = create_affinity_coordinator(
                prefill_session_affinity_ttl,
                context.session_affinity_mode,
                client.clone(),
            )
            .await?;

            Arc::new(
                RoutingHost::builder(client, RouterMode::KV)
                    .kv_router(kv_chooser)
                    .load_context(load_context.clone())
                    .affinity_coordinator(affinity)
                    .build()
                    .await?,
            )
        } else {
            let affinity = create_affinity_coordinator(
                prefill_session_affinity_ttl,
                context.session_affinity_mode,
                client.clone(),
            )
            .await?;

            // Note: Per-worker metrics (active_prefill_tokens, active_decode_blocks) are only
            // available in KV routing mode where the router has actual bookkeeping.
            Arc::new(
                RoutingHost::builder(client, prefill_router_mode)
                    .load_context(load_context.clone())
                    .affinity_coordinator(affinity)
                    .build()
                    .await?,
            )
        };

        Ok(PrefillBinding {
            target_id,
            endpoint_id,
            router,
            prefill_router_mode,
        })
    }

    /// Fetch the prefill worker set's own cards and resolve how the prefill hop
    /// should be routed.
    ///
    /// Returns `Err` rather than silently inheriting when the cards cannot be
    /// read. `drive_target` retries activation with backoff, and a delayed
    /// activation is far cheaper than routing an entire deployment with the
    /// wrong strategy because of one transient discovery miss — a downgrade that
    /// would persist until the binding was rebuilt.
    async fn resolve_prefill_advertisement(
        context: &PrefillBuildContext,
        endpoint: &Endpoint,
    ) -> Result<PrefillAdvertisement> {
        let endpoint_id = endpoint.id();
        let instances = endpoint
            .component()
            .drt()
            .discovery()
            .list(DiscoveryQuery::EndpointModels {
                namespace: endpoint_id.namespace.clone(),
                component: endpoint_id.component.clone(),
                endpoint: endpoint_id.name.clone(),
            })
            .await
            .with_context(|| format!("listing prefill model cards for {endpoint_id}"))?;

        // An unparseable card is not just a missing EAGLE hint any more: it
        // drops a worker out of the vote that decides how this hop is routed.
        let cards: Vec<ModelDeploymentCard> = instances
            .into_iter()
            .filter_map(|instance| {
                instance
                    .deserialize_model::<ModelDeploymentCard>()
                    .inspect_err(|error| {
                        tracing::debug!(%error, %endpoint_id, "Skipping unreadable prefill card")
                    })
                    .ok()
            })
            .collect();

        resolve_advertisement_from_cards(&cards, context.decode_router_mode)
            .with_context(|| format!("prefill endpoint {endpoint_id}"))
    }

    async fn drive_target(
        router: std::sync::Weak<Self>,
        mut target_rx: watch::Receiver<Option<WorkerSetTarget>>,
        cancel_token: tokio_util::sync::CancellationToken,
        kv_cache_block_size: u32,
        kv_router_config: Option<KvRouterConfig>,
        load_thresholds: LoadThresholdHandle,
    ) {
        loop {
            let target = target_rx.borrow_and_update().clone();
            let Some(target) = target else {
                tokio::select! {
                    biased;
                    _ = cancel_token.cancelled() => return,
                    changed = target_rx.changed() => {
                        if changed.is_err() {
                            return;
                        }
                    }
                }
                continue;
            };
            let target_id = target.id();
            let endpoint_id = target.endpoint().id();
            let Some(router_ref) = router.upgrade() else {
                return;
            };
            let reuses_binding = router_ref
                .binding
                .load_full()
                .is_some_and(|binding| binding.target_id == target_id)
                && router_ref.lifecycle_state() == PrefillLifecycleState::Active;
            if reuses_binding {
                drop(router_ref);
                tokio::select! {
                    biased;
                    _ = cancel_token.cancelled() => return,
                    changed = target_rx.changed() => {
                        if changed.is_err() {
                            return;
                        }
                    }
                }
                continue;
            }
            let build_context = PrefillBuildContext {
                model_manager: router_ref.model_manager.clone(),
                decode_router_mode: router_ref.decode_router_mode,
                selection_policy: router_ref
                    .selection_policy
                    .clone()
                    .expect("enabled prefill router has a selection policy"),
                prefill_load_estimator: router_ref.prefill_load_estimator.clone(),
                session_affinity_ttl: router_ref.session_affinity_ttl,
                session_affinity_mode: router_ref.session_affinity_mode,
                model_name: router_ref.model_name.clone(),
                load_thresholds: load_thresholds.clone(),
                parent_token: cancel_token.child_token(),
                task_guard: router_ref.task_guard.clone(),
            };
            drop(router_ref);
            let build = Self::build_binding(
                &build_context,
                target,
                kv_cache_block_size,
                kv_router_config.clone(),
            );
            tokio::pin!(build);
            let result = tokio::select! {
                biased;
                _ = cancel_token.cancelled() => return,
                changed = target_rx.changed() => {
                    if changed.is_err() {
                        return;
                    }
                    continue;
                }
                result = &mut build => result,
            };
            let Some(router_ref) = router.upgrade() else {
                return;
            };
            match result {
                Ok(binding) => {
                    let current_target = router_ref.target.lock();
                    if current_target.as_ref() != Some(&target_id) {
                        continue;
                    }
                    router_ref.binding.store(Some(Arc::new(binding)));
                    router_ref
                        .lifecycle
                        .store(PrefillLifecycleState::Active as u8, Ordering::Release);
                    drop(current_target);
                    tracing::info!(
                        model_name = %router_ref.model_name,
                        namespace = %router_ref.namespace,
                        %endpoint_id,
                        "Prefill router target activated"
                    );
                }
                Err(error) => {
                    if router_ref.target.lock().as_ref() != Some(&target_id) {
                        continue;
                    }
                    tracing::error!(
                        %error,
                        model_name = %router_ref.model_name,
                        namespace = %router_ref.namespace,
                        %endpoint_id,
                        "Failed to activate prefill router target"
                    );
                    drop(router_ref);
                    tokio::select! {
                        biased;
                        _ = cancel_token.cancelled() => return,
                        changed = target_rx.changed() => {
                            if changed.is_err() {
                                return;
                            }
                        }
                        _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {}
                    }
                }
            }
        }
    }

    /// Update the desired Prefill endpoint. Clearing is synchronous so requests
    /// holding an older catalog snapshot bypass a removed endpoint before the
    /// replacement catalog is published.
    pub(crate) fn set_target(&self, target: Option<WorkerSetTarget>) {
        let target_id = target.as_ref().map(WorkerSetTarget::id);
        let mut current = self.target.lock();
        if *current == target_id {
            return;
        }
        *current = target_id.clone();
        let reuses_binding = target_id.is_some()
            && self
                .binding
                .load_full()
                .is_some_and(|binding| Some(&binding.target_id) == target_id.as_ref());
        let lifecycle = if target.is_none() {
            PrefillLifecycleState::Unavailable
        } else if reuses_binding {
            PrefillLifecycleState::Active
        } else {
            self.binding.store(None);
            PrefillLifecycleState::Pending
        };
        self.lifecycle.store(lifecycle as u8, Ordering::Release);
        if let Some(target_tx) = &self.target_tx {
            target_tx.send_replace(target);
        }
    }

    pub(super) fn lifecycle_state(&self) -> PrefillLifecycleState {
        PrefillLifecycleState::from_atomic(self.lifecycle.load(Ordering::Acquire))
    }

    /// One consistent view of target, lifecycle and binding, read under the
    /// target lock. Both publishers (`set_target` and the build loop) store the
    /// binding and lifecycle while holding that lock, so a routing decision made
    /// from this snapshot cannot interleave with a Pending->Active transition the
    /// way two separate lock-free reads can.
    pub(super) fn activation_snapshot(&self) -> ActivationSnapshot {
        let target = self.target.lock();
        match self.lifecycle_state() {
            PrefillLifecycleState::Active => match self.binding.load_full() {
                Some(binding) => ActivationSnapshot::Active(binding),
                // The binding is stored before `Active` under this lock, so this
                // arm is not expected; resolve by target rather than panicking.
                None if target.is_some() => ActivationSnapshot::Pending,
                None => ActivationSnapshot::Untargeted,
            },
            PrefillLifecycleState::Pending if target.is_some() => ActivationSnapshot::Pending,
            PrefillLifecycleState::Pending | PrefillLifecycleState::Unavailable => {
                ActivationSnapshot::Untargeted
            }
        }
    }

    #[cfg(test)]
    pub(crate) fn target_endpoint_id(&self) -> Option<dynamo_runtime::protocols::EndpointId> {
        self.target_tx
            .as_ref()
            .and_then(|tx| tx.borrow().as_ref().map(|target| target.endpoint().id()))
    }
}

#[cfg(test)]
mod tests {
    use dynamo_runtime::protocols::maybe_error::MaybeError;
    use std::time::Duration;

    use super::*;
    use crate::discovery::CommittedWorkerSetTarget;
    use crate::entrypoint::RouterConfig;
    use crate::kv_router::prefill_router::PrefillRouterLifecycle;
    use crate::protocols::common::llm_backend::{LLMEngineOutput, PreprocessedRequest};
    use dynamo_kv_router::config::KvRouterConfig;
    use dynamo_kv_router::protocols::RoutingConstraints;
    use dynamo_runtime::protocols::annotated::Annotated;
    use dynamo_runtime::{
        DistributedRuntime, Runtime,
        discovery::{DiscoverySpec, EventTransportKind},
        distributed::{DiscoveryBackend, DistributedConfig, RequestPlaneMode},
        error::{ErrorType, match_error_chain},
        pipeline::{
            AsyncEngine, AsyncEngineContextProvider, ManyOut, Operator, ResponseStream, SingleIn,
            network::Ingress,
        },
        storage::kv,
    };
    use futures::StreamExt;
    use std::collections::HashSet;

    fn card(router_config: Option<RouterConfig>) -> ModelDeploymentCard {
        let mut card = ModelDeploymentCard::with_name_only("test-model");
        card.router_config = router_config;
        card
    }

    #[test]
    fn inherits_decode_mode_when_card_advertises_nothing() {
        // The pre-override behavior: a prefill worker that says nothing is
        // routed exactly as the decode set is. Every deployment predating this
        // feature lands here, so it must not shift.
        let cards = vec![card(None)];
        let resolved =
            resolve_advertisement_from_cards(&cards, RouterMode::RoundRobin).expect("resolves");
        assert_eq!(resolved.router_mode, RouterMode::RoundRobin);
        assert!(resolved.kv_router_config.is_none());
    }

    #[test]
    fn session_affinity_ttl_is_taken_whole_or_not_at_all() {
        // An advertisement replaces the decode set's configuration rather than
        // merging, so a card that advertises without a TTL means "no affinity",
        // not "inherit the frontend's". A card advertising nothing means inherit.
        let advertised = vec![card(Some(RouterConfig::new(
            RouterMode::KV,
            KvRouterConfig::default(),
        )))];
        assert_eq!(
            resolve_advertisement_from_cards(&advertised, RouterMode::KV)
                .expect("resolves")
                .session_affinity_ttl,
            Some(None),
        );

        let silent = vec![card(None)];
        assert_eq!(
            resolve_advertisement_from_cards(&silent, RouterMode::KV)
                .expect("resolves")
                .session_affinity_ttl,
            None,
        );
    }

    #[test]
    fn no_readable_card_is_an_error_not_a_silent_inherit() {
        // Activation must fail and be retried rather than quietly routing the
        // whole deployment with the decode set's mode.
        let error = resolve_advertisement_from_cards(&[], RouterMode::KV)
            .expect_err("empty card list must not resolve");
        assert!(
            error.to_string().contains("no readable prefill model card"),
            "unexpected error: {error}"
        );
    }

    struct PrefillWorker(u32);

    #[async_trait::async_trait]
    impl
        AsyncEngine<
            SingleIn<PreprocessedRequest>,
            ManyOut<Annotated<LLMEngineOutput>>,
            anyhow::Error,
        > for PrefillWorker
    {
        async fn generate(
            &self,
            request: SingleIn<PreprocessedRequest>,
        ) -> Result<ManyOut<Annotated<LLMEngineOutput>>> {
            let mut output = LLMEngineOutput::stop();
            output.token_ids = vec![self.0];
            Ok(ResponseStream::new(
                Box::pin(futures::stream::iter([Annotated::from_data(output)])),
                request.context(),
            ))
        }
    }

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

    async fn prefilled_worker(router: &PrefillRouter) -> u32 {
        let mut response = router
            .generate(SingleIn::new(request()), Arc::new(PrefillWorker(99)))
            .await
            .unwrap();
        let worker = response.next().await.unwrap().data.unwrap().token_ids[0];
        while response.next().await.is_some() {}
        worker
    }

    /// Worker 99 is the downstream aggregated path, which must never be reached.
    async fn await_activation(router: &PrefillRouter, expected_prefill_worker: u32) {
        tokio::time::timeout(Duration::from_secs(5), async {
            loop {
                match router
                    .generate(SingleIn::new(request()), Arc::new(PrefillWorker(99)))
                    .await
                {
                    Err(error) => {
                        assert!(
                            match_error_chain(error.as_ref(), &[ErrorType::WorkerUnavailable], &[]),
                            "activation window must surface WorkerUnavailable, got: {error}"
                        );
                        tokio::task::yield_now().await;
                    }
                    Ok(mut response) => {
                        let worker = response.next().await.unwrap().data.unwrap().token_ids[0];
                        while response.next().await.is_some() {}
                        assert_eq!(
                            worker, expected_prefill_worker,
                            "activated router must route through prefill"
                        );
                        break;
                    }
                }
            }
        })
        .await
        .expect("committed prefill target must activate");
    }

    #[tokio::test]
    async fn committed_prefill_uses_selected_card_and_admission_across_endpoint_reuse() {
        // The request-plane server is process-global, but other Tokio tests
        // destroy the runtime that owns its accept loop.
        const TEST: &str = concat!(
            module_path!(),
            "::committed_prefill_uses_selected_card_and_admission_across_endpoint_reuse"
        );
        let test_name = TEST.split_once("::").unwrap().1;
        if std::env::var("DYNAMO_ROUTING_HOP_TEST").as_deref() != Ok(test_name) {
            let mut child = tokio::process::Command::new(std::env::current_exe().unwrap());
            child
                .args(["--exact", test_name, "--nocapture"])
                .env("DYNAMO_ROUTING_HOP_TEST", test_name)
                // The debug routing future exceeds libtest's default 2 MiB stack.
                .env("RUST_MIN_STACK", (4 * 1024 * 1024).to_string())
                .env("DYN_TCP_RPC_HOST", "127.0.0.1")
                .env("DYN_TCP_RPC_PORT", "0")
                .env("DYN_TCP_RESPONSE_STREAM_HOST", "127.0.0.1")
                .env("DYN_TCP_RESPONSE_STREAM_PORT", "0")
                .kill_on_drop(true);
            let output = tokio::time::timeout(Duration::from_secs(30), child.output())
                .await
                .expect("prefill subprocess must finish within its deadline")
                .unwrap();
            assert!(
                output.status.success(),
                "{}\n{}",
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr)
            );
            return;
        }
        let runtime = Runtime::from_current().unwrap();
        let store = tempfile::tempdir().unwrap();
        let config = || DistributedConfig {
            discovery_backend: DiscoveryBackend::KvStore(kv::Selector::File(store.path().into())),
            nats_config: None,
            request_plane: RequestPlaneMode::Tcp,
            response_plane: None,
            event_transport_kind: EventTransportKind::Zmq,
        };
        let namespace = format!("prefill-admission-{}", uuid::Uuid::new_v4());
        let mut workers = Vec::new();
        let mut runtimes = Vec::new();
        for marker in 0..3 {
            let drt = DistributedRuntime::new(runtime.clone(), config())
                .await
                .unwrap();
            let endpoint = drt
                .namespace(namespace.clone())
                .unwrap()
                .component("workers")
                .unwrap()
                .endpoint("prefill");
            workers.push(
                endpoint
                    .endpoint_builder()
                    .handler(Ingress::for_engine(Arc::new(PrefillWorker(marker))).unwrap())
                    .start_with_registration()
                    .await
                    .unwrap(),
            );
            // Raw cards provide per-worker runtime data, but the hop's effective
            // routing configuration must come from its committed target.
            let mut advertised = card(Some(RouterConfig::new(
                RouterMode::RoundRobin,
                KvRouterConfig::default(),
            )));
            advertised.kv_cache_block_size = if marker == 2 { 32 } else { 64 };
            drt.discovery()
                .register(
                    DiscoverySpec::from_model(
                        namespace.clone(),
                        "workers".into(),
                        "prefill".into(),
                        &advertised,
                    )
                    .unwrap(),
                )
                .await
                .unwrap();
            runtimes.push(drt);
        }
        let drt = DistributedRuntime::new(runtime.clone(), config())
            .await
            .unwrap();
        let endpoint = drt
            .namespace(namespace.clone())
            .unwrap()
            .component("workers")
            .unwrap()
            .endpoint("prefill");
        let raw_client = endpoint.client().await.unwrap();
        tokio::time::timeout(Duration::from_secs(5), async {
            let mut instances = raw_client.instance_source.as_ref().clone();
            while instances.borrow_and_update().len() != 3 {
                instances.changed().await.unwrap();
            }
        })
        .await
        .expect("raw endpoint discovery must contain every worker");
        let ids: Vec<_> = workers
            .iter()
            .map(|worker| worker.instance().id())
            .collect();
        let kv_config = KvRouterConfig {
            use_kv_events: false,
            router_track_active_blocks: false,
            ..Default::default()
        };
        let group_id = endpoint.id().to_string();
        let target = |generation, block_size, admitted_ids| {
            let mut selected = card(Some(RouterConfig::new(RouterMode::KV, kv_config.clone())));
            selected.kv_cache_block_size = block_size;
            WorkerSetTarget::Committed(CommittedWorkerSetTarget {
                endpoint: endpoint.clone(),
                group: endpoint.id().to_string(),
                generation,
                card: Arc::new(selected),
                admitted_ids,
            })
        };
        let router = PrefillRouter::new_with_selection_policy(
            None,
            Arc::new(ModelManager::new()),
            RouterMode::RoundRobin,
            false,
            16,
            None,
            SelectionPolicySource::Registry,
            None,
            None,
            SessionAffinityMode::Hard,
            "test-model".into(),
            namespace,
            LoadThresholdHandle::new(Default::default()),
            drt.child_token(),
            None,
        );
        let (admissions, admitted_ids) = watch::channel(vec![ids[0]]);
        router.set_target(Some(target(1, 64, admitted_ids)));
        await_activation(&router, 0).await;
        assert_eq!(
            router.available_worker_ids_for(&group_id, &endpoint.id()),
            Some(HashSet::from([ids[0]]))
        );
        assert!(
            router
                .available_worker_ids_for("other-group", &endpoint.id())
                .is_none()
        );
        let retired = router.binding.load_full().unwrap();
        let chooser = retired
            .router
            .kv_router_if_enabled()
            .expect("selected KV mode must override raw RR cards");
        assert_eq!(chooser.block_size(), 64);
        for _ in 0..6 {
            assert_eq!(prefilled_worker(&router).await, 0);
        }
        let reservation = router
            .reserve_prefill_worker(
                "committed-prefill",
                &[1; 128],
                None,
                None,
                None,
                0.0,
                0,
                None,
                None,
                RoutingConstraints::default(),
            )
            .await
            .unwrap();
        assert_eq!(reservation.worker_id(), ids[0]);
        assert_eq!(reservation.dp_rank(), Some(0));
        reservation.release().await.unwrap();

        admissions.send_replace(vec![ids[0], ids[1]]);
        admissions.send_replace(vec![ids[1]]);
        tokio::time::timeout(Duration::from_secs(5), async {
            loop {
                let reservation = router
                    .reserve_prefill_worker(
                        "admitted-probe",
                        &[1; 128],
                        None,
                        None,
                        None,
                        0.0,
                        0,
                        None,
                        None,
                        RoutingConstraints::default(),
                    )
                    .await
                    .expect("prefill reservation must remain routable");
                let worker_id = reservation.worker_id();
                reservation.release().await.unwrap();
                assert!(
                    ids[..2].contains(&worker_id),
                    "rejected prefill worker became selectable"
                );
                if worker_id == ids[1] {
                    break;
                }
            }
        })
        .await
        .expect("compatible replacement must route through the existing channel");
        assert_eq!(prefilled_worker(&router).await, 1);
        let mut retained_response = retired
            .router
            .generate(SingleIn::new(request()))
            .await
            .unwrap();
        assert_eq!(
            retained_response
                .next()
                .await
                .unwrap()
                .data
                .unwrap()
                .token_ids,
            vec![1]
        );
        while retained_response.next().await.is_some() {}

        admissions.send_replace(Vec::new());
        drop(admissions);
        router.set_target(None);
        assert!(
            router
                .available_worker_ids_for(&group_id, &endpoint.id())
                .is_none()
        );
        let (_successor_admissions, successor_ids) = watch::channel(vec![ids[2]]);
        router.set_target(Some(target(2, 32, successor_ids)));
        assert_eq!(
            router.available_worker_ids_for(&group_id, &endpoint.id()),
            Some(HashSet::new())
        );
        assert!(
            router
                .available_worker_ids_for("other-group", &endpoint.id())
                .is_none()
        );
        await_activation(&router, 2).await;
        assert_eq!(
            router.available_worker_ids_for(&group_id, &endpoint.id()),
            Some(HashSet::from([ids[2]]))
        );
        assert_eq!(
            router
                .binding
                .load_full()
                .unwrap()
                .router
                .kv_router_if_enabled()
                .unwrap()
                .block_size(),
            32
        );
        for _ in 0..6 {
            assert_eq!(prefilled_worker(&router).await, 2);
        }
        assert!(
            tokio::time::timeout(
                Duration::from_secs(5),
                retired.router.generate(SingleIn::new(request()),)
            )
            .await
            .expect("retired prefill admission must fail promptly")
            .is_err()
        );

        drop(router);
        for worker in workers {
            worker.shutdown().await.unwrap();
        }
        runtime.shutdown();
    }

    struct WaitingPrefillWorker(tokio::sync::mpsc::UnboundedSender<String>);

    #[async_trait::async_trait]
    impl
        AsyncEngine<
            SingleIn<PreprocessedRequest>,
            ManyOut<Annotated<LLMEngineOutput>>,
            anyhow::Error,
        > for WaitingPrefillWorker
    {
        async fn generate(
            &self,
            request: SingleIn<PreprocessedRequest>,
        ) -> Result<ManyOut<Annotated<LLMEngineOutput>>> {
            let context = request.context();
            let worker_context = context.clone();
            let cancelled = self.0.clone();
            let response = async_stream::stream! {
                yield Annotated::from_data(LLMEngineOutput {
                    disaggregated_params: Some(serde_json::json!({
                        "bootstrap_host": "127.0.0.1", "bootstrap_port": 1, "bootstrap_room": 7,
                    })),
                    ..Default::default()
                });
                worker_context.stopped().await;
                let _ = cancelled.send(worker_context.id().to_string());
            };
            Ok(ResponseStream::new(Box::pin(response), context))
        }
    }

    struct RejectingDecodeHost {
        stream: bool,
    }

    #[async_trait::async_trait]
    impl
        AsyncEngine<
            SingleIn<PreprocessedRequest>,
            ManyOut<Annotated<LLMEngineOutput>>,
            anyhow::Error,
        > for RejectingDecodeHost
    {
        async fn generate(
            &self,
            request: SingleIn<PreprocessedRequest>,
        ) -> Result<ManyOut<Annotated<LLMEngineOutput>>> {
            let error = dynamo_runtime::error::DynamoError::builder()
                .error_type(dynamo_runtime::error::ErrorType::WorkerOverloaded)
                .message("decode admission rejected")
                .build();
            if !self.stream {
                return Err(error.into());
            }
            Ok(ResponseStream::new(
                Box::pin(futures::stream::iter([Annotated::from_err(error)])),
                request.context(),
            ))
        }
    }

    #[tokio::test]
    async fn decode_rejection_reaches_remote_prefill_context() {
        // Isolate the process-global TCP request server, as in the routing-hop test above.
        const TEST: &str = concat!(
            module_path!(),
            "::decode_rejection_reaches_remote_prefill_context"
        );
        let test_name = TEST.split_once("::").unwrap().1;
        if std::env::var("DYNAMO_ROUTING_HOP_TEST").as_deref() != Ok(test_name) {
            let mut child = tokio::process::Command::new(std::env::current_exe().unwrap());
            child
                .args(["--exact", test_name, "--nocapture"])
                .env("DYNAMO_ROUTING_HOP_TEST", test_name)
                .env("RUST_MIN_STACK", (4 * 1024 * 1024).to_string())
                .env("DYN_TCP_RPC_HOST", "127.0.0.1")
                .env("DYN_TCP_RPC_PORT", "0")
                .env("DYN_TCP_RESPONSE_STREAM_HOST", "127.0.0.1")
                .env("DYN_TCP_RESPONSE_STREAM_PORT", "0")
                .kill_on_drop(true);
            let output = tokio::time::timeout(Duration::from_secs(30), child.output())
                .await
                .unwrap()
                .unwrap();
            assert!(
                output.status.success(),
                "{}\n{}",
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr)
            );
            return;
        }

        let runtime = Runtime::from_current().unwrap();
        let store = tempfile::tempdir().unwrap();
        let config = || DistributedConfig {
            discovery_backend: DiscoveryBackend::KvStore(kv::Selector::File(store.path().into())),
            nats_config: None,
            request_plane: RequestPlaneMode::Tcp,
            response_plane: None,
            event_transport_kind: EventTransportKind::Zmq,
        };
        let namespace = format!("prefill-rejection-{}", uuid::Uuid::new_v4());
        let worker_runtime = DistributedRuntime::new(runtime.clone(), config())
            .await
            .unwrap();
        let worker_endpoint = worker_runtime
            .namespace(namespace.clone())
            .unwrap()
            .component("workers")
            .unwrap()
            .endpoint("prefill");
        let (cancelled, mut cancellations) = tokio::sync::mpsc::unbounded_channel();
        let worker = worker_endpoint
            .endpoint_builder()
            .handler(Ingress::for_engine(Arc::new(WaitingPrefillWorker(cancelled))).unwrap())
            .start_with_registration()
            .await
            .unwrap();
        let kv_config = KvRouterConfig {
            use_kv_events: false,
            router_track_active_blocks: false,
            ..Default::default()
        };
        let mut advertised = card(Some(RouterConfig::new(RouterMode::KV, kv_config)));
        advertised.kv_cache_block_size = 64;
        worker_runtime
            .discovery()
            .register(
                DiscoverySpec::from_model(
                    namespace.clone(),
                    "workers".into(),
                    "prefill".into(),
                    &advertised,
                )
                .unwrap(),
            )
            .await
            .unwrap();
        let frontend_runtime = DistributedRuntime::new(runtime, config()).await.unwrap();
        let endpoint = frontend_runtime
            .namespace(namespace.clone())
            .unwrap()
            .component("workers")
            .unwrap()
            .endpoint("prefill");
        let router = PrefillRouter::new_with_selection_policy(
            None,
            Arc::new(ModelManager::new()),
            RouterMode::KV,
            false,
            64,
            None,
            SelectionPolicySource::Registry,
            None,
            None,
            SessionAffinityMode::Hard,
            "test-model".into(),
            namespace,
            LoadThresholdHandle::new(Default::default()),
            frontend_runtime.child_token(),
            None,
        );
        let (_admissions, admitted_ids) = watch::channel(vec![worker.instance().id()]);
        router.set_target(Some(WorkerSetTarget::Committed(CommittedWorkerSetTarget {
            group: endpoint.id().to_string(),
            endpoint,
            generation: 1,
            card: Arc::new(advertised),
            admitted_ids,
        })));
        tokio::time::timeout(Duration::from_secs(5), async {
            while router.lifecycle_state() != PrefillLifecycleState::Active {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("prefill target must activate");

        // Exercise the production generate path, discovery, TCP dispatch, and
        // cancellation propagation for all output modes and both refusal paths.
        for annotations in [
            vec![],
            vec!["prefill_output"],
            vec!["prefill_output", "prefill_output_first"],
        ] {
            for streamed in [false, true] {
                let mut input = request();
                input.annotations = annotations.iter().map(|s| s.to_string()).collect();
                let input = SingleIn::new(input);
                let id = input.context().id().to_string();
                let downstream = Arc::new(RejectingDecodeHost { stream: streamed });
                let result = tokio::time::timeout(
                    Duration::from_secs(5),
                    router.generate(input, downstream),
                )
                .await
                .unwrap();
                if streamed {
                    let mut response = result.unwrap();
                    let item = tokio::time::timeout(Duration::from_secs(5), response.next())
                        .await
                        .unwrap()
                        .unwrap();
                    assert!(item.err().is_some());
                } else {
                    assert!(result.is_err());
                }
                let cancelled = tokio::time::timeout(Duration::from_secs(5), cancellations.recv())
                    .await
                    .expect("decode refusal did not cancel the dispatched prefill worker")
                    .unwrap();
                assert_eq!(
                    cancelled, id,
                    "must cancel the matching remote prefill request"
                );
            }
        }
        drop(router);
        worker.shutdown().await.unwrap();
        frontend_runtime.shutdown();
        worker_runtime.shutdown();
    }

    /// Holds each prefill in flight after bootstrap until the worker context is
    /// stopped, reporting that cancellation, or until the test releases it.
    struct HeldPrefillWorker {
        cancelled: tokio::sync::mpsc::UnboundedSender<String>,
        held: tokio_util::sync::CancellationToken,
    }

    #[async_trait::async_trait]
    impl
        AsyncEngine<
            SingleIn<PreprocessedRequest>,
            ManyOut<Annotated<LLMEngineOutput>>,
            anyhow::Error,
        > for HeldPrefillWorker
    {
        async fn generate(
            &self,
            request: SingleIn<PreprocessedRequest>,
        ) -> Result<ManyOut<Annotated<LLMEngineOutput>>> {
            let context = request.context();
            let worker_context = context.clone();
            let cancelled = self.cancelled.clone();
            let held = self.held.clone();
            let response = async_stream::stream! {
                yield Annotated::from_data(LLMEngineOutput {
                    disaggregated_params: Some(serde_json::json!({
                        "bootstrap_host": "127.0.0.1", "bootstrap_port": 1, "bootstrap_room": 7,
                    })),
                    ..Default::default()
                });
                tokio::select! {
                    _ = worker_context.stopped() => {
                        let _ = cancelled.send(worker_context.id().to_string());
                    }
                    _ = held.cancelled() => {}
                }
            };
            Ok(ResponseStream::new(Box::pin(response), context))
        }
    }

    /// Fails its first `failures` calls with a migratable error, at dispatch or
    /// as the first stream item, then streams token 7. The token is not
    /// terminal, so it is not held back while prefill is in flight.
    struct UnreachableDecodeHost {
        stream: bool,
        failures: std::sync::atomic::AtomicU32,
    }

    #[async_trait::async_trait]
    impl
        AsyncEngine<
            SingleIn<PreprocessedRequest>,
            ManyOut<Annotated<LLMEngineOutput>>,
            anyhow::Error,
        > for UnreachableDecodeHost
    {
        async fn generate(
            &self,
            request: SingleIn<PreprocessedRequest>,
        ) -> Result<ManyOut<Annotated<LLMEngineOutput>>> {
            use std::sync::atomic::Ordering;
            if self
                .failures
                .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1))
                .is_err()
            {
                let token = LLMEngineOutput {
                    token_ids: vec![7],
                    ..Default::default()
                };
                return Ok(ResponseStream::new(
                    Box::pin(futures::stream::iter([
                        Annotated::from_data(token),
                        Annotated::from_data(LLMEngineOutput::stop()),
                    ])),
                    request.context(),
                ));
            }
            let error = dynamo_runtime::error::DynamoError::builder()
                .error_type(ErrorType::CannotConnect)
                .message("decode worker unreachable")
                .build();
            if !self.stream {
                return Err(error.into());
            }
            Ok(ResponseStream::new(
                Box::pin(futures::stream::iter([Annotated::from_err(error)])),
                request.context(),
            ))
        }
    }

    /// Remote prefill followed by decode, as the pipeline below `Migration`.
    struct PrefillThenDecode {
        router: Arc<PrefillRouter>,
        decode: Arc<UnreachableDecodeHost>,
    }

    #[async_trait::async_trait]
    impl
        AsyncEngine<
            SingleIn<PreprocessedRequest>,
            ManyOut<Annotated<LLMEngineOutput>>,
            anyhow::Error,
        > for PrefillThenDecode
    {
        async fn generate(
            &self,
            request: SingleIn<PreprocessedRequest>,
        ) -> Result<ManyOut<Annotated<LLMEngineOutput>>> {
            self.router.generate(request, self.decode.clone()).await
        }
    }

    /// Run one request through `Migration` with up to one retry, returning its
    /// first decode tokens or the error the client would see.
    async fn migrate(
        router: &Arc<PrefillRouter>,
        id: &str,
        decode: UnreachableDecodeHost,
    ) -> Result<Vec<u32>> {
        let migration = crate::migration::Migration::new(
            1,
            None,
            "test-model".into(),
            Arc::new(crate::http::service::metrics::Metrics::new()),
        );
        let next: dynamo_runtime::pipeline::ServerStreamingEngine<
            PreprocessedRequest,
            Annotated<LLMEngineOutput>,
        > = Arc::new(PrefillThenDecode {
            router: router.clone(),
            decode: Arc::new(decode),
        });
        let request = dynamo_runtime::pipeline::Context::with_id_and_metadata(
            request(),
            id.to_string(),
            Default::default(),
        );
        let mut response = migration.generate(request, next).await?;
        let item = response.next().await.expect("decode must respond");
        if let Some(error) = item.err() {
            return Err(error.into());
        }
        Ok(item.data.map(|data| data.token_ids).unwrap_or_default())
    }

    #[tokio::test]
    async fn migration_releases_prefill_booking_only_for_committed_retry() {
        // Isolate the process-global TCP request server, as in the routing-hop test above.
        const TEST: &str = concat!(
            module_path!(),
            "::migration_releases_prefill_booking_only_for_committed_retry"
        );
        let test_name = TEST.split_once("::").unwrap().1;
        if std::env::var("DYNAMO_ROUTING_HOP_TEST").as_deref() != Ok(test_name) {
            let mut child = tokio::process::Command::new(std::env::current_exe().unwrap());
            child
                .args(["--exact", test_name, "--nocapture"])
                .env("DYNAMO_ROUTING_HOP_TEST", test_name)
                .env("RUST_MIN_STACK", (4 * 1024 * 1024).to_string())
                .env("DYN_TCP_RPC_HOST", "127.0.0.1")
                .env("DYN_TCP_RPC_PORT", "0")
                .env("DYN_TCP_RESPONSE_STREAM_HOST", "127.0.0.1")
                .env("DYN_TCP_RESPONSE_STREAM_PORT", "0")
                .kill_on_drop(true);
            let output = tokio::time::timeout(Duration::from_secs(30), child.output())
                .await
                .unwrap()
                .unwrap();
            assert!(
                output.status.success(),
                "{}\n{}",
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr)
            );
            return;
        }

        let runtime = Runtime::from_current().unwrap();
        let store = tempfile::tempdir().unwrap();
        let config = || DistributedConfig {
            discovery_backend: DiscoveryBackend::KvStore(kv::Selector::File(store.path().into())),
            nats_config: None,
            request_plane: RequestPlaneMode::Tcp,
            response_plane: None,
            event_transport_kind: EventTransportKind::Zmq,
        };
        let namespace = format!("prefill-retry-{}", uuid::Uuid::new_v4());
        let worker_runtime = DistributedRuntime::new(runtime.clone(), config())
            .await
            .unwrap();
        let worker_endpoint = worker_runtime
            .namespace(namespace.clone())
            .unwrap()
            .component("workers")
            .unwrap()
            .endpoint("prefill");
        let (cancelled, mut cancellations) = tokio::sync::mpsc::unbounded_channel();
        let held = tokio_util::sync::CancellationToken::new();
        let worker = worker_endpoint
            .endpoint_builder()
            .handler(
                Ingress::for_engine(Arc::new(HeldPrefillWorker {
                    cancelled,
                    held: held.clone(),
                }))
                .unwrap(),
            )
            .start_with_registration()
            .await
            .unwrap();
        let kv_config = KvRouterConfig {
            use_kv_events: false,
            router_track_active_blocks: false,
            ..Default::default()
        };
        let mut advertised = card(Some(RouterConfig::new(RouterMode::KV, kv_config)));
        advertised.kv_cache_block_size = 64;
        worker_runtime
            .discovery()
            .register(
                DiscoverySpec::from_model(
                    namespace.clone(),
                    "workers".into(),
                    "prefill".into(),
                    &advertised,
                )
                .unwrap(),
            )
            .await
            .unwrap();
        let frontend_runtime = DistributedRuntime::new(runtime, config()).await.unwrap();
        let endpoint = frontend_runtime
            .namespace(namespace.clone())
            .unwrap()
            .component("workers")
            .unwrap()
            .endpoint("prefill");
        let router = PrefillRouter::new_with_selection_policy(
            None,
            Arc::new(ModelManager::new()),
            RouterMode::KV,
            false,
            64,
            None,
            SelectionPolicySource::Registry,
            None,
            None,
            SessionAffinityMode::Hard,
            "test-model".into(),
            namespace,
            LoadThresholdHandle::new(Default::default()),
            frontend_runtime.child_token(),
            None,
        );
        let (_admissions, admitted_ids) = watch::channel(vec![worker.instance().id()]);
        router.set_target(Some(WorkerSetTarget::Committed(CommittedWorkerSetTarget {
            group: endpoint.id().to_string(),
            endpoint,
            generation: 1,
            card: Arc::new(advertised),
            admitted_ids,
        })));
        tokio::time::timeout(Duration::from_secs(5), async {
            while router.lifecycle_state() != PrefillLifecycleState::Active {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("prefill target must activate");

        // Migration retries a failed attempt under the same request ID, starting
        // again from remote prefill. Each attempt's prefill is still in flight
        // when its decode fails, as when a decode worker dies between discovery
        // and dispatch or fails before its first token.
        for streamed in [false, true] {
            let decode = |failures: u32| UnreachableDecodeHost {
                stream: streamed,
                failures: failures.into(),
            };
            let id = uuid::Uuid::new_v4().to_string();
            let tokens =
                tokio::time::timeout(Duration::from_secs(5), migrate(&router, &id, decode(1)))
                    .await
                    .expect("retry must not hang")
                    .unwrap_or_else(|error| {
                        panic!("migration retry must re-book remote prefill: {error:#}")
                    });
            assert_eq!(tokens, vec![7]);

            // Once retries run out, the last attempt's prefill keeps its booking
            // while it runs.
            let id = uuid::Uuid::new_v4().to_string();
            let error =
                tokio::time::timeout(Duration::from_secs(5), migrate(&router, &id, decode(2)))
                    .await
                    .expect("exhausted migration must not hang")
                    .expect_err("every decode attempt fails");
            assert!(
                crate::migration::is_migratable(error.as_ref()),
                "decode failure must be migratable: {error:#}"
            );
            let rebook = router
                .generate(
                    dynamo_runtime::pipeline::Context::with_id_and_metadata(
                        request(),
                        id,
                        Default::default(),
                    ),
                    Arc::new(PrefillWorker(7)),
                )
                .await;
            match rebook {
                Ok(_) => panic!("the final attempt's prefill booking must be retained"),
                Err(error) => assert!(
                    format!("{error:#}").contains("already exists"),
                    "unexpected re-book failure: {error:#}"
                ),
            }
        }
        // An unreachable decode worker may still have received the request, so
        // its prefill must stay alive to serve the KV transfer.
        assert!(
            cancellations.try_recv().is_err(),
            "a transport failure must not cancel the remote prefill"
        );
        held.cancel();
        drop(router);
        worker.shutdown().await.unwrap();
        frontend_runtime.shutdown();
        worker_runtime.shutdown();
    }
}