indexer.rs 148 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// SPDX-License-Identifier: Apache-2.0

//! KV RadixTree
//!
//! This module implements a key-value (KV) store using a Radix Tree structure to efficiently manage and retrieve data blocks.
//! It is designed to support LLM (Large Language Model) inference by re-using a global KV cache.
//!
//! # Overview
//!
//! The main components of this module include:
//!
//! - **Radix Tree Structure**:
//!   - The `RadixTree` struct represents the main data structure, with nodes (`RadixBlock`) containing children and associated worker IDs.
//!   - It allows efficient storage and retrieval of data blocks based on their hashes.
//!
//! - **Event Handling**:
//!   - The `RouterEvent` struct represents events emitted by LLM workers, which can be applied to the Radix Tree to update its state.
//!   - The `KvIndexer` struct manages these events and match requests asynchronously using Tokio channels.
//!
//! - **Hash Computation**:
//!   - Functions like `compute_block_hash` and `compute_block_hash_for_seq` compute hashes for data blocks and sequences of tokens, facilitating quick lookups.
//!
//! - **Concurrency and Asynchronous Operations**:
//!   - The `KvIndexer` uses a single-threaded Tokio runtime to handle events and match requests concurrently, ensuring efficient processing without blocking.
//!
//! - **Match Requests**:
//!   - The `MatchRequest` struct represents requests to find matches in the Radix Tree, returning overlap scores indicating the best matches.
//!
//! # Purpose
//!
//! This module provides a scalable and efficient way to manage and retrieve data blocks for LLM inference, leveraging a global KV cache to optimize performance.

34
35
36
#[cfg(feature = "bench")]
use std::time::Instant;

37
use async_trait::async_trait;
Yan Ru Pei's avatar
Yan Ru Pei committed
38
use dashmap::DashMap;
39
40
41
#[cfg(feature = "metrics")]
pub use dynamo_runtime::protocols::maybe_error::MaybeError;
#[cfg(feature = "metrics")]
42
43
use dynamo_runtime::{
    component::Component,
44
    error::DynamoError,
45
    metrics::{MetricsHierarchy, prometheus_names::kvrouter},
46
47
};
use prometheus::{IntCounterVec, Opts};
48
use rustc_hash::FxBuildHasher;
49
50
51
52
53
54

/// Trait for types that may represent an error response.
/// Used for RPC-style responses that can indicate success or failure.
#[cfg(not(feature = "metrics"))]
pub trait MaybeError {
    /// Construct an instance from an error.
55
    fn from_err(err: impl std::error::Error + 'static) -> Self;
56
    /// Convert to an error instance if this represents an error.
57
    fn err(&self) -> Option<Box<dyn std::error::Error + Send + Sync>>;
58
}
59
use serde::{Deserialize, Serialize};
60
61
#[cfg(feature = "metrics")]
use std::sync::OnceLock;
62
use std::{
Yan Ru Pei's avatar
Yan Ru Pei committed
63
    collections::VecDeque,
64
    iter,
Yan Ru Pei's avatar
Yan Ru Pei committed
65
    sync::{Arc, Mutex, atomic::AtomicUsize},
66
    thread::JoinHandle,
67
    time::Duration,
68
69
70
71
};
use tokio::sync::{broadcast, mpsc, oneshot};
use tokio_util::sync::CancellationToken;

72
use crate::approx::{BlockEntry, PruneConfig, PruneManager};
Yan Ru Pei's avatar
Yan Ru Pei committed
73
// use crate::nested_map::NestedMap;
74
use crate::protocols::*;
75
pub use crate::radix_tree::RadixTree;
76
use dynamo_tokens::SequenceHash;
77
78
79
80
81
82
83
84
85
86
87
88

/// Errors that can occur in the KV Router.
#[derive(Debug, thiserror::Error)]
pub enum KvRouterError {
    #[error("Block not found")]
    BlockNotFound,

    #[error("Indexer is offline")]
    IndexerOffline,

    #[error("Indexer is dropped request")]
    IndexerDroppedRequest,
89
90
91

    #[error("Prune operation failed: {0}")]
    PruneFailed(String),
92
93
}

94
95
96
97
98
99
100
101
102
103
// -------
// Distributed router - Worker KV Query types
// -------

/// Request to query a worker's local KV indexer.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct WorkerKvQueryRequest {
    /// The worker ID of the worker to query.
    pub worker_id: WorkerId,

104
    /// Start event ID (inclusive). If `None`, dumps entire tree.
105
    pub start_event_id: Option<u64>,
106
    /// End event ID (inclusive). If `None`, returns up to newest available.
107
108
109
110
111
    pub end_event_id: Option<u64>,
}

/// Response from a worker's local KV indexer.
#[derive(Serialize, Deserialize, Debug, Clone)]
112
113
114
115
116
117
118
119
120
121
122
123
124
pub enum WorkerKvQueryResponse {
    /// Events served from the circular buffer (with original event IDs)
    Events(Vec<RouterEvent>),
    /// Full tree dump (with synthetic 0-indexed event IDs)
    TreeDump(Vec<RouterEvent>),
    /// Requested range is newer than available data
    TooNew {
        requested_start: Option<u64>,
        requested_end: Option<u64>,
        newest_available: u64,
    },
    /// Invalid range: end_id < start_id
    InvalidRange { start_id: u64, end_id: u64 },
125
126
127
128
    /// Query failed on worker (serialized error)
    Error(String),
}

129
#[cfg(feature = "metrics")]
130
impl MaybeError for WorkerKvQueryResponse {
131
    fn from_err(err: impl std::error::Error + 'static) -> Self {
132
133
134
        WorkerKvQueryResponse::Error(err.to_string())
    }

135
    fn err(&self) -> Option<DynamoError> {
136
        match self {
137
            WorkerKvQueryResponse::Error(msg) => Some(DynamoError::msg(msg.clone())),
138
139
140
            _ => None,
        }
    }
141
142
}

143
144
145
146
147
148
149
150
151
152
153
/// Metrics for the KV Indexer.
#[derive(Clone)]
pub struct KvIndexerMetrics {
    /// Counter of events applied.
    pub kv_cache_events_applied: IntCounterVec,
}

/// Metric status labels.
pub const METRIC_STATUS_OK: &str = "ok";
pub const METRIC_STATUS_PARENT_NOT_FOUND: &str = "parent_block_not_found";
pub const METRIC_STATUS_BLOCK_NOT_FOUND: &str = "block_not_found";
154
pub const METRIC_STATUS_INVALID_BLOCK: &str = "invalid_block";
155
156
157
158
159
160

/// Metric event labels.
pub const METRIC_EVENT_STORED: &str = "stored";
pub const METRIC_EVENT_REMOVED: &str = "removed";
pub const METRIC_EVENT_CLEARED: &str = "cleared";

161
162
163
164
/// Metric name for KV cache events applied counter.
const KV_CACHE_EVENTS_APPLIED_NAME: &str = "dynamo_kvrouter_kv_cache_events_applied";

#[cfg(feature = "metrics")]
165
166
167
static KV_INDEXER_METRICS: OnceLock<Arc<KvIndexerMetrics>> = OnceLock::new();

impl KvIndexerMetrics {
168
    #[cfg(feature = "metrics")]
169
170
171
172
173
174
175
176
    fn new(kv_cache_events_applied: IntCounterVec) -> Self {
        Self {
            kv_cache_events_applied,
        }
    }

    /// Creates a new KvIndexerMetrics from a Component, memoizing the result in
    /// KV_INDEXER_METRICS to avoid duplicate registration issues.
177
    #[cfg(feature = "metrics")]
178
179
    pub fn from_component(component: &Component) -> Arc<Self> {
        KV_INDEXER_METRICS.get_or_init(|| {
180
            match component.metrics().create_intcountervec(
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
                kvrouter::KV_CACHE_EVENTS_APPLIED,
                "Total number of KV cache events applied to index",
                &["event_type", "status"],
                &[],
            ) {
                Ok(kv_cache_events_applied) => Arc::new(Self::new(kv_cache_events_applied)),
                Err(e) => {
                    tracing::warn!("Failed to create kv indexer metrics from component: {}. Using unregistered metrics as fallback.", e);
                    Arc::new(Self::new_unregistered())
                }
            }
        }).clone()
    }

    /// Creates a new KvIndexerMetrics which is not registered with a MetricsRegistry.
    /// This may be used for tests or as a fallback for when a MetricsRegistry is not available / has errored.
    pub fn new_unregistered() -> Self {
        Self {
            kv_cache_events_applied: IntCounterVec::new(
                Opts::new(
201
                    KV_CACHE_EVENTS_APPLIED_NAME,
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
                    "Total number of KV cache events applied to index",
                ),
                &["event_type", "status"],
            )
            .unwrap(),
        }
    }

    pub fn get_event_type(event_data: &KvCacheEventData) -> &'static str {
        match event_data {
            KvCacheEventData::Stored(_) => METRIC_EVENT_STORED,
            KvCacheEventData::Removed(_) => METRIC_EVENT_REMOVED,
            KvCacheEventData::Cleared => METRIC_EVENT_CLEARED,
        }
    }

    pub fn increment_event_applied(
        &self,
        event_type: &'static str,
        result: Result<(), KvCacheEventError>,
    ) {
        match result {
            Ok(_) => {
                self.kv_cache_events_applied
                    .with_label_values(&[event_type, METRIC_STATUS_OK])
                    .inc_by(1);
            }
            Err(e) => {
                let error_label = match e {
                    KvCacheEventError::ParentBlockNotFound => METRIC_STATUS_PARENT_NOT_FOUND,
                    KvCacheEventError::BlockNotFound => METRIC_STATUS_BLOCK_NOT_FOUND,
233
                    KvCacheEventError::InvalidBlockSequence => METRIC_STATUS_INVALID_BLOCK,
234
235
236
237
238
239
240
241
242
                };
                self.kv_cache_events_applied
                    .with_label_values(&[event_type, error_label])
                    .inc_by(1);
            }
        }
    }
}

243
244
245
/// A request to find matches in the Radix Tree.
pub struct MatchRequest {
    /// A vector of `LocalBlockHash` representing the sequence to match.
Yan Ru Pei's avatar
Yan Ru Pei committed
246
    pub sequence: Vec<LocalBlockHash>,
247
    /// A boolean indicating whether to exit early if a single match is found.
Yan Ru Pei's avatar
Yan Ru Pei committed
248
    pub early_exit: bool,
249
    /// A channel sender to send the `OverlapScores` response.
Yan Ru Pei's avatar
Yan Ru Pei committed
250
    pub resp: oneshot::Sender<OverlapScores>,
251
252
    /// Timestamp when the request was created (for queue wait time measurement)
    #[cfg(feature = "bench")]
Yan Ru Pei's avatar
Yan Ru Pei committed
253
    pub created_at: Instant,
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
}

impl MatchRequest {
    fn new(
        sequence: Vec<LocalBlockHash>,
        early_exit: bool,
        resp: oneshot::Sender<OverlapScores>,
    ) -> Self {
        Self {
            sequence,
            early_exit,
            resp,
            #[cfg(feature = "bench")]
            created_at: Instant::now(),
        }
    }
270
271
}

272
273
274
275
276
277
/// A request to dump the tree as events
pub struct DumpRequest {
    /// Channel to send the dumped events
    pub resp: oneshot::Sender<Vec<RouterEvent>>,
}

278
279
280
281
282
283
/// A request to get all workers currently tracked
pub struct GetWorkersRequest {
    /// Channel to send the worker IDs
    pub resp: oneshot::Sender<Vec<WorkerId>>,
}

284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#[async_trait]
pub trait KvIndexerInterface {
    /// Find matches for a given sequence of `LocalBlockHash`es.
    ///
    /// ### Arguments
    ///
    /// * `sequence` - A vector of `LocalBlockHash` representing the sequence to match.
    ///
    /// ### Returns
    ///
    /// An `OverlapScores` representing the match scores.
    async fn find_matches(
        &self,
        sequence: Vec<LocalBlockHash>,
    ) -> Result<OverlapScores, KvRouterError>;

    /// Find matches for a given sequence of tokens.
    ///
    /// ### Arguments
    ///
    /// * `tokens` - A vector of `u32` tokens.
305
    /// * `lora_name` - Optional LoRA adapter name to include in block hash computation.
306
307
308
309
310
311
312
    ///
    /// ### Returns
    ///
    /// An `OverlapScores` representing the match scores.
    async fn find_matches_for_request(
        &self,
        tokens: &[u32],
313
        lora_name: Option<&str>,
314
315
316
317
318
319
320
    ) -> Result<OverlapScores, KvRouterError>;

    /// Apply a `RouterEvent` to the KV store.
    ///
    /// ### Arguments
    ///
    /// * `event` - The `RouterEvent` to apply.
Yan Ru Pei's avatar
Yan Ru Pei committed
321
    async fn apply_event(&self, event: RouterEvent);
322
323
324
325
326
327

    /// Remove a worker's entries from the trie.
    ///
    /// ### Arguments
    ///
    /// * `worker` - The worker to remove from the trie.
Yan Ru Pei's avatar
Yan Ru Pei committed
328
    async fn remove_worker(&self, worker: WorkerId);
329

330
331
332
333
334
335
336
337
    /// Remove a single dp_rank for a worker from the trie.
    ///
    /// Default implementation falls back to removing the entire worker.
    /// Indexers that track dp_rank-level granularity should override this.
    async fn remove_worker_dp_rank(&self, worker: WorkerId, _dp_rank: DpRank) {
        self.remove_worker(worker).await;
    }

338
    /// Shutdown the KV Indexer.
Yan Ru Pei's avatar
Yan Ru Pei committed
339
    fn shutdown(&self);
340
341
342
343
344
345
346

    /// Dump the entire tree as RouterEvents.
    ///
    /// ### Returns
    ///
    /// A vector of RouterEvents representing the current state of the tree.
    async fn dump_events(&self) -> Result<Vec<RouterEvent>, KvRouterError>;
347
348
349

    /// Process a routing decision for a request with tokens.
    ///
350
351
352
    /// Uses TokensWithHashes for lazy hash computation - if hashes were already
    /// computed (e.g., by find_best_match), they will be reused.
    ///
353
354
    /// ### Arguments
    ///
355
    /// * `tokens_with_hashes` - Tokens with lazily computed hashes.
356
357
358
    /// * `worker` - The worker (with dp_rank) that was selected.
    async fn process_routing_decision_for_request(
        &self,
359
        tokens_with_hashes: &mut TokensWithHashes,
360
361
        worker: WorkerWithDpRank,
    ) -> Result<(), KvRouterError>;
Yan Ru Pei's avatar
Yan Ru Pei committed
362
363
364
365
366
367
368
369

    /// Async task that returns when all pending events have been processed.
    /// For now, we assume that no requests or events are being sent in the meantime.
    /// Returns the amount of events still in the queue at the time of the flush.
    /// Used primarily for debugging.
    async fn flush(&self) -> usize;
}

370
371
372
373
pub enum WorkerTask {
    Event(RouterEvent),
    /// Permanently remove a worker from tracking (keep_worker: false).
    RemoveWorker(WorkerId),
374
375
    /// Remove a single dp_rank for a worker.
    RemoveWorkerDpRank(WorkerId, DpRank),
376
377
378
379
    DumpEvents(oneshot::Sender<anyhow::Result<Vec<RouterEvent>>>),
    Terminate,
}

Yan Ru Pei's avatar
Yan Ru Pei committed
380
381
382
383
384
385
386
387
388
389
390
391
392
393
// ============================================================================
// SyncIndexer trait and ThreadPoolIndexer generic wrapper
// ============================================================================

/// Trait for thread-safe data structures that support KV cache indexing operations.
///
/// All methods take `&self` and are synchronous. Implementations must be safe for
/// concurrent access (via internal locking, DashMap, etc).
///
/// This trait is used with [`ThreadPoolIndexer`], which wraps a `SyncIndexer` to
/// provide the async [`KvIndexerInterface`] with:
/// - Sticky event routing to N worker threads
/// - Inline reads on the caller's thread (no channel dispatch for find_matches)
pub trait SyncIndexer: Send + Sync + 'static {
394
395
    fn worker(&self, event_receiver: flume::Receiver<WorkerTask>) -> anyhow::Result<()>;

Yan Ru Pei's avatar
Yan Ru Pei committed
396
397
398
    /// Find matches for a sequence of block hashes.
    fn find_matches(&self, sequence: &[LocalBlockHash], early_exit: bool) -> OverlapScores;

399
400
401
402
403
404
405
    /// Dump events directly from the shared structure, bypassing worker channels.
    /// Returns `Some(events)` for backends whose tree state is fully shared (e.g.
    /// ConcurrentRadixTree). Returns `None` for backends that keep per-thread
    /// state and must dump via the worker channel.
    fn dump_events(&self) -> Option<Vec<RouterEvent>> {
        None
    }
Yan Ru Pei's avatar
Yan Ru Pei committed
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
}

/// Generic wrapper that provides [`KvIndexerInterface`] for any [`SyncIndexer`] backend.
///
/// Spawns N OS threads for processing write events (sticky-routed by WorkerId).
/// Read operations (find_matches) are executed inline on the caller's thread,
/// avoiding channel overhead and allowing reads to scale with callers.
///
/// # Architecture
///
/// ```text
///                                       +------------------------------------+
///                                       |     N Worker Threads (OS threads)  |
///                                       |                                    |
///  worker_event_channels[0] ----------> |   Thread 0: blocking recv loop     |
///  worker_event_channels[1] ----------> |   Thread 1: blocking recv loop     |
///  worker_event_channels[N] ----------> |   Thread N: blocking recv loop     |
///                                       |                                    |
///  find_matches() ---(inline)---------> |   Arc<T: SyncIndexer>              |
///                                       |   (shared, thread-safe)            |
///                                       +------------------------------------+
/// ```
pub struct ThreadPoolIndexer<T: SyncIndexer> {
    /// Shared backend - thread-safe via internal locking.
    backend: Arc<T>,

