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
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
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
854
855
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
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
//! Persistent Vocabulary ARTrie — a lock-free, overlay-only UTF-8 vocabulary (V6).
//!
//! This module provides [`PersistentVocabARTrie`], a specialized UTF-8 vocabulary trie whose
//! SOLE representation is the lock-free overlay (`PersistentCharNode` with structural sharing,
//! at `V = u64` = the vocabulary index). The owned parent-pointer tree + reverse-index sidecar
//! described historically below were deleted in V6 (the single-lock-free transition).
//!
//! - **Forward lookup** (term → index): O(k) walk of the lock-free overlay
//! - **Reverse lookup** (index → term): O(1) via the in-memory `reverse_term_map` (id → term),
//!   rebuilt from the checkpoint image on reopen
//!
//! # Design
//!
//! The vocabulary IS the lock-free overlay (a `PersistentCharNode` trie with structural sharing,
//! at `V = u64`) plus an in-memory `reverse_term_map` (id → term) for reverse lookups. Inserts
//! are `&self`-concurrent durable Order-A operations (WAL `Insert{value:id}` → overlay root-CAS →
//! CommitRank → mark_committed) — many threads may insert through a shared `Arc` with no external
//! locking (the single lock-free impl: no `install_overlay` toggle, no `ConcurrentVocabARTrie`
//! wrapper). A checkpoint publishes the overlay as a dense char-arena image (`vocabulary.vocab`),
//! RETAINING the WAL (`vocabulary.vocab.wal`) for crash recovery; the reverse map is rebuilt from
//! the image on reopen.
//!
//! # Example
//!
//! ```rust,no_run
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use libdictenstein::persistent_vocab_artrie::PersistentVocabARTrie;
//!
//! // Create a new vocabulary
//! let mut vocab = PersistentVocabARTrie::create("vocab.vocab")?;
//!
//! // Insert terms (auto-assigns indices)
//! let idx1 = vocab.insert("hello")?; // Returns 0
//! let idx2 = vocab.insert("world")?; // Returns 1
//!
//! // Forward lookup: term → index
//! assert_eq!(vocab.get_index("hello"), Some(0));
//! assert_eq!(vocab.get_index("world"), Some(1));
//!
//! // Reverse lookup: index → term (O(1) cache hit or O(k) backtracking)
//! assert_eq!(vocab.get_term(0), Some("hello".to_string()));
//! assert_eq!(vocab.get_term(1), Some("world".to_string()));
//!
//! // Sync WAL for durability
//! vocab.sync()?;
//!
//! // Checkpoint to disk
//! vocab.checkpoint()?;
//!
//! // Reopen later with crash recovery
//! let (vocab, report) = PersistentVocabARTrie::open_with_recovery("vocab.vocab")?;
//! assert_eq!(vocab.get_term(0), Some("hello".to_string()));
//! # Ok(())
//! # }
//! ```
//!
//! # Performance
//!
//! | Operation | Complexity | Notes |
//! |-----------|------------|-------|
//! | Forward lookup (`get_index`) | O(k) | overlay walk, k = term length |
//! | Reverse lookup (`get_term`) | O(1) | in-memory `reverse_term_map` |
//! | Insert (`&self`, concurrent) | O(k) | durable Order-A, lock-free CAS |

// Core types
pub mod types;

// Vocabulary-specific file-header reader (relocated out of
// `persistent_artrie_core::block_storage` so core stays free of variant deps).
pub mod header;

// VocabSyncHandle (Phase-6 split out of dict_impl).
pub mod sync_handle;

// IoUringDiskManager-specific constructors (Phase-6 split out of dict_impl).
#[cfg(feature = "io-uring-backend")]
pub mod io_uring_ctor;

// MmapDiskManager-specific constructors (Phase-6 split out of dict_impl).
pub mod mmap_ctor;

// Lock-free CAS-based concurrent inserts (Phase-6 split out of dict_impl).
pub mod lockfree_cas;

// Vocab overlay-flip seam impls (V1 — the shared overlay traits at V=u64).
pub(crate) mod overlay_write_mode;

// Overlay → disk serializer (V2 — the char-arena image writer for the flip).
pub(crate) mod overlay_serialize;

// Persistence/durability/observability API (Phase-6 split out of dict_impl).
pub mod persistence_api;

