libdictenstein 0.1.0

High-performance dictionary data structures (trie, DAWG, double-array trie, suffix automaton, lock-free durable persistent ART) behind one trait API; pairs with liblevenshtein for fuzzy matching
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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
158
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
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
716
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
//! UTF-8 integration tests for PersistentARTrieChar.
//!
//! These tests verify proper Unicode character handling:
//! - Multi-byte UTF-8 sequences
//! - Emoji and special characters
//! - Mixed ASCII/UTF-8 operations
//! - Unicode edge cases (combining chars, RTL, etc.)
//! - Character-level edit distance semantics
//!
//! # Why PersistentARTrieChar?
//!
//! The byte-level PersistentARTrie treats multi-byte UTF-8 sequences as
//! multiple bytes. This is problematic for edit distance:
//! - "" (Γ±) is 2 bytes β†’ distance from "n" is 2 (wrong)
//! - With PersistentARTrieChar, "Γ±" is 1 character β†’ distance from "n" is 1 (correct)

#![cfg(feature = "persistent-artrie")]

use libdictenstein::persistent_artrie_char::{PersistentARTrieChar, PersistentARTrieCharZipper};
use libdictenstein::zipper::DictZipper;
use libdictenstein::{DictionaryNode, MappedDictionary};

// =============================================================================
// Test: Basic Unicode Insertion and Lookup
// =============================================================================

#[test]
fn test_basic_unicode_insertion() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    // Insert various Unicode strings
    trie.insert("cafΓ©");
    trie.insert("naΓ―ve");
    trie.insert("rΓ©sumΓ©");

    assert!(trie.contains("cafΓ©"));
    assert!(trie.contains("naΓ―ve"));
    assert!(trie.contains("rΓ©sumΓ©"));
    assert!(!trie.contains("cafe")); // Different from cafΓ©
    assert_eq!(trie.len(), 3);
}

#[test]
fn test_cjk_characters() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    // Chinese characters
    trie.insert("δΈ­ζ–‡");
    trie.insert("δ½ ε₯½");
    trie.insert("δΈ–η•Œ");

    // Japanese
    trie.insert("ζ—₯本θͺž");
    trie.insert("こんにけは");
    trie.insert("γ‚γ‚ŠγŒγ¨γ†");

    // Korean
    trie.insert("ν•œκ΅­μ–΄");
    trie.insert("μ•ˆλ…•ν•˜μ„Έμš”");

    assert!(trie.contains("δΈ­ζ–‡"));
    assert!(trie.contains("こんにけは"));
    assert!(trie.contains("ν•œκ΅­μ–΄"));
    assert!(!trie.contains("δΈ­")); // Partial prefix
    assert_eq!(trie.len(), 8);
}

#[test]
fn test_emoji_handling() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    // Single emoji
    trie.insert("πŸŽ‰");
    trie.insert("🌍");
    trie.insert("❀️");

    // Emoji sequences
    trie.insert("πŸ‘¨β€πŸ‘©β€πŸ‘§"); // Family emoji (ZWJ sequence)
    trie.insert("πŸ³οΈβ€πŸŒˆ"); // Rainbow flag

    // Mixed text and emoji
    trie.insert("Hello 🌍!");
    trie.insert("I ❀️ Rust");

    assert!(trie.contains("πŸŽ‰"));
    assert!(trie.contains("Hello 🌍!"));
    assert!(!trie.contains("🎊")); // Different emoji
    assert_eq!(trie.len(), 7);
}

// =============================================================================
// Test: Unicode Edge Cases
// =============================================================================

#[test]
fn test_combining_characters() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    // Precomposed vs decomposed forms
    // Note: Rust strings are UTF-8 byte sequences, not normalized
    let precomposed = "Γ©"; // U+00E9 (single code point)
    let decomposed = "Γ©"; // U+0065 + U+0301 (e + combining acute)

    trie.insert(precomposed);
    trie.insert(decomposed);

    // These may or may not be the same depending on normalization
    assert!(trie.contains(precomposed));
    assert!(trie.contains(decomposed));

    // Count depends on whether they are identical after normalization
    // Without normalization, they are different strings
}