    /// Maps WorkerId to worker thread index for sticky routing.
433
    worker_assignments: DashMap<WorkerId, usize, FxBuildHasher>,
Yan Ru Pei's avatar
Yan Ru Pei committed
434
435
436
    /// Counter for round-robin assignment of new WorkerIds.
    worker_assignment_count: AtomicUsize,

437
438
439
    /// Channels to send tasks to worker threads (one per thread).
    /// Sending `WorkerTask::Terminate` signals the thread to shut down.
    worker_event_channels: Vec<flume::Sender<WorkerTask>>,
Yan Ru Pei's avatar
Yan Ru Pei committed
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471

    /// Number of worker threads.
    num_workers: usize,
    /// Block size for KV cache.
    kv_block_size: u32,

    /// Handles to worker threads for joining on shutdown.
    thread_handles: Mutex<Vec<JoinHandle<()>>>,
}

impl<T: SyncIndexer> ThreadPoolIndexer<T> {
    /// Create a new `ThreadPoolIndexer` wrapping the given backend.
    ///
    /// Spawns `num_workers` OS threads, each running a blocking recv loop
    /// that processes events by calling `backend.apply_event()`.
    ///
    /// # Arguments
    ///
    /// * `backend` - The thread-safe data structure to wrap
    /// * `num_workers` - Number of worker threads for event processing
    /// * `kv_block_size` - Block size for KV cache
    ///
    /// # Panics
    ///
    /// Panics if `num_workers` is 0.
    pub fn new(backend: T, num_workers: usize, kv_block_size: u32) -> Self {
        assert!(num_workers > 0, "Number of workers must be greater than 0");

        let backend = Arc::new(backend);
        let mut worker_event_senders = Vec::new();
        let mut thread_handles = Vec::new();
        for _ in 0..num_workers {
472
            let (event_sender, event_receiver) = flume::unbounded::<WorkerTask>();
Yan Ru Pei's avatar
Yan Ru Pei committed
473
474
475
476
477
            worker_event_senders.push(event_sender);

            let backend = Arc::clone(&backend);

            let handle = std::thread::spawn(move || {
478
                backend.worker(event_receiver).unwrap();
Yan Ru Pei's avatar
Yan Ru Pei committed
479
480
481
482
483
484
            });
            thread_handles.push(handle);
        }

        Self {
            backend,
485
            worker_assignments: DashMap::with_hasher(FxBuildHasher),
Yan Ru Pei's avatar
Yan Ru Pei committed
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
            worker_assignment_count: AtomicUsize::new(0),
            worker_event_channels: worker_event_senders,
            num_workers,
            kv_block_size,
            thread_handles: Mutex::new(thread_handles),
        }
    }

    /// Get a reference to the underlying backend.
    pub fn backend(&self) -> &T {
        &self.backend
    }

    /// Wait for all worker channels to drain.
    ///
    /// Used primarily for testing and benchmarking to ensure all queued events
    /// have been picked up by workers before checking results.
    pub async fn flush(&self) {
        loop {
            let all_empty = self.worker_event_channels.iter().all(|ch| ch.is_empty());

            if all_empty {
                break;
            }

            tokio::time::sleep(Duration::from_millis(1)).await;
        }
    }
}

#[async_trait]
impl<T: SyncIndexer> KvIndexerInterface for ThreadPoolIndexer<T> {
    async fn find_matches(
        &self,
        sequence: Vec<LocalBlockHash>,
    ) -> Result<OverlapScores, KvRouterError> {
        // Execute inline on caller's thread - no channel dispatch
        Ok(self.backend.find_matches(&sequence, false))
    }

    async fn find_matches_for_request(
        &self,
        tokens: &[u32],
529
        lora_name: Option<&str>,
Yan Ru Pei's avatar
Yan Ru Pei committed
530
    ) -> Result<OverlapScores, KvRouterError> {
531
        let sequence = compute_block_hash_for_seq(tokens, self.kv_block_size, None, lora_name);
Yan Ru Pei's avatar
Yan Ru Pei committed
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
        Ok(self.backend.find_matches(&sequence, false))
    }

    async fn apply_event(&self, event: RouterEvent) {
        let worker_id = event.worker_id;

        // Get or assign worker thread index using sticky round-robin
        let thread_idx = *self.worker_assignments.entry(worker_id).or_insert_with(|| {
            let idx = self
                .worker_assignment_count
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            idx % self.num_workers
        });

        // Send event to the assigned worker thread
547
        if let Err(e) = self.worker_event_channels[thread_idx].send(WorkerTask::Event(event)) {
Yan Ru Pei's avatar
Yan Ru Pei committed
548
549
550
551
552
553
554
555
556
            tracing::error!(
                "Failed to send event to worker thread {}: {:?}",
                thread_idx,
                e
            );
        }
    }

    async fn remove_worker(&self, worker_id: WorkerId) {
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
        // Route to the worker's assigned thread (if any), otherwise broadcast
        // to all threads since dp_ranks may be spread across threads.
        let thread_idx = self.worker_assignments.get(&worker_id).map(|v| *v);
        match thread_idx {
            Some(idx) => {
                if let Err(e) =
                    self.worker_event_channels[idx].send(WorkerTask::RemoveWorker(worker_id))
                {
                    tracing::error!(
                        "Failed to send RemoveWorker to worker thread {}: {:?}",
                        idx,
                        e
                    );
                }
            }
            None => {
                // Worker was never assigned a thread - broadcast to all
                for channel in &self.worker_event_channels {
                    let _ = channel.send(WorkerTask::RemoveWorker(worker_id));
                }
            }
        }
Yan Ru Pei's avatar
Yan Ru Pei committed
579
580
    }

581
582
583
584
585
586
587
588
    async fn remove_worker_dp_rank(&self, worker_id: WorkerId, dp_rank: DpRank) {
        // Broadcast to all threads — the dp_rank may be on any thread.
        // Don't remove from worker_assignments since other dp_ranks may still exist.
        for channel in &self.worker_event_channels {
            let _ = channel.send(WorkerTask::RemoveWorkerDpRank(worker_id, dp_rank));
        }
    }

Yan Ru Pei's avatar
Yan Ru Pei committed
589
    fn shutdown(&self) {
590
        // Send shutdown signal to all worker threads
Yan Ru Pei's avatar
Yan Ru Pei committed
591
        for channel in self.worker_event_channels.iter() {
592
            let _ = channel.send(WorkerTask::Terminate);
Yan Ru Pei's avatar
Yan Ru Pei committed
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
        }

        // Take ownership of thread handles and join them
        let handles = std::mem::take(
            &mut *self
                .thread_handles
                .lock()
                .expect("thread_handles mutex poisoned"),
        );
        for handle in handles {
            if let Err(e) = handle.join() {
                tracing::error!("Worker thread panicked during shutdown: {:?}", e);
            }
        }
    }

    async fn dump_events(&self) -> Result<Vec<RouterEvent>, KvRouterError> {
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
        // Fast path: backend can dump directly from shared state (e.g. ConcurrentRadixTree).
        if let Some(events) = self.backend.dump_events() {
            return Ok(events);
        }

        // Slow path: collect from each worker thread via channel (e.g. PositionalIndexer).
        let mut receivers = Vec::new();

        for channel in &self.worker_event_channels {
            let (resp_tx, resp_rx) = oneshot::channel::<anyhow::Result<Vec<RouterEvent>>>();
            let dump_req = WorkerTask::DumpEvents(resp_tx);

            channel
                .send(dump_req)
                .map_err(|_| KvRouterError::IndexerOffline)?;
            receivers.push(resp_rx);
        }

        let mut event_id_counter = 0;

        let mut all_events = Vec::new();

        for resp_rx in receivers {
            let mut events = resp_rx
                .await
                .map_err(|_| KvRouterError::IndexerDroppedRequest)?
                .map_err(|_| KvRouterError::IndexerOffline)?;
            for event in &mut events {
                event.event.event_id = event_id_counter;
                event_id_counter += 1;
            }
            all_events.extend(events);
        }

        Ok(all_events)
Yan Ru Pei's avatar
Yan Ru Pei committed
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
    }

    async fn process_routing_decision_for_request(
        &self,
        _tokens_with_hashes: &mut TokensWithHashes,
        _worker: WorkerWithDpRank,
    ) -> Result<(), KvRouterError> {
        // No-op: pruning not supported in ThreadPoolIndexer
        Ok(())
    }

    async fn flush(&self) -> usize {
        let curr_size: usize = self.worker_event_channels.iter().map(|ch| ch.len()).sum();
        loop {
            let all_empty = self.worker_event_channels.iter().all(|ch| ch.is_empty());

            if all_empty {
                break;
            }

            tokio::time::sleep(Duration::from_millis(1)).await;
        }
        curr_size
    }
669
670
671
672
673
674
675
}

/// A request to process a routing decision.
struct RoutingDecisionRequest {
    worker: WorkerWithDpRank,
    local_hashes: Vec<LocalBlockHash>,
    sequence_hashes: Vec<SequenceHash>,
676
677
678
}

/// The KV Indexer, managing the KV store and handling events and match requests.
679
#[derive(Clone)]
680
681
682
683
684
685
686
687
688
pub struct KvIndexer {
    /// A `CancellationToken` for managing shutdown.
    cancel: CancellationToken,
    /// A sender for `RouterEvent`s.
    event_tx: mpsc::Sender<RouterEvent>,
    /// A sender for `MatchRequest`s.
    match_tx: mpsc::Sender<MatchRequest>,
    /// A sender for remove worker requests.
    remove_worker_tx: mpsc::Sender<WorkerId>,
689
690
    /// A sender for remove worker dp_rank requests.
    remove_worker_dp_rank_tx: mpsc::Sender<(WorkerId, DpRank)>,
691
692
    /// A sender for get workers requests.
    get_workers_tx: mpsc::Sender<GetWorkersRequest>,
693
694
    /// A sender for dump requests.
    dump_tx: mpsc::Sender<DumpRequest>,
695
696
    /// A sender for routing decision requests.
    routing_tx: mpsc::Sender<RoutingDecisionRequest>,
697
    /// The size of the KV block this indexer can handle.
698
    kv_block_size: u32,
699
700
701
    /// Reference counter for Clone-aware Drop.
    /// Only the last clone should cancel the token on drop.
    _ref_count: Arc<()>,
702
703
704
705
706
707
708
709
710
}

impl KvIndexer {
    /// Create a new `KvIndexer`.
    ///
    /// ### Arguments
    ///
    /// * `token` - A `CancellationToken` for managing shutdown.
    /// * `expiration_duration` - The amount of time that block usage should be buffered.
711
712
    /// * `ttl` - The time-to-live for blocks before they expire.
    /// * `prune_config` - Configuration for tree-size based pruning.
713
714
715
716
717
718
719
    ///
    /// ### Returns
    ///
    /// A new `KvIndexer`.
    pub fn new_with_frequency(
        token: CancellationToken,
        expiration_duration: Option<Duration>,
720
        kv_block_size: u32,
721
        metrics: Arc<KvIndexerMetrics>,
722
        prune_config: Option<PruneConfig>,
723
724
725
726
    ) -> Self {
        let (event_tx, event_rx) = mpsc::channel::<RouterEvent>(2048);
        let (match_tx, match_rx) = mpsc::channel::<MatchRequest>(128);
        let (remove_worker_tx, remove_worker_rx) = mpsc::channel::<WorkerId>(16);
727
728
        let (remove_worker_dp_rank_tx, remove_worker_dp_rank_rx) =
            mpsc::channel::<(WorkerId, DpRank)>(16);
729
        let (get_workers_tx, get_workers_rx) = mpsc::channel::<GetWorkersRequest>(16);
730
        let (dump_tx, dump_rx) = mpsc::channel::<DumpRequest>(16);
731
732
        let (routing_tx, mut routing_rx) = mpsc::channel::<RoutingDecisionRequest>(2048);
        let (prune_tx, mut prune_rx) = mpsc::channel::<()>(1);
733

734
        let cancel_clone = token.clone();
735

736
        std::thread::spawn(move || {
737
738
            // Create a single-threaded tokio runtime
            let runtime = tokio::runtime::Builder::new_current_thread()
739
740
741
742
                .enable_all()
                .build()
                .unwrap();

743
744
745
746
747
            runtime.block_on(async move {
                let cancel = cancel_clone;
                let mut match_rx = match_rx;
                let mut event_rx = event_rx;
                let mut remove_worker_rx = remove_worker_rx;
748
                let mut remove_worker_dp_rank_rx = remove_worker_dp_rank_rx;
749
                let mut get_workers_rx = get_workers_rx;
750
751
                let mut dump_rx = dump_rx;
                let mut trie = RadixTree::new_with_frequency(expiration_duration);
752
753
754
755
756
757
758

                // Create PruneManager if prune_config is specified
                let mut prune_manager = prune_config.map(|config| {
                    PruneManager::<BlockEntry>::new(50, config)
                });
                let mut event_id_counter = 0u64;

759
                loop {
760
761
762
763
764
765
766
767
                    // Create a future that sleeps until the next expiration time
                    let expiry_fut = if let Some(ref pm) = prune_manager
                        && let Some(next_expiry) = pm.peek_next_expiry() {
                        tokio::time::sleep_until(next_expiry)
                    } else {
                        tokio::time::sleep(Duration::MAX)
                    };

768
769
770
771
772
773
774
                    tokio::select! {
                        biased;

                        _ = cancel.cancelled() => {
                            tracing::debug!("KvCacheIndexer progress loop shutting down");
                            return;
                        }
775

776
777
778
                        Some(worker) = remove_worker_rx.recv() => {
                            trie.remove_worker(worker);
                        }
779

780
781
782
783
                        Some((worker_id, dp_rank)) = remove_worker_dp_rank_rx.recv() => {
                            trie.remove_worker_dp_rank(worker_id, dp_rank);
                        }

784
785
786
787
788
                        Some(get_workers_req) = get_workers_rx.recv() => {
                            let workers = trie.get_workers();
                            let _ = get_workers_req.resp.send(workers);
                        }

789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
                        Some(_) = prune_rx.recv() => {
                            // Tree size-based pruning triggered
                            let Some(ref mut pm) = prune_manager else { continue };
                            let Ok(pruned) = pm.prune(trie.current_size()) else { continue };

                            for p in pruned {
                                event_id_counter += 1;
                                let event = RouterEvent::new(
                                    p.worker.worker_id,
                                    KvCacheEvent {
                                        event_id: event_id_counter,
                                        data: KvCacheEventData::Removed(KvCacheRemoveData {
                                            block_hashes: vec![p.key],
                                        }),
                                        dp_rank: p.worker.dp_rank,
                                    }
                                );
                                let _ = trie.apply_event(event);
                            }
                        }

810
811
                        Some(event) = event_rx.recv() => {
                            let event_type = KvIndexerMetrics::get_event_type(&event.event.data);
812
813
                            let event_id = event.event.event_id;
                            let worker_id = event.worker_id;
814
815
816
                            // Only clone if we need the event for prune_manager afterward
                            let event_for_prune = prune_manager.is_some().then(|| event.clone());
                            let result = trie.apply_event(event);
817
                            let result_is_ok = result.is_ok();
818
819
820
821
                            let tree_size = trie.current_size();
                            tracing::trace!(
                                "Applied KV event to global radix tree: event_type={event_type}, event_id={event_id}, worker_id={worker_id}, success={result_is_ok}, global_radix_tree_size={tree_size}"
                            );
822
                            metrics.increment_event_applied(event_type, result);
823
824
825
826

                            // Track blocks in PruneManager if TTL is enabled and event was stored successfully
                            let Some(ref mut pm) = prune_manager else { continue };
                            if !result_is_ok { continue };
827
                            let Some(ref event) = event_for_prune else { continue };
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
                            let KvCacheEventData::Stored(ref store_data) = event.event.data else { continue };

                            let worker = WorkerWithDpRank::new(event.worker_id, event.event.dp_rank);
                            let block_entries: Vec<BlockEntry> = store_data.blocks.iter().enumerate().map(|(idx, block)| {
                                BlockEntry {
                                    key: block.block_hash,
                                    worker,
                                    seq_position: idx,
                                }
                            }).collect();
                            pm.insert(block_entries);

                            // Check if we need to prune due to tree size
                            let Some(ref pc) = pm.prune_config else { continue };
                            let current_size = trie.current_size();
                            if current_size > pc.max_tree_size {
                                tracing::info!(
                                    "Pruning: tree size ({}) exceeded max tree size ({}), scheduling pruning",
                                    current_size,
                                    pc.max_tree_size
                                );
                                let _ = prune_tx.try_send(());
                            }
851
                        }
852

853
854
855
856
                        Some(dump_req) = dump_rx.recv() => {
                            let events = trie.dump_tree_as_events();
                            let _ = dump_req.resp.send(events);
                        }
857

858
859
860
861
862
863
864
865
866
867
868
869
                        Some(routing_req) = routing_rx.recv() => {
                            // Process routing decisions when TTL/pruning is enabled
                            let Some(ref mut pm) = prune_manager else { continue };

                            event_id_counter += 1;

                            let hashes = routing_req.local_hashes.iter().zip(routing_req.sequence_hashes.iter());
                            let stored_event = KvCacheEventData::Stored(KvCacheStoreData {
                                parent_hash: None,
                                blocks: hashes.map(|(local_hash, sequence_hash)| KvCacheStoredBlockData {
                                    tokens_hash: *local_hash,
                                    block_hash: ExternalSequenceBlockHash(*sequence_hash),
870
                                mm_extra_info: None,
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
                                }).collect(),
                            });

                            let event = RouterEvent::new(
                                routing_req.worker.worker_id,
                                KvCacheEvent {
                                    event_id: event_id_counter,
                                    data: stored_event,
                                    dp_rank: routing_req.worker.dp_rank,
                                }
                            );

                            if trie.apply_event(event).is_err() {
                                continue;
                            }

                            let block_entries: Vec<BlockEntry> = routing_req.sequence_hashes.iter().enumerate().map(|(idx, h)| {
                                BlockEntry {
                                    key: ExternalSequenceBlockHash(*h),
                                    worker: routing_req.worker,
                                    seq_position: idx,
                                }
                            }).collect();
                            pm.insert(block_entries);

                            // Check if we need to prune due to tree size
                            let Some(ref pc) = pm.prune_config else { continue };
                            let current_size = trie.current_size();
                            if current_size > pc.max_tree_size {
                                tracing::info!(
                                    "Pruning: tree size ({}) exceeded max tree size ({}), scheduling pruning",
                                    current_size,
                                    pc.max_tree_size
                                );
                                let _ = prune_tx.try_send(());
                            }
                        }

909
                        Some(req) = match_rx.recv() => {
910
911
912
913
914
915
916
                            #[cfg(feature = "bench")]
                            let queue_wait = req.created_at.elapsed();
                            #[cfg(feature = "bench")]
                            let seq_len = req.sequence.len();

                            #[cfg(feature = "bench")]
                            let process_start = Instant::now();
917
                            let matches = trie.find_matches(req.sequence, req.early_exit);
918
919
920
921
922
923
924
925
926
927
                            #[cfg(feature = "bench")]
                            let process_time = process_start.elapsed();

                            #[cfg(feature = "bench")]
                            tracing::info!(
                                seq_len,
                                queue_wait_us = queue_wait.as_micros() as u64,
                                process_us = process_time.as_micros() as u64,
                                "indexer: processed find_matches"
                            );
928
                            let _ = req.resp.send(matches);
929
                        }
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950

                        _ = expiry_fut => {
                            // TTL-based expiry triggered
                            let Some(ref mut pm) = prune_manager else { continue };

                            let expired = pm.pop_expired();
                            for e in expired {
                                event_id_counter += 1;
                                let event = RouterEvent::new(
                                    e.worker.worker_id,
                                    KvCacheEvent {
                                        event_id: event_id_counter,
                                        data: KvCacheEventData::Removed(KvCacheRemoveData {
                                            block_hashes: vec![e.key],
                                        }),
                                        dp_rank: e.worker.dp_rank,
                                    }
                                );
                                let _ = trie.apply_event(event);
                            }
                        }
951
                    }
952
953
                }
            });
954

955
            tracing::debug!("KvCacheIndexer task completed");
956
957
958
959
960
961
962
        });

        Self {
            cancel: token,
            event_tx,
            match_tx,
            remove_worker_tx,
963
            remove_worker_dp_rank_tx,
964
            get_workers_tx,
965
            dump_tx,
966
            routing_tx,
967
            kv_block_size,
968
            _ref_count: Arc::new(()),
969
970
971
        }
    }

972
    pub fn block_size(&self) -> u32 {
973
974
975
        self.kv_block_size
    }

976
977
978
979
980
    pub fn new(
        token: CancellationToken,
        kv_block_size: u32,
        metrics: Arc<KvIndexerMetrics>,
    ) -> Self {
981
        Self::new_with_frequency(token, None, kv_block_size, metrics, None)
982
983
984
985
986
987
988
989
990
    }

