sequence.rs 41.5 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::kv_router::indexer::WorkerId;
27
use crate::tokens::SequenceHash;
28
29
use anyhow::Result;
use dashmap::DashMap;
30
use derive_getters::Getters;
31
32
use dynamo_runtime::component::Component;
use dynamo_runtime::traits::DistributedRuntimeProvider;
33
use dynamo_runtime::traits::events::{EventPublisher, EventSubscriber};
34
use futures::StreamExt;
35
use std::collections::{HashMap, HashSet};
36
use std::rc::{Rc, Weak};
37
use std::sync::Arc;
38
39
use std::time::Duration;
use tokio::time::Instant;
40
41
42
43
44
use uuid::Uuid;

use super::protocols::{ActiveSequenceEvent, ActiveSequenceEventData};
use crate::kv_router::ACTIVE_SEQUENCES_SUBJECT;
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
125
126
127
128
        // Check for double-add and panic early
        if self.active_seqs.contains_key(&request_id) {
            panic!("Request {request_id} is already active. Cannot accept double-add.");
        }

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

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

137
        if let Some(sequence) = token_sequence {
138
139
140
141
142
143
            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);
144
145
146
        } else {
            // dummy empty sequence
            self.active_seqs.insert(request_id.clone(), Vec::new());
147
148
        }

149
        removed_requests
150
151
    }

152
153
154
155
156
    /// 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
157
                .checked_sub(tokens)
158
159
160
161
162
163
164
                .expect("active_tokens underflow");
        }
    }

    pub fn new_tokens(&self, isl: usize, overlap: u32) -> usize {
        isl.checked_sub((overlap as usize) * self.block_size)
            .unwrap_or_else(|| panic!("prefill_tokens < 0 with overlap {overlap} and ISL {isl}"))
165
166
167
168
    }

    pub fn potential_blocks_and_tokens(
        &self,
169
        token_sequence: Option<&[SequenceHash]>,
170
        isl: usize,
171
172
        overlap: u32,
    ) -> (usize, usize) {
173
        let potential_blocks = if let Some(token_seq) = token_sequence {
174
            self.new_blocks(token_seq) + self.active_blocks()
175
        } else {
176
            self.active_blocks()
177
        };
178
        let potential_tokens = self.new_tokens(isl, overlap) + self.active_tokens;
179
180
181
        (potential_blocks, potential_tokens)
    }

182
    /// Match a request against existing blocks and return the number of new blocks that would be added
183
184
    pub fn new_blocks(&self, token_sequence: &[SequenceHash]) -> usize {
        token_sequence
185
186
187
188
189
190
191
            .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
192
    pub fn potential_blocks(&self, token_sequence: &[SequenceHash]) -> usize {
193
        self.new_blocks(token_sequence) + self.active_blocks()
194
195
196
197
    }

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

200
201
        self.expiry_requests.remove(request_id);

202
203
204
205
206
        // 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}");
207
                return self.active_blocks();
208
            }
209
210
        };

211
212
213
214
        // 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);
215
216
        }

217
        self.active_blocks()
218
    }
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241

    /// 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
    }
242
243
244
245
246
}

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

/// Multi-worker extension of ActiveSequences that distributes requests across multiple threads
pub struct ActiveSequencesMultiWorker {
283
284
    senders: Arc<DashMap<WorkerId, tokio::sync::mpsc::UnboundedSender<UpdateSequences>>>,
    request_to_worker: Arc<DashMap<RequestId, WorkerId>>,
285
    handles: Arc<DashMap<WorkerId, std::thread::JoinHandle<()>>>,
286
    block_size: usize,
287
288
289
    component: Component,
    router_id: Uuid,
    replica_sync: bool,
290
291
292
}

impl ActiveSequencesMultiWorker {
293
294
295
296
297
    pub fn new(
        component: Component,
        block_size: usize,
        worker_ids: Vec<WorkerId>,
        replica_sync: bool,
298
        router_uuid: String,
299
    ) -> Self {
300
301
        assert!(block_size > 1, "block_size must be greater than 1");

302
303
304
        let senders = Arc::new(DashMap::new());
        let handles = Arc::new(DashMap::new());
        let request_to_worker = Arc::new(DashMap::new());
305
306
307
308
309
310
311
312
        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()
        });
