sequence.rs 42.1 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::sync::Arc;
37
38
use std::time::Duration;
use tokio::time::Instant;
39
40
41
42
43
use uuid::Uuid;

use super::protocols::{ActiveSequenceEvent, ActiveSequenceEventData};
use crate::kv_router::ACTIVE_SEQUENCES_SUBJECT;
use dynamo_runtime::CancellationToken;
44

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

48
49
50
51
52
53
// 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 {
54
    active_seqs: HashMap<RequestId, Vec<SequenceHash>>,
55

56
57
    prefill_tokens: HashMap<RequestId, usize>,

58
    unique_blocks: HashMap<SequenceHash, HashSet<RequestId>>,
59
60
61
62
63
64

    #[getter(copy)]
    block_size: usize,

    #[getter(copy)]
    active_blocks: usize,
65
66
67

    #[getter(copy)]
    active_tokens: usize,
68
69
70
71
72
73

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

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

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(),
84
            prefill_tokens: HashMap::new(),
85
86
87
            unique_blocks: HashMap::new(),
            block_size,
            active_blocks: 0,
88
            active_tokens: 0,
89
90
            expiry_timer: Instant::now() + EXPIRY_DURATION,
            expiry_requests: HashSet::new(),
91
92
93
        }
    }

94
    fn add_block(&mut self, request_id: RequestId, block: &SequenceHash) {
95
96
97
        let is_new_block = !self.unique_blocks.contains_key(block);

        self.unique_blocks
98
            .entry(*block)
99
100
101
102
103
104
105
106
            .or_default()
            .insert(request_id.clone());

        if is_new_block {
            self.active_blocks += 1;
        }
    }

107
    fn remove_block(&mut self, request_id: &RequestId, block: &SequenceHash) {
108
109
110
111
112
113
114
115
116
117
118
119
120
        let Some(request_ids) = self.unique_blocks.get_mut(block) else {
            panic!("Cannot remove a block that does not exist.")
        };

        // Remove the unique block if no more requests using it
        request_ids.retain(|w| w != request_id);
        if request_ids.is_empty() {
            self.active_blocks -= 1;
            self.unique_blocks.remove(block);
        }
    }

    /// Add a new request with its initial tokens
121
    /// Returns the set of expired request IDs that were removed during cleanup
122
123
124
    pub fn add_request(
        &mut self,
        request_id: RequestId,
125
126
        token_sequence: Vec<SequenceHash>,
        isl: usize,
127
        overlap: u32,
128
129
130
131
    ) -> HashSet<RequestId> {
        // 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
        for block in &token_sequence {
138
139
140
141
142
            self.add_block(request_id.clone(), block);
        }

        self.active_seqs.insert(request_id.clone(), token_sequence);

143
        removed_requests
144
145
    }

146
147
148
149
150
    /// 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
151
                .checked_sub(tokens)
152
153
154
155
156
157
158
                .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}"))
159
160
161
162
    }

    pub fn potential_blocks_and_tokens(
        &self,
163
164
        token_sequence: &[SequenceHash],
        isl: usize,
165
166
167
        overlap: u32,
    ) -> (usize, usize) {
        let potential_blocks = self.new_blocks(token_sequence) + self.active_blocks;
168
        let potential_tokens = self.new_tokens(isl, overlap) + self.active_tokens;
169
170
171
        (potential_blocks, potential_tokens)
    }

172
    /// Match a request against existing blocks and return the number of new blocks that would be added
173
174
    pub fn new_blocks(&self, token_sequence: &[SequenceHash]) -> usize {
        token_sequence
175
176
177
178
179
180
181
            .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
182
    pub fn potential_blocks(&self, token_sequence: &[SequenceHash]) -> usize {
183
184
185
186
187
        self.new_blocks(token_sequence) + self.active_blocks
    }

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

190
191
        self.expiry_requests.remove(request_id);

192
193
194
195
196
        let Some(token_seq) = self.active_seqs.get(request_id) else {
            tracing::warn!("Trying to free free non-existent request {request_id}");
            return 0;
        };

197
198
        for block in token_seq.clone() {
            self.remove_block(request_id, &block)
199
200
201
202
203
204
        }

        self.active_seqs.remove(request_id).unwrap();

        self.active_blocks
    }
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227

    /// 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
    }
