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
//! Generic MVCC-lite primitives shared by all persistent ARTrie variants.
//!
//! This module holds the unit-agnostic parts of the MVCC subsystem:
//! the `MvccStats`/`MvccStatsTracker` counters, the `TrieRoot` trait that
//! variant-specific node types implement, the generic `ReadTransaction<T>`
//! that pins a snapshot and exposes byte- or char-keyed lookups, and the
//! lightweight `EpochGuard`.
//!
//! Variant-specific `impl TrieRoot for <variant-node>` blocks live with their
//! node types (see `persistent_artrie::mvcc` for the byte impl and
//! `persistent_artrie_char::mvcc` for the char impl).

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

use crate::persistent_artrie_core::concurrency::EpochManager;

/// Statistics for MVCC read transactions.
#[derive(Debug, Clone, Default)]
pub struct MvccStats {
    /// Total read transactions started
    pub transactions_started: u64,
    /// Total read transactions completed
    pub transactions_completed: u64,
    /// Current active transactions
    pub active_transactions: u64,
    /// Total reads performed
    pub total_reads: u64,
    /// Cache hits during reads
    pub cache_hits: u64,
}

/// Global MVCC statistics tracker.
#[derive(Debug)]
pub struct MvccStatsTracker {
    transactions_started: AtomicU64,
    transactions_completed: AtomicU64,
    active_transactions: AtomicU64,
    total_reads: AtomicU64,
    cache_hits: AtomicU64,
}

impl MvccStatsTracker {
    /// Create a new stats tracker.
    pub fn new() -> Self {
        Self {
            transactions_started: AtomicU64::new(0),
            transactions_completed: AtomicU64::new(0),
            active_transactions: AtomicU64::new(0),
            total_reads: AtomicU64::new(0),
            cache_hits: AtomicU64::new(0),
        }
    }

    /// Record a transaction start.
    pub fn record_start(&self) {
        self.transactions_started.fetch_add(1, Ordering::Relaxed);
        self.active_transactions.fetch_add(1, Ordering::Relaxed);
    }

    /// Record a transaction completion.
    pub fn record_complete(&self) {
        self.transactions_completed.fetch_add(1, Ordering::Relaxed);
        self.active_transactions.fetch_sub(1, Ordering::Relaxed);
    }

    /// Record a read operation.
    pub fn record_read(&self) {
        self.total_reads.fetch_add(1, Ordering::Relaxed);
    }

    /// Record a cache hit.
    pub fn record_cache_hit(&self) {
        self.cache_hits.fetch_add(1, Ordering::Relaxed);
    }

    /// Get current statistics.
    pub fn stats(&self) -> MvccStats {
        MvccStats {
            transactions_started: self.transactions_started.load(Ordering::Relaxed),
            transactions_completed: self.transactions_completed.load(Ordering::Relaxed),
            active_transactions: self.active_transactions.load(Ordering::Relaxed),
            total_reads: self.total_reads.load(Ordering::Relaxed),
            cache_hits: self.cache_hits.load(Ordering::Relaxed),
        }
    }
}

impl Default for MvccStatsTracker {
    fn default() -> Self {
        Self::new()
    }
}

/// Trait for trie root types that can be used with MVCC.
pub trait TrieRoot: Send + Sync + 'static {
    /// The key type for this trie (u8 or u32).
    type Key: Copy;

    /// The value type held at final nodes (`u64` for counter/index tries, `()`
    /// for membership tries, or an arbitrary `V` once the overlay is generic).
    type Value;

    /// Check if this node is a final node (end of a word).
    fn is_final(&self) -> bool;

    /// Find a child by key.
    fn find_child(&self, key: Self::Key) -> Option<Arc<Self>>;

    /// Get the value if this is a final node.
    fn get_value(&self) -> Option<Self::Value>;
}

