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
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::time::{Duration, Instant};

use dynamo_kv_router::indexer::cuckoo::ProducerIdentity;
use dynamo_kv_router::protocols::{
    ActiveLoad, SchedulerGroup, SchedulerLoad, WorkerId, WorkerWithDpRank,
};
use dynamo_runtime::transports::event_plane::EventEnvelope;

use super::serving_load::{SOURCE_RETENTION, freshness};
use crate::kv_router::sequence::SCHEDULER_LOAD_PUBLISH_INTERVAL;
use crate::local_model::runtime_config::ModelRuntimeConfig;

/// How long a router scheduler's view counts.
pub(super) const SCHEDULER_FRESHNESS: Duration = freshness(SCHEDULER_LOAD_PUBLISH_INTERVAL);

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct LoadCapacity {
    total_kv_blocks: Option<u64>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(super) struct PoolLoadState {
    capacities: HashMap<WorkerWithDpRank, LoadCapacity>,
    observations: HashMap<WorkerWithDpRank, u64>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum LoadObservationOutcome {
    UnknownRank,
    IgnoredAdvisory,
    Updated,
}

/// DC-wide load derived from worker-authoritative `kv_used_blocks` reports.
///
/// Router scheduler views (`active_decode_blocks`, `active_prefill_tokens`) are
/// not part of this snapshot; [`SchedulerLoadState`] aggregates them from the
/// scheduler-load subject, where each view carries its scheduler group.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PoolLoadSnapshot {
    pub producer: ProducerIdentity,
    /// Aggregate authoritative KV usage, available only after every declared rank
    /// has reported at least once for the current capacity generation.
    pub kv_used_blocks: Option<u64>,
    /// Aggregate KV capacity, available only when every declared rank publishes a
    /// non-zero capacity.
    pub total_kv_blocks: Option<u64>,
    /// Declared ranks that have published authoritative KV usage.
    pub kv_observed_ranks: usize,
    /// Declared ranks whose KV capacity is known and non-zero.
    pub kv_capacity_ranks: usize,
    /// Worker ranks declared by the current runtime configuration.
    pub kv_expected_ranks: usize,
}

impl PoolLoadSnapshot {
    pub fn has_degraded_coverage(self) -> bool {
        self.kv_expected_ranks == 0
            || self.kv_observed_ranks < self.kv_expected_ranks
            || self.kv_capacity_ranks < self.kv_expected_ranks
    }
}

impl PoolLoadState {
    pub(super) fn from_runtime_configs(
        runtime_configs: &HashMap<WorkerId, ModelRuntimeConfig>,
    ) -> anyhow::Result<Self> {
        Ok(Self {
            capacities: load_ranks_from_configs(runtime_configs)?,
            observations: HashMap::new(),
        })
    }

    pub(super) fn replace_capacity(
        &mut self,
        runtime_configs: &HashMap<WorkerId, ModelRuntimeConfig>,
    ) -> anyhow::Result<bool> {
        let capacities = match load_ranks_from_configs(runtime_configs) {
            Ok(capacities) => capacities,
            Err(error) => {
                // Never leave the previously authoritative snapshot live after an
                // invalid capacity refresh. The registry publishes this empty state
                // before returning the error to its caller.
                self.capacities.clear();
                self.observations.clear();
                return Err(error);
            }
        };
        if self.capacities == capacities {
            return Ok(false);
        }
        self.observations.retain(|rank, _| {
            self.capacities
                .get(rank)
                .is_some_and(|previous| capacities.get(rank) == Some(previous))
        });
        self.capacities = capacities;
        Ok(true)
    }

    pub(super) fn observe(&mut self, load: ActiveLoad) -> LoadObservationOutcome {
        let rank = WorkerWithDpRank::new(load.worker_id, load.dp_rank);
        if !self.capacities.contains_key(&rank) {
            return LoadObservationOutcome::UnknownRank;
        }
        let Some(kv_used_blocks) = load.kv_used_blocks else {
            // active_decode_blocks and active_prefill_tokens on this subject are
            // emitted by router replicas without a scheduler group, so they cannot
            // be aggregated; SchedulerLoadState consumes the scheduler-load subject.
            // Return a distinct accepted outcome so the collector does not
            // misdiagnose an advisory report as an unknown-rank event.
            return LoadObservationOutcome::IgnoredAdvisory;
        };
        self.observations.insert(rank, kv_used_blocks);
        LoadObservationOutcome::Updated
    }

    pub(super) fn has_rank(&self, rank: &WorkerWithDpRank) -> bool {
        self.capacities.contains_key(rank)
    }

    pub(super) fn declared_rank_count(&self) -> usize {
        self.capacities.len()
    }

    pub(super) fn clear_observations(&mut self) -> bool {
        if self.observations.is_empty() {
            return false;
        }
        self.observations.clear();
        true
    }

    pub(super) fn snapshot(&self, producer: ProducerIdentity) -> PoolLoadSnapshot {
        let mut kv_used_blocks = 0_u64;
        let mut total_kv_blocks = 0_u64;
        let mut snapshot = PoolLoadSnapshot {
            producer,
            kv_used_blocks: None,
            total_kv_blocks: None,
            kv_observed_ranks: 0,
            kv_capacity_ranks: 0,
            kv_expected_ranks: 0,
        };
        for (rank, capacity) in &self.capacities {
            snapshot.kv_expected_ranks = snapshot.kv_expected_ranks.saturating_add(1);
            if let Some(total) = capacity.total_kv_blocks {
                snapshot.kv_capacity_ranks = snapshot.kv_capacity_ranks.saturating_add(1);
                total_kv_blocks = total_kv_blocks.saturating_add(total);
            }
            if let Some(value) = self.observations.get(rank) {
                snapshot.kv_observed_ranks = snapshot.kv_observed_ranks.saturating_add(1);
                kv_used_blocks = kv_used_blocks.saturating_add(*value);
            }
        }
        if snapshot.kv_expected_ranks != 0
            && snapshot.kv_observed_ranks == snapshot.kv_expected_ranks
        {
            snapshot.kv_used_blocks = Some(kv_used_blocks);
        }
        if snapshot.kv_expected_ranks != 0
            && snapshot.kv_capacity_ranks == snapshot.kv_expected_ranks
        {
            snapshot.total_kv_blocks = Some(total_kv_blocks);
        }
        snapshot
    }
}

const MAX_LOAD_RANKS_PER_WORKER: u32 = 4096;

fn load_ranks_from_configs(
    runtime_configs: &HashMap<WorkerId, ModelRuntimeConfig>,
) -> anyhow::Result<HashMap<WorkerWithDpRank, LoadCapacity>> {
    let mut ranks = HashMap::new();
    for (&worker_id, config) in runtime_configs {
        anyhow::ensure!(
            config.data_parallel_size != 0,
            "worker {worker_id} has zero data_parallel_size"
        );
        anyhow::ensure!(
            config.data_parallel_size <= MAX_LOAD_RANKS_PER_WORKER,
            "worker {worker_id} declares {} data-parallel ranks, above the supported {}",
            config.data_parallel_size,
            MAX_LOAD_RANKS_PER_WORKER
        );
        let end = config
            .data_parallel_start_rank
            .checked_add(config.data_parallel_size)
            .ok_or_else(|| {
                anyhow::anyhow!("worker {worker_id} data-parallel rank range overflow")
            })?;
        // vLLM's Ray data-parallel backend cannot propagate num_gpu_blocks to the
        // registering process and uses zero as an unknown-capacity sentinel. Runtime
        // config does not carry backend identity, and zero is never a usable pressure
        // denominator for any backend, so normalize it fail-closed for every engine.
        // TODO(rank-aware-kv-capacity): resolve exact/conservative capacity per rank and carry
        // quality into the pool snapshot. Estimated fallbacks must not count as authoritative
        // rank coverage merely because every rank received a scalar.
        let total_kv_blocks = config.total_kv_blocks.filter(|&total| total != 0);
        for dp_rank in config.data_parallel_start_rank..end {
            ranks.insert(
                WorkerWithDpRank::new(worker_id, dp_rank),
                LoadCapacity { total_kv_blocks },
            );
        }
    }
    Ok(ranks)
}

/// How much of an aggregate's expected sources reported recently.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Coverage<T> {
    /// Every expected source reported; the aggregate is exact.
    Complete(T),
    /// Some expected sources reported. A partial sum would read as lower load,
    /// so no aggregate is exposed.
    Partial,
    /// No expected source reported.
    Missing,
}