    /// Get a sender for `RouterEvent`s.
    ///
    /// ### Returns
    ///
    /// A `mpsc::Sender` for `RouterEvent`s.
    pub fn event_sender(&self) -> mpsc::Sender<RouterEvent> {
        self.event_tx.clone()
991
992
993
994
995
996
997
998
999
    }

    /// Get a sender for dump requests (snapshot events).
    ///
    /// ### Returns
    ///
    /// A `mpsc::Sender` for `DumpRequest`s.
    pub fn snapshot_event_sender(&self) -> mpsc::Sender<DumpRequest> {
        self.dump_tx.clone()
1000
    }
1001
1002
1003
1004
1005
1006
1007
1008
1009

    /// Get a sender for worker removal requests.
    ///
    /// ### Returns
    ///
    /// A `mpsc::Sender` for `WorkerId`s.
    pub fn remove_worker_sender(&self) -> mpsc::Sender<WorkerId> {
        self.remove_worker_tx.clone()
    }
1010
1011
1012
1013
1014
1015
1016
1017
1018

    /// Get a sender for get workers requests.
    ///
    /// ### Returns
    ///
    /// A `mpsc::Sender` for `GetWorkersRequest`s.
    pub fn get_workers_sender(&self) -> mpsc::Sender<GetWorkersRequest> {
        self.get_workers_tx.clone()
    }
1019
1020
1021
1022
1023
1024
1025
1026
}

#[async_trait]
impl KvIndexerInterface for KvIndexer {
    async fn find_matches(
        &self,
        sequence: Vec<LocalBlockHash>,
    ) -> Result<OverlapScores, KvRouterError> {
1027
1028
1029
        #[cfg(feature = "bench")]
        let start = Instant::now();
        let seq_len = sequence.len();
1030
        let (resp_tx, resp_rx) = oneshot::channel();
1031
        let req = MatchRequest::new(sequence, false, resp_tx);
1032
1033

        if let Err(e) = self.match_tx.send(req).await {
1034
            tracing::error!(
1035
1036
1037
1038
1039
1040
                "Failed to send match request: {:?}; the indexer maybe offline",
                e
            );
            return Err(KvRouterError::IndexerOffline);
        }

1041
        let result = resp_rx
1042
            .await
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
            .map_err(|_| KvRouterError::IndexerDroppedRequest);

        #[cfg(feature = "bench")]
        {
            let elapsed = start.elapsed();
            tracing::info!(
                seq_len,
                elapsed_us = elapsed.as_micros() as u64,
                "find_matches completed"
            );
        }
        #[cfg(not(feature = "bench"))]
        let _ = seq_len;

        result
1058
1059
1060
1061
1062
    }

    async fn find_matches_for_request(
        &self,
        tokens: &[u32],
1063
        lora_name: Option<&str>,
1064
    ) -> Result<OverlapScores, KvRouterError> {
1065
        tracing::debug!(
1066
1067
1068
1069
            "Finding matches for request tokens: {:?} / len: {}",
            tokens,
            tokens.len()
        );
1070
        let sequence = compute_block_hash_for_seq(tokens, self.kv_block_size, None, lora_name);
1071
        tracing::debug!("Computed sequence: {:?}", sequence);
1072
1073
1074
        self.find_matches(sequence).await
    }

Yan Ru Pei's avatar
Yan Ru Pei committed
1075
    async fn apply_event(&self, event: RouterEvent) {
1076
1077
1078
        self.event_tx.send(event).await.unwrap();
    }

Yan Ru Pei's avatar
Yan Ru Pei committed
1079
    async fn remove_worker(&self, worker: WorkerId) {
1080
1081
1082
        self.remove_worker_tx.send(worker).await.unwrap();
    }

1083
1084
1085
1086
1087
1088
1089
    async fn remove_worker_dp_rank(&self, worker: WorkerId, dp_rank: DpRank) {
        self.remove_worker_dp_rank_tx
            .send((worker, dp_rank))
            .await
            .unwrap();
    }

Yan Ru Pei's avatar
Yan Ru Pei committed
1090
    fn shutdown(&self) {
1091
1092
        self.cancel.cancel();
    }
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106