#[test]
fn test_rtl_text() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    // Arabic
    trie.insert("Ω…Ψ±Ψ­Ψ¨Ψ§");
    trie.insert("Ψ§Ω„ΨΉΨ§Ω„Ω…");

    // Hebrew
    trie.insert("Χ©ΧœΧ•Χ");
    trie.insert("Χ’Χ•ΧœΧ");

    assert!(trie.contains("Ω…Ψ±Ψ­Ψ¨Ψ§"));
    assert!(trie.contains("Χ©ΧœΧ•Χ"));
    assert_eq!(trie.len(), 4);
}

#[test]
fn test_mixed_scripts() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    // Mixed script strings
    trie.insert("CafΓ© δΈ­ζ–‡");
    trie.insert("Tōkyō 東京");
    trie.insert("MΓΌnchen MΓΌnchen");
    trie.insert("SΓ£o Paulo");

    assert!(trie.contains("CafΓ© δΈ­ζ–‡"));
    assert!(trie.contains("Tōkyō 東京"));
    assert_eq!(trie.len(), 4);
}

#[test]
fn test_special_unicode_categories() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    // Mathematical symbols
    trie.insert("βˆ‘βˆβˆ«βˆ‚");
    trie.insert("βˆ€xβˆƒy");

    // Currency symbols
    trie.insert("$€£Β₯β‚Ώ");

    // Musical symbols
    trie.insert("β™©β™ͺ♫♬");

    // Technical symbols
    trie.insert("βš‘βš™οΈπŸ”§");

    assert!(trie.contains("βˆ‘βˆβˆ«βˆ‚"));
    assert!(trie.contains("$€£Β₯β‚Ώ"));
    assert_eq!(trie.len(), 5);
}

// =============================================================================
// Test: Values with Unicode Keys
// =============================================================================

#[test]
fn test_unicode_keys_with_values() {
    let trie: PersistentARTrieChar<i32> = PersistentARTrieChar::new();

    trie.insert_with_value("cafΓ©", 1);
    trie.insert_with_value("δΈ­ζ–‡", 2);
    trie.insert_with_value("πŸŽ‰", 3);

    assert_eq!(trie.get_value("cafΓ©"), Some(1));
    assert_eq!(trie.get_value("δΈ­ζ–‡"), Some(2));
    assert_eq!(trie.get_value("πŸŽ‰"), Some(3));
    assert_eq!(trie.get_value("notfound"), None);
}

#[test]
fn test_unicode_keys_with_string_values() {
    let trie: PersistentARTrieChar<String> = PersistentARTrieChar::new();

    trie.insert_with_value("hello", "greeting".to_string());
    trie.insert_with_value("δΈ–η•Œ", "world".to_string());
    trie.insert_with_value("cafΓ©", "coffee place".to_string());

    assert_eq!(trie.get_value("hello"), Some("greeting".to_string()));
    assert_eq!(trie.get_value("δΈ–η•Œ"), Some("world".to_string()));
    assert_eq!(trie.get_value("cafΓ©"), Some("coffee place".to_string()));
}

// =============================================================================
// Test: Zipper Navigation with Unicode
// =============================================================================

#[test]
fn test_zipper_unicode_navigation() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    trie.insert("cafΓ©");
    trie.insert("cat");

    let zipper = PersistentARTrieCharZipper::new(&trie);

    // Navigate to "cafΓ©" using char-by-char descent
    let z = zipper
        .descend('c')
        .and_then(|z| z.descend('a'))
        .and_then(|z| z.descend('f'))
        .and_then(|z| z.descend('Γ©'));

    assert!(z.is_some());
    let z = z.unwrap();
    assert!(z.is_final());

    // Path should be characters, not bytes
    let path = z.path();
    assert_eq!(path, vec!['c', 'a', 'f', 'Γ©']);
}

