sequence.rs 46 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! KV Cache Sequence Management for LLM Inference
//!
//! This module provides efficient management of token sequences and their associated KV cache blocks
//! for distributed LLM inference. It implements a shared block system where multiple requests can
//! reuse the same KV cache blocks for common token prefixes, significantly reducing memory usage.
//!
//! # Key Components
//!
//! - [`ActiveSequences`]: Single-threaded sequence manager that tracks active requests and their
//!   token sequences, managing shared KV cache blocks efficiently.
//!
//! - [`ActiveSequencesMultiWorker`]: Multi-threaded extension that distributes sequence management
//!   across multiple worker threads, enabling parallel processing of requests while maintaining
//!   consistency.
//!
//! # Architecture
//!
//! The system uses a block-based approach where token sequences are divided into fixed-size blocks.
//! Each block is identified by a hash of its contents, allowing for deduplication when multiple
//! requests share common prefixes (e.g., system prompts, few-shot examples).

25
use crate::kv_router::indexer::OverlapScores;
26
use crate::tokens::SequenceHash;
27
28
use anyhow::Result;
use dashmap::DashMap;
29
use derive_getters::Getters;
30
31
use dynamo_runtime::component::Component;
use dynamo_runtime::traits::DistributedRuntimeProvider;
32
use dynamo_runtime::traits::events::{EventPublisher, EventSubscriber};
33
use futures::StreamExt;
34
use std::collections::{HashMap, HashSet};
35
use std::rc::{Rc, Weak};
36
use std::sync::Arc;
37
38
use std::time::Duration;
use tokio::time::Instant;
39
40
use uuid::Uuid;

Yan Ru Pei's avatar
Yan Ru Pei committed
41
use super::protocols::{ActiveSequenceEvent, ActiveSequenceEventData, WorkerWithDpRank};
42
use crate::kv_router::ACTIVE_SEQUENCES_SUBJECT;
Yan Ru Pei's avatar
Yan Ru Pei committed
43
use crate::local_model::runtime_config::ModelRuntimeConfig;
44
use dynamo_runtime::CancellationToken;
45

46
47
48
/// Duration after which stale requests are forcibly expired (5 minutes)
const EXPIRY_DURATION: Duration = Duration::from_secs(300);

49
50
51
52
53
54
// TODO: use the common request_id if it exists in the repo
pub type RequestId = String;

/// A multi-request sequence manager that handles multiple active sequences with shared KV cache
#[derive(Debug, Getters)]
pub struct ActiveSequences {
55
    active_seqs: HashMap<RequestId, Vec<(SequenceHash, Rc<()>)>>,
56

57
58
    prefill_tokens: HashMap<RequestId, usize>,

59
    unique_blocks: HashMap<SequenceHash, Weak<()>>,
60
61
62
63

    #[getter(copy)]
    block_size: usize,

64
65
    #[getter(copy)]
    active_tokens: usize,
66
67
68
69
70
71

    /// Timer for when to force expiry of stale requests
    expiry_timer: Instant,

    /// Set of request IDs to check for expiry
    expiry_requests: HashSet<RequestId>,
72
73
74
75
76
77
78
79
80
81
}

impl ActiveSequences {
    /// Create a new SharedSequenceManager instance
    pub fn new(block_size: usize) -> Self {
        // TODO: make this not a hard req
        assert!(block_size > 1, "block_size must be greater than 1");

        Self {
            active_seqs: HashMap::new(),
82
            prefill_tokens: HashMap::new(),
83
84
            unique_blocks: HashMap::new(),
            block_size,
85
            active_tokens: 0,
86
87
            expiry_timer: Instant::now() + EXPIRY_DURATION,
            expiry_requests: HashSet::new(),
88
89
90
        }
    }

91
92
93
94
95
    fn touch_block(&mut self, block: &SequenceHash) -> Rc<()> {
        if let Some(weak) = self.unique_blocks.get(block)
            && let Some(rc) = weak.upgrade()
        {
            return rc;
96
97
        }

98
99
100
101
        let rc = Rc::new(());
        self.unique_blocks.insert(*block, Rc::downgrade(&rc));
        rc
    }
102

103
104
105
106
    fn try_remove_block(&mut self, block: &SequenceHash) {
        if let Some(weak) = self.unique_blocks.get(block)
            && weak.strong_count() == 0
        {
107
108
109
110
            self.unique_blocks.remove(block);
        }
    }

111
112
113
114
    pub fn active_blocks(&self) -> usize {
        self.unique_blocks.len()
    }

115
    /// Add a new request with its initial tokens
116
    /// Returns the set of expired request IDs that were removed during cleanup
117
118
119
    pub fn add_request(
        &mut self,
        request_id: RequestId,
120
        token_sequence: Option<Vec<SequenceHash>>,
121
        isl: usize,
122
        overlap: u32,
123
    ) -> HashSet<RequestId> {
124
        // Check for double-add and log error, returning early
125
        if self.active_seqs.contains_key(&request_id) {
126
127
            tracing::error!("Request {request_id} is already active. Ignoring duplicate add.");
            return HashSet::new();
128
129
        }

130
131
132
        // Lazily check and clean up expired requests, capturing removed IDs
        let removed_requests = self.force_expiry();

133
        let prefill_tokens = self.new_tokens(isl, overlap);
134
135
136
137
        self.prefill_tokens
            .insert(request_id.clone(), prefill_tokens);
        self.active_tokens += prefill_tokens;

138
        if let Some(sequence) = token_sequence {
139
140
141
142
143
144
            let sequence_with_refs: Vec<(SequenceHash, Rc<()>)> = sequence
                .iter()
                .map(|block| (*block, self.touch_block(block)))
                .collect();
            self.active_seqs
                .insert(request_id.clone(), sequence_with_refs);
145
146
147
        } else {
            // dummy empty sequence
            self.active_seqs.insert(request_id.clone(), Vec::new());
148
149
        }

150
        removed_requests
151
152
    }

153
154
155
156
157
    /// Mark prefill as completed for a request, removing it from prefill_tokens tracking
    pub fn mark_prefill_completed(&mut self, request_id: &RequestId) {
        if let Some(tokens) = self.prefill_tokens.remove(request_id) {
            self.active_tokens = self
                .active_tokens
158
                .checked_sub(tokens)
159
160
161
162
163
                .expect("active_tokens underflow");
        }
    }