228
229
230
231
232
}

enum UpdateSequences {
    AddRequest {
        request_id: RequestId,
233
234
        token_sequence: Vec<SequenceHash>,
        isl: usize,
235
        overlap: u32,
236
        resp_tx: tokio::sync::oneshot::Sender<HashSet<RequestId>>,
237
238
239
240
    },
    Free {
        request_id: RequestId,
    },
241
    MarkPrefillCompleted {
242
243
244
        request_id: RequestId,
    },
    NewBlocks {
245
        token_sequence: Arc<Vec<SequenceHash>>,
246
        resp_tx: tokio::sync::oneshot::Sender<usize>,
247
248
    },
    PotentialBlocks {
249
        token_sequence: Arc<Vec<SequenceHash>>,
250
        resp_tx: tokio::sync::oneshot::Sender<usize>,
251
    },
252
    PotentialBlocksAndTokens {
253
254
        token_sequence: Arc<Vec<SequenceHash>>,
        isl: usize,
255
        overlap: u32,
256
        resp_tx: tokio::sync::oneshot::Sender<(usize, usize)>,
257
    },
258
    ActiveBlocks {
259
        resp_tx: tokio::sync::oneshot::Sender<usize>,
260
    },
261
    ActiveTokens {
262
        resp_tx: tokio::sync::oneshot::Sender<usize>,
263
    },
264
265
266
267
268
    Shutdown,
}

/// Multi-worker extension of ActiveSequences that distributes requests across multiple threads
pub struct ActiveSequencesMultiWorker {
269
270
271
    senders: Arc<DashMap<WorkerId, tokio::sync::mpsc::UnboundedSender<UpdateSequences>>>,
    request_to_worker: Arc<DashMap<RequestId, WorkerId>>,
    handles: Arc<DashMap<WorkerId, tokio::task::JoinHandle<()>>>,
272
    block_size: usize,
273
274
275
    component: Component,
    router_id: Uuid,
    replica_sync: bool,
276
277
278
}

