disagg.rs 53.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use std::collections::{BinaryHeap, HashMap, VecDeque};

use anyhow::{Result, anyhow, bail};
use dynamo_kv_router::config::KvRouterConfig;
use dynamo_kv_router::protocols::RouterEvent;
use uuid::Uuid;

11
12
13
pub(super) use super::components::ReplayMode;
use super::components::{
    AdmissionQueue, EngineComponent, EngineEffects, EnginePassMode, OfflineReplayRouter,
14
    ScheduledWorkerCompletion, TrafficAccumulator, TrafficStats, WorkerAdmission,
15
};
16
use super::events::{SimulationEvent, SimulationWorkerStage};
17
use super::progress::ReplayProgress;
18
use super::runtime_utils::{
19
    next_timestamp as choose_next_timestamp, pop_ready_decode_handoff, pop_ready_worker_completion,
20
    pop_ready_worker_ready, push_decode_handoff, push_worker_completion, push_worker_ready,
21
22
23
};
#[cfg(test)]
use super::state::DisaggRequestSnapshot;
24
use super::state::{DisaggPhase, DisaggRequestState};
25
use crate::common::protocols::{DirectRequest, ForwardPassSnapshot, MockEngineArgs, OutputSignal};
26
use crate::loadgen::{ReplayRequestHashes, WorkloadDriver};
27
28
29
use crate::replay::{
    OfflineDisaggReplayConfig, ReplayPrefillLoadEstimator, ReplayRouterMode, TraceCollector,
};
30
use crate::scheduler::AdmissionEvent;
31

32
33
34
35
36
37
38
39
40
41
#[cfg(test)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DisaggTransition {
    PrefillMarkCompleted { uuid: Uuid },
    PrefillFree { uuid: Uuid },
    DecodeHandoffQueued { uuid: Uuid },
    DecodeEnqueued { uuid: Uuid },
    DecodeFree { uuid: Uuid },
    RequestMarkedDone { uuid: Uuid },
    WorkloadCompleted { uuid: Uuid },
42
43
44
45
}

#[cfg(test)]
#[derive(Debug, Default, Clone, PartialEq)]
46
pub(super) struct DisaggRuntimeStats {
47
48
49
50
51
    request_snapshots: HashMap<Uuid, DisaggRequestSnapshot>,
    prefill_assignments: HashMap<Uuid, usize>,
    decode_assignments: HashMap<Uuid, usize>,
    handoff_ms: HashMap<Uuid, f64>,
    prefill_marked_count: usize,
52
53
54
55
    prefill_router_freed_count: usize,
    decode_router_freed_count: usize,
    max_prefill_router_pending_count: usize,
    max_decode_router_pending_count: usize,
56
    transition_log: Vec<DisaggTransition>,
57
58
59
60
}

#[cfg(not(test))]
#[derive(Debug, Default, Clone, PartialEq, Eq)]
61
pub(super) struct DisaggRuntimeStats;
62

63
pub(in crate::replay) struct DisaggRuntime {
64
65
66
67
    now_ms: f64,
    next_prefill_worker_idx: usize,
    next_decode_worker_idx: usize,
    next_event_seq: u64,
68
69
70
    admission: AdmissionQueue,
    prefill_engine: EngineComponent,
    decode_engine: EngineComponent,
71
72
73
74
75
    prefill_router: Option<OfflineReplayRouter>,
    decode_router: Option<OfflineReplayRouter>,
    requests: HashMap<Uuid, DisaggRequestState>,
    collector: TraceCollector,
    events: BinaryHeap<SimulationEvent>,
76
    progress: ReplayProgress,
77
    stats: DisaggRuntimeStats,
78
79
80
81
82
    /// Forward pass metrics accumulated between planner ticks, keyed by (stage, worker_idx).
    prefill_fpm_buffer: Vec<(usize, ForwardPassSnapshot)>,
    decode_fpm_buffer: Vec<(usize, ForwardPassSnapshot)>,
    /// Traffic statistics accumulated between planner ticks.
    traffic: TrafficAccumulator,
83
84
85
}