    pub fn new_tokens(&self, isl: usize, overlap: u32) -> usize {
164
165
166
167
168
169
170
171
172
        let cached_tokens = (overlap as usize) * self.block_size;
        isl.checked_sub(cached_tokens)
            .unwrap_or_else(|| {
                tracing::error!(
                    "prefill_tokens < 0 with ISL {isl} < cached_tokens {cached_tokens} (overlap {overlap} * block_size {}), returning 0",
                    self.block_size
                );
                0
            })
173
174
175
176
    }

    pub fn potential_blocks_and_tokens(
        &self,
177
        token_sequence: Option<&[SequenceHash]>,
178
        isl: usize,
179
180
        overlap: u32,
    ) -> (usize, usize) {
181
        let potential_blocks = if let Some(token_seq) = token_sequence {
182
            self.new_blocks(token_seq) + self.active_blocks()
183
        } else {
184
            self.active_blocks()
185
        };
186
        let potential_tokens = self.new_tokens(isl, overlap) + self.active_tokens;
187
188
189
        (potential_blocks, potential_tokens)
    }

190
    /// Match a request against existing blocks and return the number of new blocks that would be added
191
192
    pub fn new_blocks(&self, token_sequence: &[SequenceHash]) -> usize {
        token_sequence
193
194
195
196
197
198
199
            .iter()
            .filter(|block| !self.unique_blocks.contains_key(block))
            .count()
    }

    /// Return the total number of blocks that would be used if the token sequence was added
    /// This is the sum of new blocks that would be added plus the current active blocks
200
    pub fn potential_blocks(&self, token_sequence: &[SequenceHash]) -> usize {
201
        self.new_blocks(token_sequence) + self.active_blocks()
202
203
204
205
    }

    /// Free all blocks associated with a request
    pub fn free(&mut self, request_id: &RequestId) -> usize {
206
        self.mark_prefill_completed(request_id);
207

208
209
        self.expiry_requests.remove(request_id);

210
211
212
213
214
        // Remove from active_seqs and get the token sequence
        let token_seq = match self.active_seqs.remove(request_id) {
            Some(seq) => seq,
            None => {
                tracing::warn!("Trying to free non-existent request {request_id}");
215
                return self.active_blocks();
216
            }
217
218
        };

219
220
221
222
        // Drop each Rc reference, then clean up the corresponding weak reference
        for (block_hash, rc) in token_seq {
            drop(rc);
            self.try_remove_block(&block_hash);
223
224
        }

225
        self.active_blocks()
226
    }
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249

    /// Force expiry of stale requests if the timer has elapsed
    /// Returns the set of expired request IDs that were removed
    pub fn force_expiry(&mut self) -> HashSet<RequestId> {
        let now = Instant::now();

        // Early return if timer hasn't expired yet
        if now < self.expiry_timer {
            return HashSet::new();
        }

        // Process expired requests - drain to avoid clone
        let expired_requests: HashSet<RequestId> = self.expiry_requests.drain().collect();
        for request_id in &expired_requests {
            tracing::warn!("Force expiring stale request: {}", request_id);
            self.free(request_id);
        }

        self.expiry_timer = now + EXPIRY_DURATION;
        self.expiry_requests = self.active_seqs.keys().cloned().collect();

        expired_requests
    }
250
251
252
253
254
}

enum UpdateSequences {
    AddRequest {
        request_id: RequestId,
255
        token_sequence: Option<Vec<SequenceHash>>,
256
        isl: usize,
257
        overlap: u32,
258
        resp_tx: tokio::sync::oneshot::Sender<HashSet<RequestId>>,
259
260
261
262
    },
    Free {
        request_id: RequestId,
    },
263
    MarkPrefillCompleted {
264
265
266
        request_id: RequestId,
    },
    NewBlocks {
267
        token_sequence: Arc<Vec<SequenceHash>>,
268
        resp_tx: tokio::sync::oneshot::Sender<usize>,
269
270
    },
    PotentialBlocks {
271
        token_sequence: Arc<Vec<SequenceHash>>,
272
        resp_tx: tokio::sync::oneshot::Sender<usize>,
273
    },
274
    PotentialBlocksAndTokens {
275
        token_sequence: Option<Arc<Vec<SequenceHash>>>,
276
        isl: usize,
277
        overlap: u32,
278
        resp_tx: tokio::sync::oneshot::Sender<(usize, usize)>,
279
    },
280
    ActiveBlocks {
281
        resp_tx: tokio::sync::oneshot::Sender<usize>,
282
    },
283
    ActiveTokens {
284
        resp_tx: tokio::sync::oneshot::Sender<usize>,
285
    },
286
287
288
289
290
    Shutdown,
}

/// Multi-worker extension of ActiveSequences that distributes requests across multiple threads
pub struct ActiveSequencesMultiWorker {
Yan Ru Pei's avatar
Yan Ru Pei committed
291
292
293
    senders: Arc<DashMap<WorkerWithDpRank, tokio::sync::mpsc::UnboundedSender<UpdateSequences>>>,
    request_to_worker: Arc<DashMap<RequestId, WorkerWithDpRank>>,
    handles: Arc<DashMap<WorkerWithDpRank, std::thread::JoinHandle<()>>>,
294
    block_size: usize,
295
296
297
    component: Component,
    router_id: Uuid,
    replica_sync: bool,
298
299
300
}