impl ActiveSequencesMultiWorker {
279
280
281
282
283
284
    pub fn new(
        component: Component,
        block_size: usize,
        worker_ids: Vec<WorkerId>,
        replica_sync: bool,
    ) -> Self {
285
286
        assert!(block_size > 1, "block_size must be greater than 1");

287
288
289
290
        let senders = Arc::new(DashMap::new());
        let handles = Arc::new(DashMap::new());
        let request_to_worker = Arc::new(DashMap::new());
        let router_id = Uuid::new_v4();
291
292

        for worker_id in worker_ids {
293
294
295
            // 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);
296
297
298
299
            senders.insert(worker_id, sender);
            handles.insert(worker_id, handle);
        }

300
301
302
        let multi_worker = Self {
            senders: senders.clone(),
            request_to_worker: request_to_worker.clone(),
303
304
            handles,
            block_size,
305
306
307
308
309
310
311
312
313
314
315
316
            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;

317
            tokio::spawn(async move {
318
                // NATS subscription loop
319
320
321
322
323
324
325
326
327
328
329
                if let Err(e) = Self::subscribe_to_events(
                    senders_clone,
                    request_to_worker_clone,
                    component_clone,
                    router_id_clone,
                )
                .await
                {
                    tracing::error!("Error in active sequences events subscription: {}", e);
                }
            });
330
        }
331
332

        multi_worker
333
334
    }

335
336
337
338
339
340
341
342
343
    /// Helper method to start a worker task
    fn start_worker(
        block_size: usize,
        cancel_token: CancellationToken, // Add cancellation token parameter
    ) -> (
        tokio::sync::mpsc::UnboundedSender<UpdateSequences>,
        tokio::task::JoinHandle<()>,
    ) {
        let (request_tx, mut request_rx) = tokio::sync::mpsc::unbounded_channel();
344

345
        let handle = tokio::spawn(async move {
346
347
            let mut active_sequences = ActiveSequences::new(block_size);

348
349
350
351
352
353
354
355
356
357
358
359
            loop {
                tokio::select! {
                    // Handle incoming commands
                    command = request_rx.recv() => {
                        match command {
                            Some(command) => {
                                match command {
                                    UpdateSequences::AddRequest {
                                        request_id,
                                        token_sequence,
                                        isl,
                                        overlap,
360
                                        resp_tx,
361
                                    } => {
362
363
                                        let removed = active_sequences.add_request(request_id, token_sequence, isl, overlap);
                                        let _ = resp_tx.send(removed);
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
                                    }
                                    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,
                                            isl,
                                            overlap,
                                        );
                                        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;
                                    }
                                }
                            }
                            None => {
                                // Channel closed, exit
                                break;
                            }
                        }
416
                    }
417
418
419
420
                    // Handle cancellation
                    _ = cancel_token.cancelled() => {
                        tracing::debug!("Worker task cancelled");
                        break;
421
                    }
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
                }
            }
        });

        (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,
    ) -> Result<()> {
        let mut subscriber = component
            .subscribe_with_type::<ActiveSequenceEvent>(ACTIVE_SEQUENCES_SUBJECT)
            .await?;

        while let Some(result) = subscriber.next().await {
            let Ok(event) = result else {
                tracing::error!(
                    "Error receiving active sequence event: {}",
                    result.unwrap_err()
                );
                continue;
            };

            // Skip events emitted by itself
            if event.router_id == router_id {
                continue;
            }

            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) {
463
464
                        // 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();
465
466
467
468
469
                        let _ = sender.send(UpdateSequences::AddRequest {
                            request_id: event.request_id.clone(),
                            token_sequence: token_sequence.clone(),
                            isl: *isl,
                            overlap: *overlap,
470
                            resp_tx,
471
472
473
474
475
                        });
                    } else {
                        tracing::warn!(
                            "Worker {} not found, cannot process AddRequest",
                            event.worker_id
476
                        );
477
                    }
478
479
                }
                ActiveSequenceEventData::Free => {
480
481
482
483
484
485
                    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(),
                        });
486
                    }
487
488
                }
                ActiveSequenceEventData::MarkPrefillCompleted => {
489
490
491
492
493
494
                    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(),
                        });
495
496
497
                    }
                }
            }
498
        }
499

500
        Ok(())
501
502
503
    }

    /// Update the set of workers, adding and removing as needed
504
505
506
    pub fn update_workers(&self, new_worker_ids: Vec<WorkerId>) {
        let current_workers: HashSet<WorkerId> =
            self.senders.iter().map(|entry| *entry.key()).collect();
507
508
509
510
511
512
513
514
515
516
517
518
        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
519
            if let Some((_, sender)) = self.senders.remove(worker_id) {
520
521
                let _ = sender.send(UpdateSequences::Shutdown);
            }
522
523
            if let Some((_, handle)) = self.handles.remove(worker_id) {
                handle.abort();
524
525
526
527
528
529
530
            }
        }

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

531
532
533
534
            let (sender, handle) = Self::start_worker(
                self.block_size,
                self.component.drt().runtime().child_token(),
            );
535
536
537
538
539
            self.senders.insert(*worker_id, sender);
            self.handles.insert(*worker_id, handle);
        }
    }

