tree.rs 48 KB
Newer Older
1
2
use dashmap::mapref::entry::Entry;
use dashmap::DashMap;
3
use tracing::info;
Byron Hsu's avatar
Byron Hsu committed
4

5
6
use std::cmp::Reverse;
use std::collections::BinaryHeap;
7
use std::collections::HashMap;
8
use std::collections::VecDeque;
9
10
use std::sync::Arc;
use std::sync::RwLock;
Byron Hsu's avatar
Byron Hsu committed
11

12
13
14
15
use std::time::Duration;
use std::time::{SystemTime, UNIX_EPOCH};

type NodeRef = Arc<Node>;
16

17
#[derive(Debug)]
18
19
20
21
22
struct Node {
    children: DashMap<char, NodeRef>,
    text: RwLock<String>,
    tenant_last_access_time: DashMap<String, u128>,
    parent: RwLock<Option<NodeRef>>,
23
24
}

25
#[derive(Debug)]
26
27
28
pub struct Tree {
    root: NodeRef,
    pub tenant_char_count: DashMap<String, usize>,
29
30
}

31
32
33
34
35
36
37
38
39
40
// For the heap

struct EvictionEntry {
    timestamp: u128,
    tenant: String,
    node: NodeRef,
}

impl Eq for EvictionEntry {}

41
#[allow(clippy::non_canonical_partial_ord_impl)]
42
43
44
impl PartialOrd for EvictionEntry {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.timestamp.cmp(&other.timestamp))
45
46
47
    }
}

48
49
50
impl Ord for EvictionEntry {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.timestamp.cmp(&other.timestamp)
51
52
53
    }
}

54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
impl PartialEq for EvictionEntry {
    fn eq(&self, other: &Self) -> bool {
        self.timestamp == other.timestamp
    }
}

// For char operations
// Note that in rust, `.len()` or slice is operated on the "byte" level. It causes issues for UTF-8 characters because one character might use multiple bytes.
// https://en.wikipedia.org/wiki/UTF-8

fn shared_prefix_count(a: &str, b: &str) -> usize {
    let mut i = 0;
    let mut a_iter = a.chars();
    let mut b_iter = b.chars();

    loop {
        match (a_iter.next(), b_iter.next()) {
            (Some(a_char), Some(b_char)) if a_char == b_char => {
                i += 1;
            }
            _ => break,
        }
    }

78
    i
79
80
81
82
83
84
}

fn slice_by_chars(s: &str, start: usize, end: usize) -> String {
    s.chars().skip(start).take(end - start).collect()
}

85
86
87
88
89
90
impl Default for Tree {
    fn default() -> Self {
        Self::new()
    }
}