impl ActiveSequencesMultiWorker {
301
302
303
    pub fn new(
        component: Component,
        block_size: usize,
304
        workers_with_configs: HashMap<u64, Option<ModelRuntimeConfig>>,
305
        replica_sync: bool,
306
        router_uuid: String,
307
    ) -> Self {
308
309
        assert!(block_size > 1, "block_size must be greater than 1");

310
311
312
        let senders = Arc::new(DashMap::new());
        let handles = Arc::new(DashMap::new());
        let request_to_worker = Arc::new(DashMap::new());
313
314
315
316
317
318
319
320
        let router_id = Uuid::parse_str(&router_uuid).unwrap_or_else(|e| {
            tracing::warn!(
                "Failed to parse router UUID '{}': {}, using new UUID",
                router_uuid,
                e
            );
            Uuid::new_v4()
        });
321

Yan Ru Pei's avatar
Yan Ru Pei committed
322
323
324
325
326
327
328
329
330
331
332
333
        // Expand workers by their dp_rank
        for (worker_id, config) in workers_with_configs {
            let dp_size = config.as_ref().map(|c| c.data_parallel_size).unwrap_or(1);

            for dp_rank in 0..dp_size {
                let worker = WorkerWithDpRank::new(worker_id, dp_rank);
                // Create a child cancellation token from the component's runtime
                let cancel_token = component.drt().runtime().child_token();
                let (sender, handle) = Self::start_worker(block_size, cancel_token);
                senders.insert(worker, sender);
                handles.insert(worker, handle);
            }
334
335
        }

336
337
338
        let multi_worker = Self {
            senders: senders.clone(),
            request_to_worker: request_to_worker.clone(),
339
340
            handles,
            block_size,
341
342
343
344
345
346
347
348
349
350
351
            component: component.clone(),
            router_id,
            replica_sync,
        };

        // Start the subscription loop only if replica_sync is enabled
        if replica_sync {
            let senders_clone = senders.clone();
            let request_to_worker_clone = request_to_worker.clone();
            let component_clone = component.clone();
            let router_id_clone = router_id;
352
            let cancel_token = component.drt().runtime().child_token();
353

354
            tokio::spawn(async move {
355
                // NATS subscription loop
356
357
358
359
360
                if let Err(e) = Self::subscribe_to_events(
                    senders_clone,
                    request_to_worker_clone,
                    component_clone,
                    router_id_clone,
361
                    cancel_token,
362
363
364
365
366
367
                )
                .await
                {
                    tracing::error!("Error in active sequences events subscription: {}", e);
                }
            });
368
        }
369
370

        multi_worker
371
372
    }

373
374
375
    /// Helper method to start a worker task
    fn start_worker(
        block_size: usize,
376
        cancel_token: CancellationToken,
377
378
    ) -> (
        tokio::sync::mpsc::UnboundedSender<UpdateSequences>,
379
        std::thread::JoinHandle<()>,
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
        let (request_tx, request_rx) = tokio::sync::mpsc::unbounded_channel();

        let handle = std::thread::spawn(move || {
            // Create a single-threaded tokio runtime
            let runtime = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .unwrap();

            runtime.block_on(async move {
                let mut active_sequences = ActiveSequences::new(block_size);
                let mut request_rx = request_rx;

                loop {
                    tokio::select! {
                        command = request_rx.recv() => {
                            let Some(command) = command else {
                                break;
                            };

                            match command {
                                UpdateSequences::AddRequest {
                                    request_id,
                                    token_sequence,
                                    isl,
                                    overlap,
                                    resp_tx,
                                } => {
                                    let removed = active_sequences.add_request(request_id, token_sequence, isl, overlap);
                                    let _ = resp_tx.send(removed);
                                }
                                UpdateSequences::Free { request_id } => {
                                    active_sequences.free(&request_id);
                                }
                                UpdateSequences::MarkPrefillCompleted { request_id } => {
                                    active_sequences.mark_prefill_completed(&request_id);
                                }
                                UpdateSequences::NewBlocks {
                                    token_sequence,
                                    resp_tx,
                                } => {
                                    let new_blocks = active_sequences.new_blocks(&token_sequence);
                                    let _ = resp_tx.send(new_blocks);
                                }
                                UpdateSequences::PotentialBlocks {
                                    token_sequence,
                                    resp_tx,
                                } => {
                                    let potential_blocks = active_sequences.potential_blocks(&token_sequence);
                                    let _ = resp_tx.send(potential_blocks);
                                }
                                UpdateSequences::PotentialBlocksAndTokens {
                                    token_sequence,
                                    isl,
                                    overlap,
                                    resp_tx,
                                } => {
                                    let potential_tokens = active_sequences.potential_blocks_and_tokens(
                                        token_sequence.as_ref().map(|v| v.as_slice()),
440
441
                                        isl,
                                        overlap,
442
443
444
445
446
447
448
449
450
451
452
453
454
                                    );
                                    let _ = resp_tx.send(potential_tokens);
                                }
                                UpdateSequences::ActiveBlocks { resp_tx } => {
                                    let active_blocks = active_sequences.active_blocks();
                                    let _ = resp_tx.send(active_blocks);
                                }
                                UpdateSequences::ActiveTokens { resp_tx } => {
                                    let active_tokens = active_sequences.active_tokens();
                                    let _ = resp_tx.send(active_tokens);
                                }
                                UpdateSequences::Shutdown => {
                                    break;
455
456
457
                                }
                            }
                        }
458
459
460
461
462
                        // Handle cancellation
                        _ = cancel_token.cancelled() => {
                            tracing::debug!("Worker task cancelled");
                            break;
                        }
463
                    }
464
                }
465
466
467
            });

            tracing::debug!("ActiveSequences worker task completed");
468
469
470
471
472
473
474
        });

        (request_tx, handle)
    }

    /// Background task to subscribe to active sequence events and update all workers
    async fn subscribe_to_events(
Yan Ru Pei's avatar
Yan Ru Pei committed
475
476
477
478
        senders: Arc<
            DashMap<WorkerWithDpRank, tokio::sync::mpsc::UnboundedSender<UpdateSequences>>,
        >,
        request_to_worker: Arc<DashMap<RequestId, WorkerWithDpRank>>,
479
480
        component: Component,
        router_id: Uuid,
481
        cancel_token: CancellationToken,
482
483
484
485
486
    ) -> Result<()> {
        let mut subscriber = component
            .subscribe_with_type::<ActiveSequenceEvent>(ACTIVE_SEQUENCES_SUBJECT)
            .await?;

487
488
489
490
491
492
493
494
        loop {
            tokio::select! {
                // Handle incoming events
                result = subscriber.next() => {
                    let Some(result) = result else {
                        // Stream ended
                        break;
                    };
495

496
497
498
499
                    let Ok(event) = result else {
                        tracing::error!(
                            "Error receiving active sequence event: {}",
                            result.unwrap_err()
500
                        );
501
502
503
504
505
506
                        continue;
                    };

                    // Skip events emitted by itself
                    if event.router_id == router_id {
                        continue;
507
                    }
508
509
510
511
512
513
514

                    match &event.data {
                        ActiveSequenceEventData::AddRequest {
                            token_sequence,
                            isl,
                            overlap,
                        } => {
Yan Ru Pei's avatar
Yan Ru Pei committed
515
                            request_to_worker.insert(event.request_id.clone(), event.worker);
516

Yan Ru Pei's avatar
Yan Ru Pei committed
517
                            if let Some(sender) = senders.get(&event.worker) {
518
519
520
521
522
523
524
525
526
527
528
                                // For replicated events, we create a dummy response channel since we don't need to handle expired requests
                                let (resp_tx, _) = tokio::sync::oneshot::channel();
                                let _ = sender.send(UpdateSequences::AddRequest {
                                    request_id: event.request_id.clone(),
                                    token_sequence: token_sequence.clone(),
                                    isl: *isl,
                                    overlap: *overlap,
                                    resp_tx,
                                });
                            } else {
                                tracing::warn!(
Yan Ru Pei's avatar
Yan Ru Pei committed
529
530
                                    "Worker {:?} not found, cannot process AddRequest",
                                    event.worker
531
532
533
534
                                );
                            }
                        }
                        ActiveSequenceEventData::Free => {
Yan Ru Pei's avatar
Yan Ru Pei committed
535
536
                            if let Some((_, worker)) = request_to_worker.remove(&event.request_id)
                                && let Some(sender) = senders.get(&worker)
537
538
539
540
541
542
543
                            {
                                let _ = sender.send(UpdateSequences::Free {
                                    request_id: event.request_id.clone(),
                                });
                            }
                        }
                        ActiveSequenceEventData::MarkPrefillCompleted => {
Yan Ru Pei's avatar
Yan Ru Pei committed
544
545
                            if let Some(worker) = request_to_worker.get(&event.request_id)
                                && let Some(sender) = senders.get(&*worker)
546
547
548
549
550
551
                            {
                                let _ = sender.send(UpdateSequences::MarkPrefillCompleted {
                                    request_id: event.request_id.clone(),
                                });
                            }
                        }
552
                    }
553
                }
554
555
556
557
                // Handle cancellation
                _ = cancel_token.cancelled() => {
                    tracing::debug!("Subscription task cancelled");
                    break;
558
559
                }
            }
560
        }
561

562
        Ok(())
563
564
565
    }