313
314

        for worker_id in worker_ids {
315
316
317
            // 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);
318
319
320
321
            senders.insert(worker_id, sender);
            handles.insert(worker_id, handle);
        }

322
323
324
        let multi_worker = Self {
            senders: senders.clone(),
            request_to_worker: request_to_worker.clone(),
325
326
            handles,
            block_size,
327
328
329
330
331
332
333
334
335
336
337
            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;
338
            let cancel_token = component.drt().runtime().child_token();
339

340
            tokio::spawn(async move {
341
                // NATS subscription loop
342
343
344
345
346
                if let Err(e) = Self::subscribe_to_events(
                    senders_clone,
                    request_to_worker_clone,
                    component_clone,
                    router_id_clone,
347
                    cancel_token,
348
349
350
351
352
353
                )
                .await
                {
                    tracing::error!("Error in active sequences events subscription: {}", e);
                }
            });
354
        }
355
356

        multi_worker
357
358
    }

359
360
361
    /// Helper method to start a worker task
    fn start_worker(
        block_size: usize,
362
        cancel_token: CancellationToken,
363
364
    ) -> (
        tokio::sync::mpsc::UnboundedSender<UpdateSequences>,
365
        std::thread::JoinHandle<()>,
366
    ) {
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
        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()),
426
427
                                        isl,
                                        overlap,
428
429
430
431
432
433
434
435
436
437
438
439
440
                                    );
                                    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;
441
442
443
                                }
                            }
                        }
444
445
446
447
448
                        // Handle cancellation
                        _ = cancel_token.cancelled() => {
                            tracing::debug!("Worker task cancelled");
                            break;
                        }
449
                    }
450
                }
451
452
453
            });

            tracing::debug!("ActiveSequences worker task completed");
454
455
456
457
458
459
460
461
462
463
464
        });

        (request_tx, handle)
    }

    /// Background task to subscribe to active sequence events and update all workers
    async fn subscribe_to_events(
        senders: Arc<DashMap<WorkerId, tokio::sync::mpsc::UnboundedSender<UpdateSequences>>>,
        request_to_worker: Arc<DashMap<RequestId, WorkerId>>,
        component: Component,
        router_id: Uuid,
465
        cancel_token: CancellationToken,
466
467
468
469
470
    ) -> Result<()> {
        let mut subscriber = component
            .subscribe_with_type::<ActiveSequenceEvent>(ACTIVE_SEQUENCES_SUBJECT)
            .await?;

471
472
473
474
475
476
477
478
        loop {
            tokio::select! {
                // Handle incoming events
                result = subscriber.next() => {
                    let Some(result) = result else {
                        // Stream ended
                        break;
                    };
479

480
481
482
483
                    let Ok(event) = result else {
                        tracing::error!(
                            "Error receiving active sequence event: {}",
                            result.unwrap_err()
484
                        );
485
486
487
488
489
490
                        continue;
                    };

                    // Skip events emitted by itself
                    if event.router_id == router_id {
                        continue;
491
                    }
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535

                    match &event.data {
                        ActiveSequenceEventData::AddRequest {
                            token_sequence,
                            isl,
                            overlap,
                        } => {
                            request_to_worker.insert(event.request_id.clone(), event.worker_id);

                            if let Some(sender) = senders.get(&event.worker_id) {
                                // 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!(
                                    "Worker {} not found, cannot process AddRequest",
                                    event.worker_id
                                );
                            }
                        }
                        ActiveSequenceEventData::Free => {
                            if let Some((_, worker_id)) = request_to_worker.remove(&event.request_id)
                                && let Some(sender) = senders.get(&worker_id)
                            {
                                let _ = sender.send(UpdateSequences::Free {
                                    request_id: event.request_id.clone(),
                                });
                            }
                        }
                        ActiveSequenceEventData::MarkPrefillCompleted => {
                            if let Some(worker_id) = request_to_worker.get(&event.request_id)
                                && let Some(sender) = senders.get(&*worker_id)
                            {
                                let _ = sender.send(UpdateSequences::MarkPrefillCompleted {
                                    request_id: event.request_id.clone(),
                                });
                            }
                        }
536
                    }
537
                }
538
539
540
541
                // Handle cancellation
                _ = cancel_token.cancelled() => {
                    tracing::debug!("Subscription task cancelled");
                    break;
542
543
                }
            }
544
        }