540
541
    pub async fn add_request(
        &self,
542
        request_id: RequestId,
543
544
        token_sequence: Vec<SequenceHash>,
        isl: usize,
545
        overlap: u32,
546
        worker_id: WorkerId,
547
    ) -> Result<()> {
548
        if !self.senders.contains_key(&worker_id) {
549
550
551
            return Err(anyhow::anyhow!("Worker ID {worker_id} not found"));
        }

552
553
554
        // Create response channel
        let (resp_tx, resp_rx) = tokio::sync::oneshot::channel();

555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
        // 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?;
570
571
        }

572
        // Update local state
573
574
        self.request_to_worker.insert(request_id.clone(), worker_id);

575
576
577
        self.senders
            .get(&worker_id)
            .unwrap()
578
579
580
            .send(UpdateSequences::AddRequest {
                request_id,
                token_sequence,
581
                isl,
582
                overlap,
583
                resp_tx,
584
            })
585
586
            .map_err(|_| anyhow::anyhow!("Failed to send add_request command to worker"))?;

587
588
589
590
591
592
593
594
595
596
        // 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);
        }

597
        Ok(())
598
599
    }

600
    pub async fn free(&self, request_id: &RequestId) -> Result<()> {
601
602
603
        let worker_id = self
            .request_to_worker
            .get(request_id)
604
605
            .map(|entry| *entry)
            .ok_or_else(|| anyhow::anyhow!("Request ID not found in request_to_worker mapping"))?;
606

607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
        // 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()
624
625
626
            .send(UpdateSequences::Free {
                request_id: request_id.clone(),
            })
627
            .map_err(|_| anyhow::anyhow!("Failed to send free command to worker"))?;
628
629

        self.request_to_worker.remove(request_id);
630
631

        Ok(())
632
633
    }

634
    /// Mark prefill as completed for a request
635
    pub async fn mark_prefill_completed(&self, request_id: &RequestId) -> Result<()> {
636
637
638
        let worker_id = self
            .request_to_worker
            .get(request_id)
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
            .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?;
        }
654

655
656
657
658
        // Update local state
        self.senders
            .get(&worker_id)
            .unwrap()
659
            .send(UpdateSequences::MarkPrefillCompleted {
660
661
                request_id: request_id.clone(),
            })
662
663
664
665
666
            .map_err(|_| {
                anyhow::anyhow!("Failed to send mark_prefill_completed command to worker")
            })?;

        Ok(())
667
668
669
670
671
672
673
674
    }

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

    /// Generic method to query all workers with a given command
675
    async fn query_workers<T: Send + 'static>(
676
        &self,
677
        token_sequence: Option<Vec<SequenceHash>>,
678
679
680
681
682
        command_fn: impl Fn(
            Option<Arc<Vec<SequenceHash>>>,
            tokio::sync::oneshot::Sender<T>,
        ) -> UpdateSequences,
    ) -> HashMap<WorkerId, T> {
683
684
685
686
687
        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
688
689
690
691
        for entry in self.senders.iter() {
            let worker_id = *entry.key();
            let sender = entry.value();
            let (resp_tx, resp_rx) = tokio::sync::oneshot::channel();
692
            receivers.push((worker_id, resp_rx));
693
694
695
            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);
            }
696
697
698
699
        }

        // Collect results from all workers
        for (worker_id, receiver) in receivers {
700
701
702
703
704
705
706
707
708
709
710
            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);
                }
            }
711
712
713
714
715
716
        }

        results
    }

    /// Query all workers for the number of new blocks that would be added by a token sequence
717
    pub async fn new_blocks(&self, token_sequence: Vec<SequenceHash>) -> HashMap<WorkerId, usize> {
718
719
720
721
722
723
724
        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"),
        })
725
        .await
726
727
728
    }

    /// Query all workers for the total number of blocks (new + active) that would be used by a token sequence
729
730
731
732
    pub async fn potential_blocks(
        &self,
        token_sequence: Vec<SequenceHash>,
    ) -> HashMap<WorkerId, usize> {
733
734
735
736
737
738
739
        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"),
        })