/// A read transaction for MVCC-lite snapshot isolation.
///
/// This struct pins a version of the trie and allows consistent reads from that
/// version. Concurrent writes are not visible to this transaction.
///
/// # Lifetime
///
/// The transaction is active from creation until drop. While active:
/// - The pinned version is protected from garbage collection
/// - All reads see the state at transaction start time
/// - No blocking occurs (all operations are lock-free)
///
/// # Thread Safety
///
/// `ReadTransaction` is `Send` but not `Sync` — it can be moved between threads
/// but should not be shared. Each thread should have its own transaction.
#[derive(Debug)]
pub struct ReadTransaction<T: TrieRoot> {
    /// The pinned root node for this transaction's version
    root: Option<Arc<T>>,
    /// Version ID captured at transaction start
    version_id: u64,
    /// Epoch captured at transaction start (for GC protection)
    epoch: u64,
    /// Reference to the epoch manager (for cleanup on drop)
    epoch_manager: Arc<EpochManager>,
    /// Statistics tracker
    stats: Option<Arc<MvccStatsTracker>>,
}

impl<T: TrieRoot> ReadTransaction<T> {
    /// Begin a new read transaction.
    pub fn begin(root: Arc<T>, epoch_manager: Arc<EpochManager>) -> Self {
        let epoch = epoch_manager.enter_read();
        let version_id = epoch_manager.current_epoch();

        Self {
            root: Some(root),
            version_id,
            epoch,
            epoch_manager,
            stats: None,
        }
    }

    /// Begin a transaction with statistics tracking.
    pub fn begin_with_stats(
        root: Arc<T>,
        epoch_manager: Arc<EpochManager>,
        stats: Arc<MvccStatsTracker>,
    ) -> Self {
        let epoch = epoch_manager.enter_read();
        let version_id = epoch_manager.current_epoch();
        stats.record_start();

        Self {
            root: Some(root),
            version_id,
            epoch,
            epoch_manager,
            stats: Some(stats),
        }
    }

    /// Get the version ID of this transaction.
    #[inline]
    pub fn version_id(&self) -> u64 {
        self.version_id
    }

    /// Get the epoch of this transaction.
    #[inline]
    pub fn epoch(&self) -> u64 {
        self.epoch
    }

    /// Get a reference to the pinned root node.
    #[inline]
    pub fn root(&self) -> Option<&Arc<T>> {
        self.root.as_ref()
    }
}

impl<T: TrieRoot<Key = u8>> ReadTransaction<T> {
    /// Check if a byte term exists in the pinned version.
    pub fn contains(&self, term: &[u8]) -> bool {
        if let Some(stats) = &self.stats {
            stats.record_read();
        }

        let Some(root) = &self.root else {
            return false;
        };

        let mut current = Arc::clone(root);
        for &key in term {
            match current.find_child(key) {
                Some(child) => current = child,
                None => return false,
            }
        }

        current.is_final()
    }

    /// Get the value for a byte term in the pinned version.
    pub fn get(&self, term: &[u8]) -> Option<T::Value> {
        if let Some(stats) = &self.stats {
            stats.record_read();
        }

        let root = self.root.as_ref()?;

        let mut current = Arc::clone(root);
        for &key in term {
            match current.find_child(key) {
                Some(child) => current = child,
                None => return None,
            }
        }

        if current.is_final() {
            current.get_value()
        } else {
            None
        }
    }
}

impl<T: TrieRoot<Key = u32>> ReadTransaction<T> {
    /// Check if a string term exists in the pinned version.
    pub fn contains_str(&self, term: &str) -> bool {
        if let Some(stats) = &self.stats {
            stats.record_read();
        }

        let Some(root) = &self.root else {
            return false;
        };

        let mut current = Arc::clone(root);
        for c in term.chars() {
            match current.find_child(c as u32) {
                Some(child) => current = child,
                None => return false,
            }
        }

        current.is_final()
    }

    /// Get the value for a string term in the pinned version.
    pub fn get_str(&self, term: &str) -> Option<T::Value> {
        if let Some(stats) = &self.stats {
            stats.record_read();
        }

        let root = self.root.as_ref()?;

        let mut current = Arc::clone(root);
        for c in term.chars() {
            match current.find_child(c as u32) {
                Some(child) => current = child,
                None => return None,
            }
        }

        if current.is_final() {
            current.get_value()
        } else {
            None
        }
    }
}

impl<T: TrieRoot> Drop for ReadTransaction<T> {
    fn drop(&mut self) {
        // Release the epoch guard
        self.epoch_manager.exit_read();

        // Release the root reference
        self.root = None;

        // Update statistics
        if let Some(stats) = &self.stats {
            stats.record_complete();
        }
    }
}