#[test]
fn test_zipper_cjk_navigation() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    trie.insert("δΈ­ζ–‡");

    let zipper = PersistentARTrieCharZipper::new(&trie);

    // Navigate character by character
    let z = zipper.descend('δΈ­').and_then(|z| z.descend('ζ–‡'));

    assert!(z.is_some());
    let z = z.unwrap();
    assert!(z.is_final());
    assert_eq!(z.path(), vec!['δΈ­', 'ζ–‡']);
}

#[test]
fn test_zipper_children_with_unicode() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    // Insert terms with different second characters
    trie.insert("ab");
    trie.insert("aΓ©");
    trie.insert("aδΈ­");
    trie.insert("aπŸŽ‰");

    let zipper = PersistentARTrieCharZipper::new(&trie);
    let a_zipper = zipper.descend('a').expect("should have 'a'");

    // Collect all children labels
    let children: Vec<char> = a_zipper.children().map(|(c, _)| c).collect();

    assert!(children.contains(&'b'));
    assert!(children.contains(&'Γ©'));
    assert!(children.contains(&'δΈ­'));
    assert!(children.contains(&'πŸŽ‰'));
    assert_eq!(children.len(), 4);
}

// =============================================================================
// Test: Dictionary Trait Implementation
// =============================================================================

#[test]
fn test_dictionary_trait_unicode() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    trie.insert("hello");
    trie.insert("δΈ–η•Œ");
    trie.insert("cafΓ©");

    // Test Dictionary trait methods
    assert!(trie.contains("hello"));
    assert!(trie.contains("δΈ–η•Œ"));
    assert_eq!(trie.len(), 3);

    // Test root navigation
    let root = trie.root();
    assert!(!root.is_final()); // Empty string is not in dictionary
}

#[test]
fn test_dictionary_node_trait_unicode() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    trie.insert("abc");
    trie.insert("aΓ©c");

    let root = trie.root();

    // Test transition to 'a'
    let a_node = root.transition('a');
    assert!(a_node.is_some());

    let a_node = a_node.unwrap();

    // Test edges from 'a' - should include both 'b' and 'Γ©'
    let edges: Vec<char> = a_node.edges().map(|(c, _)| c).collect();
    assert!(edges.contains(&'b'));
    assert!(edges.contains(&'Γ©'));
}

// =============================================================================
// Test: FromIterator with Unicode
// =============================================================================

#[test]
fn test_from_iterator_unicode() {
    let terms = vec!["cafΓ©", "naΓ―ve", "δΈ­ζ–‡", "πŸŽ‰"];
    let trie: PersistentARTrieChar<()> = terms.into_iter().collect();

    assert_eq!(trie.len(), 4);
    assert!(trie.contains("cafΓ©"));
    assert!(trie.contains("δΈ­ζ–‡"));
    assert!(trie.contains("πŸŽ‰"));
}

#[test]
fn test_from_iterator_owned_strings() {
    let terms: Vec<String> = vec![
        "rΓ©sumΓ©".to_string(),
        "東京".to_string(),
        "🌍🌎🌏".to_string(),
    ];
    let trie: PersistentARTrieChar<()> = terms.into_iter().collect();

    assert_eq!(trie.len(), 3);
    assert!(trie.contains("rΓ©sumΓ©"));
    assert!(trie.contains("東京"));
}

// =============================================================================
// Test: Iterator with Unicode
// =============================================================================

#[test]
fn test_iterator_unicode() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    trie.insert("aaa");
    trie.insert("cafΓ©");
    trie.insert("δΈ­ζ–‡");

    // Collect all terms via iteration
    let terms: Vec<String> = trie.iter().collect();

    assert_eq!(terms.len(), 3);
    assert!(terms.contains(&"aaa".to_string()));
    assert!(terms.contains(&"cafΓ©".to_string()));
    assert!(terms.contains(&"δΈ­ζ–‡".to_string()));
}

