concurrent_radix_tree.rs 25.3 KB
Newer Older
Yan Ru Pei's avatar
Yan Ru Pei committed
1
2
3
4
5
6
7
8
9
10
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Concurrent Radix Tree implementation for KV cache routing.
//!
//! This module provides a thread-safe radix tree data structure that enables concurrent
//! `find_matches` operations while maintaining correctness for write operations.
//!
//! Unlike `RadixTree` which uses `Rc<RefCell<>>` and requires single-threaded access,
//! `ConcurrentRadixTree` uses `Arc<RwLock<>>` per node and a
11
//! `DashMap<..., RwLock<FxHashMap<...>>>` for the lookup table.
Yan Ru Pei's avatar
Yan Ru Pei committed
12
13
14
15
16
17
18
19
20
21
22
//!
//! # Limitations vs RadixTree
//!
//! - Does NOT support `expiration_duration` / frequency tracking
//! - `new_with_frequency()` is not provided
//! - `find_matches` does not populate `OverlapScores.frequencies`
//!
//! # Concurrency Model
//!
//! - Multiple `find_matches` can run in parallel (read locks only)
//! - Write operations (`apply_event`, `remove_worker`) acquire write locks
23
24
//! - Outer `DashMap` provides shard-level locking for per-worker access.
//!   Inner `RwLock` per worker allows per-worker write concurrency.
Yan Ru Pei's avatar
Yan Ru Pei committed
25
26
//! - Deadlock prevention: always lock parent before child, hand-over-hand locking

27
use std::sync::Arc;
Yan Ru Pei's avatar
Yan Ru Pei committed
28

29
use dashmap::DashMap;
Yan Ru Pei's avatar
Yan Ru Pei committed
30
use parking_lot::RwLock;
31
32
33
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
use std::collections::VecDeque;
use std::sync::atomic::{AtomicUsize, Ordering};
Yan Ru Pei's avatar
Yan Ru Pei committed
34

35
use super::{EventKind, KvIndexerMetrics, SyncIndexer, WorkerTask};
36
use crate::active_set::reconcile_active_workers;
37
use crate::cleanup::{self, CleanableNode, CleanupGuard, CleanupState};
Yan Ru Pei's avatar
Yan Ru Pei committed
38
39
40
41
42
use crate::protocols::*;

/// Thread-safe shared reference to a Block.
type SharedBlock = Arc<RwLock<Block>>;

43
44
45
/// Per-worker block-hash map. Inner RwLock allows concurrent reads of different workers.
type WorkerLookup = FxHashMap<ExternalSequenceBlockHash, SharedBlock>;

Yan Ru Pei's avatar
Yan Ru Pei committed
46
47
48
49
/// A block in the concurrent radix tree.
#[derive(Debug)]
struct Block {
    /// A map of child blocks, keyed by their local block hash.
50
    children: FxHashMap<LocalBlockHash, SharedBlock>,
Yan Ru Pei's avatar
Yan Ru Pei committed
51
    /// The set of workers that have this block cached.
52
    workers: FxHashSet<WorkerWithDpRank>,
Yan Ru Pei's avatar
Yan Ru Pei committed
53
54
55
56
57
58
59
60
61
62
    /// The external sequence block hash for this block (None for root).
    block_hash: Option<ExternalSequenceBlockHash>,
    // NOTE: No recent_uses field.
    // Frequency tracking is not supported - keeps find_matches fully read-only.
}

impl Block {
    /// Create a new `Block` (used for root node).
    fn new() -> Self {
        Self {
63
64
            children: FxHashMap::default(),
            workers: FxHashSet::default(),
Yan Ru Pei's avatar
Yan Ru Pei committed
65
66
67
68
69
70
71
            block_hash: None,
        }
    }

    /// Create a new `Block` with a specific block hash.
    fn with_hash(block_hash: ExternalSequenceBlockHash) -> Self {
        Self {
72
73
            children: FxHashMap::default(),
            workers: FxHashSet::default(),
Yan Ru Pei's avatar
Yan Ru Pei committed
74
75
76
            block_hash: Some(block_hash),
        }
    }
77
78
79
80
81
82
83
84