impl DisaggRuntime {
86
    /// Create a disaggregated offline runtime seeded from an explicit request queue.
87
    pub(in crate::replay) fn new(
88
89
        config: &OfflineDisaggReplayConfig,
        router_config: Option<KvRouterConfig>,
90
        prefill_load_estimator: Option<ReplayPrefillLoadEstimator>,
91
92
93
94
95
96
97
        pending: VecDeque<DirectRequest>,
        mode: ReplayMode,
        router_mode: ReplayRouterMode,
    ) -> Result<Self> {
        Self::new_with_source(
            config,
            router_config,
98
99
            prefill_load_estimator,
            AdmissionQueue::new_requests(pending, mode),
100
101
102
103
            router_mode,
        )
    }

104
    /// Create a disaggregated offline runtime whose admissions come from a workload driver.
105
    pub(in crate::replay) fn new_workload(
106
107
        config: &OfflineDisaggReplayConfig,
        router_config: Option<KvRouterConfig>,
108
        prefill_load_estimator: Option<ReplayPrefillLoadEstimator>,
109
110
111
112
113
114
115
        driver: WorkloadDriver,
        mode: ReplayMode,
        router_mode: ReplayRouterMode,
    ) -> Result<Self> {
        Self::new_with_source(
            config,
            router_config,
116
117
            prefill_load_estimator,
            AdmissionQueue::new_workload(driver, mode),
118
119
120
121
            router_mode,
        )
    }

122
    /// Shared constructor for both raw-request and workload-driven admissions.
123
124
125
    fn new_with_source(
        config: &OfflineDisaggReplayConfig,
        router_config: Option<KvRouterConfig>,
126
127
        prefill_load_estimator: Option<ReplayPrefillLoadEstimator>,
        admission: AdmissionQueue,
128
129
        router_mode: ReplayRouterMode,
    ) -> Result<Self> {
130
        let progress = ReplayProgress::new(admission.total_requests(), "offline disagg replay");
131
132
133
134
135
136
137
138
139
140
141
        let (prefill_router, decode_router) = match router_mode {
            ReplayRouterMode::RoundRobin => (None, None),
            ReplayRouterMode::KvRouter => {
                let prefill_router_config =
                    derive_prefill_router_config(&config.prefill_args, router_config.clone());
                let decode_router_config =
                    derive_decode_router_config(&config.decode_args, router_config);
                (
                    Some(OfflineReplayRouter::new(
                        &config.prefill_args,
                        Some(prefill_router_config),
142
                        prefill_load_estimator,
143
144
145
146
147
                        config.num_prefill_workers,
                    )?),
                    Some(OfflineReplayRouter::new(
                        &config.decode_args,
                        Some(decode_router_config),
148
                        None,
149
150
151
152
153
154
                        config.num_decode_workers,
                    )?),
                )
            }
        };

155
156
        let prefill_capture_kv = prefill_router.is_some();
        let mut prefill_engine = EngineComponent::new(
157
158
159
            SimulationWorkerStage::Prefill,
            EnginePassMode::Hidden,
            (0..config.num_prefill_workers)
160
                .map(|worker_idx| {
161
                    super::state::OfflineWorkerState::new(
162
163
                        worker_idx,
                        config.prefill_args.clone(),
164
                        prefill_capture_kv,
165
166
167
                    )
                })
                .collect(),
168
        );
169
170
        prefill_engine.set_scaling_args(config.prefill_args.clone(), prefill_capture_kv);
        let mut decode_engine = EngineComponent::new(
171
172
173
            SimulationWorkerStage::Decode,
            EnginePassMode::Visible,
            (0..config.num_decode_workers)
174
                .map(|worker_idx| {
175
176
177
178
179
                    super::state::OfflineWorkerState::new(
                        worker_idx,
                        config.decode_args.clone(),
                        false,
                    )
180
181
                })
                .collect(),
182
        );
183
        decode_engine.set_scaling_args(config.decode_args.clone(), false);
184
185
186
187
188
189
190
191
192

        Ok(Self {
            now_ms: 0.0,
            next_prefill_worker_idx: 0,
            next_decode_worker_idx: 0,
            next_event_seq: 0,
            admission,
            prefill_engine,
            decode_engine,
193
194
195
196
197
            prefill_router,
            decode_router,
            requests: HashMap::new(),
            collector: TraceCollector::default(),
            events: BinaryHeap::new(),
198
            progress,
199
200
201
202
            #[cfg(test)]
            stats: DisaggRuntimeStats::default(),
            #[cfg(not(test))]
            stats: DisaggRuntimeStats,
203
204
205
            prefill_fpm_buffer: Vec::new(),
            decode_fpm_buffer: Vec::new(),
            traffic: TrafficAccumulator::new(),
206
207
208
        })
    }

209
    /// Count all requests consuming cluster capacity across prefill, decode, and router queues.
210
    fn cluster_in_flight(&self) -> usize {
211
212
        self.prefill_engine.in_flight()
            + self.decode_engine.in_flight()
213
214
215
216
217
218
219
220
221
222
            + self
                .prefill_router
                .as_ref()
                .map_or(0, OfflineReplayRouter::pending_count)
            + self
                .decode_router
                .as_ref()
                .map_or(0, OfflineReplayRouter::pending_count)
    }

223
    /// Pick the next active prefill worker in round-robin order.
224
    fn next_prefill_worker(&mut self) -> usize {
225
226
227
228
229
230
231
232
        let active = self.prefill_engine.active_worker_ids();
        debug_assert!(
            !active.is_empty(),
            "no active prefill workers for round-robin"
        );
        let idx = self.next_prefill_worker_idx % active.len();
        self.next_prefill_worker_idx = idx + 1;
        active[idx]
233
234
    }

235
    /// Pick the next active decode worker in round-robin order.
236
    fn next_decode_worker(&mut self) -> usize {
237
238
239
240
241
242
243
244
        let active = self.decode_engine.active_worker_ids();
        debug_assert!(
            !active.is_empty(),
            "no active decode workers for round-robin"
        );
        let idx = self.next_decode_worker_idx % active.len();
        self.next_decode_worker_idx = idx + 1;
        active[idx]
245
246
    }

247
    /// Track the peak number of requests parked in each stage router.
248
249
250
    fn record_router_pending(&mut self) {
        #[cfg(test)]
        {
251
252
253
254
255
256
257
258
259
260
261
262
            self.stats.max_prefill_router_pending_count =
                self.stats.max_prefill_router_pending_count.max(
                    self.prefill_router
                        .as_ref()
                        .map_or(0, OfflineReplayRouter::pending_count),
                );
            self.stats.max_decode_router_pending_count =
                self.stats.max_decode_router_pending_count.max(
                    self.decode_router
                        .as_ref()
                        .map_or(0, OfflineReplayRouter::pending_count),
                );
263
264
265
        }
    }

266
    /// Borrow immutable request state with a structured missing-request error.
267
268
269
270
271
272
    fn state(&self, uuid: Uuid) -> Result<&DisaggRequestState> {
        self.requests
            .get(&uuid)
            .ok_or_else(|| anyhow!("offline disagg replay missing request state for {uuid}"))
    }

273
    /// Borrow mutable request state with a structured missing-request error.
274
275
276
277
278
279
    fn state_mut(&mut self, uuid: Uuid) -> Result<&mut DisaggRequestState> {
        self.requests
            .get_mut(&uuid)
            .ok_or_else(|| anyhow!("offline disagg replay missing request state for {uuid}"))
    }

280
    /// Dispatch a request's prefill stage onto a specific prefill worker.
281
282
    fn dispatch_prefill(&mut self, uuid: Uuid, worker_idx: usize) -> Result<()> {
        let request = self.state(uuid)?.build_prefill_request()?;
283
        self.prefill_engine.dispatch(worker_idx, request)?;
284
285
286
287
288
289
290
291
        self.state_mut(uuid)?.start_prefill(worker_idx);
        #[cfg(test)]
        {
            self.stats.prefill_assignments.insert(uuid, worker_idx);
        }
        Ok(())
    }

292
    /// Dispatch a request's decode stage onto a specific decode worker.
293
    fn dispatch_decode(&mut self, uuid: Uuid, worker_idx: usize) -> Result<()> {
294
295
        let request = self.state(uuid)?.original_request()?.clone();
        self.decode_engine.dispatch(worker_idx, request)?;
296
297
298
299
300
301
302
303
        self.state_mut(uuid)?.start_decode(worker_idx);
        #[cfg(test)]
        {
            self.stats.decode_assignments.insert(uuid, worker_idx);
        }
        Ok(())
    }

304
    /// Turn prefill router admissions into concrete worker dispatches.
305
    fn dispatch_prefill_admissions(&mut self, admissions: Vec<WorkerAdmission>) -> Result<()> {
306
307
308
309
310
311
312
313
        for WorkerAdmission {
            uuid,
            worker_idx,
            overlap_blocks,
            isl_blocks,
        } in admissions
        {
            self.traffic.on_admission(overlap_blocks, isl_blocks);
314
            if self.state(uuid)?.phase != DisaggPhase::QueuedPrefill {
315
316
317
318
319
320
321
                bail!("offline disagg replay expected queued prefill request for {uuid}");
            }
            self.dispatch_prefill(uuid, worker_idx)?;
        }
        Ok(())
    }

322
    /// Turn decode router admissions into concrete worker dispatches.
323
324
325
326
327
    ///
    /// Note: only the prefill router's admissions are fed to
    /// ``traffic.on_admission``; decode-router admissions reflect the
    /// same requests re-routing after prefill completes and would double
    /// count overlap observations.
328
    fn dispatch_decode_admissions(&mut self, admissions: Vec<WorkerAdmission>) -> Result<()> {
329
330
331
332
        for WorkerAdmission {
            uuid, worker_idx, ..
        } in admissions
        {
333
            if self.state(uuid)?.phase != DisaggPhase::QueuedDecode {
334
335
336
337
338
339
340
                bail!("offline disagg replay expected queued decode request for {uuid}");
            }
            self.dispatch_decode(uuid, worker_idx)?;
        }
        Ok(())
    }

341
342
343
    /// Queue or dispatch a request into decode, depending on whether a decode router is active.
    fn enqueue_decode(&mut self, uuid: Uuid) -> Result<()> {
        if self.decode_router.is_none() {
344
345
346
347
348
349
350
            #[cfg(test)]
            {
                self.stats
                    .transition_log
                    .push(DisaggTransition::DecodeEnqueued { uuid });
                self.stats.handoff_ms.insert(uuid, self.now_ms);
            }
351
352
353
            let worker_idx = self.next_decode_worker();
            self.dispatch_decode(uuid, worker_idx)?;
            return Ok(());
354
        }
355
356
        let request = self.state(uuid)?.original_request()?.clone();
        self.state_mut(uuid)?.queue_decode();
357
358
        #[cfg(test)]
        {
359
360
361
            self.stats
                .transition_log
                .push(DisaggTransition::DecodeEnqueued { uuid });
362
363
            self.stats.handoff_ms.insert(uuid, self.now_ms);
        }
364
365
366
367
368
369
370
371
        let admissions = self
            .decode_router
            .as_mut()
            .expect("decode router presence checked above")
            .on_request_arrival(&request, None, self.now_ms)?
            .admissions;
        self.record_router_pending();
        self.dispatch_decode_admissions(admissions)?;
372
373
374
        Ok(())
    }

375
    /// Admit one external request into prefill-side state, collector state, and optional router.
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
    fn on_external_arrival(
        &mut self,
        mut request: DirectRequest,
        arrival_time_ms: f64,
        replay_hashes: Option<ReplayRequestHashes>,
    ) -> Result<Uuid> {
        let uuid = request.uuid.unwrap_or_else(Uuid::new_v4);
        request.uuid = Some(uuid);
        request.arrival_timestamp_ms = Some(arrival_time_ms);

        self.collector.on_arrival(
            uuid,
            arrival_time_ms,
            request.tokens.len(),
            request.max_output_tokens,
        );
392
        let queued_request = request.clone();
393
394
        self.requests
            .insert(uuid, DisaggRequestState::new(request, arrival_time_ms));
395
        if self.prefill_router.is_none() {
396
397
398
            let worker_idx = self.next_prefill_worker();
            self.dispatch_prefill(uuid, worker_idx)?;
            return Ok(uuid);
399
        }
400
401
402
403
404
405
406
407
        let admissions = self
            .prefill_router
            .as_mut()
            .expect("prefill router presence checked above")
            .on_request_arrival(&queued_request, replay_hashes, self.now_ms)?
            .admissions;
        self.record_router_pending();
        self.dispatch_prefill_admissions(admissions)?;
408
409
410
        Ok(uuid)
    }

411
    /// Return true once both stages, both routers, and all admissions are fully drained.
412
413
414
    fn is_done(&self) -> bool {
        self.events.is_empty()
            && self.cluster_in_flight() == 0
415
416
417
            && self.admission.is_drained()
            && self.prefill_engine.is_drained()
            && self.decode_engine.is_drained()
418
419
    }

420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
    /// Return true once the request workload is complete, even if `WorkerReady`
    /// events remain in the queue.
    fn is_workload_done(&self) -> bool {
        self.cluster_in_flight() == 0
            && self.admission.is_drained()
            && self.prefill_engine.is_drained()
            && self.decode_engine.is_drained()
            && self.only_worker_ready_events_remain()
    }