545

546
        Ok(())
547
548
549
    }

    /// Update the set of workers, adding and removing as needed
550
551
552
    pub fn update_workers(&self, new_worker_ids: Vec<WorkerId>) {
        let current_workers: HashSet<WorkerId> =
            self.senders.iter().map(|entry| *entry.key()).collect();
553
554
555
556
557
558
559
560
561
562
563
564
        let new_workers: HashSet<WorkerId> = new_worker_ids.into_iter().collect();

        let workers_to_remove: Vec<WorkerId> =
            current_workers.difference(&new_workers).copied().collect();
        let workers_to_add: Vec<WorkerId> =
            new_workers.difference(&current_workers).copied().collect();

        // Remove workers
        for worker_id in &workers_to_remove {
            tracing::warn!("Removing worker {}", worker_id);

            // Send shutdown command to the worker
565
            if let Some((_, sender)) = self.senders.remove(worker_id) {
566
567
                let _ = sender.send(UpdateSequences::Shutdown);
            }
568
            self.handles.remove(worker_id);
569
570
571
572

            // Clean up request_to_worker mappings for this worker
            self.request_to_worker
                .retain(|_request_id, mapped_worker_id| *mapped_worker_id != *worker_id);
573
574
575
576
577
578
        }

        // Add new workers
        for worker_id in &workers_to_add {
            tracing::warn!("Adding worker {}", worker_id);

579
580
581
582
            let (sender, handle) = Self::start_worker(
                self.block_size,
                self.component.drt().runtime().child_token(),
            );
583
584
585
586
587
            self.senders.insert(*worker_id, sender);
            self.handles.insert(*worker_id, handle);
        }
    }

588
589
    pub async fn add_request(
        &self,
590
        request_id: RequestId,
591
        token_sequence: Option<Vec<SequenceHash>>,
592
        isl: usize,
593
        overlap: u32,
594
        worker_id: WorkerId,
595
    ) -> Result<()> {
596
        if !self.senders.contains_key(&worker_id) {
597
598
599
            return Err(anyhow::anyhow!("Worker ID {worker_id} not found"));
        }

600
601
602
        // Create response channel
        let (resp_tx, resp_rx) = tokio::sync::oneshot::channel();

603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
        // Publish event only if replica_sync is enabled
        if self.replica_sync {
            let event = ActiveSequenceEvent {
                request_id: request_id.clone(),
                worker_id,
                data: ActiveSequenceEventData::AddRequest {
                    token_sequence: token_sequence.clone(),
                    isl,
                    overlap,
                },
                router_id: self.router_id,
            };
            self.component
                .publish(ACTIVE_SEQUENCES_SUBJECT, &event)
                .await?;
618
619
        }

620
        // Update local state
621
622
        self.request_to_worker.insert(request_id.clone(), worker_id);

623
624
625
        self.senders
            .get(&worker_id)
            .unwrap()
626
627
628
            .send(UpdateSequences::AddRequest {
                request_id,
                token_sequence,
629
                isl,
630
                overlap,
631
                resp_tx,
632
            })
633
634
            .map_err(|_| anyhow::anyhow!("Failed to send add_request command to worker"))?;

635
636
637
638
639
640
641
642
643
644
        // 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);
        }

645
        Ok(())
646
647
    }

