tree.rs 47.9 KB
Newer Older
1
2
3
4
5
6
7
8
use std::{
    cmp::Reverse,
    collections::{BinaryHeap, HashMap, VecDeque},
    sync::{Arc, RwLock},
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use dashmap::{mapref::entry::Entry, DashMap};
9
use tracing::info;
Byron Hsu's avatar
Byron Hsu committed
10

11
type NodeRef = Arc<Node>;
12

13
#[derive(Debug)]
14
15
16
17
18
struct Node {
    children: DashMap<char, NodeRef>,
    text: RwLock<String>,
    tenant_last_access_time: DashMap<String, u128>,
    parent: RwLock<Option<NodeRef>>,
19
20
}

21
#[derive(Debug)]
22
23
24
pub struct Tree {
    root: NodeRef,
    pub tenant_char_count: DashMap<String, usize>,
25
26
}

27
28
29
30
31
32
33
34
35
36
// For the heap

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

impl Eq for EvictionEntry {}

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

44
45
46
impl Ord for EvictionEntry {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.timestamp.cmp(&other.timestamp)
47
48
49
    }
}

50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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,
        }
    }

74
    i
75
76
77
78
79
80
}

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

81
82
83
84
85
86
impl Default for Tree {
    fn default() -> Self {
        Self::new()
    }
}

