liblevenshtein 0.9.1

Levenshtein/Universal Automata for approximate string matching using various dictionary backends
Documentation
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
//! Cost-aware eviction wrapper.
//!
//! This wrapper tracks age, size, and hit counts to make cost-based eviction
//! decisions. It balances regeneration cost against cache space.
//!
//! # Architecture
//!
//! Unlike the old `CostAwareStrategy` which required `CacheEntry<V>` metadata,
//! this wrapper maintains separate metadata tracking age, size, and hits.
//!
//! # Use Cases
//!
//! - AI code chat: Keep expensive LLM responses cached longer
//! - Documentation search: Evict large, rarely-hit results
//! - Error solutions: Balance between recomputation cost and cache space
//!
//! # Examples
//!
//! ```rust,ignore
//! use liblevenshtein::prelude::*;
//! use liblevenshtein::dictionary::MappedDictionary;
//! use liblevenshtein::cache::eviction::CostAware;
//!
//! let dict = PathMapDictionary::from_terms_with_values([
//!     ("foo", 42),
//!     ("bar", 99),
//! ]);
//!
//! let cost_aware = CostAware::new(dict);
//! assert_eq!(cost_aware.get_value("foo"), Some(42));
//! ```

use libdictenstein::{
    Dictionary, DictionaryNode, DictionaryValue, MappedDictionary, MappedDictionaryNode,
    SyncStrategy,
};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::Instant;

/// Metadata tracked for each entry.
#[derive(Debug, Clone)]
struct EntryMetadata {
    inserted_at: Instant,
    hit_count: u32,
    size_bytes: usize,
}

impl EntryMetadata {
    fn new(size: usize) -> Self {
        Self {
            inserted_at: Instant::now(),
            hit_count: 1, // First access
            size_bytes: size,
        }
    }

    fn increment(&mut self) {
        self.hit_count = self.hit_count.saturating_add(1);
    }

    fn age(&self) -> std::time::Duration {
        self.inserted_at.elapsed()
    }

    /// Cost-aware score: (age * size) / (hits + 1)
    /// Higher score = more likely to evict
    fn cost_score(&self) -> f64 {
        let age = self.age().as_secs_f64();
        let size = self.size_bytes as f64;
        let hits = self.hit_count as f64;
        (age * size) / (hits + 1.0)
    }
}

/// Cost-aware eviction wrapper.
///
/// Evicts entries based on cost-to-value ratio. Entries with high age,
/// large size, and low hit count are evicted first.
///
/// # Type Parameters
///
/// - `D`: Inner dictionary type
///
/// # Examples
///
/// ```rust,ignore
/// use liblevenshtein::prelude::*;
/// use liblevenshtein::dictionary::MappedDictionary;
/// use liblevenshtein::cache::eviction::CostAware;
///
/// let dict = PathMapDictionary::from_terms_with_values([
///     ("hello", 1),
///     ("world", 2),
/// ]);
///
/// let cost_aware = CostAware::new(dict);
/// assert_eq!(cost_aware.get_value("hello"), Some(1));
/// ```
#[derive(Clone)]
pub struct CostAware<D> {
    inner: D,
    metadata: Arc<RwLock<HashMap<String, EntryMetadata>>>,
}