    async fn dump_events(&self) -> Result<Vec<RouterEvent>, KvRouterError> {
        let (resp_tx, resp_rx) = oneshot::channel();
        let dump_req = DumpRequest { resp: resp_tx };

        if let Err(e) = self.dump_tx.send(dump_req).await {
            tracing::error!("Failed to send dump request: {:?}", e);
            return Err(KvRouterError::IndexerOffline);
        }

        resp_rx
            .await
            .map_err(|_| KvRouterError::IndexerDroppedRequest)
    }
1107

1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
    async fn process_routing_decision_for_request(
        &self,
        tokens_with_hashes: &mut TokensWithHashes,
        worker: WorkerWithDpRank,
    ) -> Result<(), KvRouterError> {
        let local_hashes = tokens_with_hashes.get_or_compute_block_hashes().to_vec();
        let sequence_hashes = tokens_with_hashes.get_or_compute_seq_hashes().to_vec();

        self.process_routing_decision_internal(worker, local_hashes, sequence_hashes)
            .await
    }
Yan Ru Pei's avatar
Yan Ru Pei committed
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
    async fn flush(&self) -> usize {
        let curr_size = self.event_tx.max_capacity() - self.event_tx.capacity();
        loop {
            if self.event_tx.capacity() == self.event_tx.max_capacity() {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
        curr_size
    }
1129
1130
1131
1132
1133
}

impl KvIndexer {
    /// Internal method to process a routing decision with pre-computed hashes.
    async fn process_routing_decision_internal(
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
        &self,
        worker: WorkerWithDpRank,
        local_hashes: Vec<LocalBlockHash>,
        sequence_hashes: Vec<SequenceHash>,
    ) -> Result<(), KvRouterError> {
        self.routing_tx
            .send(RoutingDecisionRequest {
                worker,
                local_hashes,
                sequence_hashes,
            })
            .await
            .map_err(|_| KvRouterError::IndexerDroppedRequest)?;
        Ok(())
    }
1149
1150
}

1151
1152
impl Drop for KvIndexer {
    fn drop(&mut self) {
1153
1154
1155
1156
1157
        // Only cancel the token if we're the last reference.
        // This allows clones to be dropped without killing the background task.
        if Arc::strong_count(&self._ref_count) == 1 {
            self.shutdown();
        }
1158
1159
1160
    }
}

1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
// -------------------------------------------------
// Decentralized router: LocalKvIndexer for workers
// -------------------------------------------------

/// A thin wrapper around KvIndexer that buffers recent events
/// (e.g. which may be queued by router upon startup)
///
pub struct LocalKvIndexer {
    /// The underlying indexer
    indexer: KvIndexer,
    /// Circular buffer of recent events
    event_buffer: Mutex<VecDeque<RouterEvent>>,
    /// Maximum number of events to keep in buffer
    max_buffer_size: usize, // Router sets this to WORKER_KV_INDEXER_BUFFER_SIZE
}

impl LocalKvIndexer {
    /// create a new LocalKvIndexer pointing to a KvIndexer.
    pub fn new(
        token: CancellationToken,
        kv_block_size: u32,
        metrics: Arc<KvIndexerMetrics>,
        max_buffer_size: usize,
    ) -> Self {
        Self {
            indexer: KvIndexer::new(token, kv_block_size, metrics),
            event_buffer: Mutex::new(VecDeque::with_capacity(max_buffer_size)),
            max_buffer_size,
        }
    }

    /// Get all buffered events (oldest first).
    pub fn get_all_events_in_buffer(&self) -> Vec<RouterEvent> {
        let buffer = self.event_buffer.lock().unwrap();
        buffer.iter().cloned().collect()
    }

    /// Query events by ID range, returning events in `[start_id, end_id]` (both inclusive).
    ///
    /// ### Arguments
    ///
1202
    /// * `start_id` - Starting event ID (inclusive). If `None`, dumps entire tree.
1203
1204
1205
1206
    /// * `end_id` - Ending event ID (inclusive). If `None`, returns up to newest available.
    ///
    /// ### Returns
    ///
1207
1208
1209
1210
    /// - `Events`: Buffered events with original IDs (when range is within buffer)
    /// - `TreeDump`: Full tree dump with synthetic IDs (when range is too old or unspecified)
    /// - `TooNew`: Error when requested range is newer than available data
    /// - `InvalidRange`: Error when end_id < start_id
1211
1212
1213
1214
    pub async fn get_events_in_id_range(
        &self,
        start_id: Option<u64>,
        end_id: Option<u64>,
1215
    ) -> WorkerKvQueryResponse {
1216
1217
        // Validate range if both specified
        if let (Some(s), Some(e)) = (start_id, end_id)
1218
            && e < s
1219
        {
1220
1221
1222
1223
1224
            tracing::warn!(start_id = s, end_id = e, "Invalid range: end_id < start_id");
            return WorkerKvQueryResponse::InvalidRange {
                start_id: s,
                end_id: e,
            };
1225
1226
        }

1227
1228
        // Get buffer state
        let (first_id, last_id) = {
1229
1230
            let buffer = self.event_buffer.lock().unwrap();
            if buffer.is_empty() {
1231
                (None, None)
1232
            } else {
1233
1234
1235
1236
                (
                    Some(buffer.front().unwrap().event.event_id),
                    Some(buffer.back().unwrap().event.event_id),
                )
1237
1238
1239
            }
        };

1240
1241
1242
1243
1244
        // If no start_id specified, dump entire tree
        if start_id.is_none() {
            tracing::debug!("No start_id specified, dumping entire tree");
            let events = self.dump_events().await.unwrap_or_default();
            return WorkerKvQueryResponse::TreeDump(events);
1245
1246
        }

1247
1248
        let start_id = start_id.unwrap();
        let end_id = end_id.unwrap_or_else(|| last_id.unwrap_or(start_id));
1249

1250
1251
1252
1253
1254
1255
1256
        // Check for empty buffer
        let Some(first_buffered) = first_id else {
            tracing::debug!("Buffer empty, dumping entire tree");
            let events = self.dump_events().await.unwrap_or_default();
            return WorkerKvQueryResponse::TreeDump(events);
        };
        let last_buffered = last_id.unwrap();
1257

1258
1259
        // Check if request is too new
        if start_id > last_buffered {
1260
1261
            tracing::warn!(
                start_id,
1262
1263
                last_buffered,
                "Requested start_id is newer than buffer"
1264
            );
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
            return WorkerKvQueryResponse::TooNew {
                requested_start: Some(start_id),
                requested_end: Some(end_id),
                newest_available: last_buffered,
            };
        }

        // Check if start_id is too old (before buffer) -> tree dump
        if start_id < first_buffered {
            tracing::info!(
                start_id,
                first_buffered,
                "Requested start_id is older than buffer, dumping entire tree"
            );
            let events = self.dump_events().await.unwrap_or_default();
            return WorkerKvQueryResponse::TreeDump(events);
1281
1282
        }

1283
1284
1285
        // Serve from buffer
        let buffer = self.event_buffer.lock().unwrap();

1286
1287
1288
1289
1290
        let start_idx = match buffer.binary_search_by_key(&start_id, |e| e.event.event_id) {
            Ok(idx) => idx,
            Err(insertion_point) => insertion_point,
        };

1291
1292
1293
        // Clamp end_id to buffer bounds
        let clamped_end_id = end_id.min(last_buffered);
        let end_idx = match buffer.binary_search_by_key(&clamped_end_id, |e| e.event.event_id) {
1294
1295
1296
1297
            Ok(idx) => idx + 1, // Include the matched element
            Err(insertion_point) => insertion_point,
        };

1298
        let events: Vec<RouterEvent> = buffer
1299
1300
1301
1302
            .iter()
            .skip(start_idx)
            .take(end_idx.saturating_sub(start_idx))
            .cloned()
1303
1304
1305
            .collect();

        WorkerKvQueryResponse::Events(events)
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
    }

    /// Record an event in the buffer
    fn record_event(&self, event: RouterEvent) {
        let mut buffer = self.event_buffer.lock().unwrap();

        // Check that event id is consecutive to last one
        if let Some(last_event) = buffer.back()
            && event.event.event_id != last_event.event.event_id + 1
        {
            let expected = last_event.event.event_id + 1;
            tracing::error!(
                worker_id = event.worker_id,
                expected,
                got = event.event.event_id,
                "Non-consecutive KV event id; buffer may have gaps"
            );
        }
1324
        tracing::debug!(
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
            "Recorded event {:?} in buffer, now size is {}",
            event,
            buffer.len()
        );

        // Add to back
        buffer.push_back(event);

        // Remove from front if over capacity (circular buffer behavior)
        while buffer.len() > self.max_buffer_size {
            buffer.pop_front();
        }
    }

    /// Apply event with buffering.
    ///
    /// This records the event in the buffer and forwards it to the underlying indexer.
    pub async fn apply_event_with_buffer(&self, event: RouterEvent) -> Result<(), KvRouterError> {
        // Record in buffer
        self.record_event(event.clone());

        // Forward to underlying indexer
        self.indexer
            .event_sender()
            .send(event)
            .await
            .map_err(|_| KvRouterError::IndexerOffline)
    }

    /// Clear the event buffer.
    pub fn clear_buffer(&self) {
        let mut buffer = self.event_buffer.lock().unwrap();
        buffer.clear();
    }

    /// Get the current buffer size.
    pub fn buffer_len(&self) -> usize {
        let buffer = self.event_buffer.lock().unwrap();
        buffer.len()
    }

    // Delegation methods to underlying KvIndexer
    /// Get a sender for `RouterEvent`s.
    pub fn event_sender(&self) -> mpsc::Sender<RouterEvent> {
        self.indexer.event_sender()
    }

    /// Get a sender for dump requests (snapshot events).
    pub fn snapshot_event_sender(&self) -> mpsc::Sender<DumpRequest> {
        self.indexer.snapshot_event_sender()
    }

    /// Get a sender for worker removal requests.
    pub fn remove_worker_sender(&self) -> mpsc::Sender<WorkerId> {
        self.indexer.remove_worker_sender()
    }

    /// Get a sender for get workers requests.
    pub fn get_workers_sender(&self) -> mpsc::Sender<GetWorkersRequest> {
        self.indexer.get_workers_sender()
    }

    /// Get the KV block size.
    pub fn block_size(&self) -> u32 {
        self.indexer.block_size()
    }
}

1393
1394
1395
1396
1397
1398
1399
1400
// Implement KvIndexerInterface by delegating to the underlying indexer
#[async_trait]
impl KvIndexerInterface for LocalKvIndexer {
    async fn find_matches(
        &self,
        sequence: Vec<LocalBlockHash>,
    ) -> Result<OverlapScores, KvRouterError> {
        self.indexer.find_matches(sequence).await
1401
1402
    }

1403
1404
1405
    async fn find_matches_for_request(
        &self,
        tokens: &[u32],
1406
        lora_name: Option<&str>,
1407
    ) -> Result<OverlapScores, KvRouterError> {
1408
1409
1410
        self.indexer
            .find_matches_for_request(tokens, lora_name)
            .await
1411
    }
1412

Yan Ru Pei's avatar
Yan Ru Pei committed
1413
    async fn apply_event(&self, event: RouterEvent) {
1414
1415
1416
        // Use the buffering version
        let _ = self.apply_event_with_buffer(event).await;
    }
1417

Yan Ru Pei's avatar
Yan Ru Pei committed
1418
    async fn remove_worker(&self, worker: WorkerId) {
1419
1420
        let _ = self.indexer.remove_worker_sender().send(worker).await;
    }
1421

Yan Ru Pei's avatar
Yan Ru Pei committed
1422
    fn shutdown(&self) {
1423
1424
1425
1426
        // Note: Since indexer is Arc<KvIndexer>, we can't call mutable methods directly.
        // The indexer will be shut down when the CancellationToken is cancelled
        // or when the last Arc reference is dropped.
    }
1427

1428
1429
1430
    async fn dump_events(&self) -> Result<Vec<RouterEvent>, KvRouterError> {
        self.indexer.dump_events().await
    }
1431

1432
1433
    async fn process_routing_decision_for_request(
        &self,
1434
        tokens_with_hashes: &mut TokensWithHashes,
1435
1436
1437
1438
1439
        worker: WorkerWithDpRank,
    ) -> Result<(), KvRouterError> {
        // TODO I guess the local kvindexers have little use for this method?
        // Keeping it here now to implement the trait fully
        self.indexer
1440
            .process_routing_decision_for_request(tokens_with_hashes, worker)
1441
            .await
1442
    }
Yan Ru Pei's avatar
Yan Ru Pei committed
1443
1444
1445
1446

    async fn flush(&self) -> usize {
        self.indexer.flush().await
    }
1447
}
1448

1449
1450
1451
1452
1453
#[derive(Debug, Clone)]
pub struct ShardedMatchRequest {
    sequence: Vec<LocalBlockHash>,
    early_exit: bool,
    resp: mpsc::Sender<OverlapScores>,
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
    #[cfg(feature = "bench")]
    created_at: Instant,
}

impl ShardedMatchRequest {
    fn new(
        sequence: Vec<LocalBlockHash>,
        early_exit: bool,
        resp: mpsc::Sender<OverlapScores>,
    ) -> Self {
        Self {
            sequence,
            early_exit,
            resp,
            #[cfg(feature = "bench")]
            created_at: Instant::now(),
        }
    }
1472
}
1473

1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
/// A sharded KV Indexer that partitions the RadixTree across multiple independent shards.
///
/// ## Sharding Strategy
/// - Each worker is **permanently assigned** to a single shard on first event
/// - All KV blocks from a worker exist only in that worker's assigned shard
/// - New workers are assigned to the shard with the fewest workers (load balancing)
///
/// ## Operation
/// - **Events**: Routed directly to the worker's assigned shard
/// - **Match requests**: Broadcast to all shards (scatter-gather pattern)
/// - **Threading**: Each shard runs in its own thread with a single-threaded runtime
///
/// This design ensures no cross-shard synchronization for writes while enabling
/// parallel processing and better scalability.
pub struct KvIndexerSharded {
    /// A `CancellationToken` for managing shutdown.
    cancel: CancellationToken,
    /// The size of the KV block this indexer can handle.
    kv_block_size: u32,
1493
    worker_assignments: DashMap<WorkerId, usize, FxBuildHasher>,
Yan Ru Pei's avatar
Yan Ru Pei committed
1494
    worker_counts: Arc<Mutex<Vec<usize>>>,
1495

1496
1497
1498
    event_tx: Vec<mpsc::Sender<RouterEvent>>,
    request_broadcast_tx: broadcast::Sender<ShardedMatchRequest>,
    remove_worker_tx: Vec<mpsc::Sender<WorkerId>>,
1499
    remove_worker_dp_rank_tx: Vec<mpsc::Sender<(WorkerId, DpRank)>>,
1500
1501
    dump_tx: Vec<mpsc::Sender<DumpRequest>>,
    routing_tx: Vec<mpsc::Sender<RoutingDecisionRequest>>,
Yan Ru Pei's avatar
Yan Ru Pei committed
1502
    tasks: Arc<Mutex<Vec<JoinHandle<()>>>>,
1503
}
1504

1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
impl KvIndexerSharded {
    /// Create a new `KvIndexerSharded`.
    ///
    /// ### Arguments
    ///
    /// * `token` - A `CancellationToken` for managing shutdown.
    /// * `shards` - A list of kvindexer shards.
    /// * `expiration_duration` - The amount of time that block usage should be buffered.
    /// * `ttl` - The time-to-live for blocks before they expire.
    /// * `prune_config` - Configuration for tree-size based pruning.
    ///
    /// ### Returns
    ///
    /// A new `KvIndexer`.
    pub fn new_with_frequency(
        token: CancellationToken,
        num_shards: usize,
        expiration_duration: Option<Duration>,
        kv_block_size: u32,
        metrics: Arc<KvIndexerMetrics>,
        prune_config: Option<PruneConfig>,
    ) -> Self {
1527
        let worker_assignments = DashMap::with_hasher(FxBuildHasher);
Yan Ru Pei's avatar
Yan Ru Pei committed
1528
        let worker_counts = Arc::new(Mutex::new(vec![0; num_shards]));
1529

1530
1531
        let mut event_tx = Vec::new();
        let mut remove_worker_tx = Vec::new();
1532
        let mut remove_worker_dp_rank_tx = Vec::new();
1533
1534
1535
        let mut get_workers_tx = Vec::new();
        let mut dump_tx = Vec::new();
        let mut routing_tx = Vec::new();
Yan Ru Pei's avatar
Yan Ru Pei committed
1536
        let tasks = Arc::new(Mutex::new(Vec::new()));
1537

1538
        let (request_broadcast_tx, _) = broadcast::channel::<ShardedMatchRequest>(1048576);
1539
1540
1541
1542
1543

        for _ in 0..num_shards {
            let (shard_event_tx, mut shard_event_rx) = mpsc::channel::<RouterEvent>(2048);
            let (shard_remove_worker_tx, mut shard_remove_worker_rx) =
                mpsc::channel::<WorkerId>(16);
1544
1545
            let (shard_remove_worker_dp_rank_tx, mut shard_remove_worker_dp_rank_rx) =
                mpsc::channel::<(WorkerId, DpRank)>(16);
1546
1547
            let (shard_get_workers_tx, mut shard_get_workers_rx) =
                mpsc::channel::<GetWorkersRequest>(16);
1548
1549
1550
1551
            let (shard_dump_tx, mut shard_dump_rx) = mpsc::channel::<DumpRequest>(16);
            let (shard_routing_tx, mut shard_routing_rx) =
                mpsc::channel::<RoutingDecisionRequest>(2048);
            let (shard_prune_tx, mut shard_prune_rx) = mpsc::channel::<()>(1);
1552
1553
            let mut shard_broadcast_rx = request_broadcast_tx.subscribe();
            let cancel = token.clone();
1554
            let metrics = metrics.clone();
1555
            let prune_config_clone = prune_config.clone();
1556
1557
1558

            event_tx.push(shard_event_tx);
            remove_worker_tx.push(shard_remove_worker_tx);
1559
            remove_worker_dp_rank_tx.push(shard_remove_worker_dp_rank_tx);
1560
            get_workers_tx.push(shard_get_workers_tx);
1561
1562
            dump_tx.push(shard_dump_tx);
            routing_tx.push(shard_routing_tx);
1563

1564
            let runtime = tokio::runtime::Builder::new_current_thread()
1565
1566
1567
1568
                .enable_all()
                .build()
                .unwrap();

Yan Ru Pei's avatar
Yan Ru Pei committed
1569
            tasks.lock().unwrap().push(std::thread::spawn(move || {
1570
1571
                runtime.block_on(async move {
                    let mut trie = RadixTree::new_with_frequency(expiration_duration);
1572
1573
1574
1575
1576
1577
1578

                    // Create PruneManager if prune_config is specified
                    let mut prune_manager = prune_config_clone.map(|config| {
                        PruneManager::<BlockEntry>::new(50, config)
                    });
                    let mut event_id_counter = 0u64;

1579
                    loop {
1580
1581
1582
1583
1584
1585
1586
1587
                        // Create a future that sleeps until the next expiration time
                        let expiry_fut = if let Some(ref pm) = prune_manager
                            && let Some(next_expiry) = pm.peek_next_expiry() {
                            tokio::time::sleep_until(next_expiry)
                        } else {
                            tokio::time::sleep(Duration::MAX)
                        };

1588
1589
                        tokio::select! {
                            biased;
1590

1591
1592
1593
1594
                            _ = cancel.cancelled() => {
                                tracing::trace!("KvCacheIndexer progress loop shutting down");
                                return;
                            }
1595

1596
1597
1598
                            Some(worker) = shard_remove_worker_rx.recv() => {
                                trie.remove_worker(worker);
                            }
1599

1600
1601
1602
1603
                            Some((worker_id, dp_rank)) = shard_remove_worker_dp_rank_rx.recv() => {
                                trie.remove_worker_dp_rank(worker_id, dp_rank);
                            }

1604
1605
1606
1607
1608
                            Some(get_workers_req) = shard_get_workers_rx.recv() => {
                                let workers = trie.get_workers();
                                let _ = get_workers_req.resp.send(workers);
                            }

1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
                            Some(_) = shard_prune_rx.recv() => {
                                // Tree size-based pruning triggered
                                let Some(ref mut pm) = prune_manager else { continue };
                                let Ok(pruned) = pm.prune(trie.current_size()) else { continue };

                                for p in pruned {
                                    event_id_counter += 1;
                                    let event = RouterEvent::new(
                                        p.worker.worker_id,
                                        KvCacheEvent {
                                            event_id: event_id_counter,
                                            data: KvCacheEventData::Removed(KvCacheRemoveData {
                                                block_hashes: vec![p.key],
                                            }),
                                            dp_rank: p.worker.dp_rank,
                                        }
                                    );
                                    let _ = trie.apply_event(event);
                                }
                            }

1630
1631
                            Some(event) = shard_event_rx.recv() => {
                                let event_type = KvIndexerMetrics::get_event_type(&event.event.data);
1632
1633
1634
                                // Only clone if we need the event for prune_manager afterward
                                let event_for_prune = prune_manager.is_some().then(|| event.clone());
                                let result = trie.apply_event(event);
1635
                                let result_is_ok = result.is_ok();
1636
                                metrics.increment_event_applied(event_type, result);
1637
1638
1639
1640

                                // Track blocks in PruneManager if TTL is enabled and event was stored successfully
                                let Some(ref mut pm) = prune_manager else { continue };
                                if !result_is_ok { continue };
1641
                                let Some(ref event) = event_for_prune else { continue };
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
                                let KvCacheEventData::Stored(ref store_data) = event.event.data else { continue };

                                let worker = WorkerWithDpRank::new(event.worker_id, event.event.dp_rank);
                                let block_entries: Vec<BlockEntry> = store_data.blocks.iter().enumerate().map(|(idx, block)| {
                                    BlockEntry {
                                        key: block.block_hash,
                                        worker,
                                        seq_position: idx,
                                    }
                                }).collect();
                                pm.insert(block_entries);

                                // Check if we need to prune due to tree size
                                let Some(ref pc) = pm.prune_config else { continue };
                                let current_size = trie.current_size();
                                if current_size > pc.max_tree_size {
                                    tracing::info!(
                                        "Pruning: tree size ({}) exceeded max tree size ({}), scheduling pruning",
                                        current_size,
                                        pc.max_tree_size
                                    );
                                    let _ = shard_prune_tx.try_send(());
                                }
                            }

                            Some(routing_req) = shard_routing_rx.recv() => {
                                // Process routing decisions when TTL/pruning is enabled
                                let Some(ref mut pm) = prune_manager else { continue };

                                event_id_counter += 1;

                                let hashes = routing_req.local_hashes.iter().zip(routing_req.sequence_hashes.iter());
                                let stored_event = KvCacheEventData::Stored(KvCacheStoreData {
                                    parent_hash: None,
                                    blocks: hashes.map(|(local_hash, sequence_hash)| KvCacheStoredBlockData {
                                        tokens_hash: *local_hash,
                                        block_hash: ExternalSequenceBlockHash(*sequence_hash),
1679
                                mm_extra_info: None,
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
                                    }).collect(),
                                });

                                let event = RouterEvent::new(
                                    routing_req.worker.worker_id,
                                    KvCacheEvent {
                                        event_id: event_id_counter,
                                        data: stored_event,
                                        dp_rank: routing_req.worker.dp_rank,
                                    }
                                );

                                if trie.apply_event(event).is_err() {
                                    continue;
                                }

                                let block_entries: Vec<BlockEntry> = routing_req.sequence_hashes.iter().enumerate().map(|(idx, h)| {
                                    BlockEntry {
                                        key: ExternalSequenceBlockHash(*h),
                                        worker: routing_req.worker,
                                        seq_position: idx,
                                    }
                                }).collect();
                                pm.insert(block_entries);

                                // Check if we need to prune due to tree size
                                let Some(ref pc) = pm.prune_config else { continue };
                                let current_size = trie.current_size();
                                if current_size > pc.max_tree_size {
                                    tracing::info!(
                                        "Pruning: tree size ({}) exceeded max tree size ({}), scheduling pruning",
                                        current_size,
                                        pc.max_tree_size
                                    );
                                    let _ = shard_prune_tx.try_send(());
                                }
1716
                            }
1717

1718
1719
1720
1721
1722
1723
                            Some(dump_req) = shard_dump_rx.recv() => {
                                let events = trie.dump_tree_as_events();
                                let _ = dump_req.resp.send(events);
                            }

                            Ok(req) = shard_broadcast_rx.recv() => {
1724
1725
1726
1727
1728
1729
1730
                                #[cfg(feature = "bench")]
                                let queue_wait = req.created_at.elapsed();
                                #[cfg(feature = "bench")]
                                let seq_len = req.sequence.len();

                                #[cfg(feature = "bench")]
                                let process_start = Instant::now();
1731
                                let matches = trie.find_matches(req.sequence, req.early_exit);
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
                                #[cfg(feature = "bench")]
                                let process_time = process_start.elapsed();

                                #[cfg(feature = "bench")]
                                tracing::info!(
                                    seq_len,
                                    queue_wait_us = queue_wait.as_micros() as u64,
                                    process_us = process_time.as_micros() as u64,
                                    "sharded indexer: processed find_matches"
                                );
1742
1743
                                if let Err(e) = req.resp.send(matches).await {
                                    tracing::trace!("Failed to send match response: {:?}", e);
1744
1745
                                }
                            }
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766

                            _ = expiry_fut => {
                                // TTL-based expiry triggered
                                let Some(ref mut pm) = prune_manager else { continue };

                                let expired = pm.pop_expired();
                                for e in expired {
                                    event_id_counter += 1;
                                    let event = RouterEvent::new(
                                        e.worker.worker_id,
                                        KvCacheEvent {
                                            event_id: event_id_counter,
                                            data: KvCacheEventData::Removed(KvCacheRemoveData {
                                                block_hashes: vec![e.key],
                                            }),
                                            dp_rank: e.worker.dp_rank,
                                        }
                                    );
                                    let _ = trie.apply_event(event);
                                }
                            }
1767
                        }
1768
1769
                    }
                });
1770

1771
                tracing::debug!("KvCacheIndexer task completed");
1772
1773
1774
1775
1776
            }));
        }

        Self {
            cancel: token,
1777
            kv_block_size,
1778
1779
1780
1781
1782
            worker_assignments,
            worker_counts,
            event_tx,
            request_broadcast_tx,
            remove_worker_tx,
1783
            remove_worker_dp_rank_tx,
1784
1785
            dump_tx,
            routing_tx,
1786
1787
1788
1789
            tasks,
        }
    }

1790
    pub fn block_size(&self) -> u32 {
1791
1792
1793
        self.kv_block_size
    }

1794
1795
1796
1797
1798
1799
    pub fn new(
        token: CancellationToken,
        num_shards: usize,
        kv_block_size: u32,
        metrics: Arc<KvIndexerMetrics>,
    ) -> Self {
1800
        Self::new_with_frequency(token, num_shards, None, kv_block_size, metrics, None)
1801
1802
1803
1804
1805
1806
1807
1808
1809
    }
}

#[async_trait]
impl KvIndexerInterface for KvIndexerSharded {
    async fn find_matches(
        &self,
        sequence: Vec<LocalBlockHash>,
    ) -> Result<OverlapScores, KvRouterError> {
1810
1811
1812
1813
1814
1815
1816
        #[cfg(feature = "bench")]
        let start = Instant::now();
        #[cfg(feature = "bench")]
        let seq_len = sequence.len();
        #[cfg(feature = "bench")]
        let num_shards = self.event_tx.len();

1817
1818
        'match_loop: loop {
            let (match_tx, mut match_rx) = mpsc::channel(self.event_tx.len());
1819
            let sharded_req = ShardedMatchRequest::new(sequence.clone(), false, match_tx);
1820
            self.request_broadcast_tx
1821
                .send(sharded_req)
1822
1823
1824
1825
1826
1827
1828
1829
                .map_err(|_| KvRouterError::IndexerOffline)?;

            let mut scores = OverlapScores::new();

            for response_num in 0..self.event_tx.len() {
                match match_rx.recv().await {
                    Some(response) => {
                        scores.scores.extend(response.scores);
1830
                        scores.tree_sizes.extend(response.tree_sizes);
1831
1832
1833
1834
1835
1836
1837
1838

                        if response_num == 0 {
                            scores.frequencies = response.frequencies;
                        } else {
                            let diff = (response.frequencies.len() as i64)
                                - (scores.frequencies.len() as i64);

                            if diff > 0 {
1839
                                scores.frequencies.extend(iter::repeat_n(0, diff as usize));
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
                            }

                            for i in 0..response.frequencies.len() {
                                scores.frequencies[i] += response.frequencies[i];
                            }
                        }
                    }
                    None => {
                        // This can only happen if the broadcast channel overflows.
                        // In this case, we don't want to recursively call find_matches again. Otherwise, we could overflow the stack.
                        continue 'match_loop;
                    }
                }
            }
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864

            #[cfg(feature = "bench")]
            {
                let elapsed = start.elapsed();
                tracing::info!(
                    seq_len,
                    num_shards,
                    elapsed_us = elapsed.as_micros() as u64,
                    "find_matches (sharded) completed"
                );
            }
1865
1866
1867
1868
1869
1870
1871
            return Ok(scores);
        }
    }

    async fn find_matches_for_request(
        &self,
        tokens: &[u32],
1872
        lora_name: Option<&str>,
1873
    ) -> Result<OverlapScores, KvRouterError> {
1874
        let sequence = compute_block_hash_for_seq(tokens, self.kv_block_size, None, lora_name);
1875
1876
1877
        self.find_matches(sequence).await
    }

Yan Ru Pei's avatar
Yan Ru Pei committed
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
    async fn apply_event(&self, event: RouterEvent) {
        let shard = self
            .worker_assignments
            .entry(event.worker_id)
            .or_insert_with(|| {
                // Get the shard with the smallest amount of workers.
                let worker_counts = self.worker_counts.lock().unwrap();
                let selected_shard = worker_counts
                    .iter()
                    .enumerate()
                    .min_by_key(|&(_, value)| value)
                    .unwrap()
                    .0;
                drop(worker_counts);

                // Increment the count for this shard
                self.worker_counts.lock().unwrap()[selected_shard] += 1;
                selected_shard
            });
1897

Yan Ru Pei's avatar
Yan Ru Pei committed
1898
        self.event_tx[*shard].send(event).await.unwrap();
1899
1900
    }

Yan Ru Pei's avatar
Yan Ru Pei committed
1901
1902
1903
    async fn remove_worker(&self, worker: WorkerId) {
        if let Some((_, shard)) = self.worker_assignments.remove(&worker) {
            self.worker_counts.lock().unwrap()[shard] -= 1;
1904
1905
1906
1907
            self.remove_worker_tx[shard].send(worker).await.unwrap();
        }
    }

1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
    async fn remove_worker_dp_rank(&self, worker: WorkerId, dp_rank: DpRank) {
        // Worker is assigned to a single shard, so route there directly.
        // Don't remove from worker_assignments since other dp_ranks may still exist.
        if let Some(shard) = self.worker_assignments.get(&worker) {
            self.remove_worker_dp_rank_tx[*shard]
                .send((worker, dp_rank))
                .await
                .unwrap();
        }
    }

1919
    /// Shutdown the KV Indexer.
Yan Ru Pei's avatar
Yan Ru Pei committed
1920
    fn shutdown(&self) {
1921
        self.cancel.cancel();
Yan Ru Pei's avatar
Yan Ru Pei committed
1922
1923
1924
        let mut tasks = self.tasks.lock().unwrap();
        while !tasks.is_empty() {
            tasks.pop().unwrap().join().unwrap();
1925
1926
        }
    }
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955

    async fn dump_events(&self) -> Result<Vec<RouterEvent>, KvRouterError> {
        let mut all_events = Vec::new();

        // Create channels for each shard
        let mut receivers = Vec::new();

        for shard_dump_tx in &self.dump_tx {
            let (resp_tx, resp_rx) = oneshot::channel();
            let dump_req = DumpRequest { resp: resp_tx };

            if let Err(e) = shard_dump_tx.send(dump_req).await {
                tracing::error!("Failed to send dump request to shard: {:?}", e);
                return Err(KvRouterError::IndexerOffline);
            }

            receivers.push(resp_rx);
        }

        // Collect results from all shards
        for resp_rx in receivers {
            match resp_rx.await {
                Ok(events) => all_events.extend(events),
                Err(_) => return Err(KvRouterError::IndexerDroppedRequest),
            }
        }

        Ok(all_events)
    }
1956

1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
    async fn process_routing_decision_for_request(
        &self,
        tokens_with_hashes: &mut TokensWithHashes,
        worker: WorkerWithDpRank,
    ) -> Result<(), KvRouterError> {
        let local_hashes = tokens_with_hashes.get_or_compute_block_hashes().to_vec();
        let sequence_hashes = tokens_with_hashes.get_or_compute_seq_hashes().to_vec();

        self.process_routing_decision_internal(worker, local_hashes, sequence_hashes)
            .await
    }
Yan Ru Pei's avatar
Yan Ru Pei committed
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986

    async fn flush(&self) -> usize {
        let curr_size = self
            .event_tx
            .iter()
            .map(|tx| tx.max_capacity() - tx.capacity())
            .sum();
        loop {
            if self
                .event_tx
                .iter()
                .all(|tx| tx.capacity() == tx.max_capacity())
            {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
        curr_size
    }
1987
1988
1989
1990
1991
}

impl KvIndexerSharded {
    /// Internal method to process a routing decision with pre-computed hashes.
    async fn process_routing_decision_internal(
1992
1993
1994
1995
1996
1997
1998
1999
2000
        &self,
        worker: WorkerWithDpRank,
        local_hashes: Vec<LocalBlockHash>,
        sequence_hashes: Vec<SequenceHash>,
    ) -> Result<(), KvRouterError> {
        // Route to the appropriate shard based on worker assignment
        let shard_idx = self
            .worker_assignments
            .get(&worker.worker_id)
Yan Ru Pei's avatar
Yan Ru Pei committed
2001
2002
            .map(|shard_idx| *shard_idx)
            .unwrap_or_default();
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013

        self.routing_tx[shard_idx]
            .send(RoutingDecisionRequest {
                worker,
                local_hashes,
                sequence_hashes,
            })
            .await
            .map_err(|_| KvRouterError::IndexerDroppedRequest)?;
        Ok(())
    }
2014
2015
}

2016
2017
2018
2019
2020
2021
impl Drop for KvIndexerSharded {
    fn drop(&mut self) {
        self.shutdown();
    }
}

2022
2023
2024
#[cfg(test)]
mod tests {
    use super::*;
Yan Ru Pei's avatar
Yan Ru Pei committed
2025
2026
    use crate::concurrent_radix_tree::ConcurrentRadixTree;
    use crate::nested_map::PositionalIndexer;
2027
2028
2029
2030
    use crate::protocols::{
        ExternalSequenceBlockHash, LocalBlockHash, compute_block_hash_for_seq,
        compute_seq_hash_for_block,
    };
2031
    use rstest::rstest;
2032
    use rstest_reuse::{self, *};
2033
    use std::time::Instant;
2034
2035
2036
    use tokio::time;
    use tokio_util::sync::CancellationToken;

Yan Ru Pei's avatar
Yan Ru Pei committed
2037
2038
2039
2040
2041
2042
2043
    // ============================================================================
    // Helper functions
    // ============================================================================

    /// Create a store event with proper sequence hashes computed from local hashes.
    fn make_store_event(worker_id: u64, local_hashes: &[u64]) -> RouterEvent {
        make_store_event_with_dp_rank(worker_id, local_hashes, 0)
2044
2045
    }

Yan Ru Pei's avatar
Yan Ru Pei committed
2046
2047
2048
2049
2050
2051
2052
    /// Create a store event with a specific dp_rank.
    fn make_store_event_with_dp_rank(
        worker_id: u64,
        local_hashes: &[u64],
        dp_rank: u32,
    ) -> RouterEvent {
        make_store_event_full(worker_id, local_hashes, dp_rank, None)
2053
2054
    }

Yan Ru Pei's avatar
Yan Ru Pei committed
2055
2056
2057
2058
2059
2060
2061
    /// Create a store event with parent hash for continuation sequences.
    /// `prefix_hashes` are the hashes of the prefix (to compute parent_hash).
    /// `local_hashes` are the new blocks being stored.
    fn make_store_event_with_parent(
        worker_id: u64,
        prefix_hashes: &[u64],
        local_hashes: &[u64],
2062
    ) -> RouterEvent {
Yan Ru Pei's avatar
Yan Ru Pei committed
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
        // Compute the parent hash from the prefix
        let prefix_block_hashes: Vec<LocalBlockHash> =
            prefix_hashes.iter().map(|&h| LocalBlockHash(h)).collect();
        let prefix_seq_hashes = compute_seq_hash_for_block(&prefix_block_hashes);
        let parent_hash = prefix_seq_hashes
            .last()
            .map(|&h| ExternalSequenceBlockHash(h));

        // Compute the full sequence including prefix for proper seq_hash calculation
        let full_hashes: Vec<u64> = prefix_hashes
            .iter()
            .chain(local_hashes.iter())
            .copied()
            .collect();
        let full_block_hashes: Vec<LocalBlockHash> =
            full_hashes.iter().map(|&h| LocalBlockHash(h)).collect();
        let full_seq_hashes = compute_seq_hash_for_block(&full_block_hashes);

        // Only include the new blocks (skip prefix)
        let new_block_hashes: Vec<LocalBlockHash> =
            local_hashes.iter().map(|&h| LocalBlockHash(h)).collect();
        let new_seq_hashes = &full_seq_hashes[prefix_hashes.len()..];

2086
2087
2088
        RouterEvent {
            worker_id,
            event: KvCacheEvent {
Yan Ru Pei's avatar
Yan Ru Pei committed
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
                event_id: 0,
                data: KvCacheEventData::Stored(KvCacheStoreData {
                    parent_hash,
                    blocks: new_block_hashes
                        .iter()
                        .zip(new_seq_hashes.iter())
                        .map(|(&local, &seq)| KvCacheStoredBlockData {
                            tokens_hash: local,
                            block_hash: ExternalSequenceBlockHash(seq),
                            mm_extra_info: None,
                        })
                        .collect(),
                }),
Yan Ru Pei's avatar
Yan Ru Pei committed
2102
                dp_rank: 0,
2103
2104
2105
2106
            },
        }
    }

Yan Ru Pei's avatar
Yan Ru Pei committed
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
    /// Create a store event with all options.
    fn make_store_event_full(
        worker_id: u64,
        local_hashes: &[u64],
        dp_rank: u32,
        parent_hash: Option<ExternalSequenceBlockHash>,
    ) -> RouterEvent {
        let local_block_hashes: Vec<LocalBlockHash> =
            local_hashes.iter().map(|&h| LocalBlockHash(h)).collect();
        let seq_hashes = compute_seq_hash_for_block(&local_block_hashes);

        RouterEvent {
            worker_id,
            event: KvCacheEvent {
                event_id: 0,
                data: KvCacheEventData::Stored(KvCacheStoreData {
                    parent_hash,
                    blocks: local_block_hashes
                        .iter()
                        .zip(seq_hashes.iter())
                        .map(|(&local, &seq)| KvCacheStoredBlockData {
                            tokens_hash: local,
                            block_hash: ExternalSequenceBlockHash(seq),
                            mm_extra_info: None,
                        })
                        .collect(),
                }),
                dp_rank,
            },
2136
2137
2138
        }
    }

Yan Ru Pei's avatar
Yan Ru Pei committed
2139
2140
2141
    /// Create a remove event for blocks with given local hashes.
    fn make_remove_event(worker_id: u64, local_hashes: &[u64]) -> RouterEvent {
        make_remove_event_with_dp_rank(worker_id, local_hashes, 0)
2142
2143
    }

Yan Ru Pei's avatar
Yan Ru Pei committed
2144
2145
2146
2147
2148
2149
2150
2151
2152
    /// Create a remove event with a specific dp_rank.
    fn make_remove_event_with_dp_rank(
        worker_id: u64,
        local_hashes: &[u64],
        dp_rank: u32,
    ) -> RouterEvent {
        let local_block_hashes: Vec<LocalBlockHash> =
            local_hashes.iter().map(|&h| LocalBlockHash(h)).collect();
        let seq_hashes = compute_seq_hash_for_block(&local_block_hashes);
2153

Yan Ru Pei's avatar
Yan Ru Pei committed
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
        RouterEvent {
            worker_id,
            event: KvCacheEvent {
                event_id: 0,
                data: KvCacheEventData::Removed(KvCacheRemoveData {
                    block_hashes: seq_hashes
                        .iter()
                        .map(|&h| ExternalSequenceBlockHash(h))
                        .collect(),
                }),
                dp_rank,
            },
        }
    }
2168

Yan Ru Pei's avatar
Yan Ru Pei committed
2169
2170
2171
2172
    /// Create a clear event for a worker.
    fn make_clear_event(worker_id: u64) -> RouterEvent {
        make_clear_event_with_dp_rank(worker_id, 0)
    }
2173

Yan Ru Pei's avatar
Yan Ru Pei committed
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
    /// Create a clear event with a specific dp_rank.
    fn make_clear_event_with_dp_rank(worker_id: u64, dp_rank: u32) -> RouterEvent {
        RouterEvent {
            worker_id,
            event: KvCacheEvent {
                event_id: 0,
                data: KvCacheEventData::Cleared,
                dp_rank,
            },
        }
2184
2185
    }

Yan Ru Pei's avatar
Yan Ru Pei committed
2186
2187
2188
    // ============================================================================
    // KvIndexerInterface tests - parametrized over all implementations
    // ============================================================================
2189

Yan Ru Pei's avatar
Yan Ru Pei committed
2190
2191
2192
2193
2194
2195
2196
2197
    #[template]
    #[rstest]
    fn indexer_template(#[values("single", "sharded", "flat", "concurrent")] variant: &str) {}

    fn make_indexer(variant: &str) -> Box<dyn KvIndexerInterface> {
        let token = CancellationToken::new();
        let metrics = Arc::new(KvIndexerMetrics::new_unregistered());
        let kv_block_size = 32;
2198

Yan Ru Pei's avatar
Yan Ru Pei committed
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
        match variant {
            "single" => Box::new(KvIndexer::new(token, kv_block_size, metrics)),
            "sharded" => Box::new(KvIndexerSharded::new(token, 4, kv_block_size, metrics)),
            "flat" => Box::new(ThreadPoolIndexer::new(
                PositionalIndexer::new(32),
                4,
                kv_block_size,
            )),
            "concurrent" => Box::new(ThreadPoolIndexer::new(
                ConcurrentRadixTree::new(),
                4,
                kv_block_size,
            )),
            _ => panic!("Unknown variant: {}", variant),
        }
2214
2215
2216
2217
    }

    #[tokio::test]
    #[apply(indexer_template)]
Yan Ru Pei's avatar
Yan Ru Pei committed
2218
2219
    async fn test_store_and_find(variant: &str) {
        let index = make_indexer(variant);
2220

Yan Ru Pei's avatar
Yan Ru Pei committed
2221
2222
        // Store a sequence for worker 0
        index.apply_event(make_store_event(0, &[1, 2, 3])).await;
2223

Yan Ru Pei's avatar
Yan Ru Pei committed
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Find matches using local hashes
        let scores = index
            .find_matches(vec![
                LocalBlockHash(1),
                LocalBlockHash(2),
                LocalBlockHash(3),
            ])
            .await
            .unwrap();
        assert_eq!(scores.scores.len(), 1);
        assert_eq!(*scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(), 3);
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_partial_match(variant: &str) {
        let index = make_indexer(variant);

        // Store [1, 2, 3] for worker 0
        index.apply_event(make_store_event(0, &[1, 2, 3])).await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Find matches for [1, 2, 999] - should match first 2 then stop
        let scores = index
            .find_matches(vec![
                LocalBlockHash(1),
                LocalBlockHash(2),
                LocalBlockHash(999),
            ])
            .await
            .unwrap();
        assert_eq!(*scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(), 2);
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_remove(variant: &str) {
        let index = make_indexer(variant);

        // Store sequence for worker 0
        index.apply_event(make_store_event(0, &[1, 2, 3])).await;

        // Remove all blocks
        index.apply_event(make_remove_event(0, &[1, 2, 3])).await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Find should return nothing
        let scores = index
            .find_matches(vec![
                LocalBlockHash(1),
                LocalBlockHash(2),
                LocalBlockHash(3),
            ])
            .await
            .unwrap();
        assert!(scores.scores.is_empty());
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_multiple_workers_shared_prefix(variant: &str) {
        let index = make_indexer(variant);

        // Worker 0 has [1, 2], Worker 1 has [1, 3]
        // Since sequence hashes are cumulative, [1] has same hash for both,
        // but [1, 2] and [1, 3] have different hashes.
        index.apply_event(make_store_event(0, &[1, 2])).await;
        index.apply_event(make_store_event(1, &[1, 3])).await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Query [1] - both workers should match
        let scores = index.find_matches(vec![LocalBlockHash(1)]).await.unwrap();
        assert_eq!(scores.scores.len(), 2);
        assert_eq!(*scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(), 1);
        assert_eq!(*scores.scores.get(&WorkerWithDpRank::new(1, 0)).unwrap(), 1);

        // Query [1, 2] - worker 0 matches both, worker 1 matches only first block
        let scores = index
            .find_matches(vec![LocalBlockHash(1), LocalBlockHash(2)])
            .await
            .unwrap();
        assert_eq!(scores.scores.len(), 2);
        assert_eq!(*scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(), 2);
        assert_eq!(*scores.scores.get(&WorkerWithDpRank::new(1, 0)).unwrap(), 1);
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_remove_worker(variant: &str) {
        let index = make_indexer(variant);

        index.apply_event(make_store_event(0, &[1, 2, 3])).await;
        index.apply_event(make_store_event(1, &[1, 2, 3])).await;

        // Allow time for async event processing
        tokio::time::sleep(Duration::from_millis(100)).await;

        index.remove_worker(0).await;

        // Allow time for async remove_worker processing
        tokio::time::sleep(Duration::from_millis(100)).await;

        let scores = index
            .find_matches(vec![
                LocalBlockHash(1),
                LocalBlockHash(2),
                LocalBlockHash(3),
            ])
            .await
            .unwrap();
        assert_eq!(scores.scores.len(), 1);
        assert!(scores.scores.contains_key(&WorkerWithDpRank::new(1, 0)));
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_large_stores(variant: &str) {
        let index = make_indexer(variant);

        // Test sequences of increasing sizes
        for i in 0..10u64 {
            let len = 1 << i; // 1, 2, 4, 8, ..., 512
            let worker_id = i;
            let sequence: Vec<u64> = (1..=len).map(|x| x + (i * 10000)).collect();
            index
                .apply_event(make_store_event(worker_id, &sequence))
                .await;
        }

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Verify we can find matches for the last stored sequence
        let last_seq: Vec<LocalBlockHash> = (1..=512u64)
            .map(|x| LocalBlockHash(x + (9 * 10000)))
            .collect();
        let scores = index.find_matches(last_seq).await.unwrap();
        assert!(!scores.scores.is_empty());
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_dump_and_restore(variant: &str) {
        let index = make_indexer(variant);

        // Store some data
        index.apply_event(make_store_event(0, &[1, 2, 3])).await;
        index.apply_event(make_store_event(1, &[1, 2, 4])).await;

        // Allow background worker threads to process events.
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Dump the tree as events
        let events = index.dump_events().await.unwrap();
        assert!(!events.is_empty());

        // Create a new index and replay events
        let restored = make_indexer(variant);
        for event in events {
            restored.apply_event(event).await;
        }

        // Allow background worker threads to process replayed events.
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Verify find_matches produces same results
        let original_scores = index
            .find_matches(vec![LocalBlockHash(1), LocalBlockHash(2)])
            .await
            .unwrap();
        let restored_scores = restored
            .find_matches(vec![LocalBlockHash(1), LocalBlockHash(2)])
            .await
            .unwrap();
        assert_eq!(original_scores.scores, restored_scores.scores);
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_clear_all_blocks(variant: &str) {
        let index = make_indexer(variant);

        // Store some data for two workers
        index.apply_event(make_store_event(0, &[1, 2, 3])).await;
        index.apply_event(make_store_event(1, &[1, 2, 3])).await;

        // Clear worker 0's blocks using the Cleared event
        index.apply_event(make_clear_event(0)).await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Worker 0's blocks should be gone, worker 1's remain
        let scores = index
            .find_matches(vec![
                LocalBlockHash(1),
                LocalBlockHash(2),
                LocalBlockHash(3),
            ])
            .await
            .unwrap();
        assert_eq!(scores.scores.len(), 1);
        assert!(scores.scores.contains_key(&WorkerWithDpRank::new(1, 0)));
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_empty_query(variant: &str) {
        let index = make_indexer(variant);

        index.apply_event(make_store_event(0, &[1, 2, 3])).await;

        index.flush().await;

        // Empty query should return empty scores
        let scores = index.find_matches(vec![]).await.unwrap();
        assert!(scores.scores.is_empty());
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_miss_query(variant: &str) {
        let index = make_indexer(variant);

        index.apply_event(make_store_event(0, &[1, 2, 3])).await;

        index.flush().await;

        // Query for non-existent blocks
        let scores = index
            .find_matches(vec![LocalBlockHash(999), LocalBlockHash(998)])
            .await
            .unwrap();
        assert!(scores.scores.is_empty());
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_shutdown(variant: &str) {
        let index = make_indexer(variant);
        index.shutdown();
    }

2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_shutdown_idempotent(variant: &str) {
        let index = make_indexer(variant);
        index.apply_event(make_store_event(0, &[1, 2, 3])).await;
        tokio::time::sleep(Duration::from_millis(100)).await;
        index.shutdown();
        index.shutdown();
    }

Yan Ru Pei's avatar
Yan Ru Pei committed
2480
2481
2482
2483
2484
2485
2486
    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_find_matches_for_request(variant: &str) {
        let index = make_indexer(variant);

        // Empty index should return no matches
        let tokens = vec![1, 2, 3, 4];
2487
        let scores = index.find_matches_for_request(&tokens, None).await.unwrap();
Yan Ru Pei's avatar
Yan Ru Pei committed
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
        assert!(scores.scores.is_empty());

        // Store some data and verify we can find it via tokens
        index.apply_event(make_store_event(0, &[1, 2, 3])).await;

        // Allow time for async processing
        index.flush().await;

        // Note: find_matches_for_request computes block hashes from tokens,
        // so we need tokens that hash to the same LocalBlockHash values.
        // For this test, we just verify the method works without error.
2499
        let scores = index.find_matches_for_request(&tokens, None).await.unwrap();
Yan Ru Pei's avatar
Yan Ru Pei committed
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
        // The tokens [1,2,3,4] won't match our stored [1,2,3] local hashes
        // because find_matches_for_request computes different hashes from raw tokens
        assert!(scores.scores.is_empty() || !scores.scores.is_empty());
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_process_routing_decision(variant: &str) {
        let index = make_indexer(variant);

        // Create tokens with hashes
        let tokens = vec![1u32, 2, 3, 4, 5, 6, 7, 8];
        let mut tokens_with_hashes = TokensWithHashes::new(tokens, 32);

        let worker = WorkerWithDpRank::new(0, 0);

        // Process routing decision - should not error
        let result = index
            .process_routing_decision_for_request(&mut tokens_with_hashes, worker)
            .await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_parent_hash_chains(variant: &str) {
        let index = make_indexer(variant);

        // Store initial sequence [1, 2, 3]
        index.apply_event(make_store_event(0, &[1, 2, 3])).await;

        // Store continuation [4, 5] with parent pointing to block 3
        index
            .apply_event(make_store_event_with_parent(0, &[1, 2, 3], &[4, 5]))
            .await;

        index.flush().await;

        // Query for full sequence [1, 2, 3, 4, 5] should match all 5 blocks
2539
        let full_seq: Vec<LocalBlockHash> = (1..=5).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
2540
2541
2542
2543
2544
        let scores = index.find_matches(full_seq).await.unwrap();
        assert_eq!(scores.scores.len(), 1);
        assert_eq!(*scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(), 5);

        // Query for just [1, 2, 3] should match 3 blocks
2545
        let prefix_seq: Vec<LocalBlockHash> = (1..=3).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
        let scores = index.find_matches(prefix_seq).await.unwrap();
        assert_eq!(*scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(), 3);
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_multiple_dp_ranks(variant: &str) {
        let index = make_indexer(variant);

        // Same worker_id but different dp_ranks should be tracked separately
        index
            .apply_event(make_store_event_with_dp_rank(0, &[1, 2, 3], 0))
            .await;
        index
            .apply_event(make_store_event_with_dp_rank(0, &[1, 2, 3], 1))
            .await;
        index
            .apply_event(make_store_event_with_dp_rank(0, &[1, 2, 3], 2))
            .await;

        index.flush().await;

        // Query should return all 3 dp_ranks as separate entries
2569
        let seq: Vec<LocalBlockHash> = (1..=3).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
        let scores = index.find_matches(seq).await.unwrap();

        assert_eq!(scores.scores.len(), 3);
        assert_eq!(*scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(), 3);
        assert_eq!(*scores.scores.get(&WorkerWithDpRank::new(0, 1)).unwrap(), 3);
        assert_eq!(*scores.scores.get(&WorkerWithDpRank::new(0, 2)).unwrap(), 3);
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_partial_block_removal(variant: &str) {
        let index = make_indexer(variant);

        // Store [1, 2, 3]
        index.apply_event(make_store_event(0, &[1, 2, 3])).await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Verify all 3 blocks match
2589
        let seq: Vec<LocalBlockHash> = (1..=3).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
2590
2591
2592
2593
2594
2595
        let scores = index.find_matches(seq.clone()).await.unwrap();
        assert_eq!(*scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(), 3);

        // Remove only the last block (block 3)
        // To do this correctly, we need to compute the seq_hash for block 3 specifically,
        // which requires the full sequence context [1,2,3].
2596
        let full_hashes: Vec<LocalBlockHash> = (1..=3).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
        let seq_hashes = compute_seq_hash_for_block(&full_hashes);
        let block_3_seq_hash = ExternalSequenceBlockHash(seq_hashes[2]); // Last block's hash

        let remove_event = RouterEvent {
            worker_id: 0,
            event: KvCacheEvent {
                event_id: 0,
                data: KvCacheEventData::Removed(KvCacheRemoveData {
                    block_hashes: vec![block_3_seq_hash],
                }),
                dp_rank: 0,
            },
        };
        index.apply_event(remove_event).await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Query [1, 2, 3] - should only match 2 blocks now (block 3 is removed)
        let scores = index.find_matches(seq).await.unwrap();
        assert_eq!(*scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(), 2);

        // Query [1, 2] - should still match 2 blocks
2619
        let partial_seq: Vec<LocalBlockHash> = (1..=2).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
        let scores = index.find_matches(partial_seq).await.unwrap();
        assert_eq!(*scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(), 2);
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_remove_nonexistent_worker(variant: &str) {
        let index = make_indexer(variant);

        // Store data for worker 0
        index.apply_event(make_store_event(0, &[1, 2, 3])).await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Remove non-existent worker 999 - should not error or affect worker 0
        index.remove_worker(999).await;

        // Allow time for async processing
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Worker 0's data should still be there
2641
        let seq: Vec<LocalBlockHash> = (1..=3).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
        let scores = index.find_matches(seq).await.unwrap();
        assert_eq!(scores.scores.len(), 1);
        assert!(scores.scores.contains_key(&WorkerWithDpRank::new(0, 0)));
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_remove_nonexistent_blocks(variant: &str) {
        let index = make_indexer(variant);

        // Store [1, 2, 3]
        index.apply_event(make_store_event(0, &[1, 2, 3])).await;

        // Try to remove blocks [999, 998] that don't exist - should not error
        index.apply_event(make_remove_event(0, &[999, 998])).await;

        index.flush().await;

        // Original data should still be there
2661
        let seq: Vec<LocalBlockHash> = (1..=3).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
        let scores = index.find_matches(seq).await.unwrap();
        assert_eq!(*scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(), 3);
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_clear_then_reuse(variant: &str) {
        let index = make_indexer(variant);

        // Store initial data
        index.apply_event(make_store_event(0, &[1, 2, 3])).await;

        // Clear the worker
        index.apply_event(make_clear_event(0)).await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Verify data is gone
2680
        let seq: Vec<LocalBlockHash> = (1..=3).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
        let scores = index.find_matches(seq.clone()).await.unwrap();
        assert!(scores.scores.is_empty());

        // Store new data for the same worker
        index.apply_event(make_store_event(0, &[1, 2, 3])).await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Verify new data is accessible
        let scores = index.find_matches(seq).await.unwrap();
        assert_eq!(scores.scores.len(), 1);
        assert_eq!(*scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(), 3);
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_multiple_sequences_per_worker(variant: &str) {
        let index = make_indexer(variant);

        // Store two disjoint sequences for the same worker
        // Sequence 1: [1, 2, 3]
        index.apply_event(make_store_event(0, &[1, 2, 3])).await;
        // Sequence 2: [100, 101, 102] (completely different, no parent)
        index
            .apply_event(make_store_event(0, &[100, 101, 102]))
            .await;

        index.flush().await;

        // Query first sequence
2711
        let seq1: Vec<LocalBlockHash> = (1..=3).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
2712
2713
2714
2715
        let scores = index.find_matches(seq1).await.unwrap();
        assert_eq!(*scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(), 3);

        // Query second sequence
2716
        let seq2: Vec<LocalBlockHash> = (100..=102).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
        let scores = index.find_matches(seq2).await.unwrap();
        assert_eq!(*scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(), 3);

        // Query a mix that doesn't exist as a sequence - should only match first block
        let mixed: Vec<LocalBlockHash> = vec![LocalBlockHash(1), LocalBlockHash(100)];
        let scores = index.find_matches(mixed).await.unwrap();
        // Only block 1 matches because [1, 100] is not a valid prefix
        assert_eq!(*scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(), 1);
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_clear_clears_all_dp_ranks(variant: &str) {
        let index = make_indexer(variant);

        // Store same sequence for different dp_ranks
        index
            .apply_event(make_store_event_with_dp_rank(0, &[1, 2, 3], 0))
            .await;
        index
            .apply_event(make_store_event_with_dp_rank(0, &[1, 2, 3], 1))
            .await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Verify both dp_ranks are present
2743
        let seq: Vec<LocalBlockHash> = (1..=3).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
        let scores = index.find_matches(seq.clone()).await.unwrap();
        assert_eq!(scores.scores.len(), 2);

        // Clear event clears ALL blocks for the worker_id, regardless of dp_rank
        index.apply_event(make_clear_event_with_dp_rank(0, 0)).await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Both dp_ranks should be cleared
        let scores = index.find_matches(seq).await.unwrap();
        assert!(
            scores.scores.is_empty(),
            "Cleared event should clear all dp_ranks for a worker"
        );
    }

2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
    // ============================================================================
    // LoRA isolation tests
    // ============================================================================

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_lora_and_base_model_blocks_do_not_conflict(variant: &str) {
        let index = make_indexer(variant);
        let kv_block_size: u32 = 32;

        // Same token sequence for both base model and LoRA adapter
        let tokens: Vec<u32> = (0..kv_block_size * 3).collect();

        let base_hashes = compute_block_hash_for_seq(&tokens, kv_block_size, None, None);
        let lora_hashes =
            compute_block_hash_for_seq(&tokens, kv_block_size, None, Some("my-adapter"));

        // Hashes must differ despite identical tokens
        assert_ne!(
            base_hashes, lora_hashes,
            "Base and LoRA hashes must differ for the same tokens"
        );

        let base_seq = compute_seq_hash_for_block(&base_hashes);
        let lora_seq = compute_seq_hash_for_block(&lora_hashes);

        // Store base-model blocks on worker 0
        let base_event = RouterEvent {
            worker_id: 0,
            event: KvCacheEvent {
                event_id: 0,
                data: KvCacheEventData::Stored(KvCacheStoreData {
                    parent_hash: None,
                    blocks: base_hashes
                        .iter()
                        .zip(base_seq.iter())
                        .map(|(&local, &seq)| KvCacheStoredBlockData {
                            tokens_hash: local,
                            block_hash: ExternalSequenceBlockHash(seq),
                            mm_extra_info: None,
                        })
                        .collect(),
                }),
                dp_rank: 0,
            },
        };
        index.apply_event(base_event).await;

        // Store LoRA blocks on worker 1
        let lora_event = RouterEvent {
            worker_id: 1,
            event: KvCacheEvent {
                event_id: 0,
                data: KvCacheEventData::Stored(KvCacheStoreData {
                    parent_hash: None,
                    blocks: lora_hashes
                        .iter()
                        .zip(lora_seq.iter())
                        .map(|(&local, &seq)| KvCacheStoredBlockData {
                            tokens_hash: local,
                            block_hash: ExternalSequenceBlockHash(seq),
                            mm_extra_info: None,
                        })
                        .collect(),
                }),
                dp_rank: 0,
            },
        };
        index.apply_event(lora_event).await;

        // flush + settle time for thread-pool variants
        index.flush().await;
        tokio::time::sleep(Duration::from_millis(50)).await;

        // Query with base-model hashes → only worker 0
        let base_scores = index.find_matches(base_hashes.clone()).await.unwrap();
        assert_eq!(
            base_scores.scores.len(),
            1,
            "Only base-model worker should match"
        );
        assert_eq!(
            *base_scores
                .scores
                .get(&WorkerWithDpRank::new(0, 0))
                .unwrap(),
            3
        );

        // Query with LoRA hashes → only worker 1
        let lora_scores = index.find_matches(lora_hashes.clone()).await.unwrap();
        assert_eq!(lora_scores.scores.len(), 1, "Only LoRA worker should match");
        assert_eq!(
            *lora_scores
                .scores
                .get(&WorkerWithDpRank::new(1, 0))
                .unwrap(),
            3
        );
    }

    /// Reproduces the "block_hash mismatch: sequence hashes should be uniform
    /// across workers" warning seen when the same prompt is sent to both a base
    /// model worker and a LoRA worker.
    ///
    /// On main (without LoRA-aware hashing), both workers compute the same
    /// LocalBlockHash for identical tokens.  But vLLM's engine includes the
    /// adapter in its rolling ExternalSequenceBlockHash, so the radix tree
    /// sees conflicting sequence hashes at the same tree node.
    ///
    /// With LoRA-aware hashing, compute_block_hash_for_seq produces distinct
    /// LocalBlockHash values for different adapters, so the blocks land on
    /// separate tree paths and no mismatch occurs.
    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_lora_base_same_tokens_no_seq_hash_mismatch(variant: &str) {
        let index = make_indexer(variant);
        let kv_block_size: u32 = 32;

        let tokens: Vec<u32> = (0..kv_block_size * 3).collect();

        // With LoRA-aware hashing, base and adapter produce different LocalBlockHash
        let base_local = compute_block_hash_for_seq(&tokens, kv_block_size, None, None);
        let lora_local =
            compute_block_hash_for_seq(&tokens, kv_block_size, None, Some("my-adapter"));

        assert_ne!(
            base_local, lora_local,
            "LoRA-aware hashing must produce different LocalBlockHash values"
        );

        // Simulate what vLLM does: same tokens, different rolling seq hashes
        // because the engine accounts for the adapter internally.
        let base_seq = compute_seq_hash_for_block(&base_local);
        let lora_seq = compute_seq_hash_for_block(&lora_local);

        // Worker 0: base model
        index
            .apply_event(RouterEvent {
                worker_id: 0,
                event: KvCacheEvent {
                    event_id: 0,
                    data: KvCacheEventData::Stored(KvCacheStoreData {
                        parent_hash: None,
                        blocks: base_local
                            .iter()
                            .zip(base_seq.iter())
                            .map(|(&local, &seq)| KvCacheStoredBlockData {
                                tokens_hash: local,
                                block_hash: ExternalSequenceBlockHash(seq),
                                mm_extra_info: None,
                            })
                            .collect(),
                    }),
                    dp_rank: 0,
                },
            })
            .await;

        // Worker 1: LoRA adapter — different LocalBlockHash, so this goes to
        // a separate tree path instead of colliding with worker 0's node.
        index
            .apply_event(RouterEvent {
                worker_id: 1,
                event: KvCacheEvent {
                    event_id: 0,
                    data: KvCacheEventData::Stored(KvCacheStoreData {
                        parent_hash: None,
                        blocks: lora_local
                            .iter()
                            .zip(lora_seq.iter())
                            .map(|(&local, &seq)| KvCacheStoredBlockData {
                                tokens_hash: local,
                                block_hash: ExternalSequenceBlockHash(seq),
                                mm_extra_info: None,
                            })
                            .collect(),
                    }),
                    dp_rank: 0,
                },
            })
            .await;

        index.flush().await;
        tokio::time::sleep(Duration::from_millis(50)).await;

        // Base query finds only worker 0
        let base_scores = index.find_matches(base_local.clone()).await.unwrap();
        assert_eq!(base_scores.scores.len(), 1);
        assert_eq!(
            *base_scores
                .scores
                .get(&WorkerWithDpRank::new(0, 0))
                .unwrap(),
            3
        );

        // LoRA query finds only worker 1
        let lora_scores = index.find_matches(lora_local.clone()).await.unwrap();
        assert_eq!(lora_scores.scores.len(), 1);
        assert_eq!(
            *lora_scores
                .scores
                .get(&WorkerWithDpRank::new(1, 0))
                .unwrap(),
            3
        );
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_different_lora_adapters_do_not_conflict(variant: &str) {
        let index = make_indexer(variant);
        let kv_block_size: u32 = 32;

        let tokens: Vec<u32> = (0..kv_block_size * 2).collect();

        let hashes_a = compute_block_hash_for_seq(&tokens, kv_block_size, None, Some("adapter-a"));
        let hashes_b = compute_block_hash_for_seq(&tokens, kv_block_size, None, Some("adapter-b"));

        assert_ne!(
            hashes_a, hashes_b,
            "Different adapters must produce different hashes"
        );

        let seq_a = compute_seq_hash_for_block(&hashes_a);
        let seq_b = compute_seq_hash_for_block(&hashes_b);

        // Store adapter-a blocks on worker 0
        index
            .apply_event(RouterEvent {
                worker_id: 0,
                event: KvCacheEvent {
                    event_id: 0,
                    data: KvCacheEventData::Stored(KvCacheStoreData {
                        parent_hash: None,
                        blocks: hashes_a
                            .iter()
                            .zip(seq_a.iter())
                            .map(|(&local, &seq)| KvCacheStoredBlockData {
                                tokens_hash: local,
                                block_hash: ExternalSequenceBlockHash(seq),
                                mm_extra_info: None,
                            })
                            .collect(),
                    }),
                    dp_rank: 0,
                },
            })
            .await;

        // Store adapter-b blocks on worker 1
        index
            .apply_event(RouterEvent {
                worker_id: 1,
                event: KvCacheEvent {
                    event_id: 0,
                    data: KvCacheEventData::Stored(KvCacheStoreData {
                        parent_hash: None,
                        blocks: hashes_b
                            .iter()
                            .zip(seq_b.iter())
                            .map(|(&local, &seq)| KvCacheStoredBlockData {
                                tokens_hash: local,
                                block_hash: ExternalSequenceBlockHash(seq),
                                mm_extra_info: None,
                            })
                            .collect(),
                    }),
                    dp_rank: 0,
                },
            })
            .await;

        index.flush().await;
        tokio::time::sleep(Duration::from_millis(50)).await;

        // Query adapter-a → only worker 0
        let scores_a = index.find_matches(hashes_a.clone()).await.unwrap();
        assert_eq!(scores_a.scores.len(), 1);
        assert!(scores_a.scores.contains_key(&WorkerWithDpRank::new(0, 0)));
        assert!(!scores_a.scores.contains_key(&WorkerWithDpRank::new(1, 0)));

        // Query adapter-b → only worker 1
        let scores_b = index.find_matches(hashes_b.clone()).await.unwrap();
        assert_eq!(scores_b.scores.len(), 1);
        assert!(scores_b.scores.contains_key(&WorkerWithDpRank::new(1, 0)));
        assert!(!scores_b.scores.contains_key(&WorkerWithDpRank::new(0, 0)));
    }

Yan Ru Pei's avatar
Yan Ru Pei committed
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
    // ============================================================================
    // Long sequence tests - especially important for NestedMap/PositionalIndexer
    // ============================================================================

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_long_sequence_single_store(variant: &str) {
        let index = make_indexer(variant);

        // Store a long sequence (128 blocks) in a single event
        let seq_len = 128;
        let sequence: Vec<u64> = (1..=seq_len).collect();
        index.apply_event(make_store_event(0, &sequence)).await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Query full sequence - should match all blocks
        let full_query: Vec<LocalBlockHash> = sequence.iter().map(|&i| LocalBlockHash(i)).collect();
        let scores = index.find_matches(full_query).await.unwrap();
        assert_eq!(scores.scores.len(), 1);
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
            seq_len as u32
        );

        // Query prefix (first 64 blocks)
3076
        let prefix_query: Vec<LocalBlockHash> = (1..=64).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
3077
3078
3079
3080
3081
3082
3083
        let scores = index.find_matches(prefix_query).await.unwrap();
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
            64
        );

        // Query with divergence at position 50
3084
        let mut divergent_query: Vec<LocalBlockHash> = (1..=100).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
        divergent_query[49] = LocalBlockHash(99999); // Position 49 (0-indexed) diverges
        let scores = index.find_matches(divergent_query).await.unwrap();
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
            49
        );
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_long_sequence_multiple_continuations(variant: &str) {
        let index = make_indexer(variant);

        // Build a long sequence through multiple continuations
        // First store: blocks 1-50
        let first_chunk: Vec<u64> = (1..=50).collect();
        index.apply_event(make_store_event(0, &first_chunk)).await;

        // Second store: blocks 51-100 (continuation of first)
        let second_chunk: Vec<u64> = (51..=100).collect();
        index
            .apply_event(make_store_event_with_parent(0, &first_chunk, &second_chunk))
            .await;

        // Third store: blocks 101-150 (continuation of second)
        let prefix_1_2: Vec<u64> = (1..=100).collect();
        let third_chunk: Vec<u64> = (101..=150).collect();
        index
            .apply_event(make_store_event_with_parent(0, &prefix_1_2, &third_chunk))
            .await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Query full sequence - should match all 150 blocks
3119
        let full_query: Vec<LocalBlockHash> = (1..=150).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
3120
3121
3122
3123
3124
3125
3126
3127
        let scores = index.find_matches(full_query).await.unwrap();
        assert_eq!(scores.scores.len(), 1);
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
            150
        );

        // Query crossing continuation boundaries
3128
        let cross_boundary_query: Vec<LocalBlockHash> = (45..=105).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
3129
3130
3131
3132
3133
        let scores = index.find_matches(cross_boundary_query).await.unwrap();
        // Query starts at block 45, but stored sequence starts at 1, so this won't match
        // because the sequence hash at position 0 of our query (block 45) won't match
        // the stored sequence hash at position 0 (block 1)
        assert!(
3134
            scores.scores.is_empty() || !scores.scores.contains_key(&WorkerWithDpRank::new(0, 0))
Yan Ru Pei's avatar
Yan Ru Pei committed
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
        );
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_long_sequence_branching_continuations(variant: &str) {
        let index = make_indexer(variant);

        // Common prefix: blocks 1-30
        let common_prefix: Vec<u64> = (1..=30).collect();
        index.apply_event(make_store_event(0, &common_prefix)).await;

        // Branch A: blocks 31-60 on worker 0
        let branch_a: Vec<u64> = (31..=60).collect();
        index
            .apply_event(make_store_event_with_parent(0, &common_prefix, &branch_a))
            .await;

        // Branch B: blocks 131-160 (different content) on worker 1
        // First store the common prefix for worker 1
        index.apply_event(make_store_event(1, &common_prefix)).await;
        let branch_b: Vec<u64> = (131..=160).collect();
        index
            .apply_event(make_store_event_with_parent(1, &common_prefix, &branch_b))
            .await;

        index.flush().await;

        // Query common prefix - both workers should match
3164
        let prefix_query: Vec<LocalBlockHash> = (1..=30).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
        let scores = index.find_matches(prefix_query).await.unwrap();
        assert_eq!(scores.scores.len(), 2);
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
            30
        );
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(1, 0)).unwrap(),
            30
        );

        // Query branch A path - only worker 0 should match fully
3177
        let branch_a_query: Vec<LocalBlockHash> = (1..=60).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
        let scores = index.find_matches(branch_a_query).await.unwrap();
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
            60
        );
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(1, 0)).unwrap(),
            30
        );
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_long_sequence_partial_removal(variant: &str) {
        let index = make_indexer(variant);

        // Store a long sequence
        let sequence: Vec<u64> = (1..=100).collect();
        index.apply_event(make_store_event(0, &sequence)).await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Verify full match
        let full_query: Vec<LocalBlockHash> = sequence.iter().map(|&i| LocalBlockHash(i)).collect();
        let scores = index.find_matches(full_query.clone()).await.unwrap();
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
            100
        );

        // Remove blocks 80-100 (the tail)
3209
        let tail_hashes: Vec<LocalBlockHash> = (1..=100).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
        let seq_hashes = compute_seq_hash_for_block(&tail_hashes);
        let remove_hashes: Vec<ExternalSequenceBlockHash> = seq_hashes[79..100]
            .iter()
            .map(|&h| ExternalSequenceBlockHash(h))
            .collect();

        let remove_event = RouterEvent {
            worker_id: 0,
            event: KvCacheEvent {
                event_id: 0,
                data: KvCacheEventData::Removed(KvCacheRemoveData {
                    block_hashes: remove_hashes,
                }),
                dp_rank: 0,
            },
        };
        index.apply_event(remove_event).await;

        tokio::time::sleep(Duration::from_millis(100)).await;
3229

Yan Ru Pei's avatar
Yan Ru Pei committed
3230
3231
3232
3233
3234
3235
        // Query should now only match first 79 blocks
        let scores = index.find_matches(full_query).await.unwrap();
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
            79
        );
3236
3237
3238
3239
    }

    #[tokio::test]
    #[apply(indexer_template)]
Yan Ru Pei's avatar
Yan Ru Pei committed
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
    async fn test_long_sequence_interleaved_workers(variant: &str) {
        let index = make_indexer(variant);

        // Multiple workers storing overlapping long sequences concurrently
        // Worker 0: blocks 1-100
        // Worker 1: blocks 1-75
        // Worker 2: blocks 1-50
        // Worker 3: blocks 1-25

        let seq_100: Vec<u64> = (1..=100).collect();
        let seq_75: Vec<u64> = (1..=75).collect();
        let seq_50: Vec<u64> = (1..=50).collect();
        let seq_25: Vec<u64> = (1..=25).collect();

        index.apply_event(make_store_event(0, &seq_100)).await;
        index.apply_event(make_store_event(1, &seq_75)).await;
        index.apply_event(make_store_event(2, &seq_50)).await;
        index.apply_event(make_store_event(3, &seq_25)).await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Query for 60 blocks - workers 0,1 match 60, worker 2 matches 50, worker 3 matches 25
3262
        let query_60: Vec<LocalBlockHash> = (1..=60).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
        let scores = index.find_matches(query_60).await.unwrap();
        assert_eq!(scores.scores.len(), 4);
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
            60
        );
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(1, 0)).unwrap(),
            60
        );
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(2, 0)).unwrap(),
            50
        );
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(3, 0)).unwrap(),
            25
        );
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_long_sequence_exact_jump_size_boundaries(variant: &str) {
        let index = make_indexer(variant);

        // Test sequences that align exactly with jump_size boundaries (32 for PositionalIndexer)
        // This tests edge cases in the jump search algorithm

        // Store sequence of exactly 32 blocks
        let seq_32: Vec<u64> = (1..=32).collect();
        index.apply_event(make_store_event(0, &seq_32)).await;

        // Store sequence of exactly 64 blocks (2x jump_size)
        let seq_64: Vec<u64> = (1001..=1064).collect();
        index.apply_event(make_store_event(1, &seq_64)).await;

        // Store sequence of exactly 96 blocks (3x jump_size)
        let seq_96: Vec<u64> = (2001..=2096).collect();
        index.apply_event(make_store_event(2, &seq_96)).await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Verify all sequences match correctly
        let query_32: Vec<LocalBlockHash> = seq_32.iter().map(|&i| LocalBlockHash(i)).collect();
        let scores = index.find_matches(query_32).await.unwrap();
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
            32
        );

        let query_64: Vec<LocalBlockHash> = seq_64.iter().map(|&i| LocalBlockHash(i)).collect();
        let scores = index.find_matches(query_64).await.unwrap();
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(1, 0)).unwrap(),
            64
        );
3319

Yan Ru Pei's avatar
Yan Ru Pei committed
3320
3321
3322
3323
3324
3325
        let query_96: Vec<LocalBlockHash> = seq_96.iter().map(|&i| LocalBlockHash(i)).collect();
        let scores = index.find_matches(query_96).await.unwrap();
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(2, 0)).unwrap(),
            96
        );
3326
3327
3328
3329
    }

    #[tokio::test]
    #[apply(indexer_template)]
Yan Ru Pei's avatar
Yan Ru Pei committed
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
    async fn test_long_sequence_off_by_one_jump_boundaries(variant: &str) {
        let index = make_indexer(variant);

        // Test sequences at jump_size +/- 1 boundaries to catch off-by-one errors
        let seq_31: Vec<u64> = (1..=31).collect();
        let seq_33: Vec<u64> = (101..=133).collect();
        let seq_63: Vec<u64> = (201..=263).collect();
        let seq_65: Vec<u64> = (301..=365).collect();

        index.apply_event(make_store_event(0, &seq_31)).await;
        index.apply_event(make_store_event(1, &seq_33)).await;
        index.apply_event(make_store_event(2, &seq_63)).await;
        index.apply_event(make_store_event(3, &seq_65)).await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Verify all sequences match correctly
        let query_31: Vec<LocalBlockHash> = seq_31.iter().map(|&i| LocalBlockHash(i)).collect();
        let scores = index.find_matches(query_31).await.unwrap();
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
            31
        );

        let query_33: Vec<LocalBlockHash> = seq_33.iter().map(|&i| LocalBlockHash(i)).collect();
        let scores = index.find_matches(query_33).await.unwrap();
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(1, 0)).unwrap(),
            33
        );

        let query_63: Vec<LocalBlockHash> = seq_63.iter().map(|&i| LocalBlockHash(i)).collect();
        let scores = index.find_matches(query_63).await.unwrap();
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(2, 0)).unwrap(),
            63
        );