    /// Update the set of workers, adding and removing as needed
Yan Ru Pei's avatar
Yan Ru Pei committed
566
567
    pub fn update_workers(
        &self,
568
        new_workers_with_configs: HashMap<u64, Option<ModelRuntimeConfig>>,
Yan Ru Pei's avatar
Yan Ru Pei committed
569
570
    ) {
        let current_workers: HashSet<WorkerWithDpRank> =
571
            self.senders.iter().map(|entry| *entry.key()).collect();
572

Yan Ru Pei's avatar
Yan Ru Pei committed
573
574
575
576
577
578
579
580
581
582
583
        // Expand new workers by their dp_rank
        let mut new_workers: HashSet<WorkerWithDpRank> = HashSet::new();
        for (worker_id, config) in &new_workers_with_configs {
            let dp_size = config.as_ref().map(|c| c.data_parallel_size).unwrap_or(1);

            for dp_rank in 0..dp_size {
                new_workers.insert(WorkerWithDpRank::new(*worker_id, dp_rank));
            }
        }

        let workers_to_remove: Vec<WorkerWithDpRank> =
584
            current_workers.difference(&new_workers).copied().collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
585
        let workers_to_add: Vec<WorkerWithDpRank> =
586
587
            new_workers.difference(&current_workers).copied().collect();

Yan Ru Pei's avatar
Yan Ru Pei committed
588
589
590
        // Remove workers (this will naturally remove all dp ranks for a worker_id)
        for worker in &workers_to_remove {
            tracing::warn!("Removing worker {:?}", worker);
591
592

            // Send shutdown command to the worker
Yan Ru Pei's avatar
Yan Ru Pei committed
593
            if let Some((_, sender)) = self.senders.remove(worker) {
594
595
                let _ = sender.send(UpdateSequences::Shutdown);
            }
Yan Ru Pei's avatar
Yan Ru Pei committed
596
            self.handles.remove(worker);
597
598
599

            // Clean up request_to_worker mappings for this worker
            self.request_to_worker
Yan Ru Pei's avatar
Yan Ru Pei committed
600
                .retain(|_request_id, mapped_worker| mapped_worker != worker);
601
602
603
        }

        // Add new workers
Yan Ru Pei's avatar
Yan Ru Pei committed
604
605
        for worker in &workers_to_add {
            tracing::warn!("Adding worker {:?}", worker);
606

607
608
609
610
            let (sender, handle) = Self::start_worker(
                self.block_size,
                self.component.drt().runtime().child_token(),
            );
Yan Ru Pei's avatar
Yan Ru Pei committed
611
612
            self.senders.insert(*worker, sender);
            self.handles.insert(*worker, handle);
613
614
615
        }
    }

616
617
    pub async fn add_request(
        &self,
618
        request_id: RequestId,
619
        token_sequence: Option<Vec<SequenceHash>>,
620
        isl: usize,
621
        overlap: u32,
Yan Ru Pei's avatar
Yan Ru Pei committed
622
        worker: WorkerWithDpRank,
623
    ) -> Result<()> {
Yan Ru Pei's avatar
Yan Ru Pei committed
624
625
        if !self.senders.contains_key(&worker) {
            return Err(anyhow::anyhow!("Worker {:?} not found", worker));
626
627
        }

628
629
630
        // Create response channel
        let (resp_tx, resp_rx) = tokio::sync::oneshot::channel();

631
632
633
634
        // Publish event only if replica_sync is enabled
        if self.replica_sync {
            let event = ActiveSequenceEvent {
                request_id: request_id.clone(),
Yan Ru Pei's avatar
Yan Ru Pei committed
635
                worker,
636
637
638
639
640
641
642
643
644
645
                data: ActiveSequenceEventData::AddRequest {
                    token_sequence: token_sequence.clone(),
                    isl,
                    overlap,
                },
                router_id: self.router_id,
            };
            self.component
                .publish(ACTIVE_SEQUENCES_SUBJECT, &event)
                .await?;
646
647
        }

Yan Ru Pei's avatar
Yan Ru Pei committed
648
649
        // Update local state with full WorkerWithDpRank
        self.request_to_worker.insert(request_id.clone(), worker);
650

651
        self.senders
Yan Ru Pei's avatar
Yan Ru Pei committed
652
            .get(&worker)
653
            .unwrap()
654
655
656
            .send(UpdateSequences::AddRequest {
                request_id,
                token_sequence,
657
                isl,
658
                overlap,
659
                resp_tx,
660
            })
661
662
            .map_err(|_| anyhow::anyhow!("Failed to send add_request command to worker"))?;

663
664
665
666
667
668
669
670
671
672
        // Wait for response and handle removed requests
        let removed_requests = resp_rx
            .await
            .map_err(|_| anyhow::anyhow!("Failed to receive response from worker"))?;

        // Remove expired requests from request_to_worker mapping
        for expired_id in &removed_requests {
            self.request_to_worker.remove(expired_id);
        }

673
        Ok(())
674
675
    }

676
    pub async fn free(&self, request_id: &RequestId) -> Result<()> {
Yan Ru Pei's avatar
Yan Ru Pei committed
677
        let worker = self
678
679
            .request_to_worker
            .get(request_id)
680
681
            .map(|entry| *entry)
            .ok_or_else(|| anyhow::anyhow!("Request ID not found in request_to_worker mapping"))?;
682

683
684
685
686
        // Publish event only if replica_sync is enabled
        if self.replica_sync {
            let event = ActiveSequenceEvent {
                request_id: request_id.clone(),
Yan Ru Pei's avatar
Yan Ru Pei committed
687
                worker,
688
689
690
691
692
693
694
695
696
697
                data: ActiveSequenceEventData::Free,
                router_id: self.router_id,
            };
            self.component
                .publish(ACTIVE_SEQUENCES_SUBJECT, &event)
                .await?;
        }

        // Update local state
        self.senders
Yan Ru Pei's avatar
Yan Ru Pei committed
698
            .get(&worker)
699
            .unwrap()
700
701
702
            .send(UpdateSequences::Free {
                request_id: request_id.clone(),
            })
703
            .map_err(|_| anyhow::anyhow!("Failed to send free command to worker"))?;
704
705

        self.request_to_worker.remove(request_id);
706
707

        Ok(())
708
709
    }

710
    /// Mark prefill as completed for a request
711
    pub async fn mark_prefill_completed(&self, request_id: &RequestId) -> Result<()> {
Yan Ru Pei's avatar
Yan Ru Pei committed
712
        let worker = self
713
714
            .request_to_worker
            .get(request_id)
715
716
717
718
719
720
721
            .map(|entry| *entry)
            .ok_or_else(|| anyhow::anyhow!("Request ID not found in request_to_worker mapping"))?;

        // Publish event only if replica_sync is enabled
        if self.replica_sync {
            let event = ActiveSequenceEvent {
                request_id: request_id.clone(),
Yan Ru Pei's avatar
Yan Ru Pei committed
722
                worker,
723
724
725
726
727
728
729
                data: ActiveSequenceEventData::MarkPrefillCompleted,
                router_id: self.router_id,
            };
            self.component
                .publish(ACTIVE_SEQUENCES_SUBJECT, &event)
                .await?;
        }
730

731
732
        // Update local state
        self.senders
Yan Ru Pei's avatar
Yan Ru Pei committed
733
            .get(&worker)
734
            .unwrap()
735
            .send(UpdateSequences::MarkPrefillCompleted {
736
737
                request_id: request_id.clone(),
            })
738
739
740
741
742
            .map_err(|_| {
                anyhow::anyhow!("Failed to send mark_prefill_completed command to worker")
            })?;

        Ok(())
743
744
745
746
747
748
749
750
    }