/// One pool's in-flight load as the routers' schedulers see it.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(super) struct SchedulerGauges {
    pub(super) active_decode_blocks: u64,
    pub(super) active_prefill_tokens: u64,
}

impl From<&SchedulerLoad> for SchedulerGauges {
    fn from(load: &SchedulerLoad) -> Self {
        Self {
            active_decode_blocks: load.active_decode_blocks,
            active_prefill_tokens: load.active_prefill_tokens,
        }
    }
}

impl SchedulerGauges {
    fn max(self, other: Self) -> Self {
        Self {
            active_decode_blocks: self.active_decode_blocks.max(other.active_decode_blocks),
            active_prefill_tokens: self.active_prefill_tokens.max(other.active_prefill_tokens),
        }
    }

    fn saturating_add(self, other: Self) -> Self {
        Self {
            active_decode_blocks: self
                .active_decode_blocks
                .saturating_add(other.active_decode_blocks),
            active_prefill_tokens: self
                .active_prefill_tokens
                .saturating_add(other.active_prefill_tokens),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct PoolSchedulerLoad {
    pub(super) coverage: Coverage<SchedulerGauges>,
    /// Oldest publish time among the counted views; 0 when none.
    pub(super) source_observed_ms: u64,
}

#[derive(Debug)]
struct SchedulerBatch {
    loads: HashMap<WorkerWithDpRank, SchedulerLoad>,
    published_at_ms: u64,
    received_at: Instant,
}

#[derive(Debug, Clone, Copy)]
struct PublisherProgress {
    last_sequence: u64,
    last_seen: Instant,
}

/// Router scheduler views of one pool's worker ranks, from the scheduler-load
/// subject. Views expire after [`SCHEDULER_FRESHNESS`]; routers republish every
/// view each publish interval, so a lost report is repaired by the next one.
#[derive(Debug, Default)]
pub(super) struct SchedulerLoadState {
    /// Latest complete batch per publishing router.
    batches: HashMap<u64, SchedulerBatch>,
    /// Kept for [`SOURCE_RETENTION`] so duplicate or reordered deliveries from a
    /// briefly silent router are still recognized.
    publishers: HashMap<u64, PublisherProgress>,
}

impl SchedulerLoadState {
    /// Replaces one publisher's complete rank batch. Duplicate and reordered batches
    /// are ignored; gaps are accepted. Prunes first, so state stays bounded even
    /// when nothing takes snapshots (a Relay without a WAN listener).
    pub(super) fn observe(
        &mut self,
        envelope: &EventEnvelope,
        loads: Vec<SchedulerLoad>,
        received_at: Instant,
    ) {
        self.prune(received_at);
        let progress = PublisherProgress {
            last_sequence: envelope.sequence,
            last_seen: received_at,
        };
        match self.publishers.entry(envelope.publisher_id) {
            Entry::Occupied(entry) if envelope.sequence <= entry.get().last_sequence => return,
            Entry::Occupied(mut entry) => {
                entry.insert(progress);
            }
            Entry::Vacant(entry) => {
                entry.insert(progress);
            }
        }
        let mut ranks = HashMap::with_capacity(loads.len());
        for load in loads {
            if matches!(load.group, SchedulerGroup::Unknown) {
                tracing::debug!(
                    publisher_id = envelope.publisher_id,
                    "Ignoring unknown scheduler load aggregation kind"
                );
                continue;
            }
            let rank = WorkerWithDpRank::new(load.worker_id, load.dp_rank);
            ranks.insert(rank, load);
        }
        self.batches.insert(
            envelope.publisher_id,
            SchedulerBatch {
                loads: ranks,
                published_at_ms: envelope.published_at,
                received_at,
            },
        );
    }

    /// Drops expired views and publishers silent for [`SOURCE_RETENTION`].
    pub(super) fn prune(&mut self, now: Instant) {
        self.batches
            .retain(|_, batch| is_fresh(batch.received_at, SCHEDULER_FRESHNESS, now));
        self.publishers
            .retain(|_, progress| is_fresh(progress.last_seen, SOURCE_RETENTION, now));
    }

    /// Views of one replica group overlap, so each rank takes the group's
    /// maximum. A standalone scheduler that reconnected publishes under a new
    /// publisher id while its previous view is still fresh, so each rank takes
    /// its latest view. Groups are disjoint, so the pool total sums every group
    /// of every rank. A missing scheduler would silently undercount, so the
    /// total is exposed only when every expected scheduler (`discovered` plus
    /// any with a fresh view) has a fresh view of every rank `declared` by the
    /// pool. Failed discovery (`None`) cannot prove that.
    pub(super) fn snapshot(
        &self,
        declared: &PoolLoadState,
        discovered: Option<&HashSet<u64>>,
        now: Instant,
    ) -> PoolSchedulerLoad {
        let mut per_group =
            HashMap::<(WorkerWithDpRank, &SchedulerGroup), (SchedulerGauges, u64)>::new();
        let mut ranks_per_publisher = HashMap::<u64, usize>::new();
        let mut oldest = None::<u64>;
        for (publisher, batch) in &self.batches {
            if !is_fresh(batch.received_at, SCHEDULER_FRESHNESS, now) {
                continue;
            }
            let mut observed_ranks = 0;
            for (rank, report) in &batch.loads {
                if !declared.has_rank(rank) {
                    continue;
                }
                observed_ranks += 1;
                let load = SchedulerGauges::from(report);
                let group = &report.group;
                per_group
                    .entry((*rank, group))
                    .and_modify(|(total, latest)| match group {
                        SchedulerGroup::Unknown => {} // Filtered by observe().
                        SchedulerGroup::ReplicaGroup { .. } => *total = total.max(load),
                        SchedulerGroup::Standalone { .. } => {
                            if batch.published_at_ms > *latest {
                                (*total, *latest) = (load, batch.published_at_ms);
                            }
                        }
                    })
                    .or_insert((load, batch.published_at_ms));
            }
            ranks_per_publisher.insert(*publisher, observed_ranks);
            if observed_ranks > 0 {
                oldest =
                    Some(oldest.map_or(batch.published_at_ms, |at| at.min(batch.published_at_ms)));
            }
        }
        let Some(source_observed_ms) = oldest else {
            return PoolSchedulerLoad {
                coverage: Coverage::Missing,
                source_observed_ms: 0,
            };
        };
        let ranks = declared.declared_rank_count();
        let complete = discovered.is_some_and(|discovered| {
            discovered
                .iter()
                .chain(ranks_per_publisher.keys())
                .all(|publisher| ranks_per_publisher.get(publisher) == Some(&ranks))
        });
        let coverage = if complete {
            Coverage::Complete(
                per_group
                    .into_values()
                    .map(|(total, _)| total)
                    .fold(SchedulerGauges::default(), SchedulerGauges::saturating_add),
            )
        } else {
            Coverage::Partial
        };
        PoolSchedulerLoad {
            coverage,
            source_observed_ms,
        }
    }
}

fn is_fresh(at: Instant, window: Duration, now: Instant) -> bool {
    now.saturating_duration_since(at) <= window
}

/// Worker facts from a pool's runtime configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct PoolDeployment {
    pub(super) live_workers: u64,
    /// Sum over workers of `max_num_seqs * data_parallel_size`; `None` while a
    /// worker does not declare `max_num_seqs`.
    pub(super) max_concurrency: Option<u64>,
}

impl PoolDeployment {
    pub(super) fn from_runtime_configs(
        runtime_configs: &HashMap<WorkerId, ModelRuntimeConfig>,
    ) -> Self {
        Self {
            live_workers: runtime_configs.len() as u64,
            max_concurrency: runtime_configs.values().try_fold(0_u64, |total, config| {
                let per_worker = config
                    .max_num_seqs?
                    .saturating_mul(u64::from(config.data_parallel_size));
                Some(total.saturating_add(per_worker))
            }),
        }
    }
}

#[cfg(test)]
mod tests {
    use dynamo_kv_router::identity::{
        CacheSemanticsId, ClusterId, IdentitySource, IndexerDomainId, PoolId, RoutingScopeId,
    };
    use dynamo_kv_router::indexer::cuckoo::{CkfConfig, DcCkfState};

    use super::*;

    fn producer() -> ProducerIdentity {
        let format = DcCkfState::new(CkfConfig::new(32))
            .expect("fixture state")
            .format();
        ProducerIdentity::new(
            PoolId::new(
                IndexerDomainId::new(
                    CacheSemanticsId::new([1; 16], IdentitySource::Explicit),
                    RoutingScopeId::new([2; 16], IdentitySource::Explicit),
                ),
                ClusterId::new(3),
            ),
            7,
            11,
            format,
        )
    }

    fn config(
        start_rank: u32,
        rank_count: u32,
        kv_blocks: Option<u64>,
        prefill_tokens: Option<u64>,
    ) -> ModelRuntimeConfig {
        ModelRuntimeConfig {
            data_parallel_start_rank: start_rank,
            data_parallel_size: rank_count,
            total_kv_blocks: kv_blocks,
            max_num_batched_tokens: prefill_tokens,
            ..ModelRuntimeConfig::default()
        }
    }

    fn load(worker_id: WorkerId, dp_rank: u32) -> ActiveLoad {
        ActiveLoad {
            worker_id,
            dp_rank,
            ..ActiveLoad::default()
        }
    }

    #[test]
    fn authoritative_kv_reaches_full_coverage() {
        let mut state = PoolLoadState::from_runtime_configs(&HashMap::from([(
            9,
            config(0, 1, Some(100), None),
        )]))
        .unwrap();
        let mut report = load(9, 0);
        report.kv_used_blocks = Some(40);
        report.active_decode_blocks = Some(10);
        assert_eq!(state.observe(report), LoadObservationOutcome::Updated);

        let snapshot = state.snapshot(producer());
        assert_eq!(snapshot.kv_used_blocks, Some(40));
        assert_eq!(snapshot.total_kv_blocks, Some(100));
        assert_eq!(snapshot.kv_observed_ranks, 1);
        assert_eq!(snapshot.kv_capacity_ranks, 1);
        assert_eq!(snapshot.kv_expected_ranks, 1);
        assert!(!snapshot.has_degraded_coverage());
    }

    #[test]
    fn unknown_capacity_preserves_observations_but_degrades_coverage() {
        let mut state = PoolLoadState::from_runtime_configs(&HashMap::from([(
            9,
            config(0, 2, Some(0), Some(2_048)),
        )]))
        .unwrap();
        let mut report = load(9, 0);
        report.kv_used_blocks = Some(40);
        report.active_prefill_tokens = Some(512);
        assert_eq!(state.observe(report), LoadObservationOutcome::Updated);
        let mut second_report = load(9, 1);
        second_report.kv_used_blocks = Some(30);
        assert_eq!(
            state.observe(second_report),
            LoadObservationOutcome::Updated
        );

        let snapshot = state.snapshot(producer());
        assert_eq!(snapshot.kv_expected_ranks, 2);
        assert_eq!(snapshot.kv_observed_ranks, 2);
        assert_eq!(snapshot.kv_capacity_ranks, 0);
        assert_eq!(snapshot.kv_used_blocks, Some(70));
        assert_eq!(snapshot.total_kv_blocks, None);
        assert!(snapshot.has_degraded_coverage());
    }

    #[test]
    fn oversized_data_parallel_declaration_is_rejected() {
        let error = PoolLoadState::from_runtime_configs(&HashMap::from([(
            9,
            config(0, MAX_LOAD_RANKS_PER_WORKER + 1, Some(100), Some(2_048)),
        )]))
        .unwrap_err();
        assert!(error.to_string().contains("data-parallel ranks"));
    }

    #[test]
    fn partial_reports_do_not_expose_partial_aggregate() {
        let mut state = PoolLoadState::from_runtime_configs(&HashMap::from([(
            9,
            config(0, 2, Some(100), Some(2_048)),
        )]))
        .unwrap();
        let mut first = load(9, 0);
        first.kv_used_blocks = Some(40);
        first.active_prefill_tokens = Some(512);
        assert_eq!(state.observe(first), LoadObservationOutcome::Updated);
        let mut scheduler_only = load(9, 0);
        scheduler_only.active_prefill_tokens = Some(512);
        scheduler_only.active_decode_blocks = Some(30);
        assert_eq!(
            state.observe(scheduler_only),
            LoadObservationOutcome::IgnoredAdvisory
        );
        let mut second = load(9, 0);
        second.active_decode_blocks = Some(30);
        assert_eq!(
            state.observe(second),
            LoadObservationOutcome::IgnoredAdvisory
        );
        let mut replacement = load(9, 0);
        replacement.kv_used_blocks = Some(42);
        assert_eq!(state.observe(replacement), LoadObservationOutcome::Updated);

        let snapshot = state.snapshot(producer());
        assert_eq!(snapshot.kv_used_blocks, None);
        assert_eq!(snapshot.total_kv_blocks, Some(200));
        assert_eq!(snapshot.kv_observed_ranks, 1);
        assert_eq!(snapshot.kv_capacity_ranks, 2);
        assert_eq!(snapshot.kv_expected_ranks, 2);
        assert!(snapshot.has_degraded_coverage());
    }

    #[test]
    fn unknown_ranks_are_ignored_and_disconnect_clears_observations() {
        let mut state = PoolLoadState::from_runtime_configs(&HashMap::from([(
            9,
            config(0, 1, Some(100), Some(2_048)),
        )]))
        .unwrap();
        let mut unknown = load(9, 1);
        unknown.kv_used_blocks = Some(40);
        assert_eq!(state.observe(unknown), LoadObservationOutcome::UnknownRank);
        let mut known = load(9, 0);
        known.kv_used_blocks = Some(40);
        assert_eq!(state.observe(known), LoadObservationOutcome::Updated);
        assert_eq!(state.snapshot(producer()).kv_used_blocks, Some(40));
        assert_eq!(state.snapshot(producer()).kv_observed_ranks, 1);
        assert!(state.clear_observations());
        assert_eq!(state.snapshot(producer()).kv_used_blocks, None);
        assert_eq!(state.snapshot(producer()).kv_observed_ranks, 0);
    }

    #[test]
    fn capacity_change_clears_only_affected_rank_observations() {
        let mut state = PoolLoadState::from_runtime_configs(&HashMap::from([
            (9, config(0, 1, Some(100), Some(2_048))),
            (10, config(0, 1, Some(100), Some(2_048))),
        ]))
        .unwrap();
        let mut changed = load(9, 0);
        changed.kv_used_blocks = Some(40);
        assert_eq!(state.observe(changed), LoadObservationOutcome::Updated);
        let mut unchanged = load(10, 0);
        unchanged.kv_used_blocks = Some(30);
        assert_eq!(state.observe(unchanged), LoadObservationOutcome::Updated);
        assert_eq!(state.snapshot(producer()).kv_used_blocks, Some(70));

        assert!(
            state
                .replace_capacity(&HashMap::from([
                    (9, config(0, 1, Some(200), Some(2_048))),
                    (10, config(0, 1, Some(100), Some(2_048))),
                ]))
                .unwrap()
        );
        let snapshot = state.snapshot(producer());
        assert_eq!(snapshot.kv_expected_ranks, 2);
        assert_eq!(snapshot.kv_observed_ranks, 1);
        assert_eq!(snapshot.kv_used_blocks, None);
        assert_eq!(snapshot.total_kv_blocks, Some(300));
        assert!(snapshot.has_degraded_coverage());
    }

    #[test]
    fn invalid_capacity_clears_previous_authoritative_state() {
        let mut state = PoolLoadState::from_runtime_configs(&HashMap::from([(
            9,
            config(0, 1, Some(100), None),
        )]))
        .unwrap();
        let mut report = load(9, 0);
        report.kv_used_blocks = Some(40);
        assert_eq!(state.observe(report), LoadObservationOutcome::Updated);
        assert!(!state.snapshot(producer()).has_degraded_coverage());

        let error = state
            .replace_capacity(&HashMap::from([(9, config(0, 0, Some(100), None))]))
            .unwrap_err();
        assert!(error.to_string().contains("zero data_parallel_size"));

        let snapshot = state.snapshot(producer());
        assert_eq!(snapshot.kv_used_blocks, None);
        assert_eq!(snapshot.total_kv_blocks, None);
        assert_eq!(snapshot.kv_observed_ranks, 0);
        assert_eq!(snapshot.kv_capacity_ranks, 0);
        assert_eq!(snapshot.kv_expected_ranks, 0);
        assert!(snapshot.has_degraded_coverage());
    }

    fn envelope(publisher_id: u64, sequence: u64, published_at: u64) -> EventEnvelope {
        EventEnvelope {
            publisher_id,
            sequence,
            published_at,
            topic: String::new(),
            payload: Default::default(),
        }
    }

    fn standalone(scheduler_id: u64) -> SchedulerGroup {
        SchedulerGroup::Standalone { scheduler_id }
    }

    fn replicas(group_id: &str) -> SchedulerGroup {
        SchedulerGroup::ReplicaGroup {
            group_id: group_id.to_string(),
        }
    }

    fn view(dp_rank: u32, group: SchedulerGroup, decode: u64, prefill: u64) -> SchedulerLoad {
        SchedulerLoad {
            worker_id: 9,
            dp_rank,
            active_decode_blocks: decode,
            active_prefill_tokens: prefill,
            group,
        }
    }

    /// Delivers a complete rank batch at sequence 1.
    fn publish(
        state: &mut SchedulerLoadState,
        publisher: u64,
        views: impl IntoIterator<Item = SchedulerLoad>,
        now: Instant,
    ) {
        state.observe(
            &envelope(publisher, 1, publisher * 10),
            views.into_iter().collect(),
            now,
        );
    }

    fn ranks(rank_count: u32) -> PoolLoadState {
        PoolLoadState::from_runtime_configs(&HashMap::from([(
            9,
            config(0, rank_count, Some(100), None),
        )]))
        .unwrap()
    }

    fn totals(decode: u64, prefill: u64) -> Coverage<SchedulerGauges> {
        Coverage::Complete(SchedulerGauges {
            active_decode_blocks: decode,
            active_prefill_tokens: prefill,
        })
    }

    #[test]
    fn scheduler_load_takes_the_rank_maximum_within_a_group_and_sums_groups_and_ranks() {
        let now = Instant::now();
        let declared = ranks(2);
        let mut state = SchedulerLoadState::default();
        // Replicas 1 and 2 share group "a"; each lags on something.
        publish(
            &mut state,
            1,
            [view(0, replicas("a"), 12, 30), view(1, replicas("a"), 4, 5)],
            now,
        );
        publish(
            &mut state,
            2,
            [view(0, replicas("a"), 10, 34), view(1, replicas("a"), 6, 7)],
            now,
        );
        // A standalone router only knows the requests it routed itself.
        publish(
            &mut state,
            3,
            [view(0, standalone(3), 1, 2), view(1, standalone(3), 3, 4)],
            now,
        );

        let snapshot = state.snapshot(&declared, Some(&HashSet::from([1, 2, 3])), now);
        assert_eq!(snapshot.coverage, totals(12 + 6 + 1 + 3, 34 + 7 + 2 + 4));
        assert_eq!(snapshot.source_observed_ms, 10);
    }

    #[test]
    fn scheduler_batches_replace_all_ranks_and_ignore_reordered_deliveries() {
        let now = Instant::now();
        let declared = ranks(2);
        let discovered = HashSet::from([1]);
        let mut state = SchedulerLoadState::default();
        let batch = vec![
            view(0, standalone(1), 99, 99),
            view(0, standalone(1), 3, 5),
            view(1, standalone(1), 7, 11),
        ];
        state.observe(&envelope(1, 2, 20), batch, now);
        assert_eq!(
            state.snapshot(&declared, Some(&discovered), now).coverage,
            totals(10, 16)
        );
        for sequence in [2, 1] {
            state.observe(
                &envelope(1, sequence, 30),
                vec![view(0, standalone(1), 99, 99)],
                now,
            );
            assert_eq!(
                state.snapshot(&declared, Some(&discovered), now).coverage,
                totals(10, 16)
            );
        }
        state.observe(&envelope(1, 3, 40), vec![view(0, standalone(1), 2, 4)], now);
        assert_eq!(
            state.snapshot(&declared, Some(&discovered), now).coverage,
            Coverage::Partial
        );
        assert_eq!(
            state.snapshot(&ranks(1), Some(&discovered), now).coverage,
            totals(2, 4)
        );
        state.observe(&envelope(1, 4, 50), Vec::new(), now);
        assert_eq!(
            state.snapshot(&ranks(1), Some(&discovered), now).coverage,
            Coverage::Missing
        );
        state.observe(&envelope(2, 1, 60), vec![view(0, standalone(2), 1, 1)], now);
        assert_eq!(
            state
                .snapshot(&ranks(1), Some(&HashSet::new()), now)
                .coverage,
            Coverage::Partial,
            "a fresh empty batch still advertises a router in broker mode",
        );
    }

    #[test]
    fn scheduler_batch_keeps_known_ranks_when_an_aggregation_kind_is_unknown() {
        let now = Instant::now();
        let encoded = rmp_serde::to_vec_named(&serde_json::json!([
            {"worker_id": 9, "dp_rank": 0, "active_decode_blocks": 3, "active_prefill_tokens": 5,
             "group": {"kind": "standalone", "scheduler_id": 1}},
            {"worker_id": 9, "dp_rank": 1, "active_decode_blocks": 99, "active_prefill_tokens": 99,
             "group": {"kind": "future_group", "new_field": "ignored"}}
        ]))
        .unwrap();
        let batch = rmp_serde::from_slice::<Vec<SchedulerLoad>>(&encoded).unwrap();
        let mut state = SchedulerLoadState::default();
        state.observe(&envelope(1, 1, 10), batch, now);
        let discovered = HashSet::from([1]);
        assert_eq!(
            state.snapshot(&ranks(1), Some(&discovered), now).coverage,
            totals(3, 5)
        );
        assert_eq!(
            state.snapshot(&ranks(2), Some(&discovered), now).coverage,
            Coverage::Partial
        );
    }

    #[test]
    fn reconnected_standalone_scheduler_counts_only_its_latest_view() {
        let now = Instant::now();
        let mut state = SchedulerLoadState::default();
        // Router 1 reconnected as publisher 2 while its old view is still fresh.
        publish(&mut state, 1, [view(0, standalone(1), 30, 40)], now);
        publish(&mut state, 2, [view(0, standalone(1), 3, 4)], now);
        assert_eq!(
            state
                .snapshot(&ranks(1), Some(&HashSet::from([2])), now)
                .coverage,
            totals(3, 4)
        );
    }

    #[test]
    fn scheduler_load_is_partial_until_every_expected_scheduler_covers_every_rank() {
        let now = Instant::now();
        let declared = ranks(2);
        let mut state = SchedulerLoadState::default();
        let discovered = HashSet::from([1, 2]);
        assert_eq!(
            state.snapshot(&declared, Some(&discovered), now).coverage,
            Coverage::Missing
        );

        publish(
            &mut state,
            1,
            [view(0, standalone(1), 1, 1), view(1, standalone(1), 1, 1)],
            now,
        );
        // Router 2 is discovered but silent.
        assert_eq!(
            state.snapshot(&declared, Some(&discovered), now).coverage,
            Coverage::Partial
        );
        // Router 2 reports only one of the two ranks.
        publish(&mut state, 2, [view(0, standalone(2), 1, 1)], now);
        assert_eq!(
            state.snapshot(&declared, Some(&discovered), now).coverage,
            Coverage::Partial
        );
        publish(&mut state, 2, [view(1, standalone(2), 1, 1)], now);
        // Sequence 1 again: the duplicate is dropped, so rank 1 is still missing.
        assert_eq!(
            state.snapshot(&declared, Some(&discovered), now).coverage,
            Coverage::Partial
        );
        state.observe(
            &envelope(2, 2, 20),
            vec![view(0, standalone(2), 1, 1), view(1, standalone(2), 1, 1)],
            now,
        );
        assert_eq!(
            state.snapshot(&declared, Some(&discovered), now).coverage,
            totals(4, 4)
        );
        // Failed discovery cannot prove completeness.
        assert_eq!(
            state.snapshot(&declared, None, now).coverage,
            Coverage::Partial
        );
    }

    #[test]
    fn undiscovered_schedulers_fall_back_to_recent_publishers() {
        // Broker-mode publishers skip discovery registration.
        let now = Instant::now();
        let declared = ranks(1);
        let mut state = SchedulerLoadState::default();
        publish(&mut state, 1, [view(0, standalone(1), 12, 34)], now);
        publish(&mut state, 2, [view(0, standalone(2), 5, 7)], now);
        let nobody = HashSet::new();
        assert_eq!(
            state.snapshot(&declared, Some(&nobody), now).coverage,
            totals(17, 41)
        );

        // A router that stops publishing ages out of the expected set.
        let later = now + SCHEDULER_FRESHNESS + Duration::from_millis(1);
        state.observe(
            &envelope(1, 2, 30),
            vec![view(0, standalone(1), 12, 34)],
            later,
        );
        assert_eq!(
            state.snapshot(&declared, Some(&nobody), later).coverage,
            totals(12, 34)
        );
    }

    #[test]
    fn scheduler_views_expire_and_undeclared_ranks_do_not_count() {
        let now = Instant::now();
        let mut state = SchedulerLoadState::default();
        publish(
            &mut state,
            1,
            [
                view(0, standalone(1), 12, 34),
                view(5, standalone(1), 99, 99),
            ],
            now,
        );
        let discovered = HashSet::from([1]);
        assert_eq!(
            state.snapshot(&ranks(1), Some(&discovered), now).coverage,
            totals(12, 34)
        );

        let expired = now + SCHEDULER_FRESHNESS + Duration::from_millis(1);
        assert_eq!(
            state.snapshot(&ranks(1), Some(&discovered), expired),
            PoolSchedulerLoad {
                coverage: Coverage::Missing,
                source_observed_ms: 0,
            }
        );

        // Long-silent publishers are forgotten, so a restarted router's
        // sequence space is accepted again.
        let retired = now + SOURCE_RETENTION + Duration::from_secs(1);
        state.prune(retired);
        assert!(state.batches.is_empty() && state.publishers.is_empty());
        publish(&mut state, 1, [view(0, standalone(1), 1, 1)], retired);
        assert_eq!(
            state
                .snapshot(&ranks(1), Some(&discovered), retired)
                .coverage,
            totals(1, 1)
        );
    }

    #[test]
    fn deployment_counts_workers_and_requires_every_concurrency_limit() {
        let limited = |rank_count| ModelRuntimeConfig {
            max_num_seqs: Some(8),
            ..config(0, rank_count, Some(100), None)
        };
        assert_eq!(
            PoolDeployment::from_runtime_configs(&HashMap::from([
                (9, limited(2)),
                (10, limited(1))
            ])),
            PoolDeployment {
                live_workers: 2,
                max_concurrency: Some(24),
            }
        );
        assert_eq!(
            PoolDeployment::from_runtime_configs(&HashMap::from([
                (9, limited(2)),
                (10, config(0, 1, Some(100), None)),
            ]))
            .max_concurrency,
            None
        );
    }
}