        let query_65: Vec<LocalBlockHash> = seq_65.iter().map(|&i| LocalBlockHash(i)).collect();
        let scores = index.find_matches(query_65).await.unwrap();
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(3, 0)).unwrap(),
            65
        );
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_long_sequence_divergence_at_jump_boundaries(variant: &str) {
        let index = make_indexer(variant);

        // Store a long sequence
        let sequence: Vec<u64> = (1..=128).collect();
        index.apply_event(make_store_event(0, &sequence)).await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Test divergence exactly at jump boundaries (position 31, 32, 33, 63, 64, 65)
        for diverge_pos in [31usize, 32, 33, 63, 64, 65, 95, 96, 97] {
3389
            let mut query: Vec<LocalBlockHash> = (1..=128).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
            query[diverge_pos] = LocalBlockHash(99999);

            let scores = index.find_matches(query).await.unwrap();
            assert_eq!(
                *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
                diverge_pos as u32,
                "Divergence at position {} should match {} blocks",
                diverge_pos,
                diverge_pos
            );
        }
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_long_sequence_deep_continuation_chain(variant: &str) {
        let index = make_indexer(variant);

        // Build a very long sequence through many small continuations
        // This tests the parent_hash chain handling
        let chunk_size = 10;
        let num_chunks = 20; // Total 200 blocks

        let mut full_prefix: Vec<u64> = Vec::new();

        for chunk_idx in 0..num_chunks {
            let chunk_start = chunk_idx * chunk_size + 1;
            let chunk: Vec<u64> = (chunk_start..chunk_start + chunk_size)
                .map(|x| x as u64)
                .collect();

            if chunk_idx == 0 {
                index.apply_event(make_store_event(0, &chunk)).await;
            } else {
                index
                    .apply_event(make_store_event_with_parent(0, &full_prefix, &chunk))
                    .await;
            }

            full_prefix.extend(&chunk);
        }

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Query full sequence
3435
        let full_query: Vec<LocalBlockHash> = (1..=200).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
3436
3437
3438
3439
3440
3441
3442
        let scores = index.find_matches(full_query).await.unwrap();
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
            200
        );

        // Query partial prefix crossing multiple chunk boundaries
3443
        let partial_query: Vec<LocalBlockHash> = (1..=75).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
        let scores = index.find_matches(partial_query).await.unwrap();
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
            75
        );
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_long_sequence_clear_and_rebuild(variant: &str) {
        let index = make_indexer(variant);

        // Store a long sequence
        let sequence: Vec<u64> = (1..=100).collect();
        index.apply_event(make_store_event(0, &sequence)).await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Verify it's stored
        let query: Vec<LocalBlockHash> = sequence.iter().map(|&i| LocalBlockHash(i)).collect();
        let scores = index.find_matches(query.clone()).await.unwrap();
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
            100
        );

        // Clear the worker
        index.apply_event(make_clear_event(0)).await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Verify it's cleared
        let scores = index.find_matches(query.clone()).await.unwrap();
        assert!(scores.scores.is_empty());

        // Rebuild with a different sequence
        let new_sequence: Vec<u64> = (1001..=1100).collect();
        index.apply_event(make_store_event(0, &new_sequence)).await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Verify new sequence works
        let new_query: Vec<LocalBlockHash> =
            new_sequence.iter().map(|&i| LocalBlockHash(i)).collect();
        let scores = index.find_matches(new_query).await.unwrap();
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
            100
        );

        // Verify old sequence no longer matches
        let scores = index.find_matches(query).await.unwrap();
        assert!(scores.scores.is_empty());
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_long_sequence_multiple_workers_diverging(variant: &str) {
        let index = make_indexer(variant);

        // Multiple workers with long sequences that share a prefix then diverge
        // This tests precise drain point tracking across workers

        // All workers share prefix 1-40
        let shared_prefix: Vec<u64> = (1..=40).collect();

        // Worker 0: prefix + 41-100 (stores full sequence 1-100)
        let worker_0_full: Vec<u64> = (1..=100).collect();

        // Worker 1: prefix + 141-180 (diverges at block 41)
        let worker_1_suffix: Vec<u64> = (141..=180).collect();

        // Worker 2: prefix + 241-300 (diverges at block 41)
        let worker_2_suffix: Vec<u64> = (241..=300).collect();

        // Store for all workers
        index.apply_event(make_store_event(0, &worker_0_full)).await;

        index.apply_event(make_store_event(1, &shared_prefix)).await;
        index
            .apply_event(make_store_event_with_parent(
                1,
                &shared_prefix,
                &worker_1_suffix,
            ))
            .await;

        index.apply_event(make_store_event(2, &shared_prefix)).await;
        index
            .apply_event(make_store_event_with_parent(
                2,
                &shared_prefix,
                &worker_2_suffix,
            ))
            .await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Query 1-100 - worker 0 matches 100, workers 1&2 match 40
        let query: Vec<LocalBlockHash> = worker_0_full.iter().map(|&i| LocalBlockHash(i)).collect();
        let scores = index.find_matches(query).await.unwrap();

        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
            100
        );
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(1, 0)).unwrap(),
            40
        );
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(2, 0)).unwrap(),
            40
        );
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_long_sequence_staggered_lengths(variant: &str) {
        let index = make_indexer(variant);

        // Workers with sequences of staggered lengths to test drain tracking
        // Worker 0: 10 blocks
        // Worker 1: 20 blocks
        // Worker 2: 35 blocks (just past first jump)
        // Worker 3: 64 blocks (exactly 2 jumps)
        // Worker 4: 100 blocks

        for (worker_id, len) in [(0, 10), (1, 20), (2, 35), (3, 64), (4, 100)] {
            let sequence: Vec<u64> = (1..=len).collect();
            index
                .apply_event(make_store_event(worker_id, &sequence))
                .await;
        }

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Query for 100 blocks - each worker should match their stored length
3582
        let query: Vec<LocalBlockHash> = (1..=100).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
        let scores = index.find_matches(query).await.unwrap();

        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
            10
        );
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(1, 0)).unwrap(),
            20
        );
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(2, 0)).unwrap(),
            35
        );
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(3, 0)).unwrap(),
            64
        );
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(4, 0)).unwrap(),
            100
        );
    }

    #[tokio::test]
    #[apply(indexer_template)]
    async fn test_very_long_sequence(variant: &str) {
        let index = make_indexer(variant);

        // Test with a very long sequence (1000 blocks)
        let seq_len = 1000u64;
        let sequence: Vec<u64> = (1..=seq_len).collect();
        index.apply_event(make_store_event(0, &sequence)).await;

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Full match
        let full_query: Vec<LocalBlockHash> = sequence.iter().map(|&i| LocalBlockHash(i)).collect();
        let scores = index.find_matches(full_query).await.unwrap();
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
            seq_len as u32
        );

        // Partial match (first 500)