// Safety: ReadTransaction can be sent between threads
unsafe impl<T: TrieRoot> Send for ReadTransaction<T> {}

/// A lightweight read guard that doesn't pin a specific root.
///
/// This is useful when you want to protect an epoch without having a root yet,
/// or when you're doing lookups that go through a separate cache.
#[derive(Debug)]
pub struct EpochGuard {
    epoch: u64,
    epoch_manager: Arc<EpochManager>,
}

impl EpochGuard {
    /// Create a new epoch guard.
    pub fn new(epoch_manager: Arc<EpochManager>) -> Self {
        let epoch = epoch_manager.enter_read();
        Self {
            epoch,
            epoch_manager,
        }
    }

    /// Get the epoch of this guard.
    #[inline]
    pub fn epoch(&self) -> u64 {
        self.epoch
    }
}

impl Drop for EpochGuard {
    fn drop(&mut self) {
        self.epoch_manager.exit_read();
    }
}

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

    // Generic test implementation of TrieRoot (no variant deps).
    #[derive(Debug)]
    struct TestNode {
        is_final: bool,
        value: Option<u64>,
        children: std::collections::HashMap<u8, Arc<TestNode>>,
    }

    impl TestNode {
        fn new() -> Self {
            Self {
                is_final: false,
                value: None,
                children: std::collections::HashMap::new(),
            }
        }

        fn with_final(mut self) -> Self {
            self.is_final = true;
            self
        }

        fn with_value(mut self, value: u64) -> Self {
            self.value = Some(value);
            self
        }

        fn with_child(mut self, key: u8, child: TestNode) -> Self {
            self.children.insert(key, Arc::new(child));
            self
        }
    }

    impl TrieRoot for TestNode {
        type Key = u8;
        type Value = u64;

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

        fn find_child(&self, key: u8) -> Option<Arc<Self>> {
            self.children.get(&key).cloned()
        }

        fn get_value(&self) -> Option<u64> {
            self.value
        }
    }

    #[test]
    fn test_read_transaction_basic() {
        let epoch_manager = Arc::new(EpochManager::new());

        let leaf = TestNode::new().with_final().with_value(42);
        let mid = TestNode::new().with_child(b'b', leaf);
        let root = Arc::new(TestNode::new().with_child(b'a', mid));

        let tx = ReadTransaction::begin(root, epoch_manager);

        assert!(tx.contains(b"ab"));
        assert!(!tx.contains(b"a"));
        assert!(!tx.contains(b"abc"));
        assert!(!tx.contains(b""));

        assert_eq!(tx.get(b"ab"), Some(42));
        assert_eq!(tx.get(b"a"), None);
    }

    #[test]
    fn test_read_transaction_stats() {
        let epoch_manager = Arc::new(EpochManager::new());
        let stats = Arc::new(MvccStatsTracker::new());

        let leaf = TestNode::new().with_final();
        let root = Arc::new(TestNode::new().with_child(b'a', leaf));

        {
            let tx = ReadTransaction::begin_with_stats(
                root.clone(),
                epoch_manager.clone(),
                stats.clone(),
            );

            tx.contains(b"a");
            tx.contains(b"b");

            let current_stats = stats.stats();
            assert_eq!(current_stats.transactions_started, 1);
            assert_eq!(current_stats.active_transactions, 1);
            assert_eq!(current_stats.total_reads, 2);
        }

        // After drop
        let final_stats = stats.stats();
        assert_eq!(final_stats.transactions_completed, 1);
        assert_eq!(final_stats.active_transactions, 0);
    }

    #[test]
    fn test_epoch_guard() {
        let epoch_manager = Arc::new(EpochManager::new());

        assert!(!epoch_manager.has_active_readers());

        {
            let _guard = EpochGuard::new(epoch_manager.clone());
            assert!(epoch_manager.has_active_readers());
        }

        assert!(!epoch_manager.has_active_readers());
    }

    #[test]
    fn test_version_id_and_epoch() {
        let epoch_manager = Arc::new(EpochManager::new());
        let root = Arc::new(TestNode::new());

        epoch_manager.advance();
        epoch_manager.advance();

        let tx = ReadTransaction::begin(root, epoch_manager.clone());

        assert!(tx.version_id() >= 2);
        assert!(tx.epoch() >= 2);
    }
}