648
    pub async fn free(&self, request_id: &RequestId) -> Result<()> {
649
650
651
        let worker_id = self
            .request_to_worker
            .get(request_id)
652
653
            .map(|entry| *entry)
            .ok_or_else(|| anyhow::anyhow!("Request ID not found in request_to_worker mapping"))?;
654

655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
        // Publish event only if replica_sync is enabled
        if self.replica_sync {
            let event = ActiveSequenceEvent {
                request_id: request_id.clone(),
                worker_id,
                data: ActiveSequenceEventData::Free,
                router_id: self.router_id,
            };
            self.component
                .publish(ACTIVE_SEQUENCES_SUBJECT, &event)
                .await?;
        }

        // Update local state
        self.senders
            .get(&worker_id)
            .unwrap()
672
673
674
            .send(UpdateSequences::Free {
                request_id: request_id.clone(),
            })
675
            .map_err(|_| anyhow::anyhow!("Failed to send free command to worker"))?;
676
677

        self.request_to_worker.remove(request_id);
678
679

        Ok(())
680
681
    }

682
    /// Mark prefill as completed for a request
683
    pub async fn mark_prefill_completed(&self, request_id: &RequestId) -> Result<()> {
684
685
686
        let worker_id = self
            .request_to_worker
            .get(request_id)
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
            .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(),
                worker_id,
                data: ActiveSequenceEventData::MarkPrefillCompleted,
                router_id: self.router_id,
            };
            self.component
                .publish(ACTIVE_SEQUENCES_SUBJECT, &event)
                .await?;
        }
702

703
704
705
706
        // Update local state
        self.senders
            .get(&worker_id)
            .unwrap()
707
            .send(UpdateSequences::MarkPrefillCompleted {
708
709
                request_id: request_id.clone(),
            })
710
711
712
713
714
            .map_err(|_| {
                anyhow::anyhow!("Failed to send mark_prefill_completed command to worker")
            })?;

        Ok(())
715
716
717
718
719
720
721
722
    }

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

    /// Generic method to query all workers with a given command
723
    async fn query_workers<T: Send + 'static>(
724
        &self,
725
        token_sequence: Option<Vec<SequenceHash>>,
726
727
728
729
730
        command_fn: impl Fn(
            Option<Arc<Vec<SequenceHash>>>,
            tokio::sync::oneshot::Sender<T>,
        ) -> UpdateSequences,
    ) -> HashMap<WorkerId, T> {
731
732
733
734
735
        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
736
737
738
739
        for entry in self.senders.iter() {
            let worker_id = *entry.key();
            let sender = entry.value();
            let (resp_tx, resp_rx) = tokio::sync::oneshot::channel();
740
            receivers.push((worker_id, resp_rx));
741
742
743
            if let Err(e) = sender.send(command_fn(token_sequence_shared.clone(), resp_tx)) {
                tracing::error!("Failed to send command to worker {}: {}", worker_id, e);
            }
744
745
746
747
        }

        // Collect results from all workers
        for (worker_id, receiver) in receivers {
748
749
750
751
752
753
754
755
756
757
758
            match tokio::time::timeout(tokio::time::Duration::from_secs(1), receiver).await {
                Ok(Ok(result)) => {
                    results.insert(worker_id, result);
                }
                Ok(Err(_)) => {
                    tracing::error!("Worker {} dropped response channel", worker_id);
                }
                Err(_) => {
                    tracing::error!("Timeout waiting for response from worker {}", worker_id);
                }
            }
759
760
761
762
763
764
        }

        results
    }

    /// Query all workers for the number of new blocks that would be added by a token sequence
765
    pub async fn new_blocks(&self, token_sequence: Vec<SequenceHash>) -> HashMap<WorkerId, usize> {
766
767
768
769
770
771
772
        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"),
        })
773
        .await
774
775
776
    }

    /// Query all workers for the total number of blocks (new + active) that would be used by a token sequence
777
778
779
780
    pub async fn potential_blocks(
        &self,
        token_sequence: Vec<SequenceHash>,
    ) -> HashMap<WorkerId, usize> {
781
782
783
784
785
786
787
        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"),
        })