    #[inline]
    fn drop_worker(&mut self, worker: WorkerWithDpRank) {
        self.workers.remove(&worker);
        if self.workers.is_empty() {
            self.children.clear();
        }
    }
Yan Ru Pei's avatar
Yan Ru Pei committed
85
86
}

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
impl CleanableNode for Block {
    type ChildKey = LocalBlockHash;

    fn has_any_workers(&self) -> bool {
        !self.workers.is_empty()
    }

    fn children(&self) -> &FxHashMap<LocalBlockHash, SharedBlock> {
        &self.children
    }

    fn remove_child(&mut self, key: &LocalBlockHash) {
        self.children.remove(key);
    }
}

Yan Ru Pei's avatar
Yan Ru Pei committed
103
104
105
106
/// Thread-safe radix tree for concurrent KV cache lookups.
///
/// Unlike `RadixTree` which uses `Rc<RefCell<>>` and requires single-threaded access,
/// `ConcurrentRadixTree` uses `Arc<RwLock<>>` per node and a
107
/// `DashMap<..., RwLock<FxHashMap<...>>>` for the lookup table,
Yan Ru Pei's avatar
Yan Ru Pei committed
108
109
110
111
112
113
114
115
116
117
118
119
/// enabling concurrent `find_matches` operations.
///
/// # Limitations vs RadixTree
///
/// - Does NOT support `expiration_duration` / frequency tracking
/// - `new_with_frequency()` is not provided
/// - `find_matches` does not populate `OverlapScores.frequencies`
///
/// # Concurrency Model
///
/// - Multiple `find_matches` can run in parallel (read locks only)
/// - Write operations (`apply_event`, `remove_worker`) acquire write locks
120
/// - Outer `DashMap` provides shard-level locking for per-worker access.
121
/// - Inner `RwLock` per worker allows per-worker write concurrency.
Yan Ru Pei's avatar
Yan Ru Pei committed
122
123
124
125
126
127
/// - Deadlock prevention: always lock parent before child, hand-over-hand locking
pub struct ConcurrentRadixTree {
    /// This is the root of the radix/prefix tree.
    /// This will only contain root blocks.
    root: SharedBlock,

128
    tree_sizes: DashMap<WorkerWithDpRank, AtomicUsize, FxBuildHasher>,
129
    cleanup: CleanupState,
Yan Ru Pei's avatar
Yan Ru Pei committed
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
}

impl Default for ConcurrentRadixTree {
    fn default() -> Self {
        Self::new()
    }
}

// Dropping blocks can cause a cascade of drops that can overflow the stack.
// This custom drop implementation avoids this using an iterative approach.
impl Drop for ConcurrentRadixTree {
    fn drop(&mut self) {
        let mut stack: Vec<SharedBlock> = Vec::new();

        // Break root -> children edge up front
        {
            let mut root = self.root.write();
            stack.extend(root.children.drain().map(|(_, v)| v));
        }

150
151
152
        // Iteratively drop blocks to avoid stack overflow on deep trees.
        // Without this loop, dropping `stack` would recursively drop each
        // Arc<RwLock<Block>> through its `children` map.
Yan Ru Pei's avatar
Yan Ru Pei committed
153
154
155
156
157
158
159
160
161
162
163
164
165
166
        while let Some(block) = stack.pop() {
            if let Ok(rwlock) = Arc::try_unwrap(block) {
                let mut inner = rwlock.into_inner();
                stack.extend(inner.children.drain().map(|(_, v)| v));
            }
        }
    }
}

impl ConcurrentRadixTree {
    /// Create a new `ConcurrentRadixTree`.
    pub fn new() -> Self {
        Self {
            root: Arc::new(RwLock::new(Block::new())),
167
            tree_sizes: DashMap::with_hasher(FxBuildHasher),
168
            cleanup: CleanupState::new(),
Yan Ru Pei's avatar
Yan Ru Pei committed
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
        }
    }