3628
        let partial_query: Vec<LocalBlockHash> = (1..=500).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
3629
3630
3631
3632
3633
3634
3635
        let scores = index.find_matches(partial_query).await.unwrap();
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
            500
        );

        // Divergence in the middle
3636
        let mut mid_diverge: Vec<LocalBlockHash> = (1..=1000).map(LocalBlockHash).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
        mid_diverge[499] = LocalBlockHash(99999);
        let scores = index.find_matches(mid_diverge).await.unwrap();
        assert_eq!(
            *scores.scores.get(&WorkerWithDpRank::new(0, 0)).unwrap(),
            499
        );
    }

    // ============================================================================
    // Tests specific to tree-based implementations (KvIndexer, KvIndexerSharded)
    // These use features not available in PositionalIndexer
    // ============================================================================

    #[template]
    #[rstest]
    fn tree_indexer_template(#[values("single", "sharded")] variant: &str) {}
3653

Yan Ru Pei's avatar
Yan Ru Pei committed
3654
3655
3656
3657
    fn make_tree_indexer_with_frequency(
        variant: &str,
        expiration: Duration,
    ) -> Box<dyn KvIndexerInterface> {
3658
3659
        let token = CancellationToken::new();
        let metrics = Arc::new(KvIndexerMetrics::new_unregistered());
Yan Ru Pei's avatar
Yan Ru Pei committed
3660
        let kv_block_size = 32;
3661

Yan Ru Pei's avatar
Yan Ru Pei committed
3662
3663
        match variant {
            "single" => Box::new(KvIndexer::new_with_frequency(
3664
3665
3666
3667
3668
                token,
                Some(expiration),
                kv_block_size,
                metrics,
                None,
Yan Ru Pei's avatar
Yan Ru Pei committed
3669
3670
            )),
            "sharded" => Box::new(KvIndexerSharded::new_with_frequency(
3671
                token,
Yan Ru Pei's avatar
Yan Ru Pei committed
3672
                4,
3673
3674
3675
3676
                Some(expiration),
                kv_block_size,
                metrics,
                None,
Yan Ru Pei's avatar
Yan Ru Pei committed
3677
3678
            )),
            _ => panic!("Unknown variant: {}", variant),
3679
        }
Yan Ru Pei's avatar
Yan Ru Pei committed
3680
3681
3682
3683
3684
3685
3686
3687
3688
    }

    #[tokio::test]
    #[apply(tree_indexer_template)]
    async fn test_frequency(variant: &str) {
        const ONE_MILLIS: Duration = Duration::from_millis(1);

        let expiration = Duration::from_millis(50);
        let kv_indexer = make_tree_indexer_with_frequency(variant, expiration);
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705

        // The blocks
        let block_hashes = vec![
            LocalBlockHash(1),
            LocalBlockHash(2),
            LocalBlockHash(3),
            LocalBlockHash(4),
        ];

        let overlap = kv_indexer.find_matches(block_hashes.clone()).await.unwrap();
        assert_eq!(
            overlap.frequencies.len(),
            0,
            "Should be no cached blocks yet"
        );

        // Blocks go in cache
Yan Ru Pei's avatar
Yan Ru Pei committed
3706
        let event = make_store_event(0, &[1, 2, 3, 4]);
3707
3708
        kv_indexer.apply_event(event).await;

Yan Ru Pei's avatar
Yan Ru Pei committed
3709
        // First access - poll briefly since store event is applied async
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
        let mut overlap = OverlapScores::default();
        let timeout = Duration::from_millis(10);
        let start = Instant::now();
        while overlap.scores.is_empty() && Instant::now().duration_since(start) < timeout {
            time::sleep(ONE_MILLIS).await;
            overlap = kv_indexer.find_matches(block_hashes.clone()).await.unwrap();
        }
        assert_eq!(
            overlap.scores.len(),
            1,
            "One worker has these blocks cached"
        );
        assert_eq!(
            overlap.frequencies.len(),
            0,
            "Blocks have not previously been accessed"
        );

        // Second access
        let overlap = kv_indexer.find_matches(block_hashes.clone()).await.unwrap();
        assert_eq!(overlap.scores.len(), 1, "Still one worker matches");
        assert_eq!(
            overlap.frequencies,
            vec![1, 1, 1, 1],
            "We should see the first access now"
        );

        // Let those two accesses expire
Yan Ru Pei's avatar
Yan Ru Pei committed
3738
3739
3740
3741
3742
3743
3744
3745
3746
        time::sleep(expiration + Duration::from_millis(10)).await;

        // New first access
        let overlap = kv_indexer.find_matches(block_hashes.clone()).await.unwrap();
        assert_eq!(
            overlap.frequencies.len(),
            0,
            "Blocks were accessed too long ago"
        );
3747

Yan Ru Pei's avatar
Yan Ru Pei committed
3748
3749
        // New second access
        let _ = kv_indexer.find_matches(block_hashes.clone()).await.unwrap();
3750

Yan Ru Pei's avatar
Yan Ru Pei committed
3751
3752
3753
3754
3755
3756
3757
        // Access only the first three blocks
        let overlap = kv_indexer
            .find_matches(block_hashes[0..3].to_vec())
            .await
            .unwrap();
        // We see the previous two new accesses
        assert_eq!(overlap.frequencies, vec![2, 2, 2]);
3758

Yan Ru Pei's avatar
Yan Ru Pei committed
3759
3760
3761
        // The third access did not touch the last block
        let overlap = kv_indexer.find_matches(block_hashes.clone()).await.unwrap();
        assert_eq!(overlap.frequencies, vec![3, 3, 3, 2]);
3762
    }
3763

Yan Ru Pei's avatar
Yan Ru Pei committed
3764
3765
3766
3767
    // ============================================================================
    // KvIndexerMetrics tests
    // ============================================================================

3768
3769
3770
3771
3772
    #[test]
    fn test_increment_event_applied() {
        let metrics = KvIndexerMetrics::new_unregistered();

        metrics.increment_event_applied(METRIC_EVENT_STORED, Ok(()));
3773
        assert_eq!(
3774
3775
3776
3777
3778
3779
            metrics
                .kv_cache_events_applied
                .get_metric_with_label_values(&[METRIC_EVENT_STORED, METRIC_STATUS_OK])
                .unwrap()
                .get(),
            1
3780
3781
        );

3782
3783
3784
        metrics.increment_event_applied(
            METRIC_EVENT_STORED,
            Err(KvCacheEventError::ParentBlockNotFound),
3785
3786
        );
        assert_eq!(
3787
3788
3789
3790
3791
3792
3793
3794
3795
            metrics
                .kv_cache_events_applied
                .get_metric_with_label_values(&[
                    METRIC_EVENT_STORED,
                    METRIC_STATUS_PARENT_NOT_FOUND
                ])
                .unwrap()
                .get(),
            1
3796
3797
        );

3798
3799
        metrics
            .increment_event_applied(METRIC_EVENT_REMOVED, Err(KvCacheEventError::BlockNotFound));
3800
        assert_eq!(
3801
3802
3803
3804
3805
3806
3807
3808
3809
            metrics
                .kv_cache_events_applied
                .get_metric_with_label_values(&[
                    METRIC_EVENT_REMOVED,
                    METRIC_STATUS_BLOCK_NOT_FOUND
                ])
                .unwrap()
                .get(),
            1
3810
        );
3811
    }
3812

Yan Ru Pei's avatar
Yan Ru Pei committed
3813
    // ============================================================================
3814
    // LocalKvIndexer tests
Yan Ru Pei's avatar
Yan Ru Pei committed
3815
3816
3817
    // ============================================================================

    fn make_local_indexer_with_events(ids: &[u64]) -> LocalKvIndexer {
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
        let indexer = LocalKvIndexer::new(
            CancellationToken::new(),
            4,
            Arc::new(KvIndexerMetrics::new_unregistered()),
            32,
        );
        {
            let mut buffer = indexer.event_buffer.lock().unwrap();
            for &id in ids {
                buffer.push_back(RouterEvent::new(
                    0,
                    KvCacheEvent {
                        event_id: id,
                        data: KvCacheEventData::Cleared,
                        dp_rank: 0,
                    },
                ));
            }
        }
        indexer
3838
    }
3839
3840

    #[tokio::test]
Yan Ru Pei's avatar
Yan Ru Pei committed
3841
3842
    async fn test_local_indexer_slice_within_range() {
        let indexer = make_local_indexer_with_events(&[1, 2, 3, 4, 5]);
3843

3844
3845
3846
3847
3848
3849
3850
3851
        // Helper to extract events from response
        let extract_events = |resp: WorkerKvQueryResponse| -> Vec<RouterEvent> {
            match resp {
                WorkerKvQueryResponse::Events(e) => e,
                WorkerKvQueryResponse::TreeDump(e) => e,
                _ => panic!("Unexpected response type"),
            }
        };
3852

3853
3854
3855
        let get_ids = |events: Vec<RouterEvent>| -> Vec<u64> {
            events.iter().map(|e| e.event.event_id).collect()
        };
3856

3857
3858
3859
3860
3861
        // Test get_events_in_id_range (buffer queries)
        // Range is [start, end] inclusive
        let result = indexer.get_events_in_id_range(Some(2), Some(4)).await;
        let ids = get_ids(extract_events(result));
        assert_eq!(ids, vec![2, 3, 4]); // inclusive range [2, 4]
3862

3863
3864
3865
        let result = indexer.get_events_in_id_range(Some(2), Some(6)).await;
        let ids = get_ids(extract_events(result));
        assert_eq!(ids, vec![2, 3, 4, 5]); // clamp end to buffer max
3866

3867
3868
3869
        // start_id=0 is before buffer (first is 1), so should trigger tree dump
        let result = indexer.get_events_in_id_range(Some(0), Some(4)).await;
        assert!(matches!(result, WorkerKvQueryResponse::TreeDump(_)));
3870

3871
3872
3873
        let result = indexer.get_events_in_id_range(Some(3), Some(3)).await;
        let ids = get_ids(extract_events(result));
        assert_eq!(ids, vec![3]); // single element when start == end
3874

3875
3876
3877
3878
        // Invalid range: end < start
        let result = indexer.get_events_in_id_range(Some(5), Some(2)).await;
        assert!(matches!(result, WorkerKvQueryResponse::InvalidRange { .. }));
    }
3879

3880
    #[tokio::test]
Yan Ru Pei's avatar
Yan Ru Pei committed
3881
    async fn test_local_indexer_get_events_in_id_range_all_cases() {
3882
3883
3884
        // Create indexer with small buffer (5 events max)
        let indexer = LocalKvIndexer::new(
            CancellationToken::new(),
Yan Ru Pei's avatar
Yan Ru Pei committed
3885
            4,
3886
            Arc::new(KvIndexerMetrics::new_unregistered()),
Yan Ru Pei's avatar
Yan Ru Pei committed
3887
            5,
3888
        );
3889

3890
3891
3892
        // Helper to create a test event
        let make_event = |id: u64| {
            RouterEvent::new(
Yan Ru Pei's avatar
Yan Ru Pei committed
3893
                0,
3894
3895
3896
3897
3898
3899
3900
                KvCacheEvent {
                    event_id: id,
                    data: KvCacheEventData::Stored(KvCacheStoreData {
                        parent_hash: None,
                        blocks: vec![KvCacheStoredBlockData {
                            block_hash: ExternalSequenceBlockHash(id * 100),
                            tokens_hash: LocalBlockHash(id * 200),
3901
                            mm_extra_info: None,
3902
3903
3904
3905
3906
3907
                        }],
                    }),
                    dp_rank: 0,
                },
            )
        };
3908

Yan Ru Pei's avatar
Yan Ru Pei committed
3909
        // Add 10 events (IDs 5-14), buffer keeps last 5: events 10-14
3910
3911
3912
3913
3914
        for id in 5..15 {
            indexer
                .apply_event_with_buffer(make_event(id))
                .await
                .unwrap();
3915
3916
        }

Yan Ru Pei's avatar
Yan Ru Pei committed
3917
3918
        // Wait for events to be processed
        tokio::time::sleep(Duration::from_millis(100)).await;
3919

3920
3921
3922
3923
3924
        let extract_events = |resp: WorkerKvQueryResponse| -> Vec<RouterEvent> {
            match resp {
                WorkerKvQueryResponse::Events(e) => e,
                WorkerKvQueryResponse::TreeDump(e) => e,
                _ => panic!("Unexpected response type: {:?}", resp),
3925
3926
3927
            }
        };

3928
3929
3930
        let get_ids = |events: Vec<RouterEvent>| -> Vec<u64> {
            events.iter().map(|e| e.event.event_id).collect()
        };
3931

Yan Ru Pei's avatar
Yan Ru Pei committed
3932
        // Verify buffer state
3933
        let buffer_events = indexer.get_all_events_in_buffer();
Yan Ru Pei's avatar
Yan Ru Pei committed
3934
        assert_eq!(get_ids(buffer_events), vec![10, 11, 12, 13, 14]);
3935

Yan Ru Pei's avatar
Yan Ru Pei committed
3936
        // Buffer path tests
3937
        let result = indexer.get_events_in_id_range(Some(11), None).await;
Yan Ru Pei's avatar
Yan Ru Pei committed
3938
        assert_eq!(get_ids(extract_events(result)), vec![11, 12, 13, 14]);
3939

3940
        let result = indexer.get_events_in_id_range(Some(10), Some(14)).await;
Yan Ru Pei's avatar
Yan Ru Pei committed
3941
        assert_eq!(get_ids(extract_events(result)), vec![10, 11, 12, 13, 14]);
3942

Yan Ru Pei's avatar
Yan Ru Pei committed
3943
        // Tree dump path tests
3944
3945
        let result = indexer.get_events_in_id_range(None, None).await;
        assert!(matches!(result, WorkerKvQueryResponse::TreeDump(_)));
Yan Ru Pei's avatar
Yan Ru Pei committed
3946
        assert_eq!(extract_events(result).len(), 10);
3947
3948
3949

        let result = indexer.get_events_in_id_range(Some(7), None).await;
        assert!(matches!(result, WorkerKvQueryResponse::TreeDump(_)));
3950

Yan Ru Pei's avatar
Yan Ru Pei committed
3951
        // Edge cases
3952
        let result = indexer.get_events_in_id_range(Some(15), Some(10)).await;
Yan Ru Pei's avatar
Yan Ru Pei committed
3953
        assert!(matches!(result, WorkerKvQueryResponse::InvalidRange { .. }));
3954

3955
        let result = indexer.get_events_in_id_range(Some(100), Some(200)).await;
Yan Ru Pei's avatar
Yan Ru Pei committed
3956
        assert!(matches!(result, WorkerKvQueryResponse::TooNew { .. }));
3957
3958
3959
3960
3961
3962
3963
    }

    #[tokio::test]
    async fn test_local_indexer_buffer_and_serialization() {
        let worker_id = 42u64;
        let token = CancellationToken::new();
        let metrics = Arc::new(KvIndexerMetrics::new_unregistered());
Yan Ru Pei's avatar
Yan Ru Pei committed
3964
        let local_indexer = Arc::new(LocalKvIndexer::new(token, 4, metrics, 100));
3965

Yan Ru Pei's avatar
Yan Ru Pei committed
3966
        let test_event = RouterEvent::new(
3967
3968
3969
3970
3971
3972
3973
3974
            worker_id,
            KvCacheEvent {
                event_id: 1,
                data: KvCacheEventData::Stored(KvCacheStoreData {
                    parent_hash: None,
                    blocks: vec![KvCacheStoredBlockData {
                        block_hash: ExternalSequenceBlockHash(100),
                        tokens_hash: LocalBlockHash(200),
3975
                        mm_extra_info: None,
3976
3977
3978
3979
3980
3981
3982
                    }],
                }),
                dp_rank: 0,
            },
        );

        local_indexer
Yan Ru Pei's avatar
Yan Ru Pei committed
3983
            .apply_event_with_buffer(test_event)
3984
3985
3986
            .await
            .unwrap();

Yan Ru Pei's avatar
Yan Ru Pei committed
3987
        tokio::time::sleep(Duration::from_millis(50)).await;
3988
3989

        let buffered_events = local_indexer.get_all_events_in_buffer();
Yan Ru Pei's avatar
Yan Ru Pei committed
3990
        assert_eq!(buffered_events.len(), 1);
3991
3992
        assert_eq!(buffered_events[0].worker_id, worker_id);

Yan Ru Pei's avatar
Yan Ru Pei committed
3993
3994
        // Test serialization round-trip
        let response = WorkerKvQueryResponse::Events(buffered_events);
3995
3996
3997
        let serialized = serde_json::to_vec(&response).unwrap();
        let deserialized: WorkerKvQueryResponse = serde_json::from_slice(&serialized).unwrap();

3998
3999
4000
4001
4002
4003
        let events = match deserialized {
            WorkerKvQueryResponse::Events(e) => e,
            _ => panic!("Expected Events variant"),
        };
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].worker_id, worker_id);
4004
4005
    }
}