788
        .await
789
790
    }

791
    /// Query all workers for the potential tokens (new + active) that would be used by a token sequence with overlap
792
    pub async fn potential_blocks_and_tokens(
793
        &self,
794
        token_sequence: Option<Vec<SequenceHash>>,
795
        isl: usize,
796
797
798
799
        overlaps: OverlapScores,
    ) -> (HashMap<WorkerId, usize>, HashMap<WorkerId, usize>) {
        let mut potential_blocks = HashMap::new();
        let mut potential_tokens = HashMap::new();
800
        let token_sequence_shared = token_sequence.map(Arc::new);
801
802
803
        let mut receivers = Vec::new();

        // Send queries to all workers in parallel
804
805
806
807
        for entry in self.senders.iter() {
            let worker_id = *entry.key();
            let sender = entry.value();
            let (resp_tx, resp_rx) = tokio::sync::oneshot::channel();
808
809
            receivers.push((worker_id, resp_rx));

810
811
812
813
814
815
816
817
818
819
820
821
            if let Err(e) = sender.send(UpdateSequences::PotentialBlocksAndTokens {
                token_sequence: token_sequence_shared.clone(),
                isl,
                overlap: overlaps.scores.get(&worker_id).copied().unwrap_or(0),
                resp_tx,
            }) {
                tracing::error!(
                    "Failed to send potential_tokens command to worker {}: {}",
                    worker_id,
                    e
                );
            }
822
823
824
825
        }

        // Collect results from all workers
        for (worker_id, receiver) in receivers {
826
827
828
829
830
831
832
833
834
835
836
837
            match tokio::time::timeout(tokio::time::Duration::from_secs(1), receiver).await {
                Ok(Ok((blocks, tokens))) => {
                    potential_blocks.insert(worker_id, blocks);
                    potential_tokens.insert(worker_id, tokens);
                }
                Ok(Err(_)) => {
                    tracing::error!("Worker {} dropped response channel", worker_id);
                }
                Err(_) => {
                    tracing::error!("Timeout waiting for response from worker {}", worker_id);
                }
            }
838
839
840
841
842
        }

        (potential_blocks, potential_tokens)
    }

843
    /// Query all workers for their current number of active blocks
844
    pub async fn active_blocks(&self) -> HashMap<WorkerId, usize> {
845
        self.query_workers(None, |_, resp_tx| UpdateSequences::ActiveBlocks { resp_tx })
846
            .await
847
    }
848
849

    /// Query all workers for their current number of active tokens
850
    pub async fn active_tokens(&self) -> HashMap<WorkerId, usize> {
851
        self.query_workers(None, |_, resp_tx| UpdateSequences::ActiveTokens { resp_tx })
852
            .await
853
    }
854
855
856
857
}