    /// True if the event heap is empty or contains only `WorkerReady` events.
    fn only_worker_ready_events_remain(&self) -> bool {
        use super::events::SimulationEventKind;
        self.events
            .iter()
            .all(|e| matches!(e.kind, SimulationEventKind::WorkerReady { .. }))
    }

438
    /// Pick the next logical timestamp from arrivals, worker completions, or decode handoffs.
439
440
    fn next_timestamp(&mut self) -> Option<f64> {
        let next_event_ms = self.events.peek().map(|event| event.at_ms);
441
442
443
444
        choose_next_timestamp(
            self.admission.next_ready_time_ms(self.cluster_in_flight()),
            next_event_ms,
        )
445
446
    }

447
    /// Apply prefill-side KV router events at the scheduler-selected visibility phase.
448
449
450
451
    fn apply_prefill_router_events(&mut self, events: Vec<RouterEvent>) -> Result<()> {
        let Some(prefill_router) = self.prefill_router.as_mut() else {
            return Ok(());
        };
452
453
454
        let effects = prefill_router.on_kv_events(events)?;
        if !effects.admissions.is_empty() {
            bail!("offline disagg replay prefill KV events must not admit requests");
455
456
457
458
        }
        Ok(())
    }

459
    /// Process one prefill output signal, including router updates and decode handoff scheduling.
460
461
462
463
464
465
466
467
    fn process_prefill_signal(&mut self, signal: OutputSignal) -> Result<()> {
        if !signal.completed {
            return Ok(());
        }

        if self.prefill_router.is_some() {
            let prefill_complete_admissions = {
                let prefill_router = self.prefill_router.as_mut().expect("router checked above");
468
469
470
                prefill_router
                    .on_prefill_completed(signal.uuid, self.now_ms)?
                    .admissions
471
472
473
474
            };
            #[cfg(test)]
            {
                self.stats.prefill_marked_count += 1;
475
476
477
                self.stats
                    .transition_log
                    .push(DisaggTransition::PrefillMarkCompleted { uuid: signal.uuid });
478
479
480
481
482
483
            }
            self.record_router_pending();
            self.dispatch_prefill_admissions(prefill_complete_admissions)?;

            let admissions = {
                let prefill_router = self.prefill_router.as_mut().expect("router checked above");
484
485
486
                prefill_router
                    .on_request_completed(signal.uuid, self.now_ms)?
                    .admissions
487
488
489
            };
            #[cfg(test)]
            {
490
                self.stats.prefill_router_freed_count += 1;
491
492
493
                self.stats
                    .transition_log
                    .push(DisaggTransition::PrefillFree { uuid: signal.uuid });
494
495
496
497
498
499
500
501
            }
            self.record_router_pending();
            self.dispatch_prefill_admissions(admissions)?;
        }

        self.enqueue_decode_after_handoff(signal.uuid, signal.handoff_delay_ms)
    }

502
    /// Process one decode output signal, including decode router frees and request completion.
503
504
505
506
507
508
    fn process_decode_signal(&mut self, signal: OutputSignal) -> Result<()> {
        if !signal.completed {
            return Ok(());
        }

        let admissions = if let Some(decode_router) = self.decode_router.as_mut() {
509
510
511
            let admissions = decode_router
                .on_request_completed(signal.uuid, self.now_ms)?
                .admissions;
512
513
            #[cfg(test)]
            {
514
                self.stats.decode_router_freed_count += 1;
515
516
517
                self.stats
                    .transition_log
                    .push(DisaggTransition::DecodeFree { uuid: signal.uuid });
518
519
520
521
522
523
            }
            admissions
        } else {
            Vec::new()
        };
        self.record_router_pending();
524
525
526
527
528
529
530
531
        self.admission
            .on_request_completed(signal.uuid, self.now_ms)?;
        self.progress.inc_completed();
        #[cfg(test)]
        if self.admission.is_workload() {
            self.stats
                .transition_log
                .push(DisaggTransition::WorkloadCompleted { uuid: signal.uuid });
532
        }
533
534
535
536
        let state = self.state(signal.uuid)?;
        let original = state.original_request()?;
        let input_tokens = original.tokens.len();
        let output_tokens = original.max_output_tokens;
537
538
539
        let latencies = self.collector.request_latencies(signal.uuid);
        self.traffic
            .on_request(input_tokens, output_tokens, latencies);
540
        self.state_mut(signal.uuid)?.mark_done();
541
542
543
544
545
546
        #[cfg(test)]
        {
            self.stats
                .transition_log
                .push(DisaggTransition::RequestMarkedDone { uuid: signal.uuid });
        }
547
548
549
550
        self.dispatch_decode_admissions(admissions)?;
        Ok(())
    }

551
    /// Apply the side effects of a finished prefill pass.
552
553
    fn process_prefill_pass(
        &mut self,
554
555
        _worker_idx: usize,
        _completed_requests: usize,
556
557
558
559
560
561
562
563
564
565
        output_signals: Vec<OutputSignal>,
        kv_events: Vec<RouterEvent>,
    ) -> Result<()> {
        self.apply_prefill_router_events(kv_events)?;
        for signal in output_signals {
            self.process_prefill_signal(signal)?;
        }
        Ok(())
    }

566
    /// Apply the side effects of a finished decode pass.
567
568
    fn process_decode_pass(
        &mut self,
569
570
        _worker_idx: usize,
        _completed_requests: usize,
571
572
573
574
575
576
577
578
        output_signals: Vec<OutputSignal>,
    ) -> Result<()> {
        for signal in output_signals {
            self.process_decode_signal(signal)?;
        }
        Ok(())
    }

579
    /// Drain all worker-completion events scheduled for the current logical timestamp.
580
581
    fn apply_worker_completions(&mut self) -> Result<bool> {
        let mut changed = false;
582
583
        while let Some(payload) = pop_ready_worker_completion(&mut self.events, self.now_ms) {
            match payload.stage {
584
                SimulationWorkerStage::Prefill => {
585
                    let payload = self.prefill_engine.on_scheduled_completion(payload)?;
586
                    self.process_prefill_pass(
587
588
589
590
                        payload.worker_idx,
                        payload.completed_requests,
                        payload.output_signals,
                        payload.kv_events,
591
592
593
                    )?;
                }
                SimulationWorkerStage::Decode => {
594
595
596
597
598
599
                    let payload = self.decode_engine.on_scheduled_completion(payload)?;
                    self.process_decode_pass(
                        payload.worker_idx,
                        payload.completed_requests,
                        payload.output_signals,
                    )?;
600
601
602
603
604
605
606
607
608
609
                }
                SimulationWorkerStage::Aggregated => {
                    bail!("offline disagg replay received an aggregated completion event")
                }
            }
            changed = true;
        }
        Ok(changed)
    }

610
    /// Drain all delayed decode handoff events scheduled for the current logical timestamp.
611
612
613
614
615
616
617
618
619
    fn apply_decode_handoffs(&mut self) -> Result<bool> {
        let mut changed = false;
        while let Some(uuid) = pop_ready_decode_handoff(&mut self.events, self.now_ms) {
            self.enqueue_decode(uuid)?;
            changed = true;
        }
        Ok(changed)
    }

620
    /// Either enqueue decode immediately or schedule a delayed handoff event on the event heap.
621
622
623
624
625
    fn enqueue_decode_after_handoff(
        &mut self,
        uuid: Uuid,
        handoff_delay_ms: Option<f64>,
    ) -> Result<()> {
626
627
628
629
        let Some(delay_ms) = handoff_delay_ms else {
            return self.enqueue_decode(uuid);
        };
        if delay_ms > 0.0 {
630
631
632
633
634
635
            push_decode_handoff(
                &mut self.events,
                &mut self.next_event_seq,
                self.now_ms + delay_ms,
                uuid,
            );
636
637
638
639
            #[cfg(test)]
            self.stats
                .transition_log
                .push(DisaggTransition::DecodeHandoffQueued { uuid });
640
641
642
643
644
            return Ok(());
        }
        self.enqueue_decode(uuid)
    }

645
646
    /// Release every admission made ready by the shared admission queue.
    fn release_ready_arrivals(&mut self) -> Result<bool> {
647
        let mut released_any = false;
648
649
650
651
652
        for ready in self
            .admission
            .drain_ready(self.now_ms, self.cluster_in_flight())?
        {
            self.on_external_arrival(ready.request, ready.arrival_time_ms, ready.replay_hashes)?;
653
654
655
656
657
            released_any = true;
        }
        Ok(released_any)
    }

658
    /// Start passes on every idle prefill worker that can make progress at the current timestamp.
659
660
    fn drive_prefill_workers(&mut self) -> Result<bool> {
        let mut changed = false;
661
662
663
664
        loop {
            let effects = self.prefill_engine.drive_ready(self.now_ms, None)?;
            if effects.is_empty() {
                return Ok(changed);
665
            }
666
667
            changed = true;
            self.handle_prefill_engine_effects(effects)?;
668
669
670
        }
    }

671
    /// Start passes on every idle decode worker that can make progress at the current timestamp.
672
673
    fn drive_decode_workers(&mut self) -> Result<bool> {
        let mut changed = false;
674
675
676
677
678
679
680
681
682
683
684
        loop {
            let effects = self
                .decode_engine
                .drive_ready(self.now_ms, Some(&mut self.collector))?;
            if effects.is_empty() {
                return Ok(changed);
            }
            changed = true;
            self.handle_decode_engine_effects(effects)?;
        }
    }
685

686
    fn handle_prefill_engine_effects(&mut self, effects: EngineEffects) -> Result<()> {
687
        self.prefill_fpm_buffer.extend(effects.fpm_snapshots);
688
        self.record_prefill_admissions(effects.admissions);
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
        self.apply_prefill_router_events(effects.pass_start_kv_events)?;
        for payload in effects.immediate_completions {
            let payload = self.prefill_engine.on_scheduled_completion(payload)?;
            self.process_prefill_pass(
                payload.worker_idx,
                payload.completed_requests,
                payload.output_signals,
                payload.kv_events,
            )?;
        }
        for ScheduledWorkerCompletion { at_ms, payload } in effects.scheduled_completions {
            push_worker_completion(&mut self.events, &mut self.next_event_seq, at_ms, payload);
        }
        Ok(())
    }
704

705
706
707
708
709
710
711
    fn record_prefill_admissions(&mut self, admissions: Vec<AdmissionEvent>) {
        for admission in admissions {
            self.collector
                .on_admit(admission.uuid, self.now_ms, admission.reused_input_tokens);
        }
    }

712
    fn handle_decode_engine_effects(&mut self, effects: EngineEffects) -> Result<()> {
713
        self.decode_fpm_buffer.extend(effects.fpm_snapshots);
714
715
716
717
718
719
720
        for payload in effects.immediate_completions {
            let payload = self.decode_engine.on_scheduled_completion(payload)?;
            self.process_decode_pass(
                payload.worker_idx,
                payload.completed_requests,
                payload.output_signals,
            )?;
721
        }
722
723
724
725
        for ScheduledWorkerCompletion { at_ms, payload } in effects.scheduled_completions {
            push_worker_completion(&mut self.events, &mut self.next_event_seq, at_ms, payload);
        }
        Ok(())
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
    /// Activate workers whose startup period has elapsed at the current timestamp.
    fn apply_worker_ready_events(&mut self) -> Result<bool> {
        let mut changed = false;
        while let Some((stage, worker_id)) = pop_ready_worker_ready(&mut self.events, self.now_ms) {
            match stage {
                SimulationWorkerStage::Prefill => {
                    if self.prefill_engine.mark_worker_ready(worker_id) {
                        if let Some(router) = self.prefill_router.as_mut() {
                            router.add_worker(worker_id)?;
                            let effects = router.try_drain_pending(self.now_ms)?;
                            self.dispatch_prefill_admissions(effects.admissions)?;
                        }
                        changed = true;
                    }
                }
                SimulationWorkerStage::Decode => {
                    if self.decode_engine.mark_worker_ready(worker_id) {
                        if let Some(router) = self.decode_router.as_mut() {
                            router.add_worker(worker_id)?;
                            let effects = router.try_drain_pending(self.now_ms)?;
                            self.dispatch_decode_admissions(effects.admissions)?;
                        }
                        changed = true;
                    }
                }
                SimulationWorkerStage::Aggregated => {
                    unreachable!("disagg replay should not receive aggregated worker ready events")
                }
            }
        }
        Ok(changed)
    }

761
    /// Repeatedly process all work that becomes possible without advancing logical time.
762
763
764
    fn drain_current_timestamp(&mut self) -> Result<()> {
        loop {
            let mut changed = self.apply_worker_completions()?;
765
            changed |= self.apply_worker_ready_events()?;
766
            changed |= self.apply_decode_handoffs()?;
767
            changed |= self.release_ready_arrivals()?;
768
769
770
771
772
773
774
775
776
777
            changed |= self.drive_prefill_workers()?;
            changed |= self.drive_decode_workers()?;

            if !changed {
                break;
            }
        }
        Ok(())
    }

778
    /// Finalize test-only request snapshots before returning.
779
780
781
782
783
784
785
786
787
788
789
    fn finish_test_stats(&mut self) {
        #[cfg(test)]
        {
            self.stats.request_snapshots = self
                .requests
                .iter()
                .map(|(uuid, state)| (*uuid, state.debug_snapshot()))
                .collect();
        }
    }

790
791
792
793
794
    // ------------------------------------------------------------------
    // Planner integration: step-based execution
    // ------------------------------------------------------------------

    /// Advance the simulation up to `until_ms` simulated time, then pause.
795
796
    /// Returns `true` if the request workload is done — pending `WorkerReady`
    /// events do not block completion since there is no work for those workers.
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
    pub(in crate::replay) fn advance_to(&mut self, until_ms: f64) -> Result<bool> {
        self.drain_current_timestamp()?;

        while !self.is_done() {
            let Some(next_timestamp_ms) = self.next_timestamp() else {
                bail!(
                    "offline disagg replay reached a dead end with {} in-flight requests remaining",
                    self.cluster_in_flight()
                );
            };

            if next_timestamp_ms > until_ms {
                break;
            }

            self.now_ms = next_timestamp_ms;
            self.drain_current_timestamp()?;
        }

816
        Ok(self.is_workload_done())
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
    }

    /// Current simulated time in milliseconds.
    pub(in crate::replay) fn now_ms(&self) -> f64 {
        self.now_ms
    }

    pub(in crate::replay) fn active_prefill_count(&self) -> usize {
        self.prefill_engine.active_worker_ids().len()
    }

    pub(in crate::replay) fn active_decode_count(&self) -> usize {
        self.decode_engine.active_worker_ids().len()
    }

    pub(in crate::replay) fn total_prefill_count(&self) -> usize {
        self.prefill_engine.worker_count()
    }

    pub(in crate::replay) fn total_decode_count(&self) -> usize {
        self.decode_engine.worker_count()
    }

    /// Drain accumulated prefill FPM snapshots since the last drain.
    pub(in crate::replay) fn drain_prefill_fpm(&mut self) -> Vec<(usize, ForwardPassSnapshot)> {
        std::mem::take(&mut self.prefill_fpm_buffer)
    }

    /// Drain accumulated decode FPM snapshots since the last drain.
    pub(in crate::replay) fn drain_decode_fpm(&mut self) -> Vec<(usize, ForwardPassSnapshot)> {
        std::mem::take(&mut self.decode_fpm_buffer)
    }

    /// Drain accumulated traffic stats since the last drain.
851
    pub(in crate::replay) fn drain_traffic(&mut self) -> TrafficStats {
852
853
854
855
        self.traffic.drain(self.now_ms)
    }

    /// Apply a scaling decision with separate prefill and decode targets.
856
857
858
859
860
861
862
863
    ///
    /// Scale-up: if `startup_time` is configured on the respective engine args,
    /// new workers enter a startup phase and a `WorkerReady` event is scheduled.
    /// They become active (and are registered with the router) only when that
    /// event fires.  Without `startup_time`, workers are available immediately.
    ///
    /// Scale-down: the worker is removed from the router immediately so no
    /// new requests land on it while it drains in-flight work.
864
865
866
867
868
    pub(in crate::replay) fn apply_scaling(
        &mut self,
        target_prefill: usize,
        target_decode: usize,
    ) -> Result<()> {
869
        // -- prefill --
870
        let (added, newly_marked) = self.prefill_engine.apply_target_count(target_prefill);
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
        let prefill_delay = self.prefill_engine.startup_time_ms();
        for &id in &added {
            match prefill_delay {
                Some(delay) => {
                    push_worker_ready(
                        &mut self.events,
                        &mut self.next_event_seq,
                        self.now_ms + delay,
                        SimulationWorkerStage::Prefill,
                        id,
                    );
                }
                None => {
                    if let Some(router) = self.prefill_router.as_mut() {
                        router.add_worker(id)?;
                    }
                }
888
            }
889
890
        }
        let prefill_admissions = if let Some(router) = self.prefill_router.as_mut() {
891
892
893
            for id in newly_marked {
                router.remove_worker(id)?;
            }
894
895
896
897
            router.on_topology_changed(self.now_ms)?.admissions
        } else {
            Vec::new()
        };
898
899

        // -- decode --
900
        let (added, newly_marked) = self.decode_engine.apply_target_count(target_decode);
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
        let decode_delay = self.decode_engine.startup_time_ms();
        for &id in &added {
            match decode_delay {
                Some(delay) => {
                    push_worker_ready(
                        &mut self.events,
                        &mut self.next_event_seq,
                        self.now_ms + delay,
                        SimulationWorkerStage::Decode,
                        id,
                    );
                }
                None => {
                    if let Some(router) = self.decode_router.as_mut() {
                        router.add_worker(id)?;
                    }
                }
918
            }
919
920
        }
        let decode_admissions = if let Some(router) = self.decode_router.as_mut() {
921
922
923
            for id in newly_marked {
                router.remove_worker(id)?;
            }
924
925
926
927
928
929
930
            router.on_topology_changed(self.now_ms)?.admissions
        } else {
            Vec::new()
        };
        self.record_router_pending();
        self.dispatch_prefill_admissions(prefill_admissions)?;
        self.dispatch_decode_admissions(decode_admissions)?;
931
932
933
934
935
936
937
938
939
        Ok(())
    }

    /// Finalize the replay and return the simulation report directly.
    pub(in crate::replay) fn finalize_report(self) -> crate::replay::TraceSimulationReport {
        self.progress.finish();
        self.collector.finish()
    }

940
941
    /// Run the staged offline replay until both prefill and decode pipelines are drained.
    pub(super) fn run(mut self) -> Result<(TraceCollector, DisaggRuntimeStats)> {
942
943
944
945
946
947
948
949
950
951
952
953
954
        self.drain_current_timestamp()?;

        while !self.is_done() {
            let Some(next_timestamp_ms) = self.next_timestamp() else {
                bail!(
                    "offline disagg replay reached a dead end with {} in-flight requests remaining",
                    self.cluster_in_flight()
                );
            };
            self.now_ms = next_timestamp_ms;
            self.drain_current_timestamp()?;
        }

955
        self.progress.finish();
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
        self.finish_test_stats();
        Ok((self.collector, self.stats))
    }
}

fn base_router_config(
    args: &MockEngineArgs,
    router_config: Option<KvRouterConfig>,
) -> KvRouterConfig {
    let mut config = router_config.unwrap_or_default();
    if let Some(policy) = args.router_queue_policy {
        config.router_queue_policy = policy;
    }
    config
}

fn derive_prefill_router_config(
    args: &MockEngineArgs,
    router_config: Option<KvRouterConfig>,
) -> KvRouterConfig {
    let mut config = base_router_config(args, router_config);
    config.router_track_active_blocks = false;
    config
}

fn derive_decode_router_config(
    args: &MockEngineArgs,
    router_config: Option<KvRouterConfig>,
) -> KvRouterConfig {
    let mut config = base_router_config(args, router_config);
    config.overlap_score_weight = 0.0;
    config.router_assume_kv_reuse = false;
    config.router_track_prefill_tokens = false;
989
    config.router_prefill_load_model = dynamo_kv_router::config::RouterPrefillLoadModel::None;
990
991
992
993
994
    config
}

#[cfg(test)]
mod tests {
995
996
    use std::collections::VecDeque;

997
998
999
1000
    use super::super::entrypoints::{
        run_concurrency_collect, run_concurrency_workload_collect, run_trace_collect,
        run_trace_workload_collect,
    };
1001
    use super::*;
1002
1003
    use crate::common::protocols::{EngineType, MockEngineArgs, SglangArgs, WorkerType};
    use crate::loadgen::{SessionTrace, Trace, TurnTrace};
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019