// Public query API (get_index, get_term, contains, len) — Phase-6 split.
pub mod query_api;

// Public mutation API (insert / insert_batch / insert_with_index) — Phase-6 split.
pub mod mutation_api;

// Path-based queries + iter_terms wrappers — Phase-6 split.
pub mod path_query;

// Disk-backed implementation
pub mod dict_impl;

// Re-export main types
pub use types::{
    NodeRef, // Re-export from persistent_artrie_char
    VocabTrieFileHeader,
    DEFAULT_VOCAB_BUFFER_POOL_SIZE,
    VOCAB_FILE_HEADER_SIZE,
    VOCAB_HEADER_VERSION_V2,
    VOCAB_TRIE_MAGIC,
};

pub use dict_impl::{PersistentVocabARTrie, SharedVocabARTrie, VocabSyncHandle};

// Re-export DurabilityPolicy from base layer
pub use crate::persistent_artrie::dict_impl::DurabilityPolicy;

// Re-export eviction types from byte-level implementation (shared)
pub use crate::persistent_artrie::eviction::{
    AccessTracker, DiskLocationRegistry, EvictionConfig, EvictionCoordinator, EvictionStats,
    EvictionUrgency, LruRegistry,
};

// ============================================================================
// Trait Implementations
// ============================================================================

use crate::bijective::BijectiveDictionary;
use crate::persistent_artrie::error::Result;
use crate::persistent_artrie::recovery::RecoveryReport;
use crate::{Dictionary, DictionaryNode, MappedDictionary, MutableMappedDictionary};
use std::path::Path;

// Dictionary trait implementation
impl Dictionary for PersistentVocabARTrie {
    type Node = VocabTrieNodeRef;

    fn root(&self) -> Self::Node {
        // Get root children info from the trie
        let children = self.get_root_children();
        VocabTrieNodeRef::new(false, children, Vec::new())
    }

    fn contains(&self, term: &str) -> bool {
        PersistentVocabARTrie::contains(self, term)
    }

    fn len(&self) -> Option<usize> {
        Some(PersistentVocabARTrie::len(self))
    }
}

/// Node reference for Dictionary trait implementation.
///
/// This provides a snapshot-based node reference for navigating the trie
/// through the Dictionary trait. Note that since PersistentVocabARTrie
/// requires internal iteration for navigation, this implementation creates
/// shallow copies of node data rather than holding direct pointers.
///
/// For full trie operations, use the PersistentVocabARTrie methods directly.
#[derive(Clone)]
pub struct VocabTrieNodeRef {
    /// Whether this node is final
    is_final: bool,
    /// Children of this node (label -> whether child is final)
    /// This is a snapshot taken at the time of construction
    children: Vec<(char, bool)>,
    /// Path from root to this node (for reconstruction)
    path: Vec<char>,
}

impl VocabTrieNodeRef {
    /// Create a new node reference with snapshot data
    fn new(is_final: bool, children: Vec<(char, bool)>, path: Vec<char>) -> Self {
        Self {
            is_final,
            children,
            path,
        }
    }

    /// Create a root node reference (placeholder - requires trie access for real data)
    fn placeholder() -> Self {
        Self {
            is_final: false,
            children: Vec::new(),
            path: Vec::new(),
        }
    }
}

impl DictionaryNode for VocabTrieNodeRef {
    type Unit = char;

    fn is_final(&self) -> bool {
        self.is_final
    }

    fn transition(&self, label: char) -> Option<Self> {
        // Check if we have this child
        for &(child_label, child_is_final) in &self.children {
            if child_label == label {
                // Create a new path with this label appended
                let mut new_path = self.path.clone();
                new_path.push(label);
                // Note: We can't get the child's children without trie access,
                // so this returns a node with no children info.
                // For full navigation, use PersistentVocabARTrie methods directly.
                return Some(VocabTrieNodeRef::new(child_is_final, Vec::new(), new_path));
            }
        }
        None
    }

    fn edges(&self) -> Box<dyn Iterator<Item = (char, Self)> + '_> {
        let path = self.path.clone();
        let edges: Vec<_> = self
            .children
            .iter()
            .map(move |&(label, is_final)| {
                let mut new_path = path.clone();
                new_path.push(label);
                (label, VocabTrieNodeRef::new(is_final, Vec::new(), new_path))
            })
            .collect();
        Box::new(edges.into_iter())
    }
}