87
88
89
90
91
impl Tree {
    /*
    Thread-safe multi tenant radix tree

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

96
    pub fn new() -> Self {
97
98
99
100
101
102
103
104
        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(),
105
106
107
        }
    }

108
109
    pub fn insert(&self, text: &str, tenant: &str) {
        // Insert text into tree with given tenant
110

111
        let mut curr = Arc::clone(&self.root);
112
        let mut curr_idx = 0;
113
114
115
116
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

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

158
                    // Attach tenant to the new node (map is empty here) and increment count once
159
160
161
162
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
                    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);

218
219
220
221
222
223
224
225
226
227
228
229
                        // 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);
                            }
230
231
232
233
234
235
236
                        }

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

237
238
239
240
241
242
243
244
245
246
247
248
                        // 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);
                            }
249
250
251
                        }
                        curr_idx += shared_count;
                    }
252
253
254
255
256
                }
            }
        }
    }

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

262
263
264
265
266
267
268
269
        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();
270

271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
            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);
286
287
                    break;
                }
288
289
290
            } else {
                // No match found, stop here
                break;
291
292
293
            }
        }

294
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
        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)
322
323
    }

Byron Hsu's avatar
Byron Hsu committed
324
    #[allow(unused_assignments)]
325
326
327
328
329
330
331
332
333
334
335
336
337
    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();

338
339
            if let Some(entry) = curr.children.get(&first_char) {
                let matched_node = entry.value().clone();
340

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

                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);
359
360
                    break;
                }
361
362
363
            } else {
                // No match found, stop here
                break;
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
            }
        }

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

387
388
389
390
391
392
393
394
395
    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();
396

397
398
399
400
401
        for child in node.children.iter() {
            for tenant in child.value().tenant_last_access_time.iter() {
                candidates.insert(tenant.key().clone(), false);
            }
        }
402

403
404
405
406
407
408
        candidates
            .into_iter()
            .filter(|(_, is_leaf)| *is_leaf)
            .map(|(tenant, _)| tenant)
            .collect()
    }
409

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

415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
        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),
                    }));
                }
            }
        }

432
        info!("Before eviction - Used size per tenant:");
433
434
        for entry in self.tenant_char_count.iter() {
            info!("Tenant: {}, Size: {}", entry.key(), entry.value());
435
        }
436

437
438
439
440
        // Process eviction
        while let Some(Reverse(entry)) = pq.pop() {
            let EvictionEntry { tenant, node, .. } = entry;

441
442
            if let Some(used_size) = self.tenant_char_count.get(&tenant) {
                if *used_size <= max_size {
443
444
                    continue;
                }
445
            }
446

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

457
458
            // Remove tenant from node
            node.tenant_last_access_time.remove(&tenant);
459

460
461
            // Remove empty nodes
            if node.children.is_empty() && node.tenant_last_access_time.is_empty() {
462
463
464
465
466
                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);
                    }
467
                }
468
            }
469

470
471
472
473
474
475
476
477
478
            // 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),
                        }));
479
480
                    }
                }
481
            };
482
        }
483

484
        info!("After eviction - Used size per tenant:");
485
486
        for entry in self.tenant_char_count.iter() {
            info!("Tenant: {}, Size: {}", entry.key(), entry.value());
487
488
489
        }
    }

490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
    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() {
513
514
515
516
                    let text_guard = curr.text.read().unwrap();
                    if let Some(first_char) = text_guard.chars().next() {
                        parent.children.remove(&first_char);
                    }
517
518
519
520
521
522
                }
            }

            // 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()) {
523
                    queue.push_back(Arc::clone(parent));
524
525
526
527
528
529
530
531
                }
            }
        }

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

532
533
534
535
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
    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
642
643
644
    }

    pub fn pretty_print(&self) {
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
        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 {
665
666
667
668
669
670
    use std::{thread, time::Instant};

    use rand::{
        distr::{Alphanumeric, SampleString},
        rng as thread_rng, Rng,
    };
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689

    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
690
            "Expected tenant2 to be smallest with 3 characters."
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
        );

        // 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"
        );

716
        tree.evict_tenant_by_size(3); // This should evict tenants with more than 3 chars
717
718
719
720
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

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

793
        tree.evict_tenant_by_size(10);
794
795
796
797
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

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

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

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

908
        static TEXTS: [&str; 3] = ["apple", "apabc", "acbdeds"];
909
910
911

        let mut handles = vec![];

912
        for text in TEXTS.iter() {
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
            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);

933
        for text in TEXTS.iter() {
934
935
936
937
938
            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);
939
                assert_eq!(matched_text, *text);
940
941
942
943
944
945
946
947
948
949
                assert_eq!(matched_tenant, tenant);
            });

            handles.push(handle);
        }

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

952
953
    #[test]
    fn test_group_prefix_insert_match_concurrent() {
954
        static PREFIXES: [&str; 4] = [
955
956
957
958
959
            "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",
        ];
960
        let suffixes = [
961
962
963
964
            "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());
965

966
967
        let mut handles = vec![];

968
969
        for (i, prefix) in PREFIXES.iter().enumerate() {
            for suffix in suffixes.iter() {
970
                let tree_clone = Arc::clone(&tree);
971
                let text = format!("{} {}", prefix, suffix);
972
973
974
975
976
977
978
979
980
981
982
983
984
                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();
985
        }
986
987
988
989
990
991

        tree.pretty_print();

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

992
        for (i, prefix) in PREFIXES.iter().enumerate() {
993
994
995
            let tree_clone = Arc::clone(&tree);

            let handle = thread::spawn(move || {
996
                let (matched_text, matched_tenant) = tree_clone.prefix_match(prefix);
997
                let tenant = format!("tenant{}", i);
998
                assert_eq!(matched_text, *prefix);
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
                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

1015
        static PREFIXES: [&str; 4] = [
1016
1017
1018
1019
1020
            "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",
        ];
1021
        let suffixes = [
1022
1023
1024
1025
1026
1027
1028
            "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![];

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

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

                handles.push(handle);
            }
        }

        // check matching using multi threads
1044
        for prefix in PREFIXES.iter() {
1045
1046
1047
            let tree_clone = Arc::clone(&tree);

            let handle = thread::spawn(move || {
1048
                let (_matched_text, _matched_tenant) = tree_clone.prefix_match(prefix);
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
            });

            handles.push(handle);
        }

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

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

1066
        static TEST_PAIRS: [(&str, &str); 3] = [
1067
1068
1069
1070
1071
1072
            ("你好嗎", "tenant1"),
            ("你好喔", "tenant2"),
            ("你心情好嗎", "tenant3"),
        ];

        // Insert sequentially
1073
        for (text, tenant) in TEST_PAIRS.iter() {
1074
1075
1076
1077
1078
            tree.insert(text, tenant);
        }

        tree.pretty_print();

1079
1080
1081
1082
        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);
1083
1084
1085
1086
1087
1088
1089
        }
    }

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

1090
        static TEST_PAIRS: [(&str, &str); 3] = [
1091
1092
1093
1094
1095
1096
1097
1098
            ("你好嗎", "tenant1"),
            ("你好喔", "tenant2"),
            ("你心情好嗎", "tenant3"),
        ];

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

1099
        for (text, tenant) in TEST_PAIRS.iter() {
1100
1101
1102
            let tree_clone = Arc::clone(&tree);

            let handle = thread::spawn(move || {
1103
                tree_clone.insert(text, tenant);
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
            });

            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![];

1119
        for (text, tenant) in TEST_PAIRS.iter() {
1120
1121
1122
            let tree_clone = Arc::clone(&tree);

            let handle = thread::spawn(move || {
1123
1124
1125
                let (matched_text, matched_tenant) = tree_clone.prefix_match(text);
                assert_eq!(matched_text, *text);
                assert_eq!(matched_tenant, *tenant);
1126
1127
1128
1129
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
            });

            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
1156
        tree.evict_tenant_by_size(max_size);
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176

        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
1177
        let prefixes = ["aqwefcisdf", "iajsdfkmade", "kjnzxcvewqe", "iejksduqasd"];
1178
1179

        // Insert strings with shared prefixes
Byron Hsu's avatar
Byron Hsu committed
1180
        for _i in 0..100 {
1181
1182
1183
1184
1185
1186
1187
1188
1189
            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
1190
        tree.evict_tenant_by_size(max_size);
1191
1192
1193
1194
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

        // 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
1221
                    tree.evict_tenant_by_size(max_size);
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233

                    // 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 || {
1234
                let mut rng = rand::rng();
1235
1236
1237
1238
1239
                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)
1240
                    if rng.random_bool(0.7) {
1241
                        // Perform match operation
1242
                        let random_len = rng.random_range(3..10);
1243
                        let search_str = format!("{}{}", prefix, random_string(random_len));
Byron Hsu's avatar
Byron Hsu committed
1244
                        let (_matched, _) = tree.prefix_match(&search_str);
1245
1246
                    } else {
                        // Perform insert operation
1247
                        let random_len = rng.random_range(5..15);
1248
1249
1250
1251
1252
1253
                        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
1254
                    thread::sleep(Duration::from_millis(rng.random_range(10..100)));
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
                }
            });
            handles.push(handle);
        }

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

        // final eviction
1266
        tree.evict_tenant_by_size(max_size);
1267
1268
1269
1270
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

        // 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();
1335
    }
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368

    #[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
    }
1369
1370
1371
1372
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

    #[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"
    }
1446
}