    /// Get the number of workers
    pub fn num_workers(&self) -> usize {
        self.senders.len()
    }

    /// Generic method to query all workers with a given command
751
    async fn query_workers<T: Send + 'static>(
752
        &self,
753
        token_sequence: Option<Vec<SequenceHash>>,
754
755
756
757
        command_fn: impl Fn(
            Option<Arc<Vec<SequenceHash>>>,
            tokio::sync::oneshot::Sender<T>,
        ) -> UpdateSequences,
Yan Ru Pei's avatar
Yan Ru Pei committed
758
    ) -> HashMap<WorkerWithDpRank, T> {
759
760
761
762
763
        let mut results = HashMap::new();
        let token_sequence_shared = token_sequence.map(Arc::new);
        let mut receivers = Vec::new();

        // Send queries to all workers in parallel
764
        for entry in self.senders.iter() {
Yan Ru Pei's avatar
Yan Ru Pei committed
765
            let worker = *entry.key();
766
767
            let sender = entry.value();
            let (resp_tx, resp_rx) = tokio::sync::oneshot::channel();
Yan Ru Pei's avatar
Yan Ru Pei committed
768
            receivers.push((worker, resp_rx));
769
            if let Err(e) = sender.send(command_fn(token_sequence_shared.clone(), resp_tx)) {
Yan Ru Pei's avatar
Yan Ru Pei committed
770
                tracing::error!("Failed to send command to worker {:?}: {}", worker, e);
771
            }
772
773
774
        }

        // Collect results from all workers
Yan Ru Pei's avatar
Yan Ru Pei committed
775
        for (worker, receiver) in receivers {
776
777
            match tokio::time::timeout(tokio::time::Duration::from_secs(1), receiver).await {
                Ok(Ok(result)) => {
Yan Ru Pei's avatar
Yan Ru Pei committed
778
                    results.insert(worker, result);
779
780
                }
                Ok(Err(_)) => {
Yan Ru Pei's avatar
Yan Ru Pei committed
781
                    tracing::error!("Worker {:?} dropped response channel", worker);
782
783
                }
                Err(_) => {
Yan Ru Pei's avatar
Yan Ru Pei committed
784
                    tracing::error!("Timeout waiting for response from worker {:?}", worker);
785
786
                }
            }
787
788
789
790
791
792
        }

        results
    }

    /// Query all workers for the number of new blocks that would be added by a token sequence
Yan Ru Pei's avatar
Yan Ru Pei committed
793
794
795
796
    pub async fn new_blocks(
        &self,
        token_sequence: Vec<SequenceHash>,
    ) -> HashMap<WorkerWithDpRank, usize> {
797
798
799
800
801
802
803
        self.query_workers(Some(token_sequence), |ts, resp_tx| match ts {
            Some(ts) => UpdateSequences::NewBlocks {
                token_sequence: ts,
                resp_tx,
            },
            None => unreachable!("token_sequence should always be Some for new_blocks"),
        })
804
        .await
805
806
807
    }

    /// Query all workers for the total number of blocks (new + active) that would be used by a token sequence
808
809
810
    pub async fn potential_blocks(
        &self,
        token_sequence: Vec<SequenceHash>,
Yan Ru Pei's avatar
Yan Ru Pei committed
811
    ) -> HashMap<WorkerWithDpRank, usize> {
812
813
814
815
816
817
818
        self.query_workers(Some(token_sequence), |ts, resp_tx| match ts {
            Some(ts) => UpdateSequences::PotentialBlocks {
                token_sequence: ts,
                resp_tx,
            },
            None => unreachable!("token_sequence should always be Some for potential_blocks"),
        })
819
        .await
820
821
    }