// MappedDictionary trait implementation
impl MappedDictionary for PersistentVocabARTrie {
    type Value = u64;

    fn get_value(&self, term: &str) -> Option<Self::Value> {
        self.get_index(term)
    }
}

// MutableMappedDictionary trait implementation.
//
// `PersistentVocabARTrie` has no interior mutability (mutation methods take
// `&mut self`), so the `&self`-shaped trait methods cannot do useful work
// here. All three return their "no-op" sentinel value (`false` or `0`) and
// emit `log::warn!` so the call site shows up under `RUST_LOG=warn`. To
// actually mutate, wrap the vocab in `SharedVocabARTrie` (which holds the
// trie behind an `Arc<RwLock<…>>`) and call its trait impl, or call the
// inherent `PersistentVocabARTrie::insert(&mut self, term)` directly.
impl MutableMappedDictionary for PersistentVocabARTrie {
    fn insert_with_value(&self, term: &str, _value: Self::Value) -> bool {
        log::warn!(
            "PersistentVocabARTrie::insert_with_value({term:?}, _) is a no-op \
             — this type has no interior mutability. Use \
             SharedVocabARTrie::insert_with_value, or call the inherent \
             PersistentVocabARTrie::insert via &mut self."
        );
        false
    }

    fn union_with<F>(&self, _other: &Self, _merge_fn: F) -> usize
    where
        F: Fn(&Self::Value, &Self::Value) -> Self::Value,
        Self::Value: Clone,
    {
        log::warn!(
            "PersistentVocabARTrie::union_with is a no-op — vocab tries are \
             append-only and this type has no interior mutability. Use \
             SharedVocabARTrie::union_with (note: merge_fn will still be \
             ignored, vocab indices are auto-assigned)."
        );
        0
    }

    fn update_or_insert<F>(&self, term: &str, _default_value: Self::Value, _update_fn: F) -> bool
    where
        F: FnOnce(&mut Self::Value),
    {
        log::warn!(
            "PersistentVocabARTrie::update_or_insert({term:?}, _, _) is a no-op \
             — this type has no interior mutability. Use \
             SharedVocabARTrie::update_or_insert (note: default_value and \
             update_fn will still be ignored, indices are auto-assigned)."
        );
        false
    }
}

// BijectiveDictionary trait implementation.
//
// Reverse lookup reconstructs the term on-the-fly via parent-pointer
// backtracking (`PersistentVocabARTrie::get_term(index)`), then wraps the
// resulting `String` in `Cow::Owned`. The previous `Option<&str>` trait
// signature couldn't be honored honestly here — there's no stable in-memory
// storage to point at, since terms are reconstructed per-call — so this used
// to be a `None` stub that silently violated the documented bijection
// invariant. Cow lets the caller see the actual term.
impl BijectiveDictionary for PersistentVocabARTrie {
    fn get_term(&self, value: &Self::Value) -> Option<std::borrow::Cow<'_, str>> {
        // Delegate to the inherent method, which returns Option<String>.
        Self::get_term(self, *value).map(std::borrow::Cow::Owned)
    }

    fn contains_value(&self, value: &Self::Value) -> bool {
        self.contains_index(*value)
    }

    fn bijection_len(&self) -> usize {
        self.len()
    }
}

// `PersistentVocabARTrie` does not implement `crate::artrie_trait::ARTrie`
// directly: the trait's mutation methods (`insert`, `remove`, `checkpoint`,
// `sync`, `upsert`, `increment`, `enable_slot_tracking`, `flush_sequential`,
// `insert_with_value`, `remove_prefix`) all take `&self` but the underlying
// trie semantics require `&mut self`. Use `SharedVocabARTrie`
// (`Arc<RwLock<PersistentVocabARTrie>>`) when an `ARTrie` impl is required;
// it satisfies the trait by acquiring the write lock per call. The
// `SharedVocabARTrie` impl lives below.

// ============================================================================
// SharedVocabARTrie Trait Implementations
// ============================================================================

use parking_lot::RwLock;
use std::sync::Arc;

impl Dictionary for SharedVocabARTrie {
    type Node = VocabTrieNodeRef;