impl<D> CostAware<D> {
    /// Creates a new CostAware wrapper.
    ///
    /// # Arguments
    ///
    /// - `dict`: The dictionary to wrap
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use liblevenshtein::prelude::*;
    /// use liblevenshtein::cache::eviction::CostAware;
    ///
    /// let dict = PathMapDictionary::from_terms_with_values([
    ///     ("foo", 42),
    /// ]);
    ///
    /// let cost_aware = CostAware::new(dict);
    /// ```
    pub fn new(dict: D) -> Self {
        Self {
            inner: dict,
            metadata: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Unwraps the inner dictionary.
    #[inline]
    pub fn into_inner(self) -> D {
        self.inner
    }

    /// Gets a reference to the inner dictionary.
    #[inline]
    pub fn inner(&self) -> &D {
        &self.inner
    }

    /// Records an entry access with size tracking.
    fn record_access<V: DictionaryValue>(&self, term: &str, _value: &V) {
        let size = std::mem::size_of::<V>();
        let mut metadata = self
            .metadata
            .write()
            .expect("poisoned RwLock; only fatal if writer panicked");
        metadata
            .entry(term.to_string())
            .and_modify(|m| m.increment())
            .or_insert_with(|| EntryMetadata::new(size));
    }

    /// Gets the cost score for an entry.
    ///
    /// Returns `None` if the entry has never been accessed.
    pub fn cost_score(&self, term: &str) -> Option<f64> {
        let metadata = self
            .metadata
            .read()
            .expect("poisoned RwLock; only fatal if writer panicked");
        metadata.get(term).map(|m| m.cost_score())
    }

    /// Finds the highest cost entry among the given terms.
    ///
    /// Returns the term with the highest cost score (most likely to evict).
    pub fn find_highest_cost(&self, terms: &[&str]) -> Option<String> {
        let metadata = self
            .metadata
            .read()
            .expect("poisoned RwLock; only fatal if writer panicked");
        terms
            .iter()
            .filter_map(|&term| metadata.get(term).map(|m| (term, m.cost_score())))
            .max_by(|(_, score1), (_, score2)| {
                score1
                    .partial_cmp(score2)
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
            .map(|(term, _)| term.to_string())
    }

    /// Evicts the highest cost entry from metadata.
    ///
    /// Returns the evicted term if any.
    pub fn evict_highest_cost(&self, terms: &[&str]) -> Option<String> {
        if let Some(high_cost_term) = self.find_highest_cost(terms) {
            let mut metadata = self
                .metadata
                .write()
                .expect("poisoned RwLock; only fatal if writer panicked");
            metadata.remove(&high_cost_term);
            Some(high_cost_term)
        } else {
            None
        }
    }

    /// Clears all metadata.
    pub fn clear_metadata(&self) {
        let mut metadata = self
            .metadata
            .write()
            .expect("poisoned RwLock; only fatal if writer panicked");
        metadata.clear();
    }
}

impl<D> Dictionary for CostAware<D>
where
    D: Dictionary,
{
    type Node = CostAwareNode<D::Node>;

    #[inline]
    fn root(&self) -> Self::Node {
        CostAwareNode::new(self.inner.root(), Arc::clone(&self.metadata))
    }

    #[inline]
    fn len(&self) -> Option<usize> {
        self.inner.len()
    }

    #[inline]
    fn contains(&self, term: &str) -> bool {
        self.inner.contains(term)
    }

    #[inline]
    fn sync_strategy(&self) -> SyncStrategy {
        self.inner.sync_strategy()
    }
}

impl<D, V> MappedDictionary for CostAware<D>
where
    D: MappedDictionary<Value = V>,
    V: DictionaryValue,
{
    type Value = V;

    #[inline]
    fn get_value(&self, term: &str) -> Option<Self::Value> {
        // Get value from inner dictionary first
        let value = self.inner.get_value(term)?;

        // Record access with value for size tracking
        self.record_access(term, &value);

        Some(value)
    }

    #[inline]
    fn contains_with_value<F>(&self, term: &str, predicate: F) -> bool
    where
        F: Fn(&Self::Value) -> bool,
    {
        self.inner.contains_with_value(term, predicate)
    }
}

/// Node wrapper for CostAware dictionary.
#[derive(Clone)]
pub struct CostAwareNode<N> {
    inner: N,
    metadata: Arc<RwLock<HashMap<String, EntryMetadata>>>,
}

impl<N> CostAwareNode<N> {
    fn new(inner: N, metadata: Arc<RwLock<HashMap<String, EntryMetadata>>>) -> Self {
        Self { inner, metadata }
    }
}

impl<N> DictionaryNode for CostAwareNode<N>
where
    N: DictionaryNode,
{
    type Unit = N::Unit;

    #[inline]
    fn is_final(&self) -> bool {
        self.inner.is_final()
    }

    #[inline]
    fn transition(&self, label: Self::Unit) -> Option<Self> {
        self.inner
            .transition(label)
            .map(|node| CostAwareNode::new(node, Arc::clone(&self.metadata)))
    }

    #[inline]
    fn edges(&self) -> Box<dyn Iterator<Item = (Self::Unit, Self)> + '_> {
        let metadata = Arc::clone(&self.metadata);
        Box::new(
            self.inner
                .edges()
                .map(move |(label, node)| (label, CostAwareNode::new(node, Arc::clone(&metadata)))),
        )
    }

    #[inline]
    fn edge_count(&self) -> Option<usize> {
        self.inner.edge_count()
    }
}

impl<N, V> MappedDictionaryNode for CostAwareNode<N>
where
    N: MappedDictionaryNode<Value = V>,
    V: DictionaryValue,
{
    type Value = V;

    #[inline]
    fn value(&self) -> Option<Self::Value> {
        self.inner.value()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(feature = "pathmap-backend")]
    use libdictenstein::pathmap::PathMapDictionary;
    use std::thread;
    use std::time::Duration;

    #[test]
    #[cfg(feature = "pathmap-backend")]
    fn test_cost_aware_wrapper_basic() {
        let dict = PathMapDictionary::from_terms_with_values([("foo", 42), ("bar", 99)]);

        let cost_aware = CostAware::new(dict);

        // Values should be accessible
        assert_eq!(cost_aware.get_value("foo"), Some(42));
        assert_eq!(cost_aware.get_value("bar"), Some(99));
        assert!(cost_aware.contains("foo"));
    }

    #[test]
    #[cfg(feature = "pathmap-backend")]
    fn test_cost_aware_scoring() {
        let dict = PathMapDictionary::from_terms_with_values([("foo", 42), ("bar", 99)]);

        let cost_aware = CostAware::new(dict);

        // Access foo once
        assert_eq!(cost_aware.get_value("foo"), Some(42));
        let score1 = cost_aware
            .cost_score("foo")
            .expect("expected Some score in test");

        // Wait to increase age
        thread::sleep(Duration::from_millis(10));

        // Score should increase with age
        let score2 = cost_aware
            .cost_score("foo")
            .expect("expected Some score in test");
        assert!(score2 > score1);
    }

    #[test]
    #[cfg(feature = "pathmap-backend")]
    fn test_cost_aware_hits_lower_score() {
        let dict = PathMapDictionary::from_terms_with_values([("foo", 42)]);

        let cost_aware = CostAware::new(dict);

        // First access
        assert_eq!(cost_aware.get_value("foo"), Some(42));
        thread::sleep(Duration::from_millis(10));
        let score1 = cost_aware
            .cost_score("foo")
            .expect("expected Some score in test");

        // Multiple additional accesses
        for _ in 0..5 {
            assert_eq!(cost_aware.get_value("foo"), Some(42));
        }

        // More hits should lower the cost score (despite increased age)
        let score2 = cost_aware
            .cost_score("foo")
            .expect("expected Some score in test");
        assert!(score2 < score1);
    }

    #[test]
    #[cfg(feature = "pathmap-backend")]
    fn test_cost_aware_find_highest_cost() {
        let dict =
            PathMapDictionary::from_terms_with_values([("foo", 42), ("bar", 99), ("baz", 123)]);

        let cost_aware = CostAware::new(dict);

        // Access with different patterns
        // foo: 1 access, oldest
        assert_eq!(cost_aware.get_value("foo"), Some(42));
        thread::sleep(Duration::from_millis(10));

        // bar: 3 accesses, middle age
        assert_eq!(cost_aware.get_value("bar"), Some(99));
        assert_eq!(cost_aware.get_value("bar"), Some(99));
        assert_eq!(cost_aware.get_value("bar"), Some(99));
        thread::sleep(Duration::from_millis(10));

        // baz: 5 accesses, newest
        for _ in 0..5 {
            assert_eq!(cost_aware.get_value("baz"), Some(123));
        }

        // foo should have highest cost (oldest, fewest hits)
        let highest = cost_aware.find_highest_cost(&["foo", "bar", "baz"]);
        assert_eq!(highest, Some("foo".to_string()));
    }

    #[test]
    #[cfg(feature = "pathmap-backend")]
    fn test_cost_aware_eviction() {
        let dict = PathMapDictionary::from_terms_with_values([("foo", 42), ("bar", 99)]);

        let cost_aware = CostAware::new(dict);

        // Access both
        assert_eq!(cost_aware.get_value("foo"), Some(42));
        assert_eq!(cost_aware.get_value("bar"), Some(99));

        // Evict highest cost
        let evicted = cost_aware.evict_highest_cost(&["foo", "bar"]);
        assert!(evicted.is_some());

        // Evicted term should have no metadata
        assert_eq!(
            cost_aware.cost_score(&evicted.expect("expected Some evicted in test")),
            None
        );
    }

    #[test]
    #[cfg(feature = "pathmap-backend")]
    fn test_cost_aware_clear_metadata() {
        let dict = PathMapDictionary::from_terms_with_values([("foo", 42), ("bar", 99)]);

        let cost_aware = CostAware::new(dict);

        // Access both
        assert_eq!(cost_aware.get_value("foo"), Some(42));
        assert_eq!(cost_aware.get_value("bar"), Some(99));

        // Clear metadata
        cost_aware.clear_metadata();

        // No cost scores
        assert_eq!(cost_aware.cost_score("foo"), None);
        assert_eq!(cost_aware.cost_score("bar"), None);
    }

    #[test]
    #[cfg(feature = "pathmap-backend")]
    fn test_cost_aware_node_traversal() {
        let dict = PathMapDictionary::<()>::from_terms(["hello", "help"]);
        let cost_aware = CostAware::new(dict);

        let root = cost_aware.root();
        assert!(!root.is_final());

        // Traverse 'h' -> 'e' -> 'l' -> 'p'
        let h = root
            .transition(b'h')
            .expect("expected Some transition h in test");
        let e = h
            .transition(b'e')
            .expect("expected Some transition e in test");
        let l = e
            .transition(b'l')
            .expect("expected Some transition l in test");
        let p = l
            .transition(b'p')
            .expect("expected Some transition p in test");

        assert!(p.is_final()); // "help"
    }

    #[test]
    #[cfg(feature = "pathmap-backend")]
    fn test_cost_aware_into_inner() {
        let dict = PathMapDictionary::from_terms_with_values([("foo", 42)]);
        let cost_aware = CostAware::new(dict);
        let original = cost_aware.into_inner();

        assert_eq!(original.len(), Some(1));
        assert_eq!(original.get_value("foo"), Some(42));
    }
}