822
    /// Query all workers for the potential tokens (new + active) that would be used by a token sequence with overlap
823
    pub async fn potential_blocks_and_tokens(
824
        &self,
825
        token_sequence: Option<Vec<SequenceHash>>,
826
        isl: usize,
827
        overlaps: OverlapScores,
Yan Ru Pei's avatar
Yan Ru Pei committed
828
829
830
831
    ) -> (
        HashMap<WorkerWithDpRank, usize>,
        HashMap<WorkerWithDpRank, usize>,
    ) {
832
833
        let mut potential_blocks = HashMap::new();
        let mut potential_tokens = HashMap::new();
834
        let token_sequence_shared = token_sequence.map(Arc::new);
835
836
        let mut receivers = Vec::new();

837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
        // Iterate through all workers, not just those with overlap
        // This ensures we properly account for active tokens/blocks on all workers
        for sender_entry in self.senders.iter() {
            let worker = *sender_entry.key();
            let sender = sender_entry.value();

            // Get overlap for this worker (defaults to 0 if not in overlaps)
            let overlap = *overlaps.scores.get(&worker).unwrap_or(&0);

            let (resp_tx, resp_rx) = tokio::sync::oneshot::channel();
            receivers.push((worker, resp_rx));

            if let Err(e) = sender.send(UpdateSequences::PotentialBlocksAndTokens {
                token_sequence: token_sequence_shared.clone(),
                isl,
                overlap,
                resp_tx,
            }) {
                tracing::error!(
                    "Failed to send potential_tokens command to worker {:?}: {}",
                    worker,
                    e
                );
860
            }
861
862
863
        }

        // Collect results from all workers
Yan Ru Pei's avatar
Yan Ru Pei committed
864
        for (worker, receiver) in receivers {
865
866
            match tokio::time::timeout(tokio::time::Duration::from_secs(1), receiver).await {
                Ok(Ok((blocks, tokens))) => {
Yan Ru Pei's avatar
Yan Ru Pei committed
867
868
                    potential_blocks.insert(worker, blocks);
                    potential_tokens.insert(worker, tokens);
869
870
                }
                Ok(Err(_)) => {
Yan Ru Pei's avatar
Yan Ru Pei committed
871
                    tracing::error!("Worker {:?} dropped response channel", worker);
872
873
                }
                Err(_) => {
Yan Ru Pei's avatar
Yan Ru Pei committed
874
                    tracing::error!("Timeout waiting for response from worker {:?}", worker);
875
876
                }
            }
877
878
879
880
881
        }

        (potential_blocks, potential_tokens)
    }

882
    /// Query all workers for their current number of active blocks
Yan Ru Pei's avatar
Yan Ru Pei committed
883
    pub async fn active_blocks(&self) -> HashMap<WorkerWithDpRank, usize> {
884
        self.query_workers(None, |_, resp_tx| UpdateSequences::ActiveBlocks { resp_tx })
885
            .await
886
    }
887
888

    /// Query all workers for their current number of active tokens
Yan Ru Pei's avatar
Yan Ru Pei committed
889
    pub async fn active_tokens(&self) -> HashMap<WorkerWithDpRank, usize> {
890
        self.query_workers(None, |_, resp_tx| UpdateSequences::ActiveTokens { resp_tx })
891
            .await
892
    }
893
894
895
896
}