740
        .await
741
742
    }

743
    /// Query all workers for the potential tokens (new + active) that would be used by a token sequence with overlap
744
    pub async fn potential_blocks_and_tokens(
745
        &self,
746
747
        token_sequence: Vec<SequenceHash>,
        isl: usize,
748
749
750
751
752
753
754
755
        overlaps: OverlapScores,
    ) -> (HashMap<WorkerId, usize>, HashMap<WorkerId, usize>) {
        let mut potential_blocks = HashMap::new();
        let mut potential_tokens = HashMap::new();
        let token_sequence_shared = Arc::new(token_sequence);
        let mut receivers = Vec::new();

        // Send queries to all workers in parallel
756
757
758
759
        for entry in self.senders.iter() {
            let worker_id = *entry.key();
            let sender = entry.value();
            let (resp_tx, resp_rx) = tokio::sync::oneshot::channel();
760
761
            receivers.push((worker_id, resp_rx));

762
763
764
765
766
767
768
769
770
771
772
773
            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
                );
            }
774
775
776
777
        }

        // Collect results from all workers
        for (worker_id, receiver) in receivers {
778
779
780
781
782
783
784
785
786
787
788
789
            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);
                }
            }
790
791
792
793
794
        }

        (potential_blocks, potential_tokens)
    }

795
    /// Query all workers for their current number of active blocks
796
    pub async fn active_blocks(&self) -> HashMap<WorkerId, usize> {
797
        self.query_workers(None, |_, resp_tx| UpdateSequences::ActiveBlocks { resp_tx })
798
            .await
799
    }
800
801

    /// Query all workers for their current number of active tokens
802
    pub async fn active_tokens(&self) -> HashMap<WorkerId, usize> {
803
        self.query_workers(None, |_, resp_tx| UpdateSequences::ActiveTokens { resp_tx })
804
            .await
805
    }
806
807
808
809
}