    /// Traverse the radix tree to find the best match for a given sequence of [`LocalBlockHash`]es.
    ///
    /// This operation is thread-safe and can run concurrently with other `find_matches` calls.
    /// Uses hand-over-hand read locking to minimize lock contention.
    ///
    /// ### Arguments
    ///
    /// * `sequence` - A slice of `LocalBlockHash` representing the sequence to match.
    /// * `early_exit` - A boolean indicating whether to exit early if a single match is found.
    ///
    /// ### Returns
    ///
    /// An `OverlapScores` representing the match scores.
    /// Note: `frequencies` field will be empty since frequency tracking is not supported.
    pub fn find_matches_impl(
        &self,
        sequence: &[LocalBlockHash],
        early_exit: bool,
    ) -> OverlapScores {
        let mut scores = OverlapScores::new();

        if sequence.is_empty() {
            return scores;
        }

        // Get first child from root.
        let first_child = {
            let guard = self.root.read();
            guard.children.get(&sequence[0]).cloned()
        };

        let Some(first_child) = first_child else {
            return scores;
        };

        // Initialize active worker set from first child.
        let (mut active, mut active_count) = {
            let guard = first_child.read();
            (guard.workers.clone(), guard.workers.len())
        };

        if active.is_empty() {
            return scores;
        }

        if early_exit && active_count == 1 {
            for worker in &active {
                scores.scores.insert(*worker, 1);
            }
            for worker in scores.scores.keys() {
222
223
224
225
                if let Some(worker_tree_size) = self.tree_sizes.get(worker) {
                    scores
                        .tree_sizes
                        .insert(*worker, worker_tree_size.load(Ordering::Relaxed));
Yan Ru Pei's avatar
Yan Ru Pei committed
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
                }
            }
            return scores;
        }

        let mut current = first_child;
        let mut matched_depth = 1u32;

        // Traverse remaining levels. In a clean tree, workers at a child node
        // are always a subset of the parent (along the same path), so:
        //   - workers can only drop out, never join, as we descend
        //   - if child.workers.len() == active_count, the sets are identical
        //
        // However, because apply_removed does NOT cascade to descendants, a
        // child may transiently have MORE workers than its parent (stale
        // entries from an ancestor remove whose descendant remove events
        // haven't arrived yet). We detect this via child_count > active_count
        // and fall back to a full membership check.
        for (idx, local_hash) in sequence.iter().enumerate().skip(1) {
            let next_block = {
                let guard = current.read();
                guard.children.get(local_hash).cloned()
            };

            let Some(block) = next_block else {
                break;
            };

            {
                let guard = block.read();
                let child_count = guard.workers.len();

258
                if child_count != active_count {
259
260
                    reconcile_active_workers(&mut active, &guard.workers, |worker| {
                        scores.scores.insert(worker, matched_depth);
Yan Ru Pei's avatar
Yan Ru Pei committed
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
                    });
                    active_count = active.len();

                    if active_count == 0 {
                        break;
                    }
                }
                // child_count == active_count: fast path, sets are identical
                // (or, in the rare edge case, different membership with same
                // cardinality -- accepted as a transient routing quality
                // degradation that resolves once pending remove events arrive).

                if early_exit && active_count == 1 {
                    matched_depth = (idx + 1) as u32;
                    break;
                }
            }

            current = block;
            matched_depth = (idx + 1) as u32;
        }

        // Record scores for workers that survived through the deepest matched level.
        for worker in &active {
            scores.scores.insert(*worker, matched_depth);
        }

        // Get tree sizes from lookup.
        for worker in scores.scores.keys() {
290
291
292
293
            if let Some(worker_tree_size) = self.tree_sizes.get(worker) {
                scores
                    .tree_sizes
                    .insert(*worker, worker_tree_size.load(Ordering::Relaxed));
Yan Ru Pei's avatar
Yan Ru Pei committed
294
295
296
297
298
299
300
301
302
303
304
305
306
307
            }
        }

        scores
    }