    fn staged_args(worker_type: WorkerType, speedup_ratio: f64) -> MockEngineArgs {
        MockEngineArgs::builder()
            .block_size(64)
            .num_gpu_blocks(256)
            .max_num_batched_tokens(Some(8192))
            .max_num_seqs(Some(8))
            .enable_prefix_caching(true)
            .enable_chunked_prefill(true)
            .speedup_ratio(speedup_ratio)
            .decode_speedup_ratio(speedup_ratio)
            .worker_type(worker_type)
            .build()
            .unwrap()
    }

1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
    fn sglang_staged_args(worker_type: WorkerType, speedup_ratio: f64) -> MockEngineArgs {
        MockEngineArgs::builder()
            .engine_type(EngineType::Sglang)
            .block_size(64)
            .num_gpu_blocks(512)
            .max_num_batched_tokens(Some(8192))
            .max_num_seqs(Some(8))
            .enable_prefix_caching(true)
            .enable_chunked_prefill(true)
            .speedup_ratio(speedup_ratio)
            .decode_speedup_ratio(speedup_ratio)
            .worker_type(worker_type)
            .sglang(Some(SglangArgs {
                page_size: Some(64),
                ..Default::default()
            }))
            .build()
            .unwrap()
    }

1040
1041
1042
1043
1044
1045
1046
1047
1048
    fn disagg_config() -> OfflineDisaggReplayConfig {
        OfflineDisaggReplayConfig {
            prefill_args: staged_args(WorkerType::Prefill, 1000.0),
            decode_args: staged_args(WorkerType::Decode, 1000.0),
            num_prefill_workers: 2,
            num_decode_workers: 2,
        }
    }

1049
1050
1051
1052
1053
1054
1055
1056
1057
    fn sglang_disagg_config() -> OfflineDisaggReplayConfig {
        OfflineDisaggReplayConfig {
            prefill_args: sglang_staged_args(WorkerType::Prefill, 1000.0),
            decode_args: sglang_staged_args(WorkerType::Decode, 1000.0),
            num_prefill_workers: 2,
            num_decode_workers: 2,
        }
    }

1058
1059
1060
1061
1062
1063
1064
    fn disagg_config_with_handoff_delay() -> OfflineDisaggReplayConfig {
        let mut config = disagg_config();
        config.prefill_args.kv_transfer_bandwidth = Some(1.0);
        config.prefill_args.kv_bytes_per_token = Some(1_000_000);
        config
    }

1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
    fn scaling_test_args(worker_type: WorkerType) -> MockEngineArgs {
        MockEngineArgs::builder()
            .block_size(64)
            .num_gpu_blocks(512)
            .max_num_batched_tokens(Some(64))
            .max_num_seqs(Some(8))
            .enable_prefix_caching(true)
            .enable_chunked_prefill(true)
            .speedup_ratio(1.0)
            .decode_speedup_ratio(1.0)
            .worker_type(worker_type)
            .build()
            .unwrap()
    }