// =============================================================================
// Test: Unicode Prefix Sharing
// =============================================================================

#[test]
fn test_unicode_prefix_sharing() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    // Terms sharing Unicode prefixes
    trie.insert("δΈ­ζ–‡");
    trie.insert("δΈ­ε›½");
    trie.insert("δΈ­εΏƒ");

    assert_eq!(trie.len(), 3);
    assert!(trie.contains("δΈ­ζ–‡"));
    assert!(trie.contains("δΈ­ε›½"));
    assert!(trie.contains("δΈ­εΏƒ"));
}

#[test]
fn test_emoji_prefix_sharing() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    // Emoji with common prefix
    trie.insert("πŸŽ‰πŸŽŠ");
    trie.insert("πŸŽ‰πŸŽ");
    trie.insert("πŸŽ‰πŸŽˆ");

    assert_eq!(trie.len(), 3);

    // Check prefix navigation
    let zipper = PersistentARTrieCharZipper::new(&trie);
    let party = zipper.descend('πŸŽ‰').expect("should have party emoji");

    let children: Vec<char> = party.children().map(|(c, _)| c).collect();
    assert_eq!(children.len(), 3);
}

// =============================================================================
// Test: Edge Cases
// =============================================================================

#[test]
fn test_empty_string() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    // Empty string should be insertable
    trie.insert("");

    assert!(trie.contains(""));
    assert_eq!(trie.len(), 1);
}

#[test]
fn test_single_character_unicode() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    // Single character terms of various types
    trie.insert("a");
    trie.insert("Γ©");
    trie.insert("δΈ­");
    trie.insert("πŸŽ‰");

    assert_eq!(trie.len(), 4);
    assert!(trie.contains("a"));
    assert!(trie.contains("Γ©"));
    assert!(trie.contains("δΈ­"));
    assert!(trie.contains("πŸŽ‰"));
}

#[test]
fn test_long_unicode_string() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    // Long Unicode string
    let long_unicode = "θΏ™ζ˜―δΈ€δΈͺιžεΈΈι•Ώηš„δΈ­ζ–‡ε­—η¬¦δΈ²οΌŒεŒ…ε«εΎˆε€šε­—η¬¦";
    trie.insert(long_unicode);

    assert!(trie.contains(long_unicode));
    assert_eq!(trie.len(), 1);
}

#[test]
fn test_duplicate_unicode_insertion() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    assert!(trie.insert("cafΓ©").expect("insert failed"));
    assert!(!trie.insert("cafΓ©").expect("insert failed")); // Duplicate should return false
    assert_eq!(trie.len(), 1);
}

// =============================================================================
// Test: Concurrent Unicode Access
// =============================================================================

#[test]
fn test_concurrent_unicode_reads() {
    use std::sync::Arc;
    use std::thread;

    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    // Insert Unicode terms
    let terms = vec!["cafΓ©", "δΈ­ζ–‡", "πŸŽ‰", "ζ—₯本θͺž", "ν•œκ΅­μ–΄"];
    for term in &terms {
        trie.insert(term);
    }

    let trie: Arc<PersistentARTrieChar<()>> = Arc::new(trie);

    // Spawn multiple reader threads
    let handles: Vec<_> = (0..4)
        .map(|_| {
            let trie_clone: Arc<PersistentARTrieChar<()>> = Arc::clone(&trie);
            let terms_clone = terms.clone();

            thread::spawn(move || {
                for term in &terms_clone {
                    assert!(trie_clone.contains(term));
                }
            })
        })
        .collect();

    for handle in handles {
        handle.join().expect("thread join");
    }
}

// =============================================================================
// Test: Clone Behavior
// =============================================================================

// Note: PersistentARTrieChar does not implement Clone because it contains
// Arc-wrapped resources (buffer manager, WAL writer, etc.) that should not
// be implicitly shared. For shared access, use SharedCharTrie instead.
// #[test]
// fn test_clone_shares_unicode_state() { ... }