    /// Apply a [`RouterEvent`] to the radix tree.
    ///
    /// This operation is thread-safe. Interior mutability via locks allows
    /// `&self` instead of `&mut self`.
    ///
    /// ### Arguments
    ///
    /// * `event` - The `RouterEvent` to apply.
308
309
310
311
312
    fn apply_event(
        &self,
        lookup: &mut FxHashMap<WorkerWithDpRank, WorkerLookup>,
        event: RouterEvent,
    ) -> Result<(), KvCacheEventError> {
Yan Ru Pei's avatar
Yan Ru Pei committed
313
314
315
316
317
318
319
        let (worker_id, kv_event) = (event.worker_id, event.event);
        let (id, op) = (kv_event.event_id, kv_event.data);

        // Construct WorkerWithDpRank from worker_id and dp_rank from the event
        let worker = WorkerWithDpRank::new(worker_id, kv_event.dp_rank);

        match op {
320
321
            KvCacheEventData::Stored(op) => self.apply_stored(lookup, worker, op, id),
            KvCacheEventData::Removed(op) => self.apply_removed(lookup, worker, op, id),
Yan Ru Pei's avatar
Yan Ru Pei committed
322
            KvCacheEventData::Cleared => {
323
324
325
326
327
328
329
330
                // Ensure the worker is tracked in lookup before clearing,
                // matching RadixTree behavior where `lookup.entry(worker).or_default()`
                // fires before the match arm.
                lookup.entry(worker).or_default();
                self.tree_sizes
                    .entry(worker)
                    .or_insert_with(|| AtomicUsize::new(0));
                self.clear_all_blocks(lookup, worker.worker_id);
Yan Ru Pei's avatar
Yan Ru Pei committed
331
332
333
334
335
336
337
338
                Ok(())
            }
        }
    }

    /// Apply a store operation.
    fn apply_stored(
        &self,
339
        lookup: &mut FxHashMap<WorkerWithDpRank, WorkerLookup>,
Yan Ru Pei's avatar
Yan Ru Pei committed
340
341
342
343
344
        worker: WorkerWithDpRank,
        op: KvCacheStoreData,
        id: u64,
    ) -> Result<(), KvCacheEventError> {
        // Ensure this worker has an entry in the outer map.
345
        let worker_lookup = lookup.entry(worker).or_default();
Yan Ru Pei's avatar
Yan Ru Pei committed
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367

        // Find parent block
        let mut current = match op.parent_hash {
            Some(parent) => match worker_lookup.get(&parent) {
                Some(block) => block.clone(),
                None => {
                    tracing::warn!(
                        worker_id = worker.worker_id.to_string(),
                        dp_rank = worker.dp_rank,
                        id,
                        parent_hash = ?op.parent_hash,
                        num_blocks = op.blocks.len(),
                        "Failed to find parent block; skipping store operation"
                    );
                    return Err(KvCacheEventError::ParentBlockNotFound);
                }
            },
            None => self.root.clone(),
        };

        let mut needs_worker_insert = false;

368
        let mut num_blocks_added = 0;
369

370
371
372
373
374
        // In each iteration, we lock the parent block and insert the worker into it from
        // the previous iteration. This avoids locking a block twice.
        //
        // Track tree size from worker_lookup insertions so it matches the single-threaded
        // radix tree's `lookup.len()` semantics and naturally includes the tail block.
Yan Ru Pei's avatar
Yan Ru Pei committed
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
        for block_data in op.blocks {
            let child = {
                let mut parent_guard = current.write();

                // Insert worker into this node if it was the child from the
                // previous iteration (skip for the initial parent, which is
                // not one of the blocks being stored).
                if needs_worker_insert {
                    parent_guard.workers.insert(worker);
                }
                needs_worker_insert = true;

                // parent_guard is dropped at the end of this block
                match parent_guard.children.get(&block_data.tokens_hash) {
                    Some(existing) => {
                        {
                            let existing_guard = existing.read();
                            if existing_guard.block_hash != Some(block_data.block_hash) {
                                tracing::warn!(
                                    expected = ?block_data.block_hash,
                                    actual = ?existing_guard.block_hash,
                                    "block_hash mismatch: sequence hashes should be uniform across workers"
                                );
                            }
                        }
                        existing.clone()
                    }
                    None => {
                        // Reuse from lookup or create new
                        let new_block = worker_lookup
                            .get(&block_data.block_hash)
                            .cloned()
                            .unwrap_or_else(|| {
                                Arc::new(RwLock::new(Block::with_hash(block_data.block_hash)))
                            });

                        parent_guard
                            .children
                            .insert(block_data.tokens_hash, new_block.clone());
                        new_block
                    }
                }
            };

            // Update lookup
420
421
422
423
424
425
            if worker_lookup
                .insert(block_data.block_hash, child.clone())
                .is_none()
            {
                num_blocks_added += 1;
            }
Yan Ru Pei's avatar
Yan Ru Pei committed
426
427
428
429

            current = child;
        }

430
431
432
433
434
435
        // Insert worker into the last child (not yet handled since there is
        // no subsequent iteration to pick it up).
        if needs_worker_insert {
            current.write().workers.insert(worker);
        }

436
437
438
439
440
441
442
443
444
445
        match self.tree_sizes.get(&worker) {
            Some(size) => {
                size.fetch_add(num_blocks_added, Ordering::Relaxed);
            }
            None => {
                self.tree_sizes
                    .insert(worker, AtomicUsize::new(num_blocks_added));
            }
        }

Yan Ru Pei's avatar
Yan Ru Pei committed
446
447
448
449
450
451
452
453
454
455
456
457
        Ok(())
    }