    fn root(&self) -> Self::Node {
        let guard = self.read();
        let children = guard.get_root_children();
        VocabTrieNodeRef::new(false, children, Vec::new())
    }

    fn contains(&self, term: &str) -> bool {
        let guard = self.read();
        guard.contains(term)
    }

    fn len(&self) -> Option<usize> {
        let guard = self.read();
        Some(guard.len())
    }
}

impl MappedDictionary for SharedVocabARTrie {
    type Value = u64;

    fn get_value(&self, term: &str) -> Option<Self::Value> {
        let guard = self.read();
        guard.get_index(term)
    }
}

// `SharedVocabARTrie` accepts mutations through its read/write guards, but
// it cannot honor the `value`/`merge_fn`/`update_fn` arguments that
// `MutableMappedDictionary` exposes — vocab indices are auto-assigned by the
// internal allocator, not chosen by the caller. The trait methods below
// insert the term and emit `log::warn!` so the discarded argument shows up
// under `RUST_LOG=warn`. Read the assigned index back with
// `MappedDictionary::get_value`.
impl MutableMappedDictionary for SharedVocabARTrie {
    fn insert_with_value(&self, term: &str, _value: Self::Value) -> bool {
        log::warn!(
            "SharedVocabARTrie::insert_with_value({term:?}, _) discards the \
             value argument — vocab indices are auto-assigned. Use \
             insert(term) and read the assigned index back via \
             MappedDictionary::get_value(term)."
        );
        let existed = self.read().contains(term);
        if !existed {
            let guard = self.write();
            if let Err(error) = guard.insert(term) {
                log::warn!("SharedVocabARTrie::insert_with_value failed: {error}");
                return false;
            }
        }
        !existed
    }

    fn union_with<F>(&self, other: &Self, _merge_fn: F) -> usize
    where
        F: Fn(&Self::Value, &Self::Value) -> Self::Value,
        Self::Value: Clone,
    {
        log::warn!(
            "SharedVocabARTrie::union_with discards the merge_fn argument — \
             vocab indices are auto-assigned, so there is nothing to merge. \
             Terms missing from self will be inserted with fresh indices."
        );
        // First collect terms from other to avoid holding locks simultaneously
        let other_terms: Vec<String> = {
            let other_guard = other.read();
            other_guard.iter_terms().collect()
        };

        let mut count = 0;
        let self_guard = self.write();
        for term in other_terms {
            if !self_guard.contains(&term) {
                match self_guard.insert(&term) {
                    Ok(_) => count += 1,
                    Err(error) => {
                        log::warn!("SharedVocabARTrie::union_with failed for {term:?}: {error}");
                    }
                }
            }
        }
        count
    }

    fn update_or_insert<F>(&self, term: &str, _default_value: Self::Value, _update_fn: F) -> bool
    where
        F: FnOnce(&mut Self::Value),
    {
        log::warn!(
            "SharedVocabARTrie::update_or_insert({term:?}, _, _) discards \
             both default_value and update_fn — vocab indices are \
             auto-assigned and immutable. Inserts the term if absent and \
             returns whether a new term was added."
        );
        let existed = self.read().contains(term);
        if !existed {
            let guard = self.write();
            if let Err(error) = guard.insert(term) {
                log::warn!("SharedVocabARTrie::update_or_insert failed: {error}");
                return false;
            }
        }
        !existed
    }
}

impl BijectiveDictionary for SharedVocabARTrie {
    fn get_term(&self, value: &Self::Value) -> Option<std::borrow::Cow<'_, str>> {
        // Acquire the read guard, reconstruct the term, drop the guard, return
        // the owned String wrapped as Cow::Owned. The Cow doesn't borrow from
        // self because the underlying String is owned outright.
        let guard = self.read();
        guard.get_term(*value).map(std::borrow::Cow::Owned)
    }

    fn contains_value(&self, value: &Self::Value) -> bool {
        let guard = self.read();
        guard.contains_index(*value)
    }

    fn bijection_len(&self) -> usize {
        let guard = self.read();
        guard.len()
    }
}

impl crate::artrie_trait::ARTrie for SharedVocabARTrie {
    type Unit = char;
    type Value = u64;

    fn create<P: AsRef<Path>>(path: P) -> Result<Self> {
        PersistentVocabARTrie::create(path).map(|t| Arc::new(RwLock::new(t)))
    }