91
92
93
94
95
impl Tree {
    /*
    Thread-safe multi tenant radix tree

    1. Storing data for multiple tenants (the overlap of multiple radix tree)
96
    2. Node-level lock to enable concurrent access on nodes
97
98
99
    3. Leaf LRU eviction based on tenant access time
    */

100
    pub fn new() -> Self {
101
102
103
104
105
106
107
108
        Tree {
            root: Arc::new(Node {
                children: DashMap::new(),
                text: RwLock::new("".to_string()),
                tenant_last_access_time: DashMap::new(),
                parent: RwLock::new(None),
            }),
            tenant_char_count: DashMap::new(),
109
110
111
        }
    }

112
113
    pub fn insert(&self, text: &str, tenant: &str) {
        // Insert text into tree with given tenant
114

115
        let mut curr = Arc::clone(&self.root);
116
        let mut curr_idx = 0;
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161

        let timestamp_ms = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_millis();

        curr.tenant_last_access_time
            .insert(tenant.to_string(), timestamp_ms);

        self.tenant_char_count
            .entry(tenant.to_string())
            .or_insert(0);

        let mut prev = Arc::clone(&self.root);

        let text_count = text.chars().count();

        while curr_idx < text_count {
            let first_char = text.chars().nth(curr_idx).unwrap();

            curr = prev;

            // dashmap.entry locks the entry until the op is done
            // if using contains_key + insert, there will be an issue that
            // 1. "apple" and "app" entered at the same time
            // 2. and get inserted to the dashmap concurrently, so only one is inserted

            match curr.children.entry(first_char) {
                Entry::Vacant(entry) => {
                    /*
                       no matched
                       [curr]
                       becomes
                       [curr] => [new node]
                    */

                    let curr_text = slice_by_chars(text, curr_idx, text_count);
                    let curr_text_count = curr_text.chars().count();
                    let new_node = Arc::new(Node {
                        children: DashMap::new(),
                        text: RwLock::new(curr_text),
                        tenant_last_access_time: DashMap::new(),
                        parent: RwLock::new(Some(Arc::clone(&curr))),
                    });

162
                    // Attach tenant to the new node (map is empty here) and increment count once
163
164
165
166
167
168
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
                    self.tenant_char_count
                        .entry(tenant.to_string())
                        .and_modify(|count| *count += curr_text_count)
                        .or_insert(curr_text_count);
                    new_node
                        .tenant_last_access_time
                        .insert(tenant.to_string(), timestamp_ms);

                    entry.insert(Arc::clone(&new_node));

                    prev = Arc::clone(&new_node);
                    curr_idx = text_count;
                }

                Entry::Occupied(mut entry) => {
                    // matched
                    let matched_node = entry.get().clone();

                    let matched_node_text = matched_node.text.read().unwrap().to_owned();
                    let matched_node_text_count = matched_node_text.chars().count();

                    let curr_text = slice_by_chars(text, curr_idx, text_count);
                    let shared_count = shared_prefix_count(&matched_node_text, &curr_text);

                    if shared_count < matched_node_text_count {
                        /*
                           split the matched node
                           [curr] -> [matched_node] =>
                           becomes
                           [curr] -> [new_node] -> [contracted_matched_node]
                        */

                        let matched_text = slice_by_chars(&matched_node_text, 0, shared_count);
                        let contracted_text = slice_by_chars(
                            &matched_node_text,
                            shared_count,
                            matched_node_text_count,
                        );
                        let matched_text_count = matched_text.chars().count();

                        let new_node = Arc::new(Node {
                            text: RwLock::new(matched_text),
                            children: DashMap::new(),
                            parent: RwLock::new(Some(Arc::clone(&curr))),
                            tenant_last_access_time: matched_node.tenant_last_access_time.clone(),
                        });

                        let first_new_char = contracted_text.chars().nth(0).unwrap();
                        new_node
                            .children
                            .insert(first_new_char, Arc::clone(&matched_node));

                        entry.insert(Arc::clone(&new_node));

                        *matched_node.text.write().unwrap() = contracted_text;
                        *matched_node.parent.write().unwrap() = Some(Arc::clone(&new_node));

                        prev = Arc::clone(&new_node);

222
223
224
225
226
227
228
229
230
231
232
233
                        // Atomically attach tenant to the new split node and increment count once
                        match prev.tenant_last_access_time.entry(tenant.to_string()) {
                            Entry::Vacant(v) => {
                                self.tenant_char_count
                                    .entry(tenant.to_string())
                                    .and_modify(|count| *count += matched_text_count)
                                    .or_insert(matched_text_count);
                                v.insert(timestamp_ms);
                            }
                            Entry::Occupied(mut o) => {
                                o.insert(timestamp_ms);
                            }
234
235
236
237
238
239
240
                        }

                        curr_idx += shared_count;
                    } else {
                        // move to next node
                        prev = Arc::clone(&matched_node);

241
242
243
244
245
246
247
248
249
250
251
252
                        // Atomically attach tenant to existing node and increment count once
                        match prev.tenant_last_access_time.entry(tenant.to_string()) {
                            Entry::Vacant(v) => {
                                self.tenant_char_count
                                    .entry(tenant.to_string())
                                    .and_modify(|count| *count += matched_node_text_count)
                                    .or_insert(matched_node_text_count);
                                v.insert(timestamp_ms);
                            }
                            Entry::Occupied(mut o) => {
                                o.insert(timestamp_ms);
                            }
253
254
255
                        }
                        curr_idx += shared_count;
                    }
256
257
258
259
260
                }
            }
        }
    }

Byron Hsu's avatar
Byron Hsu committed
261
    #[allow(unused_assignments)]
262
263
    pub fn prefix_match(&self, text: &str) -> (String, String) {
        let mut curr = Arc::clone(&self.root);
264
265
        let mut curr_idx = 0;

266
267
268
269
270
271
272
273
        let mut prev = Arc::clone(&self.root);
        let text_count = text.chars().count();

        while curr_idx < text_count {
            let first_char = text.chars().nth(curr_idx).unwrap();
            let curr_text = slice_by_chars(text, curr_idx, text_count);

            curr = prev.clone();
274

275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
            if let Some(entry) = curr.children.get(&first_char) {
                let matched_node = entry.value().clone();
                let matched_text_guard = matched_node.text.read().unwrap();
                let shared_count = shared_prefix_count(&matched_text_guard, &curr_text);
                let matched_node_text_count = matched_text_guard.chars().count();
                drop(matched_text_guard);

                if shared_count == matched_node_text_count {
                    // Full match with current node's text, continue to next node
                    curr_idx += shared_count;
                    prev = Arc::clone(&matched_node);
                } else {
                    // Partial match, stop here
                    curr_idx += shared_count;
                    prev = Arc::clone(&matched_node);
290
291
                    break;
                }
292
293
294
            } else {
                // No match found, stop here
                break;
295
296
297
            }
        }

298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
        curr = prev.clone();

        // Select the first tenant (key in the map)
        let tenant = curr
            .tenant_last_access_time
            .iter()
            .next()
            .map(|kv| kv.key().to_owned())
            .unwrap_or("empty".to_string());

        // Traverse from the curr node to the root and update the timestamp

        let timestamp_ms = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_millis();

        if !tenant.eq("empty") {
            let mut current_node = Some(curr);
            while let Some(node) = current_node {
                node.tenant_last_access_time
                    .insert(tenant.clone(), timestamp_ms);
                current_node = node.parent.read().unwrap().clone();
            }
        }

        let ret_text = slice_by_chars(text, 0, curr_idx);
        (ret_text, tenant)
326
327
    }

Byron Hsu's avatar
Byron Hsu committed
328
    #[allow(unused_assignments)]
329
330
331
332
333
334
335
336
337
338
339
340
341
    pub fn prefix_match_tenant(&self, text: &str, tenant: &str) -> String {
        let mut curr = Arc::clone(&self.root);
        let mut curr_idx = 0;

        let mut prev = Arc::clone(&self.root);
        let text_count = text.chars().count();

        while curr_idx < text_count {
            let first_char = text.chars().nth(curr_idx).unwrap();
            let curr_text = slice_by_chars(text, curr_idx, text_count);

            curr = prev.clone();

342
343
            if let Some(entry) = curr.children.get(&first_char) {
                let matched_node = entry.value().clone();
344

345
346
347
                // Only continue matching if this node belongs to the specified tenant
                if !matched_node.tenant_last_access_time.contains_key(tenant) {
                    break;
348
                }
349
350
351
352
353
354
355
356
357
358
359
360
361
362

                let matched_text_guard = matched_node.text.read().unwrap();
                let shared_count = shared_prefix_count(&matched_text_guard, &curr_text);
                let matched_node_text_count = matched_text_guard.chars().count();
                drop(matched_text_guard);

                if shared_count == matched_node_text_count {
                    // Full match with current node's text, continue to next node
                    curr_idx += shared_count;
                    prev = Arc::clone(&matched_node);
                } else {
                    // Partial match, stop here
                    curr_idx += shared_count;
                    prev = Arc::clone(&matched_node);
363
364
                    break;
                }
365
366
367
            } else {
                // No match found, stop here
                break;
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
            }
        }

        curr = prev.clone();

        // Only update timestamp if we found a match for the specified tenant
        if curr.tenant_last_access_time.contains_key(tenant) {
            let timestamp_ms = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_millis();

            let mut current_node = Some(curr);
            while let Some(node) = current_node {
                node.tenant_last_access_time
                    .insert(tenant.to_string(), timestamp_ms);
                current_node = node.parent.read().unwrap().clone();
            }
        }

        slice_by_chars(text, 0, curr_idx)
    }

391
392
393
394
395
396
397
398
399
    fn leaf_of(node: &NodeRef) -> Vec<String> {
        /*
        Return the list of tenants if it's a leaf for the tenant
         */
        let mut candidates: HashMap<String, bool> = node
            .tenant_last_access_time
            .iter()
            .map(|entry| (entry.key().clone(), true))
            .collect();
400

401
402
403
404
405
        for child in node.children.iter() {
            for tenant in child.value().tenant_last_access_time.iter() {
                candidates.insert(tenant.key().clone(), false);
            }
        }
406

407
408
409
410
411
412
        candidates
            .into_iter()
            .filter(|(_, is_leaf)| *is_leaf)
            .map(|(tenant, _)| tenant)
            .collect()
    }
413

414
    pub fn evict_tenant_by_size(&self, max_size: usize) {
415
416
417
        // Calculate used size and collect leaves
        let mut stack = vec![Arc::clone(&self.root)];
        let mut pq = BinaryHeap::new();
418

419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
        while let Some(curr) = stack.pop() {
            for child in curr.children.iter() {
                stack.push(Arc::clone(child.value()));
            }

            // Add leaves to priority queue
            for tenant in Tree::leaf_of(&curr) {
                if let Some(timestamp) = curr.tenant_last_access_time.get(&tenant) {
                    pq.push(Reverse(EvictionEntry {
                        timestamp: *timestamp,
                        tenant: tenant.clone(),
                        node: Arc::clone(&curr),
                    }));
                }
            }
        }

436
        info!("Before eviction - Used size per tenant:");
437
438
        for entry in self.tenant_char_count.iter() {
            info!("Tenant: {}, Size: {}", entry.key(), entry.value());
439
        }
440

441
442
443
444
        // Process eviction
        while let Some(Reverse(entry)) = pq.pop() {
            let EvictionEntry { tenant, node, .. } = entry;

445
446
            if let Some(used_size) = self.tenant_char_count.get(&tenant) {
                if *used_size <= max_size {
447
448
                    continue;
                }
449
            }
450

451
452
            // Decrement when removing tenant from node
            if node.tenant_last_access_time.contains_key(&tenant) {
453
                let node_len = node.text.read().unwrap().chars().count();
454
455
456
                self.tenant_char_count
                    .entry(tenant.clone())
                    .and_modify(|count| {
457
                        *count = count.saturating_sub(node_len);
458
459
                    });
            }
460

461
462
            // Remove tenant from node
            node.tenant_last_access_time.remove(&tenant);
463

464
465
            // Remove empty nodes
            if node.children.is_empty() && node.tenant_last_access_time.is_empty() {
466
467
468
469
470
                if let Some(parent) = node.parent.read().unwrap().as_ref() {
                    let text_guard = node.text.read().unwrap();
                    if let Some(first_char) = text_guard.chars().next() {
                        parent.children.remove(&first_char);
                    }
471
                }
472
            }
473

474
475
476
477
478
479
480
481
482
            // Add parent to queue if it becomes a leaf
            if let Some(parent) = node.parent.read().unwrap().as_ref() {
                if Tree::leaf_of(parent).contains(&tenant) {
                    if let Some(timestamp) = parent.tenant_last_access_time.get(&tenant) {
                        pq.push(Reverse(EvictionEntry {
                            timestamp: *timestamp,
                            tenant: tenant.clone(),
                            node: Arc::clone(parent),
                        }));
483
484
                    }
                }
485
            };
486
        }
487

488
        info!("After eviction - Used size per tenant:");
489
490
        for entry in self.tenant_char_count.iter() {
            info!("Tenant: {}, Size: {}", entry.key(), entry.value());
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
    pub fn remove_tenant(&self, tenant: &str) {
        // 1. Find all the leaves for the tenant
        let mut stack = vec![Arc::clone(&self.root)];
        let mut queue = VecDeque::new();

        while let Some(curr) = stack.pop() {
            for child in curr.children.iter() {
                stack.push(Arc::clone(child.value()));
            }

            if Tree::leaf_of(&curr).contains(&tenant.to_string()) {
                queue.push_back(Arc::clone(&curr));
            }
        }

        // 2. Start from the leaves and traverse up to the root, removing the tenant from each node
        while let Some(curr) = queue.pop_front() {
            // remove tenant from node
            curr.tenant_last_access_time.remove(&tenant.to_string());

            // remove empty nodes
            if curr.children.is_empty() && curr.tenant_last_access_time.is_empty() {
                if let Some(parent) = curr.parent.read().unwrap().as_ref() {
517
518
519
520
                    let text_guard = curr.text.read().unwrap();
                    if let Some(first_char) = text_guard.chars().next() {
                        parent.children.remove(&first_char);
                    }
521
522
523
524
525
526
                }
            }

            // add parent to queue if it becomes a leaf
            if let Some(parent) = curr.parent.read().unwrap().as_ref() {
                if Tree::leaf_of(parent).contains(&tenant.to_string()) {
527
                    queue.push_back(Arc::clone(parent));
528
529
530
531
532
533
534
535
                }
            }
        }

        // 3. Remove the tenant from the tenant_char_count map
        self.tenant_char_count.remove(&tenant.to_string());
    }

536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
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
606
607
608
609
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
645
    pub fn get_tenant_char_count(&self) -> HashMap<String, usize> {
        self.tenant_char_count
            .iter()
            .map(|entry| (entry.key().clone(), *entry.value()))
            .collect()
    }

    pub fn get_smallest_tenant(&self) -> String {
        // Return a placeholder if there are no tenants
        if self.tenant_char_count.is_empty() {
            return "empty".to_string();
        }

        // Find the tenant with minimum char count
        let mut min_tenant = None;
        let mut min_count = usize::MAX;

        for entry in self.tenant_char_count.iter() {
            let tenant = entry.key();
            let count = *entry.value();

            if count < min_count {
                min_count = count;
                min_tenant = Some(tenant.clone());
            }
        }

        // Return the found tenant or "empty" if somehow none was found
        min_tenant.unwrap_or_else(|| "empty".to_string())
    }

    pub fn get_used_size_per_tenant(&self) -> HashMap<String, usize> {
        // perform a DFS to traverse all nodes and calculate the total size used by each tenant

        let mut used_size_per_tenant: HashMap<String, usize> = HashMap::new();
        let mut stack = vec![Arc::clone(&self.root)];

        while let Some(curr) = stack.pop() {
            let text_count = curr.text.read().unwrap().chars().count();

            for tenant in curr.tenant_last_access_time.iter() {
                let size = used_size_per_tenant
                    .entry(tenant.key().clone())
                    .or_insert(0);
                *size += text_count;
            }

            for child in curr.children.iter() {
                stack.push(Arc::clone(child.value()));
            }
        }

        used_size_per_tenant
    }

    fn node_to_string(node: &NodeRef, prefix: &str, is_last: bool) -> String {
        let mut result = String::new();

        // Add prefix and branch character
        result.push_str(prefix);
        result.push_str(if is_last { "└── " } else { "├── " });

        // Add node text
        let node_text = node.text.read().unwrap();
        result.push_str(&format!("'{}' [", node_text));

        // Add tenant information with timestamps
        let mut tenant_info = Vec::new();
        for entry in node.tenant_last_access_time.iter() {
            let tenant_id = entry.key();
            let timestamp_ms = entry.value();

            // Convert milliseconds to seconds and remaining milliseconds
            let seconds = (timestamp_ms / 1000) as u64;
            let millis = (timestamp_ms % 1000) as u32;

            // Create SystemTime from Unix timestamp
            let system_time = UNIX_EPOCH + Duration::from_secs(seconds);

            // Format time as HH:MM:SS.mmm
            let datetime = system_time.duration_since(UNIX_EPOCH).unwrap();
            let hours = (datetime.as_secs() % 86400) / 3600;
            let minutes = (datetime.as_secs() % 3600) / 60;
            let seconds = datetime.as_secs() % 60;

            tenant_info.push(format!(
                "{} | {:02}:{:02}:{:02}.{:03}",
                tenant_id, hours, minutes, seconds, millis
            ));
        }

        result.push_str(&tenant_info.join(", "));
        result.push_str("]\n");

        // Process children
        let children: Vec<_> = node.children.iter().collect();
        let child_count = children.len();

        for (i, entry) in children.iter().enumerate() {
            let is_last_child = i == child_count - 1;
            let new_prefix = format!("{}{}", prefix, if is_last { "    " } else { "│   " });

            result.push_str(&Tree::node_to_string(
                entry.value(),
                &new_prefix,
                is_last_child,
            ));
        }

        result
646
647
648
    }

    pub fn pretty_print(&self) {
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
        if self.root.children.is_empty() {
            return;
        }

        let mut result = String::new();
        let children: Vec<_> = self.root.children.iter().collect();
        let child_count = children.len();

        for (i, entry) in children.iter().enumerate() {
            let is_last = i == child_count - 1;
            result.push_str(&Tree::node_to_string(entry.value(), "", is_last));
        }

        println!("{result}");
    }
}

//  Unit tests
#[cfg(test)]
mod tests {
669
670
671
    use rand::distr::Alphanumeric;
    use rand::distr::SampleString;
    use rand::rng as thread_rng;
672
    use rand::Rng;
Byron Hsu's avatar
Byron Hsu committed
673
674
    use std::thread;
    use std::time::Instant;
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693

    use super::*;

    #[test]
    fn test_get_smallest_tenant() {
        let tree = Tree::new();

        assert_eq!(tree.get_smallest_tenant(), "empty");

        // Insert data for tenant1 - "ap" + "icot" = 6 chars
        tree.insert("ap", "tenant1");
        tree.insert("icot", "tenant1");

        // Insert data for tenant2 - "cat" = 3 chars
        tree.insert("cat", "tenant2");

        assert_eq!(
            tree.get_smallest_tenant(),
            "tenant2",
Byron Hsu's avatar
Byron Hsu committed
694
            "Expected tenant2 to be smallest with 3 characters."
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
        );

        // Insert overlapping data for tenant3 and tenant4 to test equal counts
        // tenant3: "do" = 2 chars
        // tenant4: "hi" = 2 chars
        tree.insert("do", "tenant3");
        tree.insert("hi", "tenant4");

        let smallest = tree.get_smallest_tenant();
        assert!(
            smallest == "tenant3" || smallest == "tenant4",
            "Expected either tenant3 or tenant4 (both have 2 characters), got {}",
            smallest
        );

        // Add more text to tenant4 to make it larger
        tree.insert("hello", "tenant4"); // Now tenant4 has "hi" + "hello" = 6 chars

        // Now tenant3 should be smallest (2 chars vs 6 chars for tenant4)
        assert_eq!(
            tree.get_smallest_tenant(),
            "tenant3",
            "Expected tenant3 to be smallest with 2 characters"
        );

720
        tree.evict_tenant_by_size(3); // This should evict tenants with more than 3 chars
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796

        let post_eviction_smallest = tree.get_smallest_tenant();
        println!("Smallest tenant after eviction: {}", post_eviction_smallest);
    }

    #[test]
    fn test_tenant_char_count() {
        let tree = Tree::new();

        tree.insert("apple", "tenant1");
        tree.insert("apricot", "tenant1");
        tree.insert("banana", "tenant1");
        tree.insert("amplify", "tenant2");
        tree.insert("application", "tenant2");

        let computed_sizes = tree.get_used_size_per_tenant();
        let maintained_counts: HashMap<String, usize> = tree
            .tenant_char_count
            .iter()
            .map(|entry| (entry.key().clone(), *entry.value()))
            .collect();

        println!("Phase 1 - Maintained vs Computed counts:");
        println!(
            "Maintained: {:?}\nComputed: {:?}",
            maintained_counts, computed_sizes
        );
        assert_eq!(
            maintained_counts, computed_sizes,
            "Phase 1: Initial insertions"
        );

        tree.insert("apartment", "tenant1");
        tree.insert("appetite", "tenant2");
        tree.insert("ball", "tenant1");
        tree.insert("box", "tenant2");

        let computed_sizes = tree.get_used_size_per_tenant();
        let maintained_counts: HashMap<String, usize> = tree
            .tenant_char_count
            .iter()
            .map(|entry| (entry.key().clone(), *entry.value()))
            .collect();

        println!("Phase 2 - Maintained vs Computed counts:");
        println!(
            "Maintained: {:?}\nComputed: {:?}",
            maintained_counts, computed_sizes
        );
        assert_eq!(
            maintained_counts, computed_sizes,
            "Phase 2: Additional insertions"
        );

        tree.insert("zebra", "tenant1");
        tree.insert("zebra", "tenant2");
        tree.insert("zero", "tenant1");
        tree.insert("zero", "tenant2");

        let computed_sizes = tree.get_used_size_per_tenant();
        let maintained_counts: HashMap<String, usize> = tree
            .tenant_char_count
            .iter()
            .map(|entry| (entry.key().clone(), *entry.value()))
            .collect();

        println!("Phase 3 - Maintained vs Computed counts:");
        println!(
            "Maintained: {:?}\nComputed: {:?}",
            maintained_counts, computed_sizes
        );
        assert_eq!(
            maintained_counts, computed_sizes,
            "Phase 3: Overlapping insertions"
        );

797
        tree.evict_tenant_by_size(10);
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857

        let computed_sizes = tree.get_used_size_per_tenant();
        let maintained_counts: HashMap<String, usize> = tree
            .tenant_char_count
            .iter()
            .map(|entry| (entry.key().clone(), *entry.value()))
            .collect();

        println!("Phase 4 - Maintained vs Computed counts:");
        println!(
            "Maintained: {:?}\nComputed: {:?}",
            maintained_counts, computed_sizes
        );
        assert_eq!(maintained_counts, computed_sizes, "Phase 4: After eviction");
    }

    fn random_string(len: usize) -> String {
        Alphanumeric.sample_string(&mut thread_rng(), len)
    }

    #[test]
    fn test_cold_start() {
        let tree = Tree::new();

        let (matched_text, tenant) = tree.prefix_match("hello");

        assert_eq!(matched_text, "");
        assert_eq!(tenant, "empty");
    }

    #[test]
    fn test_exact_match_seq() {
        let tree = Tree::new();
        tree.insert("hello", "tenant1");
        tree.pretty_print();
        tree.insert("apple", "tenant2");
        tree.pretty_print();
        tree.insert("banana", "tenant3");
        tree.pretty_print();

        let (matched_text, tenant) = tree.prefix_match("hello");
        assert_eq!(matched_text, "hello");
        assert_eq!(tenant, "tenant1");

        let (matched_text, tenant) = tree.prefix_match("apple");
        assert_eq!(matched_text, "apple");
        assert_eq!(tenant, "tenant2");

        let (matched_text, tenant) = tree.prefix_match("banana");
        assert_eq!(matched_text, "banana");
        assert_eq!(tenant, "tenant3");
    }

    #[test]
    fn test_exact_match_concurrent() {
        let tree = Arc::new(Tree::new());

        // spawn 3 threads for insert
        let tree_clone = Arc::clone(&tree);

858
859
        let texts = ["hello", "apple", "banana"];
        let tenants = ["tenant1", "tenant2", "tenant3"];
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911

        let mut handles = vec![];

        for i in 0..3 {
            let tree_clone = Arc::clone(&tree_clone);
            let text = texts[i];
            let tenant = tenants[i];

            let handle = thread::spawn(move || {
                tree_clone.insert(text, tenant);
            });

            handles.push(handle);
        }

        // wait
        for handle in handles {
            handle.join().unwrap();
        }

        // spawn 3 threads for match
        let mut handles = vec![];

        let tree_clone = Arc::clone(&tree);

        for i in 0..3 {
            let tree_clone = Arc::clone(&tree_clone);
            let text = texts[i];
            let tenant = tenants[i];

            let handle = thread::spawn(move || {
                let (matched_text, matched_tenant) = tree_clone.prefix_match(text);
                assert_eq!(matched_text, text);
                assert_eq!(matched_tenant, tenant);
            });

            handles.push(handle);
        }

        // wait
        for handle in handles {
            handle.join().unwrap();
        }
    }

    #[test]
    fn test_partial_match_concurrent() {
        let tree = Arc::new(Tree::new());

        // spawn 3 threads for insert
        let tree_clone = Arc::clone(&tree);

912
        static TEXTS: [&str; 3] = ["apple", "apabc", "acbdeds"];
913
914
915

        let mut handles = vec![];

916
        for text in TEXTS.iter() {
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
            let tree_clone = Arc::clone(&tree_clone);
            let tenant = "tenant0";

            let handle = thread::spawn(move || {
                tree_clone.insert(text, tenant);
            });

            handles.push(handle);
        }

        // wait
        for handle in handles {
            handle.join().unwrap();
        }

        // spawn 3 threads for match
        let mut handles = vec![];

        let tree_clone = Arc::clone(&tree);

937
        for text in TEXTS.iter() {
938
939
940
941
942
            let tree_clone = Arc::clone(&tree_clone);
            let tenant = "tenant0";

            let handle = thread::spawn(move || {
                let (matched_text, matched_tenant) = tree_clone.prefix_match(text);
943
                assert_eq!(matched_text, *text);
944
945
946
947
948
949
950
951
952
953
                assert_eq!(matched_tenant, tenant);
            });

            handles.push(handle);
        }

        // wait
        for handle in handles {
            handle.join().unwrap();
        }
954
955
    }

956
957
    #[test]
    fn test_group_prefix_insert_match_concurrent() {
958
        static PREFIXES: [&str; 4] = [
959
960
961
962
963
            "Clock strikes midnight, I'm still wide awake",
            "Got dreams bigger than these city lights",
            "Time waits for no one, gotta make my move",
            "Started from the bottom, that's no metaphor",
        ];
964
        let suffixes = [
965
966
967
968
            "Got too much to prove, ain't got time to lose",
            "History in the making, yeah, you can't erase this",
        ];
        let tree = Arc::new(Tree::new());
969

970
971
        let mut handles = vec![];

972
973
        for (i, prefix) in PREFIXES.iter().enumerate() {
            for suffix in suffixes.iter() {
974
                let tree_clone = Arc::clone(&tree);
975
                let text = format!("{} {}", prefix, suffix);
976
977
978
979
980
981
982
983
984
985
986
987
988
                let tenant = format!("tenant{}", i);

                let handle = thread::spawn(move || {
                    tree_clone.insert(&text, &tenant);
                });

                handles.push(handle);
            }
        }

        // wait
        for handle in handles {
            handle.join().unwrap();
989
        }
990
991
992
993
994
995

        tree.pretty_print();

        // check matching using multi threads
        let mut handles = vec![];

996
        for (i, prefix) in PREFIXES.iter().enumerate() {
997
998
999
            let tree_clone = Arc::clone(&tree);

            let handle = thread::spawn(move || {
1000
                let (matched_text, matched_tenant) = tree_clone.prefix_match(prefix);
1001
                let tenant = format!("tenant{}", i);
1002
                assert_eq!(matched_text, *prefix);
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
                assert_eq!(matched_tenant, tenant);
            });

            handles.push(handle);
        }

        // wait
        for handle in handles {
            handle.join().unwrap();
        }
    }

    #[test]
    fn test_mixed_concurrent_insert_match() {
        // ensure it does not deadlock instead of doing correctness check

1019
        static PREFIXES: [&str; 4] = [
1020
1021
1022
1023
1024
            "Clock strikes midnight, I'm still wide awake",
            "Got dreams bigger than these city lights",
            "Time waits for no one, gotta make my move",
            "Started from the bottom, that's no metaphor",
        ];
1025
        let suffixes = [
1026
1027
1028
1029
1030
1031
1032
            "Got too much to prove, ain't got time to lose",
            "History in the making, yeah, you can't erase this",
        ];
        let tree = Arc::new(Tree::new());

        let mut handles = vec![];

1033
1034
        for (i, prefix) in PREFIXES.iter().enumerate() {
            for suffix in suffixes.iter() {
1035
                let tree_clone = Arc::clone(&tree);
1036
                let text = format!("{} {}", prefix, suffix);
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
                let tenant = format!("tenant{}", i);

                let handle = thread::spawn(move || {
                    tree_clone.insert(&text, &tenant);
                });

                handles.push(handle);
            }
        }

        // check matching using multi threads
1048
        for prefix in PREFIXES.iter() {
1049
1050
1051
            let tree_clone = Arc::clone(&tree);

            let handle = thread::spawn(move || {
1052
                let (_matched_text, _matched_tenant) = tree_clone.prefix_match(prefix);
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
            });

            handles.push(handle);
        }

        // wait
        for handle in handles {
            handle.join().unwrap();
        }
    }

    #[test]
    fn test_utf8_split_seq() {
1066
        // The string should be indexed and split by a utf-8 value basis instead of byte basis
1067
1068
1069
        // use .chars() to get the iterator of the utf-8 value
        let tree = Arc::new(Tree::new());

1070
        static TEST_PAIRS: [(&str, &str); 3] = [
1071
1072
1073
1074
1075
1076
            ("你好嗎", "tenant1"),
            ("你好喔", "tenant2"),
            ("你心情好嗎", "tenant3"),
        ];

        // Insert sequentially
1077
        for (text, tenant) in TEST_PAIRS.iter() {
1078
1079
1080
1081
1082
            tree.insert(text, tenant);
        }

        tree.pretty_print();

1083
1084
1085
1086
        for (text, tenant) in TEST_PAIRS.iter() {
            let (matched_text, matched_tenant) = tree.prefix_match(text);
            assert_eq!(matched_text, *text);
            assert_eq!(matched_tenant, *tenant);
1087
1088
1089
1090
1091
1092
1093
        }
    }

    #[test]
    fn test_utf8_split_concurrent() {
        let tree = Arc::new(Tree::new());

1094
        static TEST_PAIRS: [(&str, &str); 3] = [
1095
1096
1097
1098
1099
1100
1101
1102
            ("你好嗎", "tenant1"),
            ("你好喔", "tenant2"),
            ("你心情好嗎", "tenant3"),
        ];

        // Create multiple threads for insertion
        let mut handles = vec![];

1103
        for (text, tenant) in TEST_PAIRS.iter() {
1104
1105
1106
            let tree_clone = Arc::clone(&tree);

            let handle = thread::spawn(move || {
1107
                tree_clone.insert(text, tenant);
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
            });

            handles.push(handle);
        }

        // Wait for all insertions to complete
        for handle in handles {
            handle.join().unwrap();
        }

        tree.pretty_print();

        // Create multiple threads for matching
        let mut handles = vec![];

1123
        for (text, tenant) in TEST_PAIRS.iter() {
1124
1125
1126
            let tree_clone = Arc::clone(&tree);

            let handle = thread::spawn(move || {
1127
1128
1129
                let (matched_text, matched_tenant) = tree_clone.prefix_match(text);
                assert_eq!(matched_text, *text);
                assert_eq!(matched_tenant, *tenant);
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
            });

            handles.push(handle);
        }

        // Wait for all matches to complete
        for handle in handles {
            handle.join().unwrap();
        }
    }

    #[test]
    fn test_simple_eviction() {
        let tree = Tree::new();
        let max_size = 5;

        // Insert strings for both tenants
        tree.insert("hello", "tenant1"); // size 5

        tree.insert("hello", "tenant2"); // size 5
        thread::sleep(Duration::from_millis(10));
        tree.insert("world", "tenant2"); // size 5, total for tenant2 = 10

        tree.pretty_print();

        let sizes_before = tree.get_used_size_per_tenant();
        assert_eq!(sizes_before.get("tenant1").unwrap(), &5); // "hello" = 5
        assert_eq!(sizes_before.get("tenant2").unwrap(), &10); // "hello" + "world" = 10

        // Evict - should remove "hello" from tenant2 as it's the oldest
1160
        tree.evict_tenant_by_size(max_size);
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180

        tree.pretty_print();

        let sizes_after = tree.get_used_size_per_tenant();
        assert_eq!(sizes_after.get("tenant1").unwrap(), &5); // Should be unchanged
        assert_eq!(sizes_after.get("tenant2").unwrap(), &5); // Only "world" remains

        let (matched, tenant) = tree.prefix_match("world");
        assert_eq!(matched, "world");
        assert_eq!(tenant, "tenant2");
    }

    #[test]
    fn test_advanced_eviction() {
        let tree = Tree::new();

        // Set limits for each tenant
        let max_size: usize = 100;

        // Define prefixes
1181
        let prefixes = ["aqwefcisdf", "iajsdfkmade", "kjnzxcvewqe", "iejksduqasd"];
1182
1183

        // Insert strings with shared prefixes
Byron Hsu's avatar
Byron Hsu committed
1184
        for _i in 0..100 {
1185
1186
1187
1188
1189
1190
1191
1192
1193
            for (j, prefix) in prefixes.iter().enumerate() {
                let random_suffix = random_string(10);
                let text = format!("{}{}", prefix, random_suffix);
                let tenant = format!("tenant{}", j + 1);
                tree.insert(&text, &tenant);
            }
        }

        // Perform eviction
1194
        tree.evict_tenant_by_size(max_size);
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224

        // Check sizes after eviction
        let sizes_after = tree.get_used_size_per_tenant();
        for (tenant, &size) in sizes_after.iter() {
            assert!(
                size <= max_size,
                "Tenant {} exceeds size limit. Current size: {}, Limit: {}",
                tenant,
                size,
                max_size
            );
        }
    }

    #[test]
    fn test_concurrent_operations_with_eviction() {
        // Ensure eviction works fine with concurrent insert and match operations for a given period

        let tree = Arc::new(Tree::new());
        let mut handles = vec![];
        let test_duration = Duration::from_secs(10);
        let start_time = Instant::now();
        let max_size = 100; // Single max size for all tenants

        // Spawn eviction thread
        {
            let tree = Arc::clone(&tree);
            let handle = thread::spawn(move || {
                while start_time.elapsed() < test_duration {
                    // Run eviction
1225
                    tree.evict_tenant_by_size(max_size);
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237

                    // Sleep for 5 seconds
                    thread::sleep(Duration::from_secs(5));
                }
            });
            handles.push(handle);
        }

        // Spawn 4 worker threads
        for thread_id in 0..4 {
            let tree = Arc::clone(&tree);
            let handle = thread::spawn(move || {
1238
                let mut rng = rand::rng();
1239
1240
1241
1242
1243
                let tenant = format!("tenant{}", thread_id + 1);
                let prefix = format!("prefix{}", thread_id);

                while start_time.elapsed() < test_duration {
                    // Random decision: match or insert (70% match, 30% insert)
1244
                    if rng.random_bool(0.7) {
1245
                        // Perform match operation
1246
                        let random_len = rng.random_range(3..10);
1247
                        let search_str = format!("{}{}", prefix, random_string(random_len));
Byron Hsu's avatar
Byron Hsu committed
1248
                        let (_matched, _) = tree.prefix_match(&search_str);
1249
1250
                    } else {
                        // Perform insert operation
1251
                        let random_len = rng.random_range(5..15);
1252
1253
1254
1255
1256
1257
                        let insert_str = format!("{}{}", prefix, random_string(random_len));
                        tree.insert(&insert_str, &tenant);
                        // println!("Thread {} inserted: {}", thread_id, insert_str);
                    }

                    // Small random sleep to vary timing
1258
                    thread::sleep(Duration::from_millis(rng.random_range(10..100)));
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
                }
            });
            handles.push(handle);
        }

        // Wait for all threads to complete
        for handle in handles {
            handle.join().unwrap();
        }

        // final eviction
1270
        tree.evict_tenant_by_size(max_size);
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338

        // Final size check
        let final_sizes = tree.get_used_size_per_tenant();
        println!("Final sizes after test completion: {:?}", final_sizes);

        for (_, &size) in final_sizes.iter() {
            assert!(
                size <= max_size,
                "Tenant exceeds size limit. Final size: {}, Limit: {}",
                size,
                max_size
            );
        }
    }

    #[test]
    fn test_leaf_of() {
        let tree = Tree::new();

        // Single node
        tree.insert("hello", "tenant1");
        let leaves = Tree::leaf_of(&tree.root.children.get(&'h').unwrap());
        assert_eq!(leaves, vec!["tenant1"]);

        // Node with multiple tenants
        tree.insert("hello", "tenant2");
        let leaves = Tree::leaf_of(&tree.root.children.get(&'h').unwrap());
        assert_eq!(leaves.len(), 2);
        assert!(leaves.contains(&"tenant1".to_string()));
        assert!(leaves.contains(&"tenant2".to_string()));

        // Non-leaf node
        tree.insert("hi", "tenant1");
        let leaves = Tree::leaf_of(&tree.root.children.get(&'h').unwrap());
        assert!(leaves.is_empty());
    }

    #[test]
    fn test_get_used_size_per_tenant() {
        let tree = Tree::new();

        // Single tenant
        tree.insert("hello", "tenant1");
        tree.insert("world", "tenant1");
        let sizes = tree.get_used_size_per_tenant();

        tree.pretty_print();
        println!("{:?}", sizes);
        assert_eq!(sizes.get("tenant1").unwrap(), &10); // "hello" + "world"

        // Multiple tenants sharing nodes
        tree.insert("hello", "tenant2");
        tree.insert("help", "tenant2");
        let sizes = tree.get_used_size_per_tenant();

        tree.pretty_print();
        println!("{:?}", sizes);
        assert_eq!(sizes.get("tenant1").unwrap(), &10);
        assert_eq!(sizes.get("tenant2").unwrap(), &6); // "hello" + "p"

        // UTF-8 characters
        tree.insert("你好", "tenant3");
        let sizes = tree.get_used_size_per_tenant();
        tree.pretty_print();
        println!("{:?}", sizes);
        assert_eq!(sizes.get("tenant3").unwrap(), &2); // 2 Chinese characters

        tree.pretty_print();
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

    #[test]
    fn test_prefix_match_tenant() {
        let tree = Tree::new();

        // Insert overlapping prefixes for different tenants
        tree.insert("hello", "tenant1"); // tenant1: hello
        tree.insert("hello", "tenant2"); // tenant2: hello
        tree.insert("hello world", "tenant2"); // tenant2: hello -> world
        tree.insert("help", "tenant1"); // tenant1: hel -> p
        tree.insert("helicopter", "tenant2"); // tenant2: hel -> icopter

        assert_eq!(tree.prefix_match_tenant("hello", "tenant1"), "hello"); // Full match for tenant1
        assert_eq!(tree.prefix_match_tenant("help", "tenant1"), "help"); // Exclusive to tenant1
        assert_eq!(tree.prefix_match_tenant("hel", "tenant1"), "hel"); // Shared prefix
        assert_eq!(tree.prefix_match_tenant("hello world", "tenant1"), "hello"); // Should stop at tenant1's boundary
        assert_eq!(tree.prefix_match_tenant("helicopter", "tenant1"), "hel"); // Should stop at tenant1's boundary

        assert_eq!(tree.prefix_match_tenant("hello", "tenant2"), "hello"); // Full match for tenant2
        assert_eq!(
            tree.prefix_match_tenant("hello world", "tenant2"),
            "hello world"
        ); // Exclusive to tenant2
        assert_eq!(
            tree.prefix_match_tenant("helicopter", "tenant2"),
            "helicopter"
        ); // Exclusive to tenant2
        assert_eq!(tree.prefix_match_tenant("hel", "tenant2"), "hel"); // Shared prefix
        assert_eq!(tree.prefix_match_tenant("help", "tenant2"), "hel"); // Should stop at tenant2's boundary

        assert_eq!(tree.prefix_match_tenant("hello", "tenant3"), ""); // Non-existent tenant
        assert_eq!(tree.prefix_match_tenant("help", "tenant3"), ""); // Non-existent tenant
    }
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449

    #[test]
    fn test_simple_tenant_eviction() {
        let tree = Tree::new();

        // Insert data for multiple tenants
        tree.insert("hello", "tenant1");
        tree.insert("world", "tenant1");
        tree.insert("hello", "tenant2");
        tree.insert("help", "tenant2");

        let initial_sizes = tree.get_used_size_per_tenant();
        assert_eq!(initial_sizes.get("tenant1").unwrap(), &10); // "hello" + "world"
        assert_eq!(initial_sizes.get("tenant2").unwrap(), &6); // "hello" + "p"

        // Evict tenant1
        tree.remove_tenant("tenant1");

        let final_sizes = tree.get_used_size_per_tenant();
        assert!(
            !final_sizes.contains_key("tenant1"),
            "tenant1 should be completely removed"
        );
        assert_eq!(
            final_sizes.get("tenant2").unwrap(),
            &6,
            "tenant2 should be unaffected"
        );

        assert_eq!(tree.prefix_match_tenant("hello", "tenant1"), "");
        assert_eq!(tree.prefix_match_tenant("world", "tenant1"), "");

        assert_eq!(tree.prefix_match_tenant("hello", "tenant2"), "hello");
        assert_eq!(tree.prefix_match_tenant("help", "tenant2"), "help");
    }

    #[test]
    fn test_complex_tenant_eviction() {
        let tree = Tree::new();

        // Create a more complex tree structure with shared prefixes
        tree.insert("apple", "tenant1");
        tree.insert("application", "tenant1");
        tree.insert("apple", "tenant2");
        tree.insert("appetite", "tenant2");
        tree.insert("banana", "tenant1");
        tree.insert("banana", "tenant2");
        tree.insert("ball", "tenant2");

        let initial_sizes = tree.get_used_size_per_tenant();
        println!("Initial sizes: {:?}", initial_sizes);
        tree.pretty_print();

        // Evict tenant1
        tree.remove_tenant("tenant1");

        let final_sizes = tree.get_used_size_per_tenant();
        println!("Final sizes: {:?}", final_sizes);
        tree.pretty_print();

        assert!(
            !final_sizes.contains_key("tenant1"),
            "tenant1 should be completely removed"
        );

        assert_eq!(tree.prefix_match_tenant("apple", "tenant1"), "");
        assert_eq!(tree.prefix_match_tenant("application", "tenant1"), "");
        assert_eq!(tree.prefix_match_tenant("banana", "tenant1"), "");

        assert_eq!(tree.prefix_match_tenant("apple", "tenant2"), "apple");
        assert_eq!(tree.prefix_match_tenant("appetite", "tenant2"), "appetite");
        assert_eq!(tree.prefix_match_tenant("banana", "tenant2"), "banana");
        assert_eq!(tree.prefix_match_tenant("ball", "tenant2"), "ball");

        let tenant2_size = final_sizes.get("tenant2").unwrap();
        assert_eq!(tenant2_size, &(5 + 5 + 6 + 2)); // "apple" + "etite" + "banana" + "ll"
    }
1450
}