    /// Apply a remove operation.
    ///
    /// This method does NOT cascade to descendants. Each block hash in the event
    /// is removed individually in O(1). Descendant blocks may transiently retain
    /// the worker in their `workers` set until their own explicit remove events
    /// arrive. `find_matches_impl` handles this by detecting stale entries when
    /// `child_count > active_count`.
    fn apply_removed(
        &self,
458
        lookup: &mut FxHashMap<WorkerWithDpRank, WorkerLookup>,
Yan Ru Pei's avatar
Yan Ru Pei committed
459
460
461
462
        worker: WorkerWithDpRank,
        op: KvCacheRemoveData,
        id: u64,
    ) -> Result<(), KvCacheEventError> {
463
        let Some(worker_lookup) = lookup.get_mut(&worker) else {
Yan Ru Pei's avatar
Yan Ru Pei committed
464
465
            return Err(KvCacheEventError::BlockNotFound);
        };
466
467

        let mut num_removed = 0;
Yan Ru Pei's avatar
Yan Ru Pei committed
468
469
470
471
472
473
474
475
476
477
478
479
480

        for block_hash in op.block_hashes {
            let Some(block) = worker_lookup.remove(&block_hash) else {
                tracing::debug!(
                    worker_id = worker.worker_id.to_string(),
                    dp_rank = worker.dp_rank,
                    id,
                    block_hash = ?block_hash,
                    "Block not found during remove; skipping"
                );
                continue;
            };

481
            block.write().drop_worker(worker);
482
483
484
485
486
487
488
489
490
491
492
493

            num_removed += 1;
        }

        match self.tree_sizes.get(&worker) {
            Some(size) => {
                size.fetch_sub(num_removed, Ordering::Relaxed);
            }
            None => {
                self.tree_sizes
                    .insert(worker, AtomicUsize::new(num_removed));
            }
Yan Ru Pei's avatar
Yan Ru Pei committed
494
495
496
497
498
499
500
501
        }

        Ok(())
    }

