Skip to main content

hawdb_plan_cache/
lib.rs

1// Copyright 2026 Nowledge
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::HashMap;
16use std::hash::Hash;
17
18mod binding_cache;
19mod schema;
20mod template;
21
22#[doc(hidden)]
23pub use binding_cache::{
24    ParameterBindingAdmission, ParameterBindingCache, ParameterBindingCacheConfig,
25};
26#[doc(hidden)]
27pub use schema::OptimizerSchemaKey;
28
29pub use template::{
30    bind_physical_plan_parameters, parameter_binding_shape_fingerprint, parameter_scalar_types,
31    parameterize_logical_plan, parameterize_value_list, resolve_plan_template_value,
32    ParameterBindingTemplate, ParameterizedLogicalPlan, PlanParameterCacheKey,
33};
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum PlanCacheLookup {
37    Hit,
38    Miss,
39    Bypass(PlanCacheBypassReason),
40}
41
42impl PlanCacheLookup {
43    pub const fn as_str(self) -> &'static str {
44        match self {
45            Self::Hit => "hit",
46            Self::Miss => "miss",
47            Self::Bypass(_) => "bypass",
48        }
49    }
50
51    pub const fn bypass_reason(self) -> Option<PlanCacheBypassReason> {
52        match self {
53            Self::Bypass(reason) => Some(reason),
54            Self::Hit | Self::Miss => None,
55        }
56    }
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum PlanCacheBypassReason {
61    MutationPlanning,
62    OptimizerDirective,
63    StatementNotCacheable,
64    ParameterizedCaseTemplate,
65}
66
67impl PlanCacheBypassReason {
68    pub const fn as_str(self) -> &'static str {
69        match self {
70            Self::MutationPlanning => "mutation_planning",
71            Self::OptimizerDirective => "optimizer_directive",
72            Self::StatementNotCacheable => "statement_not_cacheable",
73            Self::ParameterizedCaseTemplate => "parameterized_case_template",
74        }
75    }
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct PlanCacheStats {
80    pub max_entries: Option<usize>,
81    pub entries: usize,
82    pub hits: u64,
83    pub misses: u64,
84    pub admissions: u64,
85    pub disabled_misses: u64,
86    pub bypasses: u64,
87    pub evictions: u64,
88    pub memory_pressure_events: u64,
89}
90
91#[derive(Debug, Clone, PartialEq)]
92struct LfuCacheEntry<V> {
93    value: V,
94    frequency: u64,
95    last_access_tick: u64,
96    heap_charge: usize,
97}
98
99#[derive(Debug, Clone)]
100pub struct LfuCache<K, V> {
101    max_entries: Option<usize>,
102    max_bytes: Option<usize>,
103    entry_heap_charge: usize,
104    table_capacity_high_water: usize,
105    entries: HashMap<K, LfuCacheEntry<V>>,
106    access_tick: u64,
107    hits: u64,
108    misses: u64,
109    admissions: u64,
110    disabled_misses: u64,
111    bypasses: u64,
112    evictions: u64,
113    memory_pressure_events: u64,
114}
115
116impl<K, V> LfuCache<K, V>
117where
118    K: Eq + Hash + Ord + Clone,
119    V: Clone,
120{
121    pub fn new(max_entries: Option<usize>) -> Self {
122        Self::with_byte_limit(max_entries, None)
123    }
124
125    /// A byte-limited cache requires `insert_weighted` with conservative heap
126    /// charges for both key and value. Table storage is charged separately.
127    pub fn with_byte_limit(max_entries: Option<usize>, max_bytes: Option<usize>) -> Self {
128        Self {
129            max_entries,
130            max_bytes,
131            entry_heap_charge: 0,
132            table_capacity_high_water: 0,
133            entries: HashMap::new(),
134            access_tick: 0,
135            hits: 0,
136            misses: 0,
137            admissions: 0,
138            disabled_misses: 0,
139            bypasses: 0,
140            evictions: 0,
141            memory_pressure_events: 0,
142        }
143    }
144
145    pub fn get(&mut self, key: &K) -> Option<V> {
146        if self.max_entries == Some(0) || self.max_bytes == Some(0) {
147            self.misses += 1;
148            self.disabled_misses += 1;
149            return None;
150        }
151        self.access_tick = self.access_tick.saturating_add(1);
152        let Some(entry) = self.entries.get_mut(key) else {
153            self.misses += 1;
154            return None;
155        };
156        self.hits += 1;
157        entry.frequency = entry.frequency.saturating_add(1);
158        entry.last_access_tick = self.access_tick;
159        Some(entry.value.clone())
160    }
161
162    pub fn record_bypass(&mut self) {
163        self.bypasses = self.bypasses.saturating_add(1);
164    }
165
166    /// Legacy count-only admission. Byte-limited caches refuse this path so
167    /// callers cannot accidentally retain an uncharged key/value payload.
168    pub fn insert(&mut self, key: K, value: V) {
169        if self.max_bytes.is_none() {
170            self.insert_weighted(key, value, 0);
171        }
172    }
173
174    /// Charge owned heap retained through the key/value, excluding their inline
175    /// bucket layout. Rejected admissions leave an existing entry unchanged.
176    /// In-flight cloned values are owned by callers, outside this cache bound.
177    pub fn insert_weighted(&mut self, key: K, value: V, heap_charge: usize) {
178        if self.max_entries == Some(0)
179            || self
180                .max_bytes
181                .is_some_and(|limit| limit == 0 || heap_charge > limit)
182        {
183            return;
184        }
185        let previous = self.entries.get(&key).map_or(0, |entry| entry.heap_charge);
186        let Some(total) = self
187            .entry_heap_charge
188            .checked_sub(previous)
189            .and_then(|bytes| bytes.checked_add(heap_charge))
190        else {
191            return;
192        };
193        self.entry_heap_charge = total;
194        self.access_tick = self.access_tick.saturating_add(1);
195        // Replace the key too: an equal old key may retain more spare heap
196        // capacity than the incoming key whose charge the caller supplied.
197        let frequency = self
198            .entries
199            .remove(&key)
200            .map_or(1, |entry| entry.frequency.saturating_add(1));
201        self.entries.insert(
202            key,
203            LfuCacheEntry {
204                value,
205                heap_charge,
206                frequency,
207                last_access_tick: self.access_tick,
208            },
209        );
210        self.table_capacity_high_water =
211            self.table_capacity_high_water.max(self.entries.capacity());
212        self.admissions = self.admissions.saturating_add(1);
213        if self.over_entry_limit() || self.over_byte_limit() {
214            self.memory_pressure_events = self.memory_pressure_events.saturating_add(1);
215        }
216        while self.over_entry_limit() || self.over_byte_limit() {
217            let Some(victim) = self.lfu_victim_key() else {
218                // An empty map must not retain an over-budget bucket buffer.
219                self.entries = HashMap::new();
220                self.table_capacity_high_water = 0;
221                break;
222            };
223            let removed = self
224                .entries
225                .remove(&victim)
226                .expect("selected victim exists");
227            self.entry_heap_charge -= removed.heap_charge;
228            self.evictions = self.evictions.saturating_add(1);
229            if self.entries.is_empty() {
230                self.entries = HashMap::new();
231                self.table_capacity_high_water = 0;
232            } else if self.over_byte_limit() {
233                self.entries.shrink_to_fit();
234            }
235        }
236    }
237
238    pub fn max_bytes(&self) -> Option<usize> {
239        self.max_bytes
240    }
241
242    /// Conservative requested-heap charge, including spare hash-table capacity.
243    /// The pinned hashbrown table uses at most twice its original advertised
244    /// capacity in buckets plus control bytes/alignment. Preserve the high-water
245    /// capacity: tombstones can lower `HashMap::capacity()` without freeing its
246    /// allocation. This excludes allocator rounding,
247    /// the fixed cache object and heap owned by callers after cloning a value.
248    pub fn charged_bytes(&self) -> Option<usize> {
249        let capacity = self.table_capacity_high_water;
250        if capacity == 0 {
251            return Some(self.entry_heap_charge);
252        }
253        let buckets = capacity.checked_mul(2)?;
254        let bucket = std::mem::size_of::<(K, LfuCacheEntry<V>)>().checked_add(1)?;
255        let table = buckets
256            .checked_mul(bucket)?
257            .checked_add(32)?
258            .checked_add(std::mem::align_of::<(K, LfuCacheEntry<V>)>())?;
259        self.entry_heap_charge.checked_add(table)
260    }
261
262    fn over_entry_limit(&self) -> bool {
263        self.max_entries
264            .is_some_and(|limit| self.entries.len() > limit)
265    }
266
267    fn over_byte_limit(&self) -> bool {
268        self.max_bytes
269            .is_some_and(|limit| self.charged_bytes().is_none_or(|bytes| bytes > limit))
270    }
271
272    fn lfu_victim_key(&self) -> Option<K> {
273        self.entries
274            .iter()
275            .min_by(|(left_key, left), (right_key, right)| {
276                (left.frequency, left.last_access_tick, *left_key).cmp(&(
277                    right.frequency,
278                    right.last_access_tick,
279                    *right_key,
280                ))
281            })
282            .map(|(key, _)| key.clone())
283    }
284
285    pub fn stats(&self) -> PlanCacheStats {
286        PlanCacheStats {
287            max_entries: self.max_entries,
288            entries: self.entries.len(),
289            hits: self.hits,
290            misses: self.misses,
291            admissions: self.admissions,
292            disabled_misses: self.disabled_misses,
293            bypasses: self.bypasses,
294            evictions: self.evictions,
295            memory_pressure_events: self.memory_pressure_events,
296        }
297    }
298}
299
300#[cfg(test)]
301mod tests {
302    use super::{LfuCache, PlanCacheBypassReason, PlanCacheLookup};
303    use std::sync::{Arc, Barrier, Mutex};
304    use std::thread;
305
306    #[test]
307    fn weighted_replacement_retains_the_charged_key_capacity() {
308        let mut cache = LfuCache::with_byte_limit(Some(8), Some(8192));
309        let mut key = String::with_capacity(4096);
310        key.push('a');
311        cache.insert_weighted(key, (), 4096);
312        let smaller_key = "a".to_owned();
313        let charge = smaller_key.capacity();
314        cache.insert_weighted(smaller_key, (), charge);
315        assert_eq!(cache.entries.keys().next().unwrap().capacity(), charge);
316        assert_eq!(cache.entry_heap_charge, charge);
317    }
318
319    #[test]
320    fn byte_limited_lfu_bounds_a_burst_and_its_table_capacity() {
321        let mut cache = LfuCache::with_byte_limit(Some(128), Some(4096));
322        for key in 0..256 {
323            cache.insert_weighted(key, vec![key as u8; 1024], 1024);
324            assert!(cache.charged_bytes().unwrap() <= 4096);
325            for (key, entry) in &cache.entries {
326                assert_eq!(entry.value[0], *key as u8);
327            }
328        }
329        assert!(cache.stats().evictions > 0);
330        assert!(cache.stats().entries <= 3);
331        assert!(cache.clone().charged_bytes().unwrap() <= 4096);
332    }
333
334    #[test]
335    fn byte_limited_lfu_refuses_uncharged_admission() {
336        let mut cache = LfuCache::with_byte_limit(Some(8), Some(4096));
337        cache.insert(1, vec![0; 8192]);
338        assert_eq!(cache.stats().entries, 0);
339        assert_eq!(cache.charged_bytes(), Some(0));
340        cache.insert_weighted(1, vec![1; 16], 16);
341        assert_eq!(cache.get(&1), Some(vec![1; 16]));
342    }
343
344    #[test]
345    fn byte_limited_lfu_replacement_and_oversize_admission_are_atomic() {
346        let mut cache = LfuCache::with_byte_limit(Some(8), Some(4096));
347        cache.insert_weighted(1, vec![1; 1024], 1024);
348        cache.insert_weighted(1, vec![2; 2048], 2048);
349        assert_eq!(cache.entry_heap_charge, 2048);
350        let before = cache.charged_bytes();
351        cache.insert_weighted(1, vec![3; 8192], 8192);
352        assert_eq!(cache.charged_bytes(), before);
353        assert_eq!(cache.get(&1), Some(vec![2; 2048]));
354        assert_eq!(cache.stats().entries, 1);
355    }
356
357    #[test]
358    fn zero_and_overflowing_byte_budgets_cannot_leave_retained_entries() {
359        let mut disabled = LfuCache::with_byte_limit(None, Some(0));
360        disabled.insert_weighted(1, 1, 0);
361        assert_eq!(disabled.get(&1), None);
362        assert_eq!(disabled.stats().disabled_misses, 1);
363        assert_eq!(disabled.charged_bytes(), Some(0));
364        let mut overflow = LfuCache::with_byte_limit(None, Some(usize::MAX));
365        overflow.insert_weighted(1, 1, usize::MAX);
366        assert_eq!(overflow.stats().entries, 0);
367        assert_eq!(overflow.charged_bytes(), Some(0));
368    }
369
370    #[test]
371    fn lfu_cache_evicts_least_frequently_used_entry() {
372        let mut cache = LfuCache::new(Some(2));
373        cache.insert("hot", 1);
374        cache.insert("cold", 2);
375
376        assert_eq!(cache.get(&"hot"), Some(1));
377        cache.insert("new", 3);
378
379        assert_eq!(cache.get(&"hot"), Some(1));
380        assert_eq!(cache.get(&"new"), Some(3));
381        assert_eq!(cache.get(&"cold"), None);
382        assert_eq!(cache.stats().admissions, 3);
383        assert_eq!(cache.stats().evictions, 1);
384        assert_eq!(cache.stats().memory_pressure_events, 1);
385    }
386
387    #[test]
388    fn lfu_cache_uses_oldest_access_as_tie_breaker() {
389        let mut cache = LfuCache::new(Some(2));
390        cache.insert("older", 1);
391        cache.insert("newer", 2);
392        cache.insert("third", 3);
393
394        assert_eq!(cache.get(&"older"), None);
395        assert_eq!(cache.get(&"newer"), Some(2));
396        assert_eq!(cache.get(&"third"), Some(3));
397    }
398
399    #[test]
400    fn zero_capacity_cache_records_misses_without_entries() {
401        let mut cache = LfuCache::new(Some(0));
402        cache.insert("ignored", 1);
403
404        assert_eq!(cache.get(&"ignored"), None);
405        assert_eq!(cache.stats().entries, 0);
406        assert_eq!(cache.stats().misses, 1);
407        assert_eq!(cache.stats().disabled_misses, 1);
408        assert_eq!(cache.stats().admissions, 0);
409        assert_eq!(cache.stats().memory_pressure_events, 0);
410    }
411
412    #[test]
413    fn lookup_reports_cacheability_and_bypass_reason() {
414        let bypass = PlanCacheLookup::Bypass(PlanCacheBypassReason::OptimizerDirective);
415
416        assert_eq!(PlanCacheLookup::Hit.as_str(), "hit");
417        assert_eq!(bypass.as_str(), "bypass");
418        assert_eq!(
419            bypass.bypass_reason(),
420            Some(PlanCacheBypassReason::OptimizerDirective)
421        );
422        assert_eq!(
423            PlanCacheBypassReason::StatementNotCacheable.as_str(),
424            "statement_not_cacheable"
425        );
426    }
427
428    #[test]
429    fn hash_lookup_updates_lfu_accounting_once() {
430        let mut cache = LfuCache::new(Some(2));
431        cache.insert("query-a", 1);
432        cache.insert("query-b", 2);
433
434        assert_eq!(cache.get(&"query-b"), Some(2));
435        assert_eq!(cache.get(&"query-c"), None);
436        assert_eq!(cache.stats().hits, 1);
437        assert_eq!(cache.stats().misses, 1);
438    }
439
440    #[test]
441    fn duplicate_hash_keys_update_one_entry() {
442        let mut cache = LfuCache::new(Some(2));
443        cache.insert("query", 1);
444        cache.insert("query", 2);
445
446        assert_eq!(cache.stats().entries, 1);
447        assert_eq!(cache.get(&"query"), Some(2));
448        assert_eq!(cache.stats().entries, 1);
449    }
450
451    #[test]
452    fn cache_records_bypassed_plans_separately_from_misses() {
453        let mut cache: LfuCache<&str, i32> = LfuCache::new(Some(2));
454
455        cache.record_bypass();
456
457        assert_eq!(cache.stats().bypasses, 1);
458        assert_eq!(cache.stats().misses, 0);
459        assert_eq!(cache.stats().hits, 0);
460        assert_eq!(cache.stats().admissions, 0);
461    }
462
463    #[test]
464    fn unbounded_cache_records_admissions_without_pressure() {
465        let mut cache = LfuCache::new(None);
466
467        cache.insert("first", 1);
468        cache.insert("second", 2);
469
470        assert_eq!(cache.stats().entries, 2);
471        assert_eq!(cache.stats().admissions, 2);
472        assert_eq!(cache.stats().memory_pressure_events, 0);
473        assert_eq!(cache.stats().evictions, 0);
474    }
475
476    #[test]
477    fn cache_remains_bounded_under_mutex_protected_concurrent_access() {
478        let cache = Arc::new(Mutex::new(LfuCache::new(Some(8))));
479        let start = Arc::new(Barrier::new(4));
480
481        let handles = (0..4)
482            .map(|worker| {
483                let cache = Arc::clone(&cache);
484                let start = Arc::clone(&start);
485                thread::spawn(move || {
486                    start.wait();
487                    for offset in 0..64 {
488                        let key = format!("key-{}", (worker + offset) % 16);
489                        let mut cache = cache.lock().unwrap();
490                        cache.insert(key.clone(), worker * 100 + offset);
491                        let _ = cache.get(&key);
492                    }
493                })
494            })
495            .collect::<Vec<_>>();
496
497        for handle in handles {
498            handle.join().unwrap();
499        }
500
501        let stats = cache.lock().unwrap().stats();
502        assert_eq!(stats.entries, 8);
503        assert_eq!(stats.admissions, 256);
504        assert!(stats.hits > 0);
505        assert!(stats.evictions > 0);
506        assert!(stats.memory_pressure_events > 0);
507    }
508}
509
510#[cfg(all(test, feature = "loom-tests"))]
511mod loom_tests {
512    use super::LfuCache;
513    use loom::sync::{Arc, Mutex};
514    use loom::thread;
515
516    #[test]
517    fn lfu_cache_preserves_bounds_under_modeled_concurrent_access() {
518        loom::model(|| {
519            let cache = Arc::new(Mutex::new(LfuCache::new(Some(2))));
520
521            let writer = {
522                let cache = Arc::clone(&cache);
523                thread::spawn(move || {
524                    let mut cache = cache.lock().unwrap();
525                    cache.insert("first", 1);
526                    cache.insert("second", 2);
527                })
528            };
529
530            let reader_writer = {
531                let cache = Arc::clone(&cache);
532                thread::spawn(move || {
533                    let mut cache = cache.lock().unwrap();
534                    let _ = cache.get(&"first");
535                    cache.insert("third", 3);
536                })
537            };
538
539            writer.join().unwrap();
540            reader_writer.join().unwrap();
541
542            let stats = cache.lock().unwrap().stats();
543            assert!(stats.entries <= 2);
544            assert!(stats.admissions <= 3);
545            assert!(stats.evictions <= 1);
546            assert_eq!(stats.max_entries, Some(2));
547        });
548    }
549}