impl Drop for ActiveSequencesMultiWorker {
    fn drop(&mut self) {
858
859
860
        // Send shutdown to all workers
        for entry in self.senders.iter() {
            let _ = entry.value().send(UpdateSequences::Shutdown);
861
862
863
864
865
866
867
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
868
    use dynamo_runtime::{DistributedRuntime, Runtime};
869
    use std::sync::Arc;
870

871
    #[tokio::test]
872
    #[ignore]
873
    async fn test_multi_worker_cross_instance_sync() -> Result<()> {
874
875
876
        // Initialize logging once
        dynamo_runtime::logging::init();

877
878
        let block_size = 4; // arbitrary block size

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

883
884
885
886
887
888
889
        // Create namespace and shared component for both seq_managers
        let namespace = distributed.namespace("test_cross_instance_sync")?;
        let component = namespace
            .component("sequences")?
            .service_builder()
            .create()
            .await?;
890

891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
        // Create multi-worker sequence managers with ALL workers [0, 1, 2]
        // Both use the same component to ensure event synchronization works
        let worker_ids = vec![0, 1, 2];
        let seq_manager_1 = Arc::new(ActiveSequencesMultiWorker::new(
            component.clone(),
            block_size,
            worker_ids.clone(),
            true,
            Uuid::new_v4().to_string(),
        ));
        let seq_manager_2 = Arc::new(ActiveSequencesMultiWorker::new(
            component,
            block_size,
            worker_ids,
            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

        // Add request_0 to worker 0: sequence [0, 1, 2]
        seq_manager_1
            .add_request(
                "request_0".to_string(),
                Some(vec![0, 1, 2]),
                12, // ISL (3 blocks * 4 block_size)
                0,  // no overlap
                0,  // worker_id
            )
            .await?;
924

925
926
927
928
929
930
931
932
933
934
        // Add request_1 to worker 1: sequence [3, 4]
        seq_manager_1
            .add_request(
                "request_1".to_string(),
                Some(vec![3, 4]),
                8, // ISL (2 blocks * 4 block_size)
                0, // no overlap
                1, // worker_id
            )
            .await?;
935

936
937
938
939
940
941
942
943
944
945
        // Add request_2 to worker 2: sequence [0, 1, 2, 3] using seq_manager_2
        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
                2,  // worker_id
            )
            .await?;
946

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

950
951
952
        // 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;
953

954
        // Verify that seq_manager_1 sees all requests including request_2 from thread 2
955
        assert_eq!(
956
957
            blocks_phase1[&0], 3,
            "Worker 0 should have 3 active blocks (from request_0)"
958
        );
959
        assert_eq!(
960
961
            blocks_phase1[&1], 2,
            "Worker 1 should have 2 active blocks (from request_1)"
962
963
        );
        assert_eq!(
964
965
            blocks_phase1[&2], 4,
            "Worker 2 should have 4 active blocks (from request_2 added by seq_manager_2)"
966
967
        );
        assert_eq!(
968
969
            tokens_phase1[&0], 12,
            "Worker 0 should have 12 active tokens"
970
        );
971
        assert_eq!(tokens_phase1[&1], 8, "Worker 1 should have 8 active tokens");
972
        assert_eq!(
973
974
            tokens_phase1[&2], 16,
            "Worker 2 should have 16 active tokens (from request_2 added by seq_manager_2)"
975
        );
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092

        // 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;

        // Verify phase 2 results - everything should be empty
        for worker_id in 0..=2 {
            assert_eq!(
                blocks_phase2[&worker_id], 0,
                "Worker {} should have 0 active blocks after all requests freed",
                worker_id
            );
            assert_eq!(
                tokens_phase2[&worker_id], 0,
                "Worker {} should have 0 active tokens after all requests freed",
                worker_id
            );
        }

        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")?;
        let component = namespace
            .component("sequences")?
            .service_builder()
            .create()
            .await?;

        // Create multi-worker sequence managers with ALL workers [0, 1, 2]
        // Both use the same component to ensure event synchronization works
        let worker_ids = vec![0, 1, 2];
        let seq_manager_1 = Arc::new(ActiveSequencesMultiWorker::new(
            component.clone(),
            block_size,
            worker_ids.clone(),
            true,
            Uuid::new_v4().to_string(),
        ));
        let seq_manager_2 = Arc::new(ActiveSequencesMultiWorker::new(
            component,
            block_size,
            worker_ids,
            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
                0,    // worker_id
            )
            .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
                1,    // worker_id
            )
            .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
                2,    // worker_id
            )
            .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
1093
        assert_eq!(
1094
1095
            tokens_phase1[&0], 12,
            "Worker 0 should have 12 active tokens"
1096
        );
1097
        assert_eq!(tokens_phase1[&1], 8, "Worker 1 should have 8 active tokens");
1098
        assert_eq!(
1099
1100
            tokens_phase1[&2], 16,
            "Worker 2 should have 16 active tokens (from request_2 added by seq_manager_2)"
1101
        );
1102

1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
        // 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 {
            assert_eq!(
                tokens_phase2[&worker_id], 0,
                "Worker {} should have 0 active tokens after all requests freed",
                worker_id
            );
        }

1136
        Ok(())
1137
1138
    }
}