    /// Helper function to remove or clear blocks for a worker.
    /// If `keep_worker` is true, the worker remains in lookup with empty blocks.
    /// If `keep_worker` is false, the worker is completely removed from lookup.
502
503
504
505
506
507
508
    fn remove_or_clear_worker_blocks(
        &self,
        lookup: &mut FxHashMap<WorkerWithDpRank, WorkerLookup>,
        worker_id: WorkerId,
        keep_worker: bool,
    ) {
        let workers: Vec<WorkerWithDpRank> = lookup
509
510
511
            .keys()
            .filter(|w| w.worker_id == worker_id)
            .copied()
Yan Ru Pei's avatar
Yan Ru Pei committed
512
513
514
            .collect();

        for worker in workers {
515
516
            if let Some(worker_lookup) = lookup.remove(&worker) {
                for (_, block) in worker_lookup.into_iter() {
517
                    block.write().drop_worker(worker);
Yan Ru Pei's avatar
Yan Ru Pei committed
518
519
520
                }

                if keep_worker {
521
522
523
524
525
526
527
528
529
530
                    lookup.insert(worker, FxHashMap::default());
                    // Reset tree size to 0 but keep the entry so get_workers()
                    // still returns this worker (matches RadixTree::clear_all_blocks behavior).
                    if let Some(size) = self.tree_sizes.get(&worker) {
                        size.store(0, Ordering::Relaxed);
                    }
                } else {
                    // Fully remove the worker from tree_sizes so get_workers()
                    // no longer returns it (matches RadixTree::remove_worker behavior).
                    self.tree_sizes.remove(&worker);
Yan Ru Pei's avatar
Yan Ru Pei committed
531
532
533
534
535
                }
            }
        }
    }

536
537
538
539
540
541
542
543
544
    fn remove_worker_dp_rank(
        &self,
        lookup: &mut FxHashMap<WorkerWithDpRank, WorkerLookup>,
        worker_id: WorkerId,
        dp_rank: DpRank,
    ) {
        let key = WorkerWithDpRank { worker_id, dp_rank };
        if let Some(worker_lookup) = lookup.remove(&key) {
            for (_, block) in worker_lookup.into_iter() {
545
                block.write().drop_worker(key);
546
547
548
549
550
            }
            self.tree_sizes.remove(&key);
        }
    }

Yan Ru Pei's avatar
Yan Ru Pei committed
551
    /// Clear all blocks for a worker but keep the worker tracked.
552
553
554
555
556
557
    fn clear_all_blocks(
        &self,
        lookup: &mut FxHashMap<WorkerWithDpRank, WorkerLookup>,
        worker_id: WorkerId,
    ) {
        self.remove_or_clear_worker_blocks(lookup, worker_id, true);
Yan Ru Pei's avatar
Yan Ru Pei committed
558
559
560
561
562
563
    }

    /// Get all worker IDs currently tracked in the radix tree.
    /// Returns unique worker_ids (ignoring dp_rank differences).
    pub fn get_workers(&self) -> Vec<WorkerId> {
        let mut worker_ids: Vec<WorkerId> = self
564
565
566
            .tree_sizes
            .iter()
            .map(|entry| entry.key().worker_id)
Yan Ru Pei's avatar
Yan Ru Pei committed
567
568
            .collect();
        worker_ids.sort_unstable();
569
        worker_ids.dedup();
Yan Ru Pei's avatar
Yan Ru Pei committed
570
571
572
573
        worker_ids
    }

    /// Dump the radix tree as a series of RouterEvents that can reconstruct the tree.
574
575
576
577
578
    /// Uses BFS traversal over the shared tree. Since all worker/block membership is
    /// stored in the tree nodes themselves, this can be called from any thread without
    /// needing per-thread lookup state.
    fn dump_tree_as_events(&self) -> Vec<RouterEvent> {
        tracing::debug!("Dumping concurrent radix tree as events");
Yan Ru Pei's avatar
Yan Ru Pei committed
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605

        let mut events = Vec::new();
        let mut event_id = 0u64;

        // Queue entries: (current_block, parent_hash, tokens_hash)
        let mut queue = VecDeque::new();

        {
            let root_guard = self.root.read();
            for (tokens_hash, child_block) in &root_guard.children {
                queue.push_back((child_block.clone(), None, *tokens_hash));
            }
        }

        while let Some((current_block, parent_hash, tokens_hash)) = queue.pop_front() {
            let current_guard = current_block.read();

            // Get this block's hash (same for all workers)
            let block_hash = current_guard
                .block_hash
                .expect("non-root block must have block_hash");

            // For each worker that has this block
            for worker in &current_guard.workers {
                // Create a store event for this worker
                let event = RouterEvent {
                    worker_id: worker.worker_id,
606
                    storage_tier: crate::protocols::StorageTier::Device,
Yan Ru Pei's avatar
Yan Ru Pei committed
607
608
609
610
                    event: KvCacheEvent {
                        event_id,
                        data: KvCacheEventData::Stored(KvCacheStoreData {
                            parent_hash,
611
                            start_position: None,
Yan Ru Pei's avatar
Yan Ru Pei committed
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
                            blocks: vec![KvCacheStoredBlockData {
                                block_hash,
                                mm_extra_info: None,
                                tokens_hash,
                            }],
                        }),
                        dp_rank: worker.dp_rank,
                    },
                };
                events.push(event);
                event_id += 1;
            }

            // Enqueue children with this block's hash as their parent
            for (child_tokens_hash, child_block) in &current_guard.children {
                queue.push_back((child_block.clone(), Some(block_hash), *child_tokens_hash));
            }
        }

        events
    }
}