    fn scaling_test_disagg_config() -> OfflineDisaggReplayConfig {
        OfflineDisaggReplayConfig {
            prefill_args: scaling_test_args(WorkerType::Prefill),
            decode_args: scaling_test_args(WorkerType::Decode),
            num_prefill_workers: 1,
            num_decode_workers: 1,
        }
    }

1089
1090
1091
1092
1093
1094
1095
    fn router_config() -> KvRouterConfig {
        KvRouterConfig {
            router_queue_threshold: Some(1.25),
            ..KvRouterConfig::default()
        }
    }

1096
1097
1098
1099
1100
1101
1102
    fn planner_router_config() -> KvRouterConfig {
        KvRouterConfig {
            router_queue_threshold: Some(0.5),
            ..KvRouterConfig::default()
        }
    }

1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
    fn request(
        uuid: u128,
        prompt_tokens: usize,
        output_tokens: usize,
        arrival_ms: f64,
    ) -> DirectRequest {
        DirectRequest {
            tokens: vec![1; prompt_tokens],
            max_output_tokens: output_tokens,
            uuid: Some(Uuid::from_u128(uuid)),
            dp_rank: 0,
            arrival_timestamp_ms: Some(arrival_ms),
        }
    }

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
    fn multiturn_trace() -> Trace {
        Trace {
            block_size: 64,
            sessions: vec![
                SessionTrace {
                    session_id: "session-a".to_string(),
                    first_arrival_timestamp_ms: Some(0.0),
                    turns: vec![
                        TurnTrace {
                            input_length: 64,
                            max_output_tokens: 2,
                            hash_ids: vec![11],
                            delay_after_previous_ms: 0.0,
                        },
                        TurnTrace {
                            input_length: 192,
                            max_output_tokens: 2,
                            hash_ids: vec![21, 22, 23],
                            delay_after_previous_ms: 10.0,
                        },
                    ],
                },
                SessionTrace {
                    session_id: "session-b".to_string(),
                    first_arrival_timestamp_ms: Some(5.0),
                    turns: vec![TurnTrace {
                        input_length: 128,
                        max_output_tokens: 2,
                        hash_ids: vec![31, 32],
                        delay_after_previous_ms: 0.0,
                    }],
                },
            ],
        }
    }