    fn create_with_slot_tracking<P: AsRef<Path>>(path: P) -> Result<Self> {
        PersistentVocabARTrie::create(path).map(|t| Arc::new(RwLock::new(t)))
    }

    fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        PersistentVocabARTrie::open(path).map(|t| Arc::new(RwLock::new(t)))
    }

    fn open_with_slot_tracking<P: AsRef<Path>>(path: P) -> Result<Self> {
        PersistentVocabARTrie::open(path).map(|t| Arc::new(RwLock::new(t)))
    }

    fn open_with_recovery<P: AsRef<Path>>(path: P) -> Result<(Self, RecoveryReport)> {
        PersistentVocabARTrie::open_with_recovery(path).map(|(t, r)| (Arc::new(RwLock::new(t)), r))
    }

    fn open_with_recovery_and_slot_tracking<P: AsRef<Path>>(
        path: P,
    ) -> Result<(Self, RecoveryReport)> {
        let (trie, report) = PersistentVocabARTrie::open_with_recovery(path)?;
        trie.enable_slot_tracking();
        Ok((Arc::new(RwLock::new(trie)), report))
    }

    fn enable_slot_tracking(&self) {
        self.write().enable_slot_tracking();
    }

    fn flush_sequential(&self) -> Result<()> {
        self.write().flush_sequential()
    }

    fn insert(&self, term: &str) -> bool
    where
        Self::Value: Default,
    {
        let mut guard = self.write();
        let old_count = guard.len();
        // Explicitly call the struct method, not trait method
        if let Err(error) = PersistentVocabARTrie::insert(&mut *guard, term) {
            log::warn!("SharedVocabARTrie::insert failed: {error}");
            return false;
        }
        // Return true if a new term was added (count increased)
        guard.len() > old_count
    }

    fn insert_with_value(&self, term: &str, _value: Self::Value) -> bool {
        log::warn!(
            "SharedVocabARTrie::insert_with_value (via ARTrie trait) for \
             {term:?} discards the value argument — vocab indices are \
             auto-assigned."
        );
        let mut guard = self.write();
        let old_count = guard.len();
        // Explicitly call the struct method, not trait method
        if let Err(error) = PersistentVocabARTrie::insert(&mut *guard, term) {
            log::warn!("SharedVocabARTrie::insert_with_value failed: {error}");
            return false;
        }
        // Return true if a new term was added (count increased)
        guard.len() > old_count
    }

    fn contains(&self, term: &str) -> bool {
        let guard = self.read();
        guard.contains(term)
    }

    fn get_value(&self, term: &str) -> Option<Self::Value> {
        let guard = self.read();
        guard.get_index(term)
    }

    fn remove(&self, term: &str) -> bool {
        log::warn!(
            "SharedVocabARTrie::remove({term:?}) is unsupported — vocab tries \
             are append-only to preserve the term ↔ index bijection. Returns \
             false unconditionally."
        );
        false
    }

    fn len(&self) -> usize {
        let guard = self.read();
        guard.len()
    }

    fn checkpoint(&self) -> Result<()> {
        let guard = self.write();
        guard.checkpoint()
    }

    fn is_dirty(&self) -> bool {
        let guard = self.read();
        guard.is_dirty()
    }

    fn remove_prefix(&self, prefix: &str) -> usize {
        log::warn!(
            "SharedVocabARTrie::remove_prefix({prefix:?}) is unsupported — \
             vocab tries are append-only. Returns 0 unconditionally."
        );
        0
    }

    fn iter_prefix(&self, prefix: &str) -> Option<Box<dyn Iterator<Item = String> + '_>> {
        // For SharedVocabARTrie, we need to collect terms to avoid holding lock
        // during iteration. This collects all matching terms upfront.
        let guard = self.read();
        let prefix_chars: Vec<char> = prefix.chars().collect();

        // Check if prefix exists
        let prefix_exists = if prefix.is_empty() {
            true
        } else {
            guard.get_index(prefix).is_some()
                || !guard.get_children_at_path(&prefix_chars).is_empty()
        };

        if prefix_exists {
            // Collect terms while holding lock, then return iterator over collected Vec
            let terms: Vec<String> = guard.iter_terms_with_prefix(prefix).collect();
            Some(Box::new(terms.into_iter()))
        } else {
            None
        }
    }

    fn sync(&self) -> Result<()> {
        let guard = self.write();
        guard.sync()
    }

    fn current_lsn(&self) -> u64 {
        let guard = self.read();
        guard.current_lsn()
    }

    fn synced_lsn(&self) -> Option<u64> {
        let guard = self.read();
        guard.synced_lsn()
    }

    fn durability_policy(&self) -> DurabilityPolicy {
        let guard = self.read();
        guard.durability_policy()
    }

    fn upsert(&self, term: &str, _value: Self::Value) -> Result<bool> {
        log::warn!(
            "SharedVocabARTrie::upsert({term:?}, _) discards the value \
             argument — vocab indices are auto-assigned. Behaves as insert."
        );
        let mut guard = self.write();
        let old_count = guard.len();
        // Explicitly call the struct method, not trait method
        PersistentVocabARTrie::insert(&mut *guard, term)?;
        Ok(guard.len() > old_count)
    }

    // C1: `increment` removed from the `ARTrie` trait. Vocab never supported it
    // (indices are auto-assigned); the former runtime reject is now simply the
    // method's ABSENCE (more honest than a runtime Err). Commented out (not deleted)
    // per convention.
    // fn increment(&self, _term: &str, _delta: i64) -> Result<i64> {
    //     Err(crate::persistent_artrie::error::PersistentARTrieError::InvalidOperation(
    //         "PersistentVocabARTrie does not support increment - indices are auto-assigned".into(),
    //     ))
    // }
}

