hawdb-plan-cache 0.23.0

An embedded Rust graph database for local data-plane workloads
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
// Copyright 2026 Nowledge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::collections::HashMap;
use std::hash::Hash;

mod binding_cache;
mod schema;
mod template;

#[doc(hidden)]
pub use binding_cache::{
    ParameterBindingAdmission, ParameterBindingCache, ParameterBindingCacheConfig,
};
#[doc(hidden)]
pub use schema::OptimizerSchemaKey;

pub use template::{
    bind_physical_plan_parameters, parameter_binding_shape_fingerprint, parameter_scalar_types,
    parameterize_logical_plan, parameterize_value_list, prepare_physical_plan_for_cache,
    prepare_physical_regexes_for_execution, resolve_plan_template_value, ParameterBindingTemplate,
    ParameterizedLogicalPlan, PlanParameterCacheKey,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PlanCacheLookup {
    Hit,
    Miss,
    Bypass(PlanCacheBypassReason),
}

impl PlanCacheLookup {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Hit => "hit",
            Self::Miss => "miss",
            Self::Bypass(_) => "bypass",
        }
    }

    pub const fn bypass_reason(self) -> Option<PlanCacheBypassReason> {
        match self {
            Self::Bypass(reason) => Some(reason),
            Self::Hit | Self::Miss => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PlanCacheBypassReason {
    MutationPlanning,
    OptimizerDirective,
    StatementNotCacheable,
    /// Legacy diagnostic spelling retained for host source compatibility.
    /// CASE templates now use ordinary weighted admission; no planner emits it.
    ParameterizedCaseTemplate,
}

impl PlanCacheBypassReason {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::MutationPlanning => "mutation_planning",
            Self::OptimizerDirective => "optimizer_directive",
            Self::StatementNotCacheable => "statement_not_cacheable",
            Self::ParameterizedCaseTemplate => "parameterized_case_template",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlanCacheStats {
    pub max_entries: Option<usize>,
    /// Requested-heap retention limit; absent for a count-only cache.
    pub max_bytes: Option<usize>,
    /// Per-entry key/value limit, including the inline entry layout.
    pub max_entry_bytes: Option<usize>,
    /// Conservative retained charge, available only for weighted caches.
    pub charged_bytes: Option<usize>,
    pub entries: usize,
    pub hits: u64,
    pub misses: u64,
    pub admissions: u64,
    pub disabled_misses: u64,
    pub bypasses: u64,
    pub evictions: u64,
    pub memory_pressure_events: u64,
    pub rejected_admissions: u64,
}

#[derive(Debug, Clone, PartialEq)]
struct LfuCacheEntry<V> {
    value: V,
    frequency: u64,
    last_access_tick: u64,
    heap_charge: usize,
}

#[derive(Debug, Clone)]
pub struct LfuCache<K, V> {
    max_entries: Option<usize>,
    max_bytes: Option<usize>,
    max_entry_bytes: Option<usize>,
    entry_heap_charge: usize,
    table_capacity_high_water: usize,
    entries: HashMap<K, LfuCacheEntry<V>>,
    access_tick: u64,
    hits: u64,
    misses: u64,
    admissions: u64,
    disabled_misses: u64,
    bypasses: u64,
    evictions: u64,
    memory_pressure_events: u64,
    rejected_admissions: u64,
}

impl<K, V> LfuCache<K, V>
where
    K: Eq + Hash + Ord + Clone,
    V: Clone,
{
    pub fn new(max_entries: Option<usize>) -> Self {
        Self::with_byte_limit(max_entries, None)
    }

    /// A byte-limited cache requires `insert_weighted` with conservative heap
    /// charges for both key and value. Table storage is charged separately.
    pub fn with_byte_limit(max_entries: Option<usize>, max_bytes: Option<usize>) -> Self {
        Self::with_byte_limits(max_entries, max_bytes, None)
    }

    /// Bound both aggregate retention and one key/value entry. The per-entry
    /// limit includes its inline layout; the aggregate additionally accounts
    /// for spare hash-table capacity. Zero disables retention.
    pub fn with_byte_limits(
        max_entries: Option<usize>,
        max_bytes: Option<usize>,
        max_entry_bytes: Option<usize>,
    ) -> Self {
        Self {
            max_entries,
            max_bytes,
            max_entry_bytes,
            entry_heap_charge: 0,
            table_capacity_high_water: 0,
            entries: HashMap::new(),
            access_tick: 0,
            hits: 0,
            misses: 0,
            admissions: 0,
            disabled_misses: 0,
            bypasses: 0,
            evictions: 0,
            memory_pressure_events: 0,
            rejected_admissions: 0,
        }
    }

    pub fn get(&mut self, key: &K) -> Option<V> {
        if self.max_entries == Some(0)
            || self.max_bytes == Some(0)
            || self.max_entry_bytes == Some(0)
        {
            self.misses += 1;
            self.disabled_misses += 1;
            return None;
        }
        self.access_tick = self.access_tick.saturating_add(1);
        let Some(entry) = self.entries.get_mut(key) else {
            self.misses += 1;
            return None;
        };
        self.hits += 1;
        entry.frequency = entry.frequency.saturating_add(1);
        entry.last_access_tick = self.access_tick;
        Some(entry.value.clone())
    }

    pub fn record_bypass(&mut self) {
        self.bypasses = self.bypasses.saturating_add(1);
    }

    pub fn record_rejected_admission(&mut self) {
        self.rejected_admissions = self.rejected_admissions.saturating_add(1);
    }

    /// Legacy count-only admission. Byte-limited caches refuse this path so
    /// callers cannot accidentally retain an uncharged key/value payload.
    pub fn insert(&mut self, key: K, value: V) {
        if self.max_bytes.is_none() && self.max_entry_bytes.is_none() {
            self.insert_weighted(key, value, 0);
        } else {
            self.rejected_admissions = self.rejected_admissions.saturating_add(1);
        }
    }

    /// Charge owned heap retained through the key/value, excluding their inline
    /// bucket layout. Rejected admissions leave an existing entry unchanged.
    /// In-flight cloned values are owned by callers, outside this cache bound.
    /// Returns whether admission checks accepted the entry. Subsequent LFU
    /// eviction can still remove it; this does not promise a future cache hit.
    pub fn insert_weighted(&mut self, key: K, value: V, heap_charge: usize) -> bool {
        let entry_bytes = heap_charge.checked_add(std::mem::size_of::<(K, LfuCacheEntry<V>)>());
        if entry_bytes.is_none()
            || self
                .max_entry_bytes
                .is_some_and(|limit| limit == 0 || entry_bytes.is_none_or(|bytes| bytes > limit))
            || self.max_entries == Some(0)
            || self.max_bytes.is_some_and(|limit| {
                // Pinned std's smallest nonempty table advertises three
                // entries. Refuse an entry that cannot fit even that table
                // before removing an existing key or evicting other plans.
                Self::table_heap_charge(3)
                    .and_then(|table| heap_charge.checked_add(table))
                    .is_none_or(|minimum| minimum > limit)
            })
        {
            self.rejected_admissions = self.rejected_admissions.saturating_add(1);
            return false;
        }
        let previous = self.entries.get(&key).map_or(0, |entry| entry.heap_charge);
        let Some(total) = self
            .entry_heap_charge
            .checked_sub(previous)
            .and_then(|bytes| bytes.checked_add(heap_charge))
        else {
            self.rejected_admissions = self.rejected_admissions.saturating_add(1);
            return false;
        };
        self.entry_heap_charge = total;
        self.access_tick = self.access_tick.saturating_add(1);
        // Replace the key too: an equal old key may retain more spare heap
        // capacity than the incoming key whose charge the caller supplied.
        let frequency = self
            .entries
            .remove(&key)
            .map_or(1, |entry| entry.frequency.saturating_add(1));
        self.entries.insert(
            key,
            LfuCacheEntry {
                value,
                heap_charge,
                frequency,
                last_access_tick: self.access_tick,
            },
        );
        self.table_capacity_high_water =
            self.table_capacity_high_water.max(self.entries.capacity());
        self.admissions = self.admissions.saturating_add(1);
        if self.over_entry_limit() || self.over_byte_limit() {
            self.memory_pressure_events = self.memory_pressure_events.saturating_add(1);
        }
        while self.over_entry_limit() || self.over_byte_limit() {
            let Some(victim) = self.lfu_victim_key() else {
                // An empty map must not retain an over-budget bucket buffer.
                self.entries = HashMap::new();
                self.table_capacity_high_water = 0;
                break;
            };
            let removed = self
                .entries
                .remove(&victim)
                .expect("selected victim exists");
            self.entry_heap_charge -= removed.heap_charge;
            self.evictions = self.evictions.saturating_add(1);
            if self.entries.is_empty() {
                self.entries = HashMap::new();
                self.table_capacity_high_water = 0;
            } else if self.over_byte_limit() {
                self.entries.shrink_to_fit();
            }
        }
        true
    }

    pub fn max_bytes(&self) -> Option<usize> {
        self.max_bytes
    }

    /// Conservative requested-heap charge, including spare hash-table capacity.
    /// The pinned hashbrown table uses at most twice its original advertised
    /// capacity in buckets plus control bytes/alignment. Preserve the high-water
    /// capacity: tombstones can lower `HashMap::capacity()` without freeing its
    /// allocation. This excludes allocator rounding,
    /// the fixed cache object and heap owned by callers after cloning a value.
    pub fn charged_bytes(&self) -> Option<usize> {
        self.entry_heap_charge
            .checked_add(Self::table_heap_charge(self.table_capacity_high_water)?)
    }

    fn table_heap_charge(capacity: usize) -> Option<usize> {
        if capacity == 0 {
            return Some(0);
        }
        let buckets = capacity.checked_mul(2)?;
        let bucket = std::mem::size_of::<(K, LfuCacheEntry<V>)>().checked_add(1)?;
        buckets
            .checked_mul(bucket)?
            .checked_add(32)?
            .checked_add(std::mem::align_of::<(K, LfuCacheEntry<V>)>())
    }

    fn over_entry_limit(&self) -> bool {
        self.max_entries
            .is_some_and(|limit| self.entries.len() > limit)
    }

    fn over_byte_limit(&self) -> bool {
        self.max_bytes
            .is_some_and(|limit| self.charged_bytes().is_none_or(|bytes| bytes > limit))
    }

    fn lfu_victim_key(&self) -> Option<K> {
        self.entries
            .iter()
            .min_by(|(left_key, left), (right_key, right)| {
                (left.frequency, left.last_access_tick, *left_key).cmp(&(
                    right.frequency,
                    right.last_access_tick,
                    *right_key,
                ))
            })
            .map(|(key, _)| key.clone())
    }

    pub fn stats(&self) -> PlanCacheStats {
        PlanCacheStats {
            max_entries: self.max_entries,
            max_bytes: self.max_bytes,
            max_entry_bytes: self.max_entry_bytes,
            charged_bytes: (self.max_bytes.is_some() || self.max_entry_bytes.is_some())
                .then(|| self.charged_bytes())
                .flatten(),
            entries: self.entries.len(),
            hits: self.hits,
            misses: self.misses,
            admissions: self.admissions,
            disabled_misses: self.disabled_misses,
            bypasses: self.bypasses,
            evictions: self.evictions,
            memory_pressure_events: self.memory_pressure_events,
            rejected_admissions: self.rejected_admissions,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{LfuCache, PlanCacheBypassReason, PlanCacheLookup};
    use std::sync::{Arc, Barrier, Mutex};
    use std::thread;

    #[test]
    fn total_limit_refuses_a_replacement_that_cannot_fit_its_table() {
        let mut cache = LfuCache::with_byte_limits(Some(8), Some(512), Some(512));
        cache.insert_weighted(1u8, vec![1u8; 64], 64);
        assert_eq!(cache.stats().entries, 1);
        let before = cache.charged_bytes();
        // The payload and inline entry each fit their limits, but the payload
        // plus even a one-entry table cannot fit the total retention budget.
        cache.insert_weighted(1u8, vec![2u8; 400], 400);
        assert_eq!(cache.get(&1), Some(vec![1u8; 64]));
        assert_eq!(cache.charged_bytes(), before);
        assert_eq!(cache.stats().admissions, 1);
        assert_eq!(cache.stats().evictions, 0);
        assert_eq!(cache.stats().rejected_admissions, 1);
    }

    #[test]
    fn per_entry_limit_refuses_oversize_replacement_without_evicting_hot_entries() {
        let mut cache = LfuCache::with_byte_limits(Some(8), Some(8192), Some(1024));
        cache.insert_weighted(1, vec![1; 256], 256);
        cache.insert_weighted(2, vec![2; 256], 256);
        let before = cache.charged_bytes();
        cache.insert_weighted(1, vec![3; 1024], 1024);
        assert_eq!(cache.charged_bytes(), before);
        assert_eq!(cache.get(&1), Some(vec![1; 256]));
        assert_eq!(cache.get(&2), Some(vec![2; 256]));
        assert_eq!(cache.stats().entries, 2);
        assert_eq!(cache.stats().evictions, 0);
        assert_eq!(cache.stats().rejected_admissions, 1);
        assert_eq!(cache.stats().max_entry_bytes, Some(1024));
        assert_eq!(cache.stats().charged_bytes, before);
    }

    #[test]
    fn per_entry_only_limit_requires_weighted_admission_and_zero_disables_retention() {
        let mut cache = LfuCache::with_byte_limits(None, None, Some(1024));
        cache.insert(1, vec![0; 8192]);
        assert_eq!(cache.stats().entries, 0);
        cache.insert_weighted(1, vec![1; 64], 64);
        assert_eq!(cache.get(&1), Some(vec![1; 64]));
        assert!(cache.stats().charged_bytes.unwrap() >= 64);

        let mut disabled = LfuCache::with_byte_limits(None, Some(8192), Some(0));
        disabled.insert_weighted(1, (), 0);
        assert_eq!(disabled.get(&1), None);
        assert_eq!(disabled.stats().disabled_misses, 1);
        assert_eq!(disabled.stats().charged_bytes, Some(0));
        assert_eq!(disabled.stats().rejected_admissions, 1);
    }

    #[test]
    fn weighted_replacement_retains_the_charged_key_capacity() {
        let mut cache = LfuCache::with_byte_limit(Some(8), Some(8192));
        let mut key = String::with_capacity(4096);
        key.push('a');
        cache.insert_weighted(key, (), 4096);
        let smaller_key = "a".to_owned();
        let charge = smaller_key.capacity();
        cache.insert_weighted(smaller_key, (), charge);
        assert_eq!(cache.entries.keys().next().unwrap().capacity(), charge);
        assert_eq!(cache.entry_heap_charge, charge);
    }

    #[test]
    fn byte_limited_lfu_bounds_a_burst_and_its_table_capacity() {
        let mut cache = LfuCache::with_byte_limit(Some(128), Some(4096));
        for key in 0..256 {
            cache.insert_weighted(key, vec![key as u8; 1024], 1024);
            assert!(cache.charged_bytes().unwrap() <= 4096);
            for (key, entry) in &cache.entries {
                assert_eq!(entry.value[0], *key as u8);
            }
        }
        assert!(cache.stats().evictions > 0);
        assert!(cache.stats().entries <= 3);
        assert!(cache.clone().charged_bytes().unwrap() <= 4096);
    }

    #[test]
    fn byte_limited_lfu_refuses_uncharged_admission() {
        let mut cache = LfuCache::with_byte_limit(Some(8), Some(4096));
        cache.insert(1, vec![0; 8192]);
        assert_eq!(cache.stats().entries, 0);
        assert_eq!(cache.charged_bytes(), Some(0));
        cache.insert_weighted(1, vec![1; 16], 16);
        assert_eq!(cache.get(&1), Some(vec![1; 16]));
    }

    #[test]
    fn byte_limited_lfu_replacement_and_oversize_admission_are_atomic() {
        let mut cache = LfuCache::with_byte_limit(Some(8), Some(4096));
        assert!(cache.insert_weighted(1, vec![1; 1024], 1024));
        assert!(cache.insert_weighted(1, vec![2; 2048], 2048));
        assert_eq!(cache.entry_heap_charge, 2048);
        let before = cache.charged_bytes();
        assert!(!cache.insert_weighted(1, vec![3; 8192], 8192));
        assert_eq!(cache.charged_bytes(), before);
        assert_eq!(cache.get(&1), Some(vec![2; 2048]));
        assert_eq!(cache.stats().entries, 1);
    }

    #[test]
    fn zero_and_overflowing_byte_budgets_cannot_leave_retained_entries() {
        let mut disabled = LfuCache::with_byte_limit(None, Some(0));
        assert!(!disabled.insert_weighted(1, 1, 0));
        assert_eq!(disabled.get(&1), None);
        assert_eq!(disabled.stats().disabled_misses, 1);
        assert_eq!(disabled.charged_bytes(), Some(0));
        let mut overflow = LfuCache::with_byte_limit(None, Some(usize::MAX));
        assert!(!overflow.insert_weighted(1, 1, usize::MAX));
        assert_eq!(overflow.stats().entries, 0);
        assert_eq!(overflow.charged_bytes(), Some(0));
    }

    #[test]
    fn lfu_cache_evicts_least_frequently_used_entry() {
        let mut cache = LfuCache::new(Some(2));
        cache.insert("hot", 1);
        cache.insert("cold", 2);

        assert_eq!(cache.get(&"hot"), Some(1));
        cache.insert("new", 3);

        assert_eq!(cache.get(&"hot"), Some(1));
        assert_eq!(cache.get(&"new"), Some(3));
        assert_eq!(cache.get(&"cold"), None);
        assert_eq!(cache.stats().admissions, 3);
        assert_eq!(cache.stats().evictions, 1);
        assert_eq!(cache.stats().memory_pressure_events, 1);
    }

    #[test]
    fn lfu_cache_uses_oldest_access_as_tie_breaker() {
        let mut cache = LfuCache::new(Some(2));
        cache.insert("older", 1);
        cache.insert("newer", 2);
        cache.insert("third", 3);

        assert_eq!(cache.get(&"older"), None);
        assert_eq!(cache.get(&"newer"), Some(2));
        assert_eq!(cache.get(&"third"), Some(3));
    }

    #[test]
    fn zero_capacity_cache_records_misses_without_entries() {
        let mut cache = LfuCache::new(Some(0));
        cache.insert("ignored", 1);

        assert_eq!(cache.get(&"ignored"), None);
        assert_eq!(cache.stats().entries, 0);
        assert_eq!(cache.stats().misses, 1);
        assert_eq!(cache.stats().disabled_misses, 1);
        assert_eq!(cache.stats().admissions, 0);
        assert_eq!(cache.stats().memory_pressure_events, 0);
    }

    #[test]
    fn lookup_reports_cacheability_and_bypass_reason() {
        let bypass = PlanCacheLookup::Bypass(PlanCacheBypassReason::OptimizerDirective);

        assert_eq!(PlanCacheLookup::Hit.as_str(), "hit");
        assert_eq!(bypass.as_str(), "bypass");
        assert_eq!(
            bypass.bypass_reason(),
            Some(PlanCacheBypassReason::OptimizerDirective)
        );
        assert_eq!(
            PlanCacheBypassReason::StatementNotCacheable.as_str(),
            "statement_not_cacheable"
        );
    }

    #[test]
    fn hash_lookup_updates_lfu_accounting_once() {
        let mut cache = LfuCache::new(Some(2));
        cache.insert("query-a", 1);
        cache.insert("query-b", 2);

        assert_eq!(cache.get(&"query-b"), Some(2));
        assert_eq!(cache.get(&"query-c"), None);
        assert_eq!(cache.stats().hits, 1);
        assert_eq!(cache.stats().misses, 1);
    }

    #[test]
    fn duplicate_hash_keys_update_one_entry() {
        let mut cache = LfuCache::new(Some(2));
        cache.insert("query", 1);
        cache.insert("query", 2);

        assert_eq!(cache.stats().entries, 1);
        assert_eq!(cache.get(&"query"), Some(2));
        assert_eq!(cache.stats().entries, 1);
    }

    #[test]
    fn cache_records_bypassed_plans_separately_from_misses() {
        let mut cache: LfuCache<&str, i32> = LfuCache::new(Some(2));

        cache.record_bypass();

        assert_eq!(cache.stats().bypasses, 1);
        assert_eq!(cache.stats().misses, 0);
        assert_eq!(cache.stats().hits, 0);
        assert_eq!(cache.stats().admissions, 0);
    }

    #[test]
    fn unbounded_cache_records_admissions_without_pressure() {
        let mut cache = LfuCache::new(None);

        cache.insert("first", 1);
        cache.insert("second", 2);

        assert_eq!(cache.stats().entries, 2);
        assert_eq!(cache.stats().admissions, 2);
        assert_eq!(cache.stats().memory_pressure_events, 0);
        assert_eq!(cache.stats().evictions, 0);
    }

    #[test]
    fn weighted_cache_bounds_survive_concurrent_misses_replacements_and_refusals() {
        let cache = Arc::new(Mutex::new(LfuCache::with_byte_limits(
            Some(8),
            Some(4096),
            Some(512),
        )));
        let start = Arc::new(Barrier::new(4));
        let handles = (0..4)
            .map(|worker| {
                let cache = Arc::clone(&cache);
                let start = Arc::clone(&start);
                thread::spawn(move || {
                    start.wait();
                    for offset in 0..64 {
                        // Build misses outside the cache lock, as the facade does.
                        let key = format!("key-{}", (worker + offset) % 32);
                        let value = vec![worker as u8; if offset % 11 == 0 { 1024 } else { 256 }];
                        let charge = key.capacity() + value.capacity();
                        let mut cache = cache.lock().unwrap();
                        cache.insert_weighted(key.clone(), value, charge);
                        let _ = cache.get(&key);
                        assert!(cache.stats().entries <= 8);
                        assert!(cache.charged_bytes().unwrap() <= 4096);
                    }
                })
            })
            .collect::<Vec<_>>();
        for handle in handles {
            handle.join().unwrap();
        }
        let stats = cache.lock().unwrap().stats();
        assert!(stats.rejected_admissions > 0);
        assert!(stats.evictions > 0);
        assert!(stats.hits > 0);
    }

    #[test]
    fn cache_remains_bounded_under_mutex_protected_concurrent_access() {
        let cache = Arc::new(Mutex::new(LfuCache::new(Some(8))));
        let start = Arc::new(Barrier::new(4));

        let handles = (0..4)
            .map(|worker| {
                let cache = Arc::clone(&cache);
                let start = Arc::clone(&start);
                thread::spawn(move || {
                    start.wait();
                    for offset in 0..64 {
                        let key = format!("key-{}", (worker + offset) % 16);
                        let mut cache = cache.lock().unwrap();
                        cache.insert(key.clone(), worker * 100 + offset);
                        let _ = cache.get(&key);
                    }
                })
            })
            .collect::<Vec<_>>();

        for handle in handles {
            handle.join().unwrap();
        }

        let stats = cache.lock().unwrap().stats();
        assert_eq!(stats.entries, 8);
        assert_eq!(stats.admissions, 256);
        assert!(stats.hits > 0);
        assert!(stats.evictions > 0);
        assert!(stats.memory_pressure_events > 0);
    }
}

#[cfg(all(test, feature = "loom-tests"))]
mod loom_tests {
    use super::LfuCache;
    use loom::sync::{Arc, Mutex};
    use loom::thread;

    #[test]
    fn lfu_cache_preserves_bounds_under_modeled_concurrent_access() {
        loom::model(|| {
            let cache = Arc::new(Mutex::new(LfuCache::new(Some(2))));

            let writer = {
                let cache = Arc::clone(&cache);
                thread::spawn(move || {
                    let mut cache = cache.lock().unwrap();
                    cache.insert("first", 1);
                    cache.insert("second", 2);
                })
            };

            let reader_writer = {
                let cache = Arc::clone(&cache);
                thread::spawn(move || {
                    let mut cache = cache.lock().unwrap();
                    let _ = cache.get(&"first");
                    cache.insert("third", 3);
                })
            };

            writer.join().unwrap();
            reader_writer.join().unwrap();

            let stats = cache.lock().unwrap().stats();
            assert!(stats.entries <= 2);
            assert!(stats.admissions <= 3);
            assert!(stats.evictions <= 1);
            assert_eq!(stats.max_entries, Some(2));
        });
    }
}