// =============================================================================
// Test: MappedDictionary with Unicode
// =============================================================================

#[test]
fn test_mapped_dictionary_unicode() {
    let trie: PersistentARTrieChar<i32> = PersistentARTrieChar::new();

    trie.insert_with_value("one", 1);
    trie.insert_with_value("δΈ€", 1); // Chinese for "one"
    trie.insert_with_value("ν•˜λ‚˜", 1); // Korean for "one"

    // MappedDictionary::get_value
    assert_eq!(trie.get_value("one"), Some(1));
    assert_eq!(trie.get_value("δΈ€"), Some(1));
    assert_eq!(trie.get_value("ν•˜λ‚˜"), Some(1));
}

// =============================================================================
// Test: Supplementary Plane Characters (> U+FFFF)
// =============================================================================

#[test]
fn test_supplementary_plane_characters() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    // Characters outside Basic Multilingual Plane (BMP)
    // These require surrogate pairs in UTF-16 but are single code points in Rust

    // Musical symbols (U+1D100-U+1D1FF)
    trie.insert("π„ž"); // G clef

    // Mathematical Alphanumeric Symbols (U+1D400-U+1D7FF)
    trie.insert("𝐀𝐁𝐂"); // Bold letters

    // Ancient scripts
    trie.insert("𐀀"); // Linear B syllable

    // Emoji with skin tone modifiers (U+1F3FB-U+1F3FF)
    trie.insert("πŸ‘‹πŸ½"); // Waving hand with medium skin tone

    assert!(trie.contains("π„ž"));
    assert!(trie.contains("𝐀𝐁𝐂"));
    assert!(trie.contains("𐀀"));
    assert!(trie.contains("πŸ‘‹πŸ½"));
    assert_eq!(trie.len(), 4);
}

// =============================================================================
// Test: Zero-Width Characters
// =============================================================================

#[test]
fn test_zero_width_characters() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    // Zero-width joiner (ZWJ) and zero-width non-joiner (ZWNJ)
    let with_zwj = "a\u{200D}b"; // a + ZWJ + b
    let without_zwj = "ab";

    trie.insert(with_zwj);
    trie.insert(without_zwj);

    // These should be different strings
    assert!(trie.contains(with_zwj));
    assert!(trie.contains(without_zwj));

    // Count depends on whether they are treated as same
    // Without normalization, they are different
    assert!(trie.len() >= 1); // At least one unique
}

// =============================================================================
// Test: Whitespace Variations
// =============================================================================

#[test]
fn test_unicode_whitespace() {
    let trie: PersistentARTrieChar<()> = PersistentARTrieChar::new();

    // Different types of spaces
    trie.insert("hello world"); // Regular space
    trie.insert("hello\u{00A0}world"); // Non-breaking space
    trie.insert("hello\u{2003}world"); // Em space
    trie.insert("hello\u{3000}world"); // Ideographic space

    // These should all be different
    assert!(trie.contains("hello world"));
    assert!(trie.contains("hello\u{00A0}world"));
    assert!(trie.contains("hello\u{2003}world"));
    assert!(trie.contains("hello\u{3000}world"));
    assert_eq!(trie.len(), 4);
}

// =============================================================================
// Test: Deep Trie Loading (Stack Overflow Prevention)
// =============================================================================