    fn transition_index(transitions: &[DisaggTransition], needle: DisaggTransition) -> usize {
        transitions
            .iter()
            .position(|transition| *transition == needle)
            .unwrap()
    }

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
    #[test]
    fn test_derive_stage_router_configs_force_required_overrides() {
        let config = KvRouterConfig {
            overlap_score_weight: 2.0,
            router_track_active_blocks: true,
            router_assume_kv_reuse: true,
            router_track_prefill_tokens: true,
            ..KvRouterConfig::default()
        };
        let args = staged_args(WorkerType::Prefill, 1.0);
        let prefill = derive_prefill_router_config(&args, Some(config.clone()));
        let decode = derive_decode_router_config(&args, Some(config));

        assert!(!prefill.router_track_active_blocks);
        assert_eq!(decode.overlap_score_weight, 0.0);
        assert!(!decode.router_assume_kv_reuse);
        assert!(!decode.router_track_prefill_tokens);
    }

    #[rstest::rstest]
    #[case(ReplayRouterMode::RoundRobin)]
    #[case(ReplayRouterMode::KvRouter)]
    fn test_trace_smoke_reports_decode_only_tokens(#[case] router_mode: ReplayRouterMode) {
        let config = disagg_config();
        let requests = vec![request(1, 128, 3, 5.0)];

        let router_config = (router_mode == ReplayRouterMode::KvRouter).then(router_config);
        let (collector, stats) =
            run_trace_collect(&config, requests, router_config, 1.0, router_mode);
        let snapshot = collector.snapshot(Uuid::from_u128(1)).unwrap();
        let report = collector.finish();

        assert_eq!(snapshot.arrival_time_ms, 0.0);
        assert!(snapshot.first_admit_ms.is_some());
        assert!(snapshot.first_token_ms.is_some());
        assert_eq!(snapshot.output_length, 3);
        assert_eq!(report.request_counts.completed_requests, 1);
1198
        assert_eq!(report.request_counts.total_output_tokens, 3);
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
        assert_eq!(
            stats.request_snapshots[&Uuid::from_u128(1)].phase,
            DisaggPhase::Done
        );
    }