// ============================================================================
// EvictableARTrie Trait Implementation (on SharedVocabARTrie)
// ============================================================================

impl crate::artrie_trait::EvictableARTrie for SharedVocabARTrie {
    fn enable_eviction(
        &self,
        config: crate::persistent_artrie::eviction::EvictionConfig,
    ) -> crate::persistent_artrie::error::Result<()> {
        use crate::persistent_artrie::error::PersistentARTrieError;

        config
            .validate()
            .map_err(|e| PersistentARTrieError::internal(&e))?;

        let mut guard = self.write();

        // Check if eviction is already enabled
        if guard.eviction_coordinator.is_some() {
            return Err(PersistentARTrieError::internal("Eviction already enabled"));
        }

        // Create the epoch manager reference
        let epoch_manager = Arc::new(crate::persistent_artrie::concurrency::EpochManager::new());

        // Create the eviction coordinator
        let coordinator = crate::persistent_artrie::eviction::EvictionCoordinator::new(
            config.clone(),
            epoch_manager,
        );

        // Start the eviction coordinator with a no-op char callback. Overlay-only (V6): the
        // overlay never evicts finals to disk (OverlayFaulter::fault_overlay_slot -> None), so
        // there is nothing to unswizzle; the coordinator lifecycle is retained for
        // memory-pressure accounting + API parity with byte/char.
        coordinator
            .start_char(move |_nodes_to_evict| (0, 0))
            .map_err(|e| PersistentARTrieError::internal(&e))?;

        // Start memory pressure monitor if configured
        coordinator
            .start_memory_monitor()
            .map_err(|e| PersistentARTrieError::internal(&e))?;

        guard.eviction_coordinator = Some(coordinator);

        Ok(())
    }

    fn disable_eviction(&self) -> crate::persistent_artrie::error::Result<()> {
        // Drop-before-join (live-deadlock fix; red-team R3-2 SWEEP C, the 8th site):
        // take the coordinator out and RELEASE the write guard BEFORE `shutdown()`
        // joins the eviction worker. The worker's reclaim callback re-enters via
        // `trie.write()` (the `enable_eviction` closure), so holding the write guard
        // across the join deadlocks (worker waits on the guard; the joining thread
        // waits on the worker). char/byte `disable_eviction` already use this
        // statement-temporary; vocab was the missed site.
        let coordinator = {
            let mut guard = self.write();
            guard.eviction_coordinator.take()
        };
        if let Some(coordinator) = coordinator {
            coordinator.shutdown();
        }
        Ok(())
    }

    fn eviction_enabled(&self) -> bool {
        let guard = self.read();
        guard.eviction_coordinator.is_some()
    }