impl Drop for ActiveSequencesMultiWorker {
    fn drop(&mut self) {
897
898
899
        // Send shutdown to all workers
        for entry in self.senders.iter() {
            let _ = entry.value().send(UpdateSequences::Shutdown);
900
901
902
903
904
905
906
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
907
    use dynamo_runtime::{DistributedRuntime, Runtime};
908
    use std::sync::Arc;
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
    #[test]
    fn test_active_sequences_shared_blocks() {
        let block_size = 4;
        let mut seq_manager = ActiveSequences::new(block_size);

        seq_manager.add_request("request_1".to_string(), Some(vec![1, 2, 3]), 12, 0);
        assert_eq!(seq_manager.active_blocks(), 3);
        assert_eq!(seq_manager.active_tokens(), 12);

        seq_manager.add_request("request_2".to_string(), Some(vec![4]), 4, 0);
        assert_eq!(seq_manager.active_blocks(), 4);
        assert_eq!(seq_manager.active_tokens(), 16);

        seq_manager.add_request("request_3".to_string(), Some(vec![1, 2, 3, 4]), 16, 4);
        assert_eq!(seq_manager.active_blocks(), 4);
        assert_eq!(seq_manager.active_tokens(), 16);

        seq_manager.free(&"request_2".to_string());
        assert_eq!(seq_manager.active_blocks(), 4);
        assert_eq!(seq_manager.active_tokens(), 12);

        seq_manager.free(&"request_3".to_string());
        assert_eq!(seq_manager.active_blocks(), 3);
        assert_eq!(seq_manager.active_tokens(), 12);

        seq_manager.free(&"request_1".to_string());
        assert_eq!(seq_manager.active_blocks(), 0);
        assert_eq!(seq_manager.active_tokens(), 0);
    }

940
    #[tokio::test]
941
    #[ignore]
942
    async fn test_multi_worker_cross_instance_sync() -> Result<()> {
943
944
945
        // Initialize logging once
        dynamo_runtime::logging::init();

946
947
        let block_size = 4; // arbitrary block size

948
949
950
        // Create runtime and distributed runtime
        let runtime = Runtime::from_current()?;
        let distributed = DistributedRuntime::from_settings(runtime.clone()).await?;
951

952
953
        // Create namespace and shared component for both seq_managers
        let namespace = distributed.namespace("test_cross_instance_sync")?;
954
955
        let mut component = namespace.component("sequences")?;
        component.add_stats_service().await?;
956

Yan Ru Pei's avatar
Yan Ru Pei committed
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
        // Create multi-worker sequence managers with:
        // - Worker 0 with dp_size=2 (dp_ranks 0 and 1)
        // - Worker 1 with dp_size=1 (dp_rank 0)
        // This gives us 3 effective workers total to test dp_rank effect
        // Both seq_managers use the same component to ensure event synchronization works
        let mut workers_with_configs = HashMap::new();

        // Create runtime config for worker 0 with dp_size=2
        let mut config_worker_0 = crate::local_model::runtime_config::ModelRuntimeConfig::new();
        config_worker_0.data_parallel_size = 2;
        workers_with_configs.insert(0, Some(config_worker_0));

        // Create runtime config for worker 1 with dp_size=1 (default)
        let config_worker_1 = crate::local_model::runtime_config::ModelRuntimeConfig::new();
        workers_with_configs.insert(1, Some(config_worker_1));

973
974
975
        let seq_manager_1 = Arc::new(ActiveSequencesMultiWorker::new(
            component.clone(),
            block_size,
Yan Ru Pei's avatar
Yan Ru Pei committed
976
            workers_with_configs.clone(),
977
978
979
980
981
982
            true,
            Uuid::new_v4().to_string(),
        ));
        let seq_manager_2 = Arc::new(ActiveSequencesMultiWorker::new(
            component,
            block_size,
Yan Ru Pei's avatar
Yan Ru Pei committed
983
            workers_with_configs,
984
985
986
987
988
989
990
991
992
            true,
            Uuid::new_v4().to_string(),
        ));

        // Give some time for the subscription loops to start
        tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;

        // PHASE 1: Add requests using both seq_manager_1 and seq_manager_2

Yan Ru Pei's avatar
Yan Ru Pei committed
993
        // Add request_0 to worker 0, dp_rank 0: sequence [0, 1, 2]
994
995
996
997
998
999
        seq_manager_1
            .add_request(
                "request_0".to_string(),
                Some(vec![0, 1, 2]),
                12, // ISL (3 blocks * 4 block_size)
                0,  // no overlap
Yan Ru Pei's avatar
Yan Ru Pei committed
1000
                WorkerWithDpRank::new(0, 0),
1001
1002
            )
            .await?;
1003

Yan Ru Pei's avatar
Yan Ru Pei committed
1004
        // Add request_1 to worker 0, dp_rank 1: sequence [3, 4]
1005
1006
1007
1008
1009
1010
        seq_manager_1
            .add_request(
                "request_1".to_string(),
                Some(vec![3, 4]),
                8, // ISL (2 blocks * 4 block_size)
                0, // no overlap
Yan Ru Pei's avatar
Yan Ru Pei committed
1011
                WorkerWithDpRank::new(0, 1),
1012
1013
            )
            .await?;
1014

Yan Ru Pei's avatar
Yan Ru Pei committed
1015
        // Add request_2 to worker 1, dp_rank 0: sequence [0, 1, 2, 3] using seq_manager_2
1016
1017
1018
1019
1020
1021
        seq_manager_2
            .add_request(
                "request_2".to_string(),
                Some(vec![0, 1, 2, 3]),
                16, // ISL (4 blocks * 4 block_size)
                0,  // no overlap
Yan Ru Pei's avatar
Yan Ru Pei committed
1022
                WorkerWithDpRank::new(1, 0),
1023
1024
            )
            .await?;
1025

1026
1027
        // Give some time for synchronization
        tokio::time::sleep(tokio::time::Duration::from_millis(300)).await;
1028

1029
1030
1031
        // Query seq_manager_1 to verify it sees all requests including request_2 from seq_manager_2
        let blocks_phase1 = seq_manager_1.active_blocks().await;
        let tokens_phase1 = seq_manager_1.active_tokens().await;
1032

Yan Ru Pei's avatar
Yan Ru Pei committed
1033
1034
1035
1036
1037
1038
1039
1040
1041
        // Verify that seq_manager_1 sees all requests including request_2 from seq_manager_2
        // We now have:
        // - Worker 0, dp_rank 0: request_0
        // - Worker 0, dp_rank 1: request_1
        // - Worker 1, dp_rank 0: request_2
        let worker_0_dp0 = WorkerWithDpRank::new(0, 0);
        let worker_0_dp1 = WorkerWithDpRank::new(0, 1);
        let worker_1_dp0 = WorkerWithDpRank::new(1, 0);

1042
        assert_eq!(
Yan Ru Pei's avatar
Yan Ru Pei committed
1043
1044
            blocks_phase1[&worker_0_dp0], 3,
            "Worker 0 dp_rank 0 should have 3 active blocks (from request_0)"
1045
        );
1046
        assert_eq!(
Yan Ru Pei's avatar
Yan Ru Pei committed
1047
1048
            blocks_phase1[&worker_0_dp1], 2,
            "Worker 0 dp_rank 1 should have 2 active blocks (from request_1)"
1049
1050
        );
        assert_eq!(
Yan Ru Pei's avatar
Yan Ru Pei committed
1051
1052
            blocks_phase1[&worker_1_dp0], 4,
            "Worker 1 dp_rank 0 should have 4 active blocks (from request_2 added by seq_manager_2)"
1053
1054
        );
        assert_eq!(
Yan Ru Pei's avatar
Yan Ru Pei committed
1055
1056
            tokens_phase1[&worker_0_dp0], 12,
            "Worker 0 dp_rank 0 should have 12 active tokens"
1057
        );
1058
        assert_eq!(
Yan Ru Pei's avatar
Yan Ru Pei committed
1059
1060
1061
1062
1063
1064
            tokens_phase1[&worker_0_dp1], 8,
            "Worker 0 dp_rank 1 should have 8 active tokens"
        );
        assert_eq!(
            tokens_phase1[&worker_1_dp0], 16,
            "Worker 1 dp_rank 0 should have 16 active tokens (from request_2 added by seq_manager_2)"
1065
        );
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082

        // PHASE 2: Free requests using opposite sequence managers, verify on seq_manager_2

        // Free request_2 (which was added by seq_manager_2) using seq_manager_1
        seq_manager_1.free(&"request_2".to_string()).await?;

        // Free request_0 and request_1 (which were added by seq_manager_1) using seq_manager_2
        seq_manager_2.free(&"request_0".to_string()).await?;
        seq_manager_2.free(&"request_1".to_string()).await?;

        // Give some time for synchronization
        tokio::time::sleep(tokio::time::Duration::from_millis(300)).await;

        // Query seq_manager_2 to verify everything is empty
        let blocks_phase2 = seq_manager_2.active_blocks().await;
        let tokens_phase2 = seq_manager_2.active_tokens().await;

Yan Ru Pei's avatar
Yan Ru Pei committed
1083
1084
1085
1086
1087
1088
1089
1090
        // Verify phase 2 results - everything should be empty for all 3 workers
        let all_workers = vec![
            WorkerWithDpRank::new(0, 0),
            WorkerWithDpRank::new(0, 1),
            WorkerWithDpRank::new(1, 0),
        ];

        for worker in all_workers {
1091
            assert_eq!(
Yan Ru Pei's avatar
Yan Ru Pei committed
1092
1093
1094
                blocks_phase2[&worker], 0,
                "Worker (id={}, dp_rank={}) should have 0 active blocks after all requests freed",
                worker.worker_id, worker.dp_rank
1095
1096
            );
            assert_eq!(
Yan Ru Pei's avatar
Yan Ru Pei committed
1097
1098
1099
                tokens_phase2[&worker], 0,
                "Worker (id={}, dp_rank={}) should have 0 active tokens after all requests freed",
                worker.worker_id, worker.dp_rank
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
            );
        }

        Ok(())
    }

    #[tokio::test]
    #[ignore]
    async fn test_multi_worker_no_token_sequence_sync() -> Result<()> {
        // Initialize logging once
        dynamo_runtime::logging::init();

        let block_size = 4; // arbitrary block size

        // Create runtime and distributed runtime
        let runtime = Runtime::from_current()?;
        let distributed = DistributedRuntime::from_settings(runtime.clone()).await?;

        // Create namespace and shared component for both seq_managers
        let namespace = distributed.namespace("test_no_token_seq_sync")?;
1120
1121
        let mut component = namespace.component("sequences")?;
        component.add_stats_service().await?;
1122
1123
1124

        // Create multi-worker sequence managers with ALL workers [0, 1, 2]
        // Both use the same component to ensure event synchronization works
Yan Ru Pei's avatar
Yan Ru Pei committed
1125
1126
1127
1128
1129
        let mut workers_with_configs = HashMap::new();
        workers_with_configs.insert(0, None);
        workers_with_configs.insert(1, None);
        workers_with_configs.insert(2, None);

1130
1131
1132
        let seq_manager_1 = Arc::new(ActiveSequencesMultiWorker::new(
            component.clone(),
            block_size,
Yan Ru Pei's avatar
Yan Ru Pei committed
1133
            workers_with_configs.clone(),
1134
1135
1136
1137
1138
1139
            true,
            Uuid::new_v4().to_string(),
        ));
        let seq_manager_2 = Arc::new(ActiveSequencesMultiWorker::new(
            component,
            block_size,
Yan Ru Pei's avatar
Yan Ru Pei committed
1140
            workers_with_configs,
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
            true,
            Uuid::new_v4().to_string(),
        ));

        // Give some time for the subscription loops to start
        tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;

        // PHASE 1: Add requests (without token sequences) using both seq_managers

        // Add request_0 to worker 0 with no token sequence
        seq_manager_1
            .add_request(
                "request_0".to_string(),
                None, // No token sequence
                12,   // ISL (12 tokens)
                0,    // no overlap
Yan Ru Pei's avatar
Yan Ru Pei committed
1157
                WorkerWithDpRank::from_worker_id(0),
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
            )
            .await?;

        // Add request_1 to worker 1 with no token sequence
        seq_manager_1
            .add_request(
                "request_1".to_string(),
                None, // No token sequence
                8,    // ISL (8 tokens)
                0,    // no overlap
Yan Ru Pei's avatar
Yan Ru Pei committed
1168
                WorkerWithDpRank::from_worker_id(1),
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
            )
            .await?;

        // Add request_2 to worker 2 with no token sequence using seq_manager_2
        seq_manager_2
            .add_request(
                "request_2".to_string(),
                None, // No token sequence
                16,   // ISL (16 tokens)
                0,    // no overlap
Yan Ru Pei's avatar
Yan Ru Pei committed
1179
                WorkerWithDpRank::from_worker_id(2),
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
            )
            .await?;

        // Give some time for synchronization
        tokio::time::sleep(tokio::time::Duration::from_millis(300)).await;

        // Query seq_manager_1 to verify it sees all requests including request_2 from seq_manager_2
        let tokens_phase1 = seq_manager_1.active_tokens().await;

        // Verify that seq_manager_1 sees all requests including request_2 from thread 2
Yan Ru Pei's avatar
Yan Ru Pei committed
1190
1191
1192
1193
        let worker_0 = WorkerWithDpRank::from_worker_id(0);
        let worker_1 = WorkerWithDpRank::from_worker_id(1);
        let worker_2 = WorkerWithDpRank::from_worker_id(2);

1194
        assert_eq!(
Yan Ru Pei's avatar
Yan Ru Pei committed
1195
            tokens_phase1[&worker_0], 12,
1196
            "Worker 0 should have 12 active tokens"
1197
1198
        );
        assert_eq!(
Yan Ru Pei's avatar
Yan Ru Pei committed
1199
1200
1201
1202
1203
            tokens_phase1[&worker_1], 8,
            "Worker 1 should have 8 active tokens"
        );
        assert_eq!(
            tokens_phase1[&worker_2], 16,
1204
            "Worker 2 should have 16 active tokens (from request_2 added by seq_manager_2)"
1205
        );
1206

1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
        // PHASE 2: Free requests using opposite sequence managers, verify on seq_manager_2

        // Mark prefill completed and free request_2 (which was added by seq_manager_2) using seq_manager_1
        seq_manager_1
            .mark_prefill_completed(&"request_2".to_string())
            .await?;
        seq_manager_1.free(&"request_2".to_string()).await?;

        // Mark prefill completed and free requests 0 and 1 (which were added by seq_manager_1) using seq_manager_2
        seq_manager_2
            .mark_prefill_completed(&"request_0".to_string())
            .await?;
        seq_manager_2
            .mark_prefill_completed(&"request_1".to_string())
            .await?;
        seq_manager_2.free(&"request_0".to_string()).await?;
        seq_manager_2.free(&"request_1".to_string()).await?;

        // Give some time for synchronization
        tokio::time::sleep(tokio::time::Duration::from_millis(300)).await;

        // Query seq_manager_2 to verify everything is empty
        let tokens_phase2 = seq_manager_2.active_tokens().await;

        // Verify phase 2 results - everything should be empty
        for worker_id in 0..=2 {
Yan Ru Pei's avatar
Yan Ru Pei committed
1233
            let worker = WorkerWithDpRank::from_worker_id(worker_id);
1234
            assert_eq!(
Yan Ru Pei's avatar
Yan Ru Pei committed
1235
                tokens_phase2[&worker], 0,
1236
1237
1238
1239
1240
                "Worker {} should have 0 active tokens after all requests freed",
                worker_id
            );
        }

1241
        Ok(())
1242
1243
    }
}