    #[rstest::rstest]
    #[case(ReplayRouterMode::RoundRobin)]
    #[case(ReplayRouterMode::KvRouter)]
    fn test_prefill_and_decode_use_separate_worker_pools(#[case] router_mode: ReplayRouterMode) {
        let config = disagg_config();
        let requests = vec![request(1, 128, 2, 0.0), request(2, 128, 2, 10.0)];

        let router_config = (router_mode == ReplayRouterMode::KvRouter).then(router_config);
        let (_, stats) = run_trace_collect(&config, requests, router_config, 1.0, router_mode);

        for uuid in [Uuid::from_u128(1), Uuid::from_u128(2)] {
            assert!(stats.prefill_assignments.contains_key(&uuid));
            assert!(stats.decode_assignments.contains_key(&uuid));
1218
1219
1220
1221
1222
1223
1224
1225
1226
            assert_eq!(stats.request_snapshots[&uuid].phase, DisaggPhase::Done);
            assert_eq!(
                stats.request_snapshots[&uuid].prefill_worker_idx,
                Some(stats.prefill_assignments[&uuid])
            );
            assert_eq!(
                stats.request_snapshots[&uuid].decode_worker_idx,
                Some(stats.decode_assignments[&uuid])
            );
1227
1228
1229
1230
1231
1232
1233
        }
    }

