Skip to main content

waratah_compute/
resolve_cache.rs

1//! Compute-wide LRU cache of registry-resolved strings.
2//!
3//! Sits between the per-query string cache and the registry inside
4//! [`crate::query::QueryEngine::resolve`]: a hit skips the registry round
5//! trip entirely, so repeat queries — and cross-query string overlap — stop
6//! touching the storage node. Entries cannot go stale: `StrHash` is a content
7//! hash and registry strings are never rewritten, so eviction is a memory
8//! decision, not an invalidation. Unregistered hashes (`None` from the
9//! registry) are deliberately not cached, so a later import stays visible.
10
11use std::fmt;
12use std::num::NonZeroUsize;
13use std::sync::atomic::{AtomicU64, Ordering};
14use std::sync::{Arc, Mutex};
15
16use lru::LruCache;
17use waratah_storage::{StrHash, StrHashIdentityBuildHasher, StrHashMap, new_str_hash_map};
18
19/// Default entry capacity (`WARATAH_RESOLVE_CACHE_ENTRIES` overrides; `0`
20/// disables the cache). At ~100–150 bytes per typical IRI entry this bounds
21/// the cache at roughly 30–60 MiB of payload plus map overhead.
22pub const DEFAULT_RESOLVE_CACHE_ENTRIES: usize = 240_000;
23/// Summed string-length budget for cached entries (bytes).
24///
25/// The entry capacity alone is unbounded in bytes — the registry accepts
26/// strings up to 1 MiB, so 240k entries could legally be hundreds of GiB.
27/// Insertion evicts least-recently-used entries until the summed string
28/// length fits this budget.
29pub const DEFAULT_RESOLVE_CACHE_BYTE_BUDGET: usize = 256 * 1024 * 1024;
30const ENTRIES_ENV: &str = "WARATAH_RESOLVE_CACHE_ENTRIES";
31
32struct Shared {
33    cache: LruCache<StrHash, String, StrHashIdentityBuildHasher>,
34    /// Summed `String::len()` of cached entries (byte-budget accounting).
35    bytes: usize,
36    byte_budget: usize,
37}
38
39/// Process-lifetime LRU of `StrHash` → resolved string, shared by all queries
40/// on a compute node.
41///
42/// Uses [`StrHashIdentityBuildHasher`] — bucket selection is the hash's upper
43/// 64 bits, no second SipHash — and enforces two budgets: [`Self::insert`]
44/// evicts least-recently-used entries until both the entry count (enforced by
45/// the LRU itself) and the byte budget hold. Cumulative hit/miss counters are
46/// reported in the `phases:` debug line.
47pub struct ResolveCache {
48    inner: Mutex<Shared>,
49    capacity_entries: usize,
50    hits: AtomicU64,
51    misses: AtomicU64,
52}
53
54impl ResolveCache {
55    /// Engine-wide cache with the env-tunable entry capacity
56    /// (`WARATAH_RESOLVE_CACHE_ENTRIES`, KiB-style plain count; `0` disables)
57    /// and the default byte budget.
58    pub fn from_env() -> Arc<Self> {
59        let entries = match std::env::var(ENTRIES_ENV) {
60            Ok(raw) => raw.trim().parse::<usize>().unwrap_or_else(|_| {
61                eprintln!(
62                    "waratah-compute: ignoring invalid {ENTRIES_ENV} {raw:?} \
63                     (expected an entry count); using {DEFAULT_RESOLVE_CACHE_ENTRIES}"
64                );
65                DEFAULT_RESOLVE_CACHE_ENTRIES
66            }),
67            Err(_) => DEFAULT_RESOLVE_CACHE_ENTRIES,
68        };
69        Arc::new(Self::new(entries, DEFAULT_RESOLVE_CACHE_BYTE_BUDGET))
70    }
71
72    /// Cache holding at most `capacity_entries` strings and `byte_budget`
73    /// summed string bytes. `capacity_entries == 0` disables the cache:
74    /// every lookup misses and inserts are dropped.
75    pub fn new(capacity_entries: usize, byte_budget: usize) -> Self {
76        // Capacity 0 still constructs an (unbounded, never inserted into)
77        // cache so the type stays uniform; every method gates on capacity.
78        let cache = match NonZeroUsize::new(capacity_entries) {
79            Some(cap) => LruCache::with_hasher(cap, StrHashIdentityBuildHasher),
80            None => LruCache::unbounded_with_hasher(StrHashIdentityBuildHasher),
81        };
82        Self {
83            inner: Mutex::new(Shared {
84                cache,
85                bytes: 0,
86                byte_budget,
87            }),
88            capacity_entries,
89            hits: AtomicU64::new(0),
90            misses: AtomicU64::new(0),
91        }
92    }
93
94    /// Probe `hashes`; returns cache hits as a map plus the ordered miss list
95    /// (order-preserving, so registry-bound batches keep their sorted walk).
96    /// Hits refresh their LRU recency; both counters accumulate.
97    pub fn probe(&self, hashes: &[StrHash]) -> (StrHashMap, Vec<StrHash>) {
98        let mut hits = new_str_hash_map();
99        let mut misses = Vec::new();
100        if self.capacity_entries == 0 {
101            misses.extend_from_slice(hashes);
102            self.misses
103                .fetch_add(hashes.len() as u64, Ordering::Relaxed);
104            return (hits, misses);
105        }
106        {
107            let mut inner = self.inner.lock().expect("resolve cache mutex poisoned");
108            for hash in hashes {
109                match inner.cache.get(hash) {
110                    Some(raw) => {
111                        hits.insert(*hash, raw.clone());
112                    }
113                    None => misses.push(*hash),
114                }
115            }
116        }
117        self.hits.fetch_add(hits.len() as u64, Ordering::Relaxed);
118        self.misses
119            .fetch_add(misses.len() as u64, Ordering::Relaxed);
120        (hits, misses)
121    }
122
123    /// Insert resolved strings, evicting least-recently-used entries until
124    /// the byte budget holds. Unregistered hashes (`None` from the registry)
125    /// are skipped by the caller.
126    pub fn insert(&self, pairs: impl IntoIterator<Item = (StrHash, String)>) {
127        if self.capacity_entries == 0 {
128            return;
129        }
130        let mut inner = self.inner.lock().expect("resolve cache mutex poisoned");
131        for (hash, raw) in pairs {
132            inner.bytes = inner.bytes.saturating_add(raw.len());
133            inner.cache.put(hash, raw);
134        }
135        while inner.bytes > inner.byte_budget {
136            match inner.cache.pop_lru() {
137                Some((_, evicted)) => inner.bytes = inner.bytes.saturating_sub(evicted.len()),
138                None => break,
139            }
140        }
141    }
142
143    /// Cumulative (hits, misses) since process start.
144    pub fn stats(&self) -> (u64, u64) {
145        (
146            self.hits.load(Ordering::Relaxed),
147            self.misses.load(Ordering::Relaxed),
148        )
149    }
150}
151
152impl fmt::Debug for ResolveCache {
153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        let (hits, misses) = self.stats();
155        f.debug_struct("ResolveCache")
156            .field("capacity_entries", &self.capacity_entries)
157            .field("hits", &hits)
158            .field("misses", &misses)
159            .finish_non_exhaustive()
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166
167    fn h(value: &str) -> StrHash {
168        StrHash::new(value)
169    }
170
171    #[test]
172    fn hit_refreshes_recency_and_evicts_lru_first() {
173        let cache = ResolveCache::new(2, usize::MAX);
174        cache.insert([(h("a"), "A".into()), (h("b"), "B".into())]);
175        // Touch `a` so `b` becomes least-recently-used.
176        cache.probe(&[h("a")]);
177        cache.insert([(h("c"), "C".into())]);
178        let (hits, misses) = cache.probe(&[h("a"), h("b"), h("c")]);
179        assert_eq!(hits.len(), 2, "a and c must survive, b was evicted");
180        assert!(hits.contains_key(&h("a")));
181        assert!(hits.contains_key(&h("c")));
182        assert_eq!(misses, vec![h("b")]);
183    }
184
185    #[test]
186    fn byte_budget_evicts_until_under_the_cap() {
187        // Two entries of 4 KiB each exceed the 6 KiB budget; the oldest goes.
188        let cache = ResolveCache::new(16, 6 * 1024);
189        cache.insert([
190            (h("big1"), "x".repeat(4 * 1024)),
191            (h("big2"), "y".repeat(4 * 1024)),
192        ]);
193        let (hits, _) = cache.probe(&[h("big1"), h("big2")]);
194        assert_eq!(hits.len(), 1, "byte budget must have evicted one entry");
195    }
196
197    #[test]
198    fn entry_capacity_is_enforced_by_the_lru() {
199        let cache = ResolveCache::new(2, usize::MAX);
200        cache.insert([
201            (h("a"), "A".into()),
202            (h("b"), "B".into()),
203            (h("c"), "C".into()),
204        ]);
205        let (hits, misses) = cache.probe(&[h("a"), h("b"), h("c")]);
206        assert_eq!(hits.len(), 2);
207        assert_eq!(misses.len(), 1);
208    }
209
210    #[test]
211    fn disabled_cache_misses_everything_and_ignores_inserts() {
212        let cache = ResolveCache::new(0, 1024);
213        cache.insert([(h("a"), "A".into())]);
214        let (hits, misses) = cache.probe(&[h("a")]);
215        assert!(hits.is_empty());
216        assert_eq!(misses, vec![h("a")]);
217    }
218
219    #[test]
220    fn probe_preserves_miss_order() {
221        let cache = ResolveCache::new(16, usize::MAX);
222        cache.insert([(h("known"), "K".into())]);
223        let ordered: Vec<StrHash> = [h("z"), h("known"), h("a")].into_iter().collect();
224        let (_, misses) = cache.probe(&ordered);
225        assert_eq!(misses, vec![h("z"), h("a")]);
226    }
227
228    #[test]
229    fn stats_accumulate() {
230        let cache = ResolveCache::new(16, usize::MAX);
231        cache.insert([(h("a"), "A".into())]);
232        let _ = cache.probe(&[h("a"), h("b")]);
233        assert_eq!(cache.stats(), (1, 1));
234    }
235}