    fn eviction_stats(&self) -> crate::persistent_artrie::eviction::EvictionStats {
        let guard = self.read();
        guard
            .eviction_coordinator
            .as_ref()
            .map(|c| c.stats())
            .unwrap_or_default()
    }

    fn force_eviction(
        &self,
        target_bytes: usize,
    ) -> crate::persistent_artrie::error::Result<(usize, usize)> {
        let guard = self.read();

        let Some(coordinator) = &guard.eviction_coordinator else {
            return Ok((0, 0));
        };

        Ok(coordinator.force_eviction(target_bytes))
    }

    fn touch_node(&self, path: &[Self::Unit]) {
        let guard = self.read();
        if let Some(coordinator) = &guard.eviction_coordinator {
            use crate::persistent_artrie::eviction::lru_tracker::hash_char_path;
            coordinator.lru_registry().touch_hash(hash_char_path(path));
        }
    }
}

// ============================================================================
// Type Aliases
// ============================================================================

/// Type alias for vocabulary use cases.
///
/// This is the recommended type for embedding vocabularies, token-to-ID mappings,
/// and similar use cases that need sequential `u64` indices with persistent storage.
///
/// # Example
///
/// ```rust,no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use libdictenstein::persistent_vocab_artrie::IndexedVocabularyPersistent;
///
/// // Create new vocabulary
/// let mut vocab = IndexedVocabularyPersistent::create("vocab.vocab")?;
/// vocab.insert("hello")?; // Returns 0
///
/// // Checkpoint and reopen with recovery
/// vocab.checkpoint()?;
/// let (vocab, report) = IndexedVocabularyPersistent::open_with_recovery("vocab.vocab")?;
///
/// // Reverse lookup works immediately!
/// assert_eq!(vocab.get_term(0), Some("hello".to_string()));
/// # Ok(())
/// # }
/// ```
pub type IndexedVocabularyPersistent = PersistentVocabARTrie;

// Backwards compatibility alias (deprecated)
#[deprecated(since = "0.9.0", note = "Use SharedVocabARTrie instead")]
pub type SharedVocabTrie = SharedVocabARTrie;