impl Drop for ActiveSequencesMultiWorker {
    fn drop(&mut self) {
810
811
812
        // Send shutdown to all workers
        for entry in self.senders.iter() {
            let _ = entry.value().send(UpdateSequences::Shutdown);
813
814
        }

815
816
817
        // Abort all tasks
        for entry in self.handles.iter() {
            entry.value().abort();
818
819
820
821
822
823
824
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
825
826
827
    use dynamo_runtime::{DistributedRuntime, Runtime};
    use std::sync::{Arc, Mutex};
    use std::thread;
828
829

    #[test]
830
831
832
833
834
    #[ignore]
    fn test_multi_worker_block_sharing() -> Result<()> {
        // Initialize logging once
        dynamo_runtime::logging::init();

835
836
        let block_size = 4; // arbitrary block size

837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
        // Shared state for collecting results from both threads
        let active_tokens_after_add = Arc::new(Mutex::new(HashMap::new()));
        let potential_blocks_result = Arc::new(Mutex::new(HashMap::new()));
        let active_blocks_after_free = Arc::new(Mutex::new(HashMap::new()));
        let active_tokens_after_free = Arc::new(Mutex::new(HashMap::new()));

        let active_tokens_after_add_clone = active_tokens_after_add.clone();
        let potential_blocks_result_clone = potential_blocks_result.clone();
        let active_blocks_after_free_clone = active_blocks_after_free.clone();
        let active_tokens_after_free_clone = active_tokens_after_free.clone();

        // Clone again for the second thread
        let active_tokens_after_add_clone2 = active_tokens_after_add.clone();
        let potential_blocks_result_clone2 = potential_blocks_result.clone();
        let active_blocks_after_free_clone2 = active_blocks_after_free.clone();
        let active_tokens_after_free_clone2 = active_tokens_after_free.clone();

        // Thread 1: First runtime with workers 0 and 1
        let handle1 = thread::spawn(move || {
            let rt = tokio::runtime::Runtime::new().unwrap();

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

                // Create namespace and component with same names as thread 2
                let namespace = distributed.namespace("test_multiworker_sequences")?;
                let component = namespace
                    .component("sequences")?
                    .service_builder()
                    .create()
                    .await?;

                // Create multi-worker sequence manager with workers 0 and 1
                let worker_ids = vec![0, 1];
                let seq_manager =
                    ActiveSequencesMultiWorker::new(component, block_size, worker_ids, true);

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

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

                // Worker 1: sequence [3, 4]
                seq_manager
                    .add_request(
                        "request_1".to_string(),
                        vec![3, 4],
                        8, // ISL (2 blocks * 4 block_size)
                        0, // no overlap
                        1, // worker_id
                    )
                    .await?;

                // Give some time for the commands to be processed and synchronization
                tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

                // Get active tokens from workers 0 and 1
                let tokens = seq_manager.active_tokens().await;
                active_tokens_after_add_clone
                    .lock()
                    .unwrap()
                    .insert(0, tokens.get(&0).copied().unwrap_or(0));
                active_tokens_after_add_clone
                    .lock()
                    .unwrap()
                    .insert(1, tokens.get(&1).copied().unwrap_or(0));

                // Test potential blocks for sequence [0, 1]
                let potential = seq_manager.potential_blocks(vec![0, 1]).await;
                potential_blocks_result_clone
                    .lock()
                    .unwrap()
                    .insert(0, potential.get(&0).copied().unwrap_or(0));
                potential_blocks_result_clone
                    .lock()
                    .unwrap()
                    .insert(1, potential.get(&1).copied().unwrap_or(0));

                // Wait for second thread to process its requests
                tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

                // Free requests from workers 0 and 1
                seq_manager.free(&"request_0".to_string()).await?;
                seq_manager.free(&"request_1".to_string()).await?;

                // Give some time for the commands to be processed
                tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

                // Get final active blocks and tokens
                let blocks = seq_manager.active_blocks().await;
                let tokens = seq_manager.active_tokens().await;

                active_blocks_after_free_clone
                    .lock()
                    .unwrap()
                    .insert(0, blocks.get(&0).copied().unwrap_or(0));
                active_blocks_after_free_clone
                    .lock()
                    .unwrap()
                    .insert(1, blocks.get(&1).copied().unwrap_or(0));
                active_tokens_after_free_clone
                    .lock()
                    .unwrap()
                    .insert(0, tokens.get(&0).copied().unwrap_or(0));
                active_tokens_after_free_clone
                    .lock()
                    .unwrap()
                    .insert(1, tokens.get(&1).copied().unwrap_or(0));

                // Keep runtime alive a bit longer for synchronization
                tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

                // Shutdown runtime
                runtime.shutdown();

                Ok::<(), anyhow::Error>(())
            })
        });
967

968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
        // Thread 2: Second runtime with worker 2
        let handle2 = thread::spawn(move || {
            let rt = tokio::runtime::Runtime::new().unwrap();

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

                // Create namespace and component with same names as thread 1
                let namespace = distributed.namespace("test_multiworker_sequences")?;
                let component = namespace
                    .component("sequences")?
                    .service_builder()
                    .create()
                    .await?;

                // Create multi-worker sequence manager with worker 2
                let worker_ids = vec![2];
                let seq_manager =
                    ActiveSequencesMultiWorker::new(component, block_size, worker_ids, true);

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

                // Wait a bit to ensure thread 1 has started
                tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

                // Worker 2: sequence [0, 1, 2, 3]
                seq_manager
                    .add_request(
                        "request_2".to_string(),
                        vec![0, 1, 2, 3],
                        16, // ISL (4 blocks * 4 block_size)
                        0,  // no overlap
                        2,  // worker_id
                    )
                    .await?;

                // Give some time for the commands to be processed and synchronization
                tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

                // Get active tokens from worker 2
                let tokens = seq_manager.active_tokens().await;
                active_tokens_after_add_clone2
                    .lock()
                    .unwrap()
                    .insert(2, tokens.get(&2).copied().unwrap_or(0));

                // Test potential blocks for sequence [0, 1]
                let potential = seq_manager.potential_blocks(vec![0, 1]).await;
                potential_blocks_result_clone2
                    .lock()
                    .unwrap()
                    .insert(2, potential.get(&2).copied().unwrap_or(0));

                // Wait for first thread to free its requests
                tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

                // Free request from worker 2
                seq_manager.free(&"request_2".to_string()).await?;

                // Give some time for the commands to be processed
                tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

                // Get final active blocks and tokens
                let blocks = seq_manager.active_blocks().await;
                let tokens = seq_manager.active_tokens().await;

                active_blocks_after_free_clone2
                    .lock()
                    .unwrap()
                    .insert(2, blocks.get(&2).copied().unwrap_or(0));
                active_tokens_after_free_clone2
                    .lock()
                    .unwrap()
                    .insert(2, tokens.get(&2).copied().unwrap_or(0));

                // Keep runtime alive a bit longer for synchronization
                tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

                // Shutdown runtime
                runtime.shutdown();

                Ok::<(), anyhow::Error>(())
            })
        });

        // Wait for both threads to complete
        handle1.join().unwrap()?;
        handle2.join().unwrap()?;

        // Extract results
        let tokens_after_add = active_tokens_after_add.lock().unwrap();
        let potential_blocks = potential_blocks_result.lock().unwrap();
        let blocks_after_free = active_blocks_after_free.lock().unwrap();
        let tokens_after_free = active_tokens_after_free.lock().unwrap();
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099

        // Verify active tokens after adding requests
        assert_eq!(
            tokens_after_add[&0], 12,
            "Worker 0 should have 12 active tokens"
        );
        assert_eq!(
            tokens_after_add[&1], 8,
            "Worker 1 should have 8 active tokens"
        );
        assert_eq!(
            tokens_after_add[&2], 16,
            "Worker 2 should have 16 active tokens"
        );

        // Test potential blocks for sequence [0, 1]
        // Worker 0 should return 3 (already has blocks 0, 1, 2, so no new blocks needed for [0, 1])
        assert_eq!(
            potential_blocks[&0], 3,
            "Worker 0 should have 3 potential blocks"
        );

        // Worker 1 should return 4 (has blocks 3, 4, would need to add blocks 0, 1)
        assert_eq!(
            potential_blocks[&1], 4,
            "Worker 1 should have 4 potential blocks"
        );

        // Worker 2 should return 4 (already has blocks 0, 1, 2, 3, so no new blocks needed for [0, 1])
        assert_eq!(
            potential_blocks[&2], 4,
            "Worker 2 should have 4 potential blocks"
        );

        // Verify active blocks are zero for all workers
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
        assert_eq!(
            blocks_after_free[&0], 0,
            "Worker 0 should have 0 active blocks"
        );
        assert_eq!(
            blocks_after_free[&1], 0,
            "Worker 1 should have 0 active blocks"
        );
        assert_eq!(
            blocks_after_free[&2], 0,
            "Worker 2 should have 0 active blocks"
        );
1112
1113
1114

        // Verify active tokens are zero for all workers
        assert_eq!(
1115
            tokens_after_free[&0], 0,
1116
1117
1118
            "Worker 0 should have 0 active tokens after freeing all"
        );
        assert_eq!(
1119
            tokens_after_free[&1], 0,
1120
1121
1122
            "Worker 1 should have 0 active tokens after freeing all"
        );
        assert_eq!(
1123
            tokens_after_free[&2], 0,
1124
1125
            "Worker 2 should have 0 active tokens after freeing all"
        );
1126
1127

        Ok(())
1128
1129
    }
}