/// Test that loading deep tries doesn't cause stack overflow.
///
/// This test creates tries with very long strings (which create deep trie structures)
/// and verifies that the iterative loading algorithm handles them correctly.
///
/// Before the fix, recursive loading would stack overflow for tries with depth > ~1000.
/// The iterative algorithm should handle arbitrarily deep tries.
#[test]
fn test_deep_trie_no_stack_overflow() {
    let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
    let path = temp_dir.path().join("deep_trie_char");

    // Create trie with very long strings to create deep structure
    // Each character adds one level of depth
    let num_strings = 10usize;
    let string_length = 500usize; // Deeper than default stack limit for many recursive calls

    {
        let trie = PersistentARTrieChar::<u64>::create(&path).expect("Failed to create trie");

        for i in 0..num_strings {
            // Generate a long string with varying characters
            let long_key: String = (0..string_length)
                .map(|j| {
                    let ch = (b'a' + ((i + j) % 26) as u8) as char;
                    ch
                })
                .collect();

            // Use upsert which takes a value
            trie.upsert(&long_key, i as u64).expect("Failed to insert");
        }

        // Verify all strings present before checkpoint
        println!("=== Before checkpoint ===");
        println!("Trie len: {}", trie.len());
        for i in 0..num_strings {
            let long_key: String = (0..string_length)
                .map(|j| {
                    let ch = (b'a' + ((i + j) % 26) as u8) as char;
                    ch
                })
                .collect();
            let present = trie.contains(&long_key);
            println!("String {} present: {}", i, present);
        }

        trie.checkpoint().expect("Failed to checkpoint");
    }

    // Reopen - this would stack overflow with recursive loading for deep tries
    let reopened = PersistentARTrieChar::<u64>::open(&path)
        .expect("Failed to reopen trie - possible stack overflow in recursive loading");

    println!("=== After reopen ===");
    println!("Reopened len: {}", reopened.len());

    // First check all strings without asserting
    for i in 0..num_strings {
        let long_key: String = (0..string_length)
            .map(|j| {
                let ch = (b'a' + ((i + j) % 26) as u8) as char;
                ch
            })
            .collect();
        let present = reopened.contains(&long_key);
        println!(
            "String {} present after reopen: {} (first char: '{}')",
            i,
            present,
            long_key.chars().next().unwrap()
        );

        // Debug: for string 9, try to trace the issue
        if i == 9 && !present {
            println!("DEBUG: Tracing string 9 lookup failure");
            // Check using get() which will trace the path
            let value = reopened.get(&long_key);
            println!("DEBUG: get() for string 9 returned: {:?}", value.is_some());
        }
    }

    assert_eq!(
        reopened.len(),
        num_strings,
        "All strings should be present after reopen"
    );

    // Verify we can still look up the strings
    for i in 0..num_strings {
        let long_key: String = (0..string_length)
            .map(|j| {
                let ch = (b'a' + ((i + j) % 26) as u8) as char;
                ch
            })
            .collect();

        assert!(
            reopened.contains(&long_key),
            "String {} should be present after reopen",
            i
        );

        // Verify the value via get() (F4: `get` now returns an owned `Option<V>`).
        if let Some(value) = reopened.get(&long_key) {
            assert_eq!(value, i as u64, "Value for string {} should match", i);
        }
    }
}

/// Test deep trie with Unicode characters.
///
/// This test uses multi-byte UTF-8 characters which still create deep tries
/// but exercise the character-level handling.
#[test]
fn test_deep_unicode_trie_no_stack_overflow() {
    let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
    let path = temp_dir.path().join("deep_unicode_trie");

    let num_strings = 5usize;
    let string_length = 300usize; // Fewer characters but still deep

    {
        let trie = PersistentARTrieChar::<u64>::create(&path).expect("Failed to create trie");

        for i in 0..num_strings {
            // Generate a long Unicode string with CJK characters
            let long_key: String = (0..string_length)
                .map(|j| {
                    // Use a range of CJK characters (U+4E00 to U+9FFF)
                    let codepoint = 0x4E00 + ((i * 17 + j * 13) % 0x51FF) as u32;
                    char::from_u32(codepoint).unwrap_or('δΈ­')
                })
                .collect();

            trie.upsert(&long_key, i as u64).expect("Failed to insert");
        }

        trie.checkpoint().expect("Failed to checkpoint");
    }

    // Reopen
    let reopened = PersistentARTrieChar::<u64>::open(&path).expect("Failed to reopen Unicode trie");

    assert_eq!(reopened.len(), num_strings);
}