// Also re-export DiskBackedVocabTrieInner as deprecated alias
#[deprecated(since = "0.9.0", note = "Use PersistentVocabARTrie directly instead")]
pub type DiskBackedVocabTrieInner = PersistentVocabARTrie;

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    #[test]
    fn test_vocab_trie_basic() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("test.vocab");

        let mut vocab = PersistentVocabARTrie::create(&path).unwrap();

        // Insert
        let idx1 = vocab.insert("apple").expect("insert apple");
        let idx2 = vocab.insert("banana").expect("insert banana");
        let idx3 = vocab.insert("cherry").expect("insert cherry");

        assert_eq!(idx1, 0);
        assert_eq!(idx2, 1);
        assert_eq!(idx3, 2);
        assert_eq!(vocab.len(), 3);

        // Forward lookup
        assert_eq!(vocab.get_index("apple"), Some(0));
        assert_eq!(vocab.get_index("banana"), Some(1));
        assert_eq!(vocab.get_index("cherry"), Some(2));
        assert_eq!(vocab.get_index("durian"), None);

        // Reverse lookup
        assert_eq!(vocab.get_term(0), Some("apple".to_string()));
        assert_eq!(vocab.get_term(1), Some("banana".to_string()));
        assert_eq!(vocab.get_term(2), Some("cherry".to_string()));
        assert_eq!(vocab.get_term(999), None);
    }

    #[test]
    fn test_vocab_trie_unicode() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("test.vocab");

        let mut vocab = PersistentVocabARTrie::create(&path).unwrap();

        vocab.insert("日本語");
        vocab.insert("中文");
        vocab.insert("한글");
        vocab.insert("العربية");
        vocab.insert("emoji😀");

        assert_eq!(vocab.get_index("日本語"), Some(0));
        assert_eq!(vocab.get_index("中文"), Some(1));
        assert_eq!(vocab.get_index("한글"), Some(2));
        assert_eq!(vocab.get_index("العربية"), Some(3));
        assert_eq!(vocab.get_index("emoji😀"), Some(4));

        assert_eq!(vocab.get_term(0), Some("日本語".to_string()));
        assert_eq!(vocab.get_term(4), Some("emoji😀".to_string()));
    }

    #[test]
    fn test_vocab_trie_custom_start() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("test.vocab");

        // Reserve 0-9 for special tokens
        let mut vocab = PersistentVocabARTrie::create_with_start_index(&path, 10).unwrap();

        let idx1 = vocab.insert("first").expect("insert first");
        let idx2 = vocab.insert("second").expect("insert second");

        assert_eq!(idx1, 10);
        assert_eq!(idx2, 11);
        assert_eq!(vocab.start_index(), 10);
    }

    #[test]
    fn test_vocab_trie_idempotent_insert() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("test.vocab");

        let mut vocab = PersistentVocabARTrie::create(&path).unwrap();

        let idx1 = vocab.insert("duplicate").expect("insert duplicate");
        let idx2 = vocab.insert("duplicate").expect("insert duplicate again");
        let idx3 = vocab
            .insert("duplicate")
            .expect("insert duplicate third time");

        assert_eq!(idx1, 0);
        assert_eq!(idx2, 0);
        assert_eq!(idx3, 0);
        assert_eq!(vocab.len(), 1);
    }

    #[test]
    fn test_vocab_trie_traits() {
        use crate::Dictionary;
        use crate::MappedDictionary;

        let dir = tempdir().unwrap();
        let path = dir.path().join("test.vocab");

        let mut vocab = PersistentVocabARTrie::create(&path).unwrap();
        vocab.insert("test");

        // Dictionary trait
        assert!(Dictionary::contains(&vocab, "test"));
        assert!(!Dictionary::contains(&vocab, "missing"));
        assert_eq!(Dictionary::len(&vocab), Some(1));

        // MappedDictionary trait
        assert_eq!(MappedDictionary::get_value(&vocab, "test"), Some(0));
        assert_eq!(MappedDictionary::get_value(&vocab, "missing"), None);
    }

    #[test]
    fn test_vocab_trie_artrie_trait() {
        use crate::artrie_trait::ARTrie;

        let dir = tempdir().unwrap();
        let path = dir.path().join("test.vocab");

        let vocab: SharedVocabARTrie = ARTrie::create(&path).unwrap();

        // ARTrie trait methods
        assert!(ARTrie::insert(&vocab, "hello"));
        assert!(!ARTrie::insert(&vocab, "hello")); // Already exists
        assert!(ARTrie::contains(&vocab, "hello"));
        assert_eq!(ARTrie::get_value(&vocab, "hello"), Some(0));
        assert_eq!(ARTrie::len(&vocab), 1);
    }

    #[test]
    fn test_vocab_trie_lsn_tracking() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("test.vocab");

        let mut vocab = PersistentVocabARTrie::create(&path).unwrap();

        // Initial state
        let initial_lsn = vocab.current_lsn();
        assert!(initial_lsn > 0);
        assert!(vocab.synced_lsn().is_none());

        // After insert
        vocab.insert("test");
        assert!(vocab.current_lsn() > initial_lsn);

        // After sync
        vocab.sync().unwrap();
        assert!(vocab.synced_lsn().is_some());
    }

    #[test]
    fn test_vocab_trie_durability_policy() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("test.vocab");

        let mut vocab = PersistentVocabARTrie::create(&path).unwrap();

        // Default is Immediate
        assert_eq!(vocab.durability_policy(), DurabilityPolicy::Immediate);

        // Change to Periodic
        vocab.set_durability_policy(DurabilityPolicy::Periodic);
        assert_eq!(vocab.durability_policy(), DurabilityPolicy::Periodic);
    }

    #[test]
    fn test_shared_vocab_artrie() {
        use crate::artrie_trait::ARTrie;

        let dir = tempdir().unwrap();
        let path = dir.path().join("test.vocab");

        let vocab: SharedVocabARTrie = ARTrie::create(&path).unwrap();

        // Insert via trait
        assert!(ARTrie::insert(&vocab, "hello"));
        assert!(ARTrie::insert(&vocab, "world"));

        // Verify
        assert!(ARTrie::contains(&vocab, "hello"));
        assert!(ARTrie::contains(&vocab, "world"));
        assert_eq!(ARTrie::len(&vocab), 2);

        // Checkpoint
        ARTrie::checkpoint(&vocab).unwrap();
    }
}