    #[test]
    fn test_prefill_overlap_prefers_same_worker_after_handoff_delay() {
        let requests = vec![request(1, 128, 2, 0.0), request(2, 128, 2, 100.0)];

1234
1235
1236
1237
1238
1239
1240
1241
1242
        let cases = [(disagg_config(), true), (sglang_disagg_config(), false)];
        for (config, expect_same_worker) in cases {
            let (_, stats) = run_trace_collect(
                &config,
                requests.clone(),
                Some(router_config()),
                1.0,
                ReplayRouterMode::KvRouter,
            );
1243

1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
            if expect_same_worker {
                assert_eq!(
                    stats.prefill_assignments[&Uuid::from_u128(1)],
                    stats.prefill_assignments[&Uuid::from_u128(2)],
                );
            } else {
                for uuid in [Uuid::from_u128(1), Uuid::from_u128(2)] {
                    assert!(stats.prefill_assignments.contains_key(&uuid));
                    assert!(stats.decode_assignments.contains_key(&uuid));
                    assert_eq!(stats.request_snapshots[&uuid].phase, DisaggPhase::Done);
                }
            }
        }
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
    #[test]
    fn test_hidden_prefill_reports_reused_tokens_even_when_decode_prefix_caching_is_disabled() {
        let mut config = disagg_config();
        config.num_prefill_workers = 1;
        config.num_decode_workers = 1;
        config.decode_args.enable_prefix_caching = false;

        let requests = vec![request(1, 128, 2, 0.0), request(2, 128, 2, 100.0)];
        let (collector, _) = run_trace_collect(
            &config,
            requests,
            Some(router_config()),
            1.0,
            ReplayRouterMode::KvRouter,
        );

        let request_2 = collector.snapshot(Uuid::from_u128(2)).unwrap();
        let report = collector.finish();

        assert!(request_2.reused_input_tokens > 0);
        assert!(report.prefix_cache_reused_ratio > 0.0);
    }

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
    #[rstest::rstest]
    #[case(ReplayRouterMode::RoundRobin)]
    #[case(ReplayRouterMode::KvRouter)]
    fn test_concurrency_backfill_waits_for_decode_completion(
        #[case] router_mode: ReplayRouterMode,
    ) {
        let config = disagg_config();
        let requests = vec![
            DirectRequest {
                tokens: vec![1; 128],
                max_output_tokens: 3,
                uuid: Some(Uuid::from_u128(1)),
                dp_rank: 0,
                arrival_timestamp_ms: None,
            },
            DirectRequest {
                tokens: vec![2; 128],
                max_output_tokens: 3,
                uuid: Some(Uuid::from_u128(2)),
                dp_rank: 0,
                arrival_timestamp_ms: None,
            },
        ];

        let router_config = (router_mode == ReplayRouterMode::KvRouter).then(router_config);
1307
        let (collector, stats) =
1308
1309
1310
1311
1312
1313
            run_concurrency_collect(&config, requests, router_config, 1, router_mode);
        let first = collector.snapshot(Uuid::from_u128(1)).unwrap();
        let second = collector.snapshot(Uuid::from_u128(2)).unwrap();

        assert_eq!(first.arrival_time_ms, 0.0);
        assert_eq!(second.arrival_time_ms, first.last_token_ms.unwrap());
1314
1315
1316
1317
1318
1319
1320
1321
        assert_eq!(
            stats.request_snapshots[&Uuid::from_u128(1)].phase,
            DisaggPhase::Done
        );
        assert_eq!(
            stats.request_snapshots[&Uuid::from_u128(2)].phase,
            DisaggPhase::Done
        );
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
    }

    #[test]
    fn test_prefill_completion_marks_and_frees_before_decode_handoff() {
        let config = disagg_config();
        let requests = vec![request(1, 128, 2, 0.0)];

        let (_, stats) = run_trace_collect(
            &config,
            requests,
            Some(router_config()),
            1.0,
            ReplayRouterMode::KvRouter,
        );

        assert_eq!(stats.prefill_marked_count, 1);
1338
1339
        assert_eq!(stats.prefill_router_freed_count, 1);
        assert_eq!(stats.decode_router_freed_count, 1);
1340
1341
1342
1343
1344
1345
1346
1347
        let transitions = &stats.transition_log;
        let uuid = Uuid::from_u128(1);
        let mark_idx =
            transition_index(transitions, DisaggTransition::PrefillMarkCompleted { uuid });
        let free_idx = transition_index(transitions, DisaggTransition::PrefillFree { uuid });
        let enqueue_idx = transition_index(transitions, DisaggTransition::DecodeEnqueued { uuid });
        assert!(mark_idx < free_idx);
        assert!(free_idx < enqueue_idx);
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
    }

    #[test]
    fn test_handoff_delay_increases_decode_visible_ttft() {
        let requests = vec![request(1, 128, 2, 0.0)];

        let (baseline_collector, _) = run_trace_collect(
            &disagg_config(),
            requests.clone(),
            None,
            1.0,
            ReplayRouterMode::RoundRobin,
        );
1361
        let (delayed_collector, delayed_stats) = run_trace_collect(
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
            &disagg_config_with_handoff_delay(),
            requests,
            None,
            1.0,
            ReplayRouterMode::RoundRobin,
        );

        let baseline = baseline_collector.snapshot(Uuid::from_u128(1)).unwrap();
        let delayed = delayed_collector.snapshot(Uuid::from_u128(1)).unwrap();
        let baseline_ttft = baseline.first_token_ms.unwrap() - baseline.arrival_time_ms;
        let delayed_ttft = delayed.first_token_ms.unwrap() - delayed.arrival_time_ms;

        assert!(
            delayed_ttft >= baseline_ttft + 120.0,
            "expected delayed TTFT to include roughly 128ms of handoff delay, baseline={baseline_ttft}, delayed={delayed_ttft}"
        );
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
        let uuid = Uuid::from_u128(1);
        let queued_idx = transition_index(
            &delayed_stats.transition_log,
            DisaggTransition::DecodeHandoffQueued { uuid },
        );
        let enqueued_idx = transition_index(
            &delayed_stats.transition_log,
            DisaggTransition::DecodeEnqueued { uuid },
        );
        assert!(queued_idx < enqueued_idx);
        assert!(delayed_stats.handoff_ms[&uuid] >= 120.0);
    }

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
    #[test]
    fn test_apply_scaling_drains_prefill_router_pending_immediately() {
        let config = scaling_test_disagg_config();
        let mut runtime = DisaggRuntime::new(
            &config,
            Some(planner_router_config()),
            None,
            VecDeque::from([request(1, 64, 8, 0.0), request(2, 64, 8, 0.0)]),
            ReplayMode::Trace,
            ReplayRouterMode::KvRouter,
        )
        .unwrap();

        runtime.advance_to(0.0).unwrap();
        assert_eq!(
            runtime.state(Uuid::from_u128(2)).unwrap().phase,
            DisaggPhase::QueuedPrefill
        );

        runtime.apply_scaling(2, 1).unwrap();

        assert_eq!(
            runtime.state(Uuid::from_u128(2)).unwrap().phase,
            DisaggPhase::RunningPrefill
        );
        assert_eq!(runtime.stats.prefill_assignments[&Uuid::from_u128(2)], 1);
    }

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
    #[test]
    fn test_trace_workload_follow_up_turn_arrives_after_completion_plus_delay() {
        let (collector, _) = run_trace_workload_collect(
            &disagg_config(),
            multiturn_trace(),
            None,
            ReplayRouterMode::RoundRobin,
        );
        let snapshots = collector.snapshots();
        let first_turn = snapshots
            .iter()
            .find(|snapshot| snapshot.input_length == 64)
            .unwrap();
        let second_turn = snapshots
            .iter()
            .find(|snapshot| snapshot.input_length == 192)
            .unwrap();
        let session_b = snapshots
            .iter()
            .find(|snapshot| snapshot.input_length == 128)
            .unwrap();

        assert_eq!(first_turn.arrival_time_ms, 0.0);
        assert_eq!(session_b.arrival_time_ms, 5.0);
        assert!(
            second_turn.arrival_time_ms >= first_turn.last_token_ms.unwrap() + 10.0,
            "follow-up turn should unlock after completion plus delay"
        );
    }

    #[test]
    fn test_concurrency_workload_delayed_follow_up_does_not_bypass_other_ready_sessions() {
        let (collector, _) = run_concurrency_workload_collect(
            &disagg_config(),
            multiturn_trace(),
            None,
            1,
            ReplayRouterMode::RoundRobin,
        );
        let mut input_lengths = collector
            .snapshots()
            .into_iter()
            .map(|snapshot| (snapshot.arrival_time_ms, snapshot.input_length))
            .collect::<Vec<_>>();
        input_lengths.sort_by(|left, right| left.0.total_cmp(&right.0));

        assert_eq!(
            input_lengths
                .into_iter()
                .map(|(_, input_length)| input_length)
                .collect::<Vec<_>>(),
            vec![64, 128, 192]
        );
1472
1473
    }
}