// ============================================================================
// SyncIndexer implementation for ConcurrentRadixTree
// ============================================================================

impl SyncIndexer for ConcurrentRadixTree {
640
641
642
643
644
    fn worker(
        &self,
        event_receiver: flume::Receiver<WorkerTask>,
        metrics: Option<Arc<KvIndexerMetrics>>,
    ) -> anyhow::Result<()> {
645
        let mut lookup = FxHashMap::default();
646
        let counters = metrics.as_ref().map(|m| m.prebind());
647
648
649
650

        while let Ok(task) = event_receiver.recv() {
            match task {
                WorkerTask::Event(event) => {
651
652
653
654
655
656
657
                    let kind = EventKind::of(&event.event.data);
                    let result = self.apply_event(&mut lookup, event);
                    if result.is_err() {
                        tracing::warn!("Failed to apply event: {:?}", result.as_ref().err());
                    }
                    if let Some(ref c) = counters {
                        c.inc(kind, result);
Yan Ru Pei's avatar
Yan Ru Pei committed
658
                    }
659
660
661
662
                }
                WorkerTask::RemoveWorker(worker_id) => {
                    self.remove_or_clear_worker_blocks(&mut lookup, worker_id, false);
                }
663
664
665
                WorkerTask::RemoveWorkerDpRank(worker_id, dp_rank) => {
                    self.remove_worker_dp_rank(&mut lookup, worker_id, dp_rank);
                }
666
667
668
                WorkerTask::CleanupStaleChildren => {
                    self.run_cleanup_task();
                }
669
670
671
672
673
674
675
676
677
                WorkerTask::DumpEvents(_sender) => {
                    // Handled directly via dump_events() on the shared tree.
                    // Should not be reached, but respond with empty to avoid blocking.
                    let _ = _sender.send(Ok(Vec::new()));
                }
                WorkerTask::Terminate => {
                    break;
                }
            }
Yan Ru Pei's avatar
Yan Ru Pei committed
678
679
        }

680
681
        tracing::debug!("ConcurrentRadixTree worker thread shutting down");
        Ok(())
Yan Ru Pei's avatar
Yan Ru Pei committed
682
683
    }

684
685
    fn find_matches(&self, sequence: &[LocalBlockHash], early_exit: bool) -> OverlapScores {
        self.find_matches_impl(sequence, early_exit)
Yan Ru Pei's avatar
Yan Ru Pei committed
686
687
    }

688
689
690
691
692
693
694
695
696
697
698
699
700
701
    fn try_schedule_cleanup(&self) -> bool {
        self.cleanup.try_schedule()
    }

    fn cancel_scheduled_cleanup(&self) {
        self.cleanup.cancel();
    }

    fn run_cleanup_task(&self) {
        let mut cleanup_guard = CleanupGuard::new(&self.cleanup);
        cleanup::sweep_stale_children(&self.root);
        cleanup_guard.mark_completed();
    }

702
703
    fn dump_events(&self) -> Option<Vec<RouterEvent>> {
        Some(self.dump_tree_as_events())
Yan Ru Pei's avatar
Yan Ru Pei committed
704
705
    }
}