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    parameter_statistics_values, parameterize_logical_plan, parameterize_value_list,
32    prepare_physical_plan_for_cache, prepare_physical_regexes_for_execution,
33    resolve_plan_template_value, ParameterBindingTemplate, ParameterizedLogicalPlan,
34    PlanParameterCacheKey,
35};
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum PlanCacheLookup {
39    Hit,
40    Miss,
41    Bypass(PlanCacheBypassReason),
42}
43
44impl PlanCacheLookup {
45    pub const fn as_str(self) -> &'static str {
46        match self {
47            Self::Hit => "hit",
48            Self::Miss => "miss",
49            Self::Bypass(_) => "bypass",
50        }
51    }
52
53    pub const fn bypass_reason(self) -> Option<PlanCacheBypassReason> {
54        match self {
55            Self::Bypass(reason) => Some(reason),
56            Self::Hit | Self::Miss => None,
57        }
58    }
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum PlanCacheBypassReason {
63    MutationPlanning,
64    OptimizerDirective,
65    StatementNotCacheable,
66    /// Legacy diagnostic spelling retained for host source compatibility.
67    /// CASE templates now use ordinary weighted admission; no planner emits it.
68    ParameterizedCaseTemplate,
69}
70
71impl PlanCacheBypassReason {
72    pub const fn as_str(self) -> &'static str {
73        match self {
74            Self::MutationPlanning => "mutation_planning",
75            Self::OptimizerDirective => "optimizer_directive",
76            Self::StatementNotCacheable => "statement_not_cacheable",
77            Self::ParameterizedCaseTemplate => "parameterized_case_template",
78        }
79    }
80}
81
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct PlanCacheStats {
84    pub max_entries: Option<usize>,
85    /// Requested-heap retention limit; absent for a count-only cache.
86    pub max_bytes: Option<usize>,
87    /// Per-entry key/value limit, including the inline entry layout.
88    pub max_entry_bytes: Option<usize>,
89    /// Conservative retained charge, available only for weighted caches.
90    pub charged_bytes: Option<usize>,
91    pub entries: usize,
92    pub hits: u64,
93    pub misses: u64,
94    pub admissions: u64,
95    pub disabled_misses: u64,
96    pub bypasses: u64,
97    pub evictions: u64,
98    pub memory_pressure_events: u64,
99    pub rejected_admissions: u64,
100}
101
102#[derive(Debug, Clone, PartialEq)]
103struct LfuCacheEntry<V> {
104    value: V,
105    frequency: u64,
106    last_access_tick: u64,
107    heap_charge: usize,
108}
109
110#[derive(Debug, Clone)]
111pub struct LfuCache<K, V> {
112    max_entries: Option<usize>,
113    max_bytes: Option<usize>,
114    max_entry_bytes: Option<usize>,
115    entry_heap_charge: usize,
116    table_capacity_high_water: usize,
117    entries: HashMap<K, LfuCacheEntry<V>>,
118    access_tick: u64,
119    hits: u64,
120    misses: u64,
121    admissions: u64,
122    disabled_misses: u64,
123    bypasses: u64,
124    evictions: u64,
125    memory_pressure_events: u64,
126    rejected_admissions: u64,
127}
128
129impl<K, V> LfuCache<K, V>
130where
131    K: Eq + Hash + Ord + Clone,
132    V: Clone,
133{
134    pub fn new(max_entries: Option<usize>) -> Self {
135        Self::with_byte_limit(max_entries, None)
136    }
137
138    /// A byte-limited cache requires `insert_weighted` with conservative heap
139    /// charges for both key and value. Table storage is charged separately.
140    pub fn with_byte_limit(max_entries: Option<usize>, max_bytes: Option<usize>) -> Self {
141        Self::with_byte_limits(max_entries, max_bytes, None)
142    }
143
144    /// Bound both aggregate retention and one key/value entry. The per-entry
145    /// limit includes its inline layout; the aggregate additionally accounts
146    /// for spare hash-table capacity. Zero disables retention.
147    pub fn with_byte_limits(
148        max_entries: Option<usize>,
149        max_bytes: Option<usize>,
150        max_entry_bytes: Option<usize>,
151    ) -> Self {
152        Self {
153            max_entries,
154            max_bytes,
155            max_entry_bytes,
156            entry_heap_charge: 0,
157            table_capacity_high_water: 0,
158            entries: HashMap::new(),
159            access_tick: 0,
160            hits: 0,
161            misses: 0,
162            admissions: 0,
163            disabled_misses: 0,
164            bypasses: 0,
165            evictions: 0,
166            memory_pressure_events: 0,
167            rejected_admissions: 0,
168        }
169    }
170
171    pub fn get(&mut self, key: &K) -> Option<V> {
172        if self.max_entries == Some(0)
173            || self.max_bytes == Some(0)
174            || self.max_entry_bytes == Some(0)
175        {
176            self.misses += 1;
177            self.disabled_misses += 1;
178            return None;
179        }
180        self.access_tick = self.access_tick.saturating_add(1);
181        let Some(entry) = self.entries.get_mut(key) else {
182            self.misses += 1;
183            return None;
184        };
185        self.hits += 1;
186        entry.frequency = entry.frequency.saturating_add(1);
187        entry.last_access_tick = self.access_tick;
188        Some(entry.value.clone())
189    }
190
191    pub fn record_bypass(&mut self) {
192        self.bypasses = self.bypasses.saturating_add(1);
193    }
194
195    pub fn record_rejected_admission(&mut self) {
196        self.rejected_admissions = self.rejected_admissions.saturating_add(1);
197    }
198
199    /// Legacy count-only admission. Byte-limited caches refuse this path so
200    /// callers cannot accidentally retain an uncharged key/value payload.
201    pub fn insert(&mut self, key: K, value: V) {
202        if self.max_bytes.is_none() && self.max_entry_bytes.is_none() {
203            self.insert_weighted(key, value, 0);
204        } else {
205            self.rejected_admissions = self.rejected_admissions.saturating_add(1);
206        }
207    }
208
209    /// Charge owned heap retained through the key/value, excluding their inline
210    /// bucket layout. Rejected admissions leave an existing entry unchanged.
211    /// In-flight cloned values are owned by callers, outside this cache bound.
212    /// Returns whether admission checks accepted the entry. Subsequent LFU
213    /// eviction can still remove it; this does not promise a future cache hit.
214    pub fn insert_weighted(&mut self, key: K, value: V, heap_charge: usize) -> bool {
215        let entry_bytes = heap_charge.checked_add(std::mem::size_of::<(K, LfuCacheEntry<V>)>());
216        if entry_bytes.is_none()
217            || self
218                .max_entry_bytes
219                .is_some_and(|limit| limit == 0 || entry_bytes.is_none_or(|bytes| bytes > limit))
220            || self.max_entries == Some(0)
221            || self.max_bytes.is_some_and(|limit| {
222                // Pinned std's smallest nonempty table advertises three
223                // entries. Refuse an entry that cannot fit even that table
224                // before removing an existing key or evicting other plans.
225                Self::table_heap_charge(3)
226                    .and_then(|table| heap_charge.checked_add(table))
227                    .is_none_or(|minimum| minimum > limit)
228            })
229        {
230            self.rejected_admissions = self.rejected_admissions.saturating_add(1);
231            return false;
232        }
233        let previous = self.entries.get(&key).map_or(0, |entry| entry.heap_charge);
234        let Some(total) = self
235            .entry_heap_charge
236            .checked_sub(previous)
237            .and_then(|bytes| bytes.checked_add(heap_charge))
238        else {
239            self.rejected_admissions = self.rejected_admissions.saturating_add(1);
240            return false;
241        };
242        self.entry_heap_charge = total;
243        self.access_tick = self.access_tick.saturating_add(1);
244        // Replace the key too: an equal old key may retain more spare heap
245        // capacity than the incoming key whose charge the caller supplied.
246        let frequency = self
247            .entries
248            .remove(&key)
249            .map_or(1, |entry| entry.frequency.saturating_add(1));
250        self.entries.insert(
251            key,
252            LfuCacheEntry {
253                value,
254                heap_charge,
255                frequency,
256                last_access_tick: self.access_tick,
257            },
258        );
259        self.table_capacity_high_water =
260            self.table_capacity_high_water.max(self.entries.capacity());
261        self.admissions = self.admissions.saturating_add(1);
262        if self.over_entry_limit() || self.over_byte_limit() {
263            self.memory_pressure_events = self.memory_pressure_events.saturating_add(1);
264        }
265        // `shrink_to_fit` does not necessarily free buckets: tombstones can
266        // lower `capacity()` while the original allocation remains. Rebuild a
267        // compact table before using its capacity as the new high-water bound.
268        if self.over_byte_limit() {
269            self.rebuild_compact_table();
270        }
271        let mut evicted = false;
272        while self.over_entry_limit() || self.over_byte_limit() {
273            let Some(victim) = self.lfu_victim_key() else {
274                // An empty map must not retain an over-budget bucket buffer.
275                self.entries = HashMap::new();
276                self.table_capacity_high_water = 0;
277                break;
278            };
279            let removed = self
280                .entries
281                .remove(&victim)
282                .expect("selected victim exists");
283            self.entry_heap_charge -= removed.heap_charge;
284            self.evictions = self.evictions.saturating_add(1);
285            evicted = true;
286            if self.entries.is_empty() {
287                self.entries = HashMap::new();
288                self.table_capacity_high_water = 0;
289            }
290        }
291        // Eviction leaves the table sized for the pre-eviction set. Rebuild
292        // once more so retained table memory and the byte charge track the
293        // entries that actually remain.
294        if evicted && !self.entries.is_empty() {
295            self.rebuild_compact_table();
296        }
297        true
298    }
299
300    fn rebuild_compact_table(&mut self) {
301        if self.entries.is_empty() {
302            self.entries = HashMap::new();
303            self.table_capacity_high_water = 0;
304            return;
305        }
306        let entries = std::mem::take(&mut self.entries);
307        self.entries = entries.into_iter().collect();
308        self.table_capacity_high_water = self.entries.capacity();
309    }
310
311    pub fn max_bytes(&self) -> Option<usize> {
312        self.max_bytes
313    }
314
315    /// Conservative requested-heap charge, including spare hash-table capacity.
316    /// The pinned hashbrown table uses at most twice its original advertised
317    /// capacity in buckets plus control bytes/alignment. Preserve the high-water
318    /// capacity: tombstones can lower `HashMap::capacity()` without freeing its
319    /// allocation. This excludes allocator rounding,
320    /// the fixed cache object and heap owned by callers after cloning a value.
321    pub fn charged_bytes(&self) -> Option<usize> {
322        self.entry_heap_charge
323            .checked_add(Self::table_heap_charge(self.table_capacity_high_water)?)
324    }
325
326    fn table_heap_charge(capacity: usize) -> Option<usize> {
327        if capacity == 0 {
328            return Some(0);
329        }
330        let buckets = capacity.checked_mul(2)?;
331        let bucket = std::mem::size_of::<(K, LfuCacheEntry<V>)>().checked_add(1)?;
332        buckets
333            .checked_mul(bucket)?
334            .checked_add(32)?
335            .checked_add(std::mem::align_of::<(K, LfuCacheEntry<V>)>())
336    }
337
338    fn over_entry_limit(&self) -> bool {
339        self.max_entries
340            .is_some_and(|limit| self.entries.len() > limit)
341    }
342
343    fn over_byte_limit(&self) -> bool {
344        self.max_bytes
345            .is_some_and(|limit| self.charged_bytes().is_none_or(|bytes| bytes > limit))
346    }
347
348    fn lfu_victim_key(&self) -> Option<K> {
349        self.entries
350            .iter()
351            .min_by(|(left_key, left), (right_key, right)| {
352                (left.frequency, left.last_access_tick, *left_key).cmp(&(
353                    right.frequency,
354                    right.last_access_tick,
355                    *right_key,
356                ))
357            })
358            .map(|(key, _)| key.clone())
359    }
360
361    pub fn stats(&self) -> PlanCacheStats {
362        PlanCacheStats {
363            max_entries: self.max_entries,
364            max_bytes: self.max_bytes,
365            max_entry_bytes: self.max_entry_bytes,
366            charged_bytes: (self.max_bytes.is_some() || self.max_entry_bytes.is_some())
367                .then(|| self.charged_bytes())
368                .flatten(),
369            entries: self.entries.len(),
370            hits: self.hits,
371            misses: self.misses,
372            admissions: self.admissions,
373            disabled_misses: self.disabled_misses,
374            bypasses: self.bypasses,
375            evictions: self.evictions,
376            memory_pressure_events: self.memory_pressure_events,
377            rejected_admissions: self.rejected_admissions,
378        }
379    }
380}
381
382#[cfg(test)]
383mod tests {
384    use super::{LfuCache, PlanCacheBypassReason, PlanCacheLookup};
385    use std::sync::{Arc, Barrier, Mutex};
386    use std::thread;
387
388    #[test]
389    fn total_limit_refuses_a_replacement_that_cannot_fit_its_table() {
390        let mut cache = LfuCache::with_byte_limits(Some(8), Some(512), Some(512));
391        cache.insert_weighted(1u8, vec![1u8; 64], 64);
392        assert_eq!(cache.stats().entries, 1);
393        let before = cache.charged_bytes();
394        // The payload and inline entry each fit their limits, but the payload
395        // plus even a one-entry table cannot fit the total retention budget.
396        cache.insert_weighted(1u8, vec![2u8; 400], 400);
397        assert_eq!(cache.get(&1), Some(vec![1u8; 64]));
398        assert_eq!(cache.charged_bytes(), before);
399        assert_eq!(cache.stats().admissions, 1);
400        assert_eq!(cache.stats().evictions, 0);
401        assert_eq!(cache.stats().rejected_admissions, 1);
402    }
403
404    #[test]
405    fn per_entry_limit_refuses_oversize_replacement_without_evicting_hot_entries() {
406        let mut cache = LfuCache::with_byte_limits(Some(8), Some(8192), Some(1024));
407        cache.insert_weighted(1, vec![1; 256], 256);
408        cache.insert_weighted(2, vec![2; 256], 256);
409        let before = cache.charged_bytes();
410        cache.insert_weighted(1, vec![3; 1024], 1024);
411        assert_eq!(cache.charged_bytes(), before);
412        assert_eq!(cache.get(&1), Some(vec![1; 256]));
413        assert_eq!(cache.get(&2), Some(vec![2; 256]));
414        assert_eq!(cache.stats().entries, 2);
415        assert_eq!(cache.stats().evictions, 0);
416        assert_eq!(cache.stats().rejected_admissions, 1);
417        assert_eq!(cache.stats().max_entry_bytes, Some(1024));
418        assert_eq!(cache.stats().charged_bytes, before);
419    }
420
421    #[test]
422    fn per_entry_only_limit_requires_weighted_admission_and_zero_disables_retention() {
423        let mut cache = LfuCache::with_byte_limits(None, None, Some(1024));
424        cache.insert(1, vec![0; 8192]);
425        assert_eq!(cache.stats().entries, 0);
426        cache.insert_weighted(1, vec![1; 64], 64);
427        assert_eq!(cache.get(&1), Some(vec![1; 64]));
428        assert!(cache.stats().charged_bytes.unwrap() >= 64);
429
430        let mut disabled = LfuCache::with_byte_limits(None, Some(8192), Some(0));
431        disabled.insert_weighted(1, (), 0);
432        assert_eq!(disabled.get(&1), None);
433        assert_eq!(disabled.stats().disabled_misses, 1);
434        assert_eq!(disabled.stats().charged_bytes, Some(0));
435        assert_eq!(disabled.stats().rejected_admissions, 1);
436    }
437
438    #[test]
439    fn weighted_replacement_retains_the_charged_key_capacity() {
440        let mut cache = LfuCache::with_byte_limit(Some(8), Some(8192));
441        let mut key = String::with_capacity(4096);
442        key.push('a');
443        cache.insert_weighted(key, (), 4096);
444        let smaller_key = "a".to_owned();
445        let charge = smaller_key.capacity();
446        cache.insert_weighted(smaller_key, (), charge);
447        assert_eq!(cache.entries.keys().next().unwrap().capacity(), charge);
448        assert_eq!(cache.entry_heap_charge, charge);
449    }
450
451    #[test]
452    fn byte_limited_lfu_bounds_a_burst_and_its_table_capacity() {
453        let mut cache = LfuCache::with_byte_limit(Some(128), Some(4096));
454        for key in 0..256 {
455            cache.insert_weighted(key, vec![key as u8; 1024], 1024);
456            assert!(cache.charged_bytes().unwrap() <= 4096);
457            for (key, entry) in &cache.entries {
458                assert_eq!(entry.value[0], *key as u8);
459            }
460        }
461        assert!(cache.stats().evictions > 0);
462        assert!(cache.stats().entries <= 3);
463        assert!(cache.clone().charged_bytes().unwrap() <= 4096);
464    }
465
466    #[test]
467    fn byte_pressure_rebuilds_a_bounded_table() {
468        let mut cache = LfuCache::<u64, u64>::with_byte_limits(None, Some(10_000), None);
469        for key in 0..60 {
470            cache.insert_weighted(key, key, 100);
471        }
472        let stats = cache.stats();
473        assert!(
474            stats.entries > 10,
475            "byte pressure collapsed the cache to {} entries",
476            stats.entries
477        );
478        assert!(
479            cache.table_capacity_high_water <= cache.entries.capacity().saturating_mul(2),
480            "retained table charge {} is far above current capacity {}",
481            cache.table_capacity_high_water,
482            cache.entries.capacity()
483        );
484        assert!(cache.charged_bytes().unwrap() <= 10_000);
485    }
486
487    #[test]
488    fn byte_limited_lfu_refuses_uncharged_admission() {
489        let mut cache = LfuCache::with_byte_limit(Some(8), Some(4096));
490        cache.insert(1, vec![0; 8192]);
491        assert_eq!(cache.stats().entries, 0);
492        assert_eq!(cache.charged_bytes(), Some(0));
493        cache.insert_weighted(1, vec![1; 16], 16);
494        assert_eq!(cache.get(&1), Some(vec![1; 16]));
495    }
496
497    #[test]
498    fn byte_limited_lfu_replacement_and_oversize_admission_are_atomic() {
499        let mut cache = LfuCache::with_byte_limit(Some(8), Some(4096));
500        assert!(cache.insert_weighted(1, vec![1; 1024], 1024));
501        assert!(cache.insert_weighted(1, vec![2; 2048], 2048));
502        assert_eq!(cache.entry_heap_charge, 2048);
503        let before = cache.charged_bytes();
504        assert!(!cache.insert_weighted(1, vec![3; 8192], 8192));
505        assert_eq!(cache.charged_bytes(), before);
506        assert_eq!(cache.get(&1), Some(vec![2; 2048]));
507        assert_eq!(cache.stats().entries, 1);
508    }
509
510    #[test]
511    fn zero_and_overflowing_byte_budgets_cannot_leave_retained_entries() {
512        let mut disabled = LfuCache::with_byte_limit(None, Some(0));
513        assert!(!disabled.insert_weighted(1, 1, 0));
514        assert_eq!(disabled.get(&1), None);
515        assert_eq!(disabled.stats().disabled_misses, 1);
516        assert_eq!(disabled.charged_bytes(), Some(0));
517        let mut overflow = LfuCache::with_byte_limit(None, Some(usize::MAX));
518        assert!(!overflow.insert_weighted(1, 1, usize::MAX));
519        assert_eq!(overflow.stats().entries, 0);
520        assert_eq!(overflow.charged_bytes(), Some(0));
521    }
522
523    #[test]
524    fn lfu_cache_evicts_least_frequently_used_entry() {
525        let mut cache = LfuCache::new(Some(2));
526        cache.insert("hot", 1);
527        cache.insert("cold", 2);
528
529        assert_eq!(cache.get(&"hot"), Some(1));
530        cache.insert("new", 3);
531
532        assert_eq!(cache.get(&"hot"), Some(1));
533        assert_eq!(cache.get(&"new"), Some(3));
534        assert_eq!(cache.get(&"cold"), None);
535        assert_eq!(cache.stats().admissions, 3);
536        assert_eq!(cache.stats().evictions, 1);
537        assert_eq!(cache.stats().memory_pressure_events, 1);
538    }
539
540    #[test]
541    fn lfu_cache_uses_oldest_access_as_tie_breaker() {
542        let mut cache = LfuCache::new(Some(2));
543        cache.insert("older", 1);
544        cache.insert("newer", 2);
545        cache.insert("third", 3);
546
547        assert_eq!(cache.get(&"older"), None);
548        assert_eq!(cache.get(&"newer"), Some(2));
549        assert_eq!(cache.get(&"third"), Some(3));
550    }
551
552    #[test]
553    fn zero_capacity_cache_records_misses_without_entries() {
554        let mut cache = LfuCache::new(Some(0));
555        cache.insert("ignored", 1);
556
557        assert_eq!(cache.get(&"ignored"), None);
558        assert_eq!(cache.stats().entries, 0);
559        assert_eq!(cache.stats().misses, 1);
560        assert_eq!(cache.stats().disabled_misses, 1);
561        assert_eq!(cache.stats().admissions, 0);
562        assert_eq!(cache.stats().memory_pressure_events, 0);
563    }
564
565    #[test]
566    fn lookup_reports_cacheability_and_bypass_reason() {
567        let bypass = PlanCacheLookup::Bypass(PlanCacheBypassReason::OptimizerDirective);
568
569        assert_eq!(PlanCacheLookup::Hit.as_str(), "hit");
570        assert_eq!(bypass.as_str(), "bypass");
571        assert_eq!(
572            bypass.bypass_reason(),
573            Some(PlanCacheBypassReason::OptimizerDirective)
574        );
575        assert_eq!(
576            PlanCacheBypassReason::StatementNotCacheable.as_str(),
577            "statement_not_cacheable"
578        );
579    }
580
581    #[test]
582    fn hash_lookup_updates_lfu_accounting_once() {
583        let mut cache = LfuCache::new(Some(2));
584        cache.insert("query-a", 1);
585        cache.insert("query-b", 2);
586
587        assert_eq!(cache.get(&"query-b"), Some(2));
588        assert_eq!(cache.get(&"query-c"), None);
589        assert_eq!(cache.stats().hits, 1);
590        assert_eq!(cache.stats().misses, 1);
591    }
592
593    #[test]
594    fn duplicate_hash_keys_update_one_entry() {
595        let mut cache = LfuCache::new(Some(2));
596        cache.insert("query", 1);
597        cache.insert("query", 2);
598
599        assert_eq!(cache.stats().entries, 1);
600        assert_eq!(cache.get(&"query"), Some(2));
601        assert_eq!(cache.stats().entries, 1);
602    }
603
604    #[test]
605    fn cache_records_bypassed_plans_separately_from_misses() {
606        let mut cache: LfuCache<&str, i32> = LfuCache::new(Some(2));
607
608        cache.record_bypass();
609
610        assert_eq!(cache.stats().bypasses, 1);
611        assert_eq!(cache.stats().misses, 0);
612        assert_eq!(cache.stats().hits, 0);
613        assert_eq!(cache.stats().admissions, 0);
614    }
615
616    #[test]
617    fn unbounded_cache_records_admissions_without_pressure() {
618        let mut cache = LfuCache::new(None);
619
620        cache.insert("first", 1);
621        cache.insert("second", 2);
622
623        assert_eq!(cache.stats().entries, 2);
624        assert_eq!(cache.stats().admissions, 2);
625        assert_eq!(cache.stats().memory_pressure_events, 0);
626        assert_eq!(cache.stats().evictions, 0);
627    }
628
629    #[test]
630    fn weighted_cache_bounds_survive_concurrent_misses_replacements_and_refusals() {
631        let cache = Arc::new(Mutex::new(LfuCache::with_byte_limits(
632            Some(8),
633            Some(4096),
634            Some(512),
635        )));
636        let start = Arc::new(Barrier::new(4));
637        let handles = (0..4)
638            .map(|worker| {
639                let cache = Arc::clone(&cache);
640                let start = Arc::clone(&start);
641                thread::spawn(move || {
642                    start.wait();
643                    for offset in 0..64 {
644                        // Build misses outside the cache lock, as the facade does.
645                        let key = format!("key-{}", (worker + offset) % 32);
646                        let value = vec![worker as u8; if offset % 11 == 0 { 1024 } else { 256 }];
647                        let charge = key.capacity() + value.capacity();
648                        let mut cache = cache.lock().unwrap();
649                        cache.insert_weighted(key.clone(), value, charge);
650                        let _ = cache.get(&key);
651                        assert!(cache.stats().entries <= 8);
652                        assert!(cache.charged_bytes().unwrap() <= 4096);
653                    }
654                })
655            })
656            .collect::<Vec<_>>();
657        for handle in handles {
658            handle.join().unwrap();
659        }
660        let stats = cache.lock().unwrap().stats();
661        assert!(stats.rejected_admissions > 0);
662        assert!(stats.evictions > 0);
663        assert!(stats.hits > 0);
664    }
665
666    #[test]
667    fn cache_remains_bounded_under_mutex_protected_concurrent_access() {
668        let cache = Arc::new(Mutex::new(LfuCache::new(Some(8))));
669        let start = Arc::new(Barrier::new(4));
670
671        let handles = (0..4)
672            .map(|worker| {
673                let cache = Arc::clone(&cache);
674                let start = Arc::clone(&start);
675                thread::spawn(move || {
676                    start.wait();
677                    for offset in 0..64 {
678                        let key = format!("key-{}", (worker + offset) % 16);
679                        let mut cache = cache.lock().unwrap();
680                        cache.insert(key.clone(), worker * 100 + offset);
681                        let _ = cache.get(&key);
682                    }
683                })
684            })
685            .collect::<Vec<_>>();
686
687        for handle in handles {
688            handle.join().unwrap();
689        }
690
691        let stats = cache.lock().unwrap().stats();
692        assert_eq!(stats.entries, 8);
693        assert_eq!(stats.admissions, 256);
694        assert!(stats.hits > 0);
695        assert!(stats.evictions > 0);
696        assert!(stats.memory_pressure_events > 0);
697    }
698}
699
700#[cfg(all(test, feature = "loom-tests"))]
701mod loom_tests {
702    use super::LfuCache;
703    use loom::sync::{Arc, Mutex};
704    use loom::thread;
705
706    #[test]
707    fn lfu_cache_preserves_bounds_under_modeled_concurrent_access() {
708        loom::model(|| {
709            let cache = Arc::new(Mutex::new(LfuCache::new(Some(2))));
710
711            let writer = {
712                let cache = Arc::clone(&cache);
713                thread::spawn(move || {
714                    let mut cache = cache.lock().unwrap();
715                    cache.insert("first", 1);
716                    cache.insert("second", 2);
717                })
718            };
719
720            let reader_writer = {
721                let cache = Arc::clone(&cache);
722                thread::spawn(move || {
723                    let mut cache = cache.lock().unwrap();
724                    let _ = cache.get(&"first");
725                    cache.insert("third", 3);
726                })
727            };
728
729            writer.join().unwrap();
730            reader_writer.join().unwrap();
731
732            let stats = cache.lock().unwrap().stats();
733            assert!(stats.entries <= 2);
734            assert!(stats.admissions <= 3);
735            assert!(stats.evictions <= 1);
736            assert_eq!(stats.max_entries, Some(2));
737        });
738    }
739}