concurrent_radix_tree.rs 26.2 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
36
37
use super::{
    EventKind, EventWarningKind, KvIndexerMetrics, PreBoundEventCounters, SyncIndexer, WorkerTask,
};
38
use crate::active_set::reconcile_active_workers;
39
use crate::cleanup::{self, CleanableNode, CleanupGuard, CleanupState};
Yan Ru Pei's avatar
Yan Ru Pei committed
40
41
42
43
44
use crate::protocols::*;

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

45
46
47
/// 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
48
49
50
51
/// A block in the concurrent radix tree.
#[derive(Debug)]
struct Block {
    /// A map of child blocks, keyed by their local block hash.
52
    children: FxHashMap<LocalBlockHash, SharedBlock>,
Yan Ru Pei's avatar
Yan Ru Pei committed
53
    /// The set of workers that have this block cached.
54
    workers: FxHashSet<WorkerWithDpRank>,
Yan Ru Pei's avatar
Yan Ru Pei committed
55
56
57
58
59
60
61
62
63
64
    /// 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 {
65
66
            children: FxHashMap::default(),
            workers: FxHashSet::default(),
Yan Ru Pei's avatar
Yan Ru Pei committed
67
68
69
70
71
72
73
            block_hash: None,
        }
    }

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

    #[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
87
88
}

89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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
105
106
107
108
/// 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
109
/// `DashMap<..., RwLock<FxHashMap<...>>>` for the lookup table,
Yan Ru Pei's avatar
Yan Ru Pei committed
110
111
112
113
114
115
116
117
118
119
120
121
/// 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
122
/// - Outer `DashMap` provides shard-level locking for per-worker access.
123
/// - Inner `RwLock` per worker allows per-worker write concurrency.
Yan Ru Pei's avatar
Yan Ru Pei committed
124
125
126
127
128
129
/// - 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,

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

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));
        }

152
153
154
        // 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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
        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())),
169
            tree_sizes: DashMap::with_hasher(FxBuildHasher),
170
            cleanup: CleanupState::new(),
Yan Ru Pei's avatar
Yan Ru Pei committed
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
222
223
        }
    }

    /// 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() {
224
225
226
227
                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
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
258
259
                }
            }
            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();

260
                if child_count != active_count {
261
262
                    reconcile_active_workers(&mut active, &guard.workers, |worker| {
                        scores.scores.insert(worker, matched_depth);
Yan Ru Pei's avatar
Yan Ru Pei committed
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
290
291
                    });
                    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() {
292
293
294
295
            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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
            }
        }

        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.
310
311
312
313
    fn apply_event(
        &self,
        lookup: &mut FxHashMap<WorkerWithDpRank, WorkerLookup>,
        event: RouterEvent,
314
        counters: Option<&PreBoundEventCounters>,
315
    ) -> Result<(), KvCacheEventError> {
Yan Ru Pei's avatar
Yan Ru Pei committed
316
317
318
319
320
321
322
        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 {
323
            KvCacheEventData::Stored(op) => self.apply_stored(lookup, worker, op, id, counters),
324
            KvCacheEventData::Removed(op) => self.apply_removed(lookup, worker, op, id),
Yan Ru Pei's avatar
Yan Ru Pei committed
325
            KvCacheEventData::Cleared => {
326
327
328
329
330
331
332
333
                // 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
334
335
336
337
338
339
340
341
                Ok(())
            }
        }
    }

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

        // 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;
371
        let mut duplicate_store = !op.blocks.is_empty();
Yan Ru Pei's avatar
Yan Ru Pei committed
372

373
        let mut num_blocks_added = 0;
374

375
376
377
378
379
        // 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
380
381
382
383
384
385
386
        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).
387
388
                if needs_worker_insert && parent_guard.workers.insert(worker) {
                    duplicate_store = false;
Yan Ru Pei's avatar
Yan Ru Pei committed
389
390
391
392
393
394
395
396
397
                }
                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) {
398
                                duplicate_store = false;
Yan Ru Pei's avatar
Yan Ru Pei committed
399
400
401
402
403
404
405
406
407
408
                                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 => {
409
                        duplicate_store = false;
Yan Ru Pei's avatar
Yan Ru Pei committed
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
                        // 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
427
428
429
430
431
432
433
            match worker_lookup.insert(block_data.block_hash, child.clone()) {
                Some(existing) if Arc::ptr_eq(&existing, &child) => {}
                Some(_) => duplicate_store = false,
                None => {
                    num_blocks_added += 1;
                    duplicate_store = false;
                }
434
            }
Yan Ru Pei's avatar
Yan Ru Pei committed
435
436
437
438

            current = child;
        }

439
440
        // Insert worker into the last child (not yet handled since there is
        // no subsequent iteration to pick it up).
441
442
        if needs_worker_insert && current.write().workers.insert(worker) {
            duplicate_store = false;
443
444
        }

445
446
447
448
449
450
451
452
453
454
        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));
            }
        }

455
456
457
458
        if duplicate_store && let Some(counters) = counters {
            counters.inc_warning(EventWarningKind::DuplicateStore);
        }

Yan Ru Pei's avatar
Yan Ru Pei committed
459
460
461
462
463
464
465
466
467
468
469
470
        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,
471
        lookup: &mut FxHashMap<WorkerWithDpRank, WorkerLookup>,
Yan Ru Pei's avatar
Yan Ru Pei committed
472
473
474
475
        worker: WorkerWithDpRank,
        op: KvCacheRemoveData,
        id: u64,
    ) -> Result<(), KvCacheEventError> {
476
        let Some(worker_lookup) = lookup.get_mut(&worker) else {
Yan Ru Pei's avatar
Yan Ru Pei committed
477
478
            return Err(KvCacheEventError::BlockNotFound);
        };
479
480

        let mut num_removed = 0;
Yan Ru Pei's avatar
Yan Ru Pei committed
481
482
483
484
485
486
487
488
489
490
491
492
493

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

494
            block.write().drop_worker(worker);
495
496
497
498
499
500
501
502
503
504
505
506

            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
507
508
509
510
511
512
513
514
        }

        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.
515
516
517
518
519
520
521
    fn remove_or_clear_worker_blocks(
        &self,
        lookup: &mut FxHashMap<WorkerWithDpRank, WorkerLookup>,
        worker_id: WorkerId,
        keep_worker: bool,
    ) {
        let workers: Vec<WorkerWithDpRank> = lookup
522
523
524
            .keys()
            .filter(|w| w.worker_id == worker_id)
            .copied()
Yan Ru Pei's avatar
Yan Ru Pei committed
525
526
527
            .collect();

        for worker in workers {
528
529
            if let Some(worker_lookup) = lookup.remove(&worker) {
                for (_, block) in worker_lookup.into_iter() {
530
                    block.write().drop_worker(worker);
Yan Ru Pei's avatar
Yan Ru Pei committed
531
532
533
                }

                if keep_worker {
534
535
536
537
538
539
540
541
542
543
                    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
544
545
546
547
548
                }
            }
        }
    }

549
550
551
552
553
554
555
556
557
    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() {
558
                block.write().drop_worker(key);
559
560
561
562
563
            }
            self.tree_sizes.remove(&key);
        }
    }

Yan Ru Pei's avatar
Yan Ru Pei committed
564
    /// Clear all blocks for a worker but keep the worker tracked.
565
566
567
568
569
570
    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
571
572
573
574
575
576
    }

    /// 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
577
578
579
            .tree_sizes
            .iter()
            .map(|entry| entry.key().worker_id)
Yan Ru Pei's avatar
Yan Ru Pei committed
580
581
            .collect();
        worker_ids.sort_unstable();
582
        worker_ids.dedup();
Yan Ru Pei's avatar
Yan Ru Pei committed
583
584
585
586
        worker_ids
    }

    /// Dump the radix tree as a series of RouterEvents that can reconstruct the tree.
587
588
589
590
591
    /// 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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618

        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,
619
                    storage_tier: crate::protocols::StorageTier::Device,
Yan Ru Pei's avatar
Yan Ru Pei committed
620
621
622
623
                    event: KvCacheEvent {
                        event_id,
                        data: KvCacheEventData::Stored(KvCacheStoreData {
                            parent_hash,
624
                            start_position: None,
Yan Ru Pei's avatar
Yan Ru Pei committed
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
                            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 {
653
654
655
656
657
    fn worker(
        &self,
        event_receiver: flume::Receiver<WorkerTask>,
        metrics: Option<Arc<KvIndexerMetrics>>,
    ) -> anyhow::Result<()> {
658
        let mut lookup = FxHashMap::default();
659
        let counters = metrics.as_ref().map(|m| m.prebind());
660
661
662
663

        while let Ok(task) = event_receiver.recv() {
            match task {
                WorkerTask::Event(event) => {
664
                    let kind = EventKind::of(&event.event.data);
665
                    let result = self.apply_event(&mut lookup, event, counters.as_ref());
666
667
668
669
670
                    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
671
                    }
672
673
674
675
                }
                WorkerTask::RemoveWorker(worker_id) => {
                    self.remove_or_clear_worker_blocks(&mut lookup, worker_id, false);
                }
676
677
678
                WorkerTask::RemoveWorkerDpRank(worker_id, dp_rank) => {
                    self.remove_worker_dp_rank(&mut lookup, worker_id, dp_rank);
                }
679
680
681
                WorkerTask::CleanupStaleChildren => {
                    self.run_cleanup_task();
                }
682
683
684
685
686
687
688
689
690
                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
691
692
        }

693
694
        tracing::debug!("ConcurrentRadixTree worker thread shutting down");
        Ok(())
Yan Ru Pei's avatar
Yan Ru Pei committed
695
696
    }

697
698
    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
699
700
    }

701
702
703
704
705
706
707
708
709
710
711
712
713
714
    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();
    }

715
716
717
718
719
720
721
722
723
724
725
    fn worker_count(&self) -> usize {
        self.tree_sizes.len()
    }

    fn block_count(&self) -> usize {
        self.tree_sizes
            .iter()
            .map(|e| e.value().load(Ordering::Relaxed))
            .sum()
    }

726
727
    fn dump_events(&self) -> Option<Vec<RouterEvent>> {
        Some(self.dump_tree_as_events())
Yan Ru Pei's avatar
Yan Ru Pei committed
728
729
    }
}