Skip to main content

reddb_engine/storage/
page_cache.rs

1//! SIEVE Page Cache Implementation
2//!
3//! A simple, efficient page cache using the SIEVE eviction algorithm.
4//! SIEVE outperforms LRU in many workloads while being simpler to implement.
5//!
6//! # SIEVE Algorithm (NSDI '24)
7//!
8//! SIEVE uses a single "visited" bit instead of LRU's complex list management:
9//! 1. On cache hit: set visited = true
10//! 2. On cache miss (insertion): add to FIFO queue
11//! 3. On eviction: sweep from "hand" position
12//!    - If visited=true: clear bit, skip
13//!    - If visited=false: evict this entry
14//!
15//! # References
16//!
17//! - Turso `core/storage/page_cache.rs:24-80` - PageCacheShardEntry with ref_bit
18//! - Turso `core/storage/page_cache.rs:129-150` - advance_clock_hand()
19//! - "SIEVE is Simpler than LRU" (NSDI '24)
20
21use std::collections::{HashMap, VecDeque};
22use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
23use std::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
24
25use super::page::Page;
26
27fn cache_read<'a, T>(lock: &'a RwLock<T>) -> RwLockReadGuard<'a, T> {
28    lock.read().unwrap_or_else(|poisoned| poisoned.into_inner())
29}
30
31fn cache_write<'a, T>(lock: &'a RwLock<T>) -> RwLockWriteGuard<'a, T> {
32    lock.write()
33        .unwrap_or_else(|poisoned| poisoned.into_inner())
34}
35
36fn cache_lock<'a, T>(lock: &'a Mutex<T>) -> MutexGuard<'a, T> {
37    lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
38}
39
40/// Default cache capacity (number of pages)
41/// Turso uses 100,000 pages (~400MB for 4KB pages)
42pub const DEFAULT_CACHE_CAPACITY: usize = 100_000;
43
44/// Minimum cache capacity
45pub const MIN_CACHE_CAPACITY: usize = 1;
46
47/// Lock-protected cache entry.
48///
49/// Per ADR 0033 (`page-cache-lock-free-hit`), the SIEVE `visited` bit
50/// no longer lives here — it moved to [`ShardMeta`], a separate
51/// cache-line-packed atomic array, so a cache hit can flip it without
52/// upgrading the per-shard write lock. `pin_count` and `dirty` stay in
53/// the entry behind the `entries` `RwLock`: they are written only by
54/// structural operations (`pin`/`unpin`/`mark_dirty`/`mark_clean`,
55/// which take the write lock) and are *never* touched by the hit path.
56struct CacheEntry {
57    /// Identity of the index key owning this slot, protected with its image.
58    page_id: u32,
59    /// The cached page
60    page: Page,
61    /// Pin count (page cannot be evicted while pinned)
62    pin_count: usize,
63    /// Whether the page is dirty (modified)
64    dirty: bool,
65}
66
67impl CacheEntry {
68    fn new(page_id: u32, page: Page, dirty: bool) -> Self {
69        Self {
70            page_id,
71            page,
72            pin_count: 0,
73            dirty,
74        }
75    }
76}
77
78/// Cache line size in bytes (x86-64 / aarch64). The SIEVE `visited`
79/// bits and per-slot `tag`s are laid out in their own line-aligned,
80/// densely packed arrays (see [`ShardMeta`]) so the lock-free hit path
81/// — which only ever touches `visited`/`tag` — never shares a cache
82/// line with the lock-protected [`CacheEntry`] payload (page bytes,
83/// `pin_count`, `dirty`). ADR 0033.
84const CACHE_LINE: usize = 64;
85
86/// Sentinel `tag` value for an unoccupied slot. `u32::MAX` is reserved
87/// (no real page id uses it) so the hit path can tell, with a single
88/// relaxed load, whether the slot it resolved still belongs to the
89/// page it is marking.
90const TAG_EMPTY: u32 = u32::MAX;
91
92/// One cache line of packed `visited` bits: one [`AtomicBool`] (1 byte)
93/// per slot, 64 slots per line. `#[repr(align(64))]` forces the boxed
94/// backing buffer onto a line boundary, so the array starts aligned and
95/// no two unrelated lines ever false-share.
96#[repr(align(64))]
97struct VisitedLine([AtomicBool; CACHE_LINE]);
98
99/// Number of `AtomicU32` tags that fit in one cache line.
100const TAGS_PER_LINE: usize = CACHE_LINE / 4;
101
102/// One cache line of packed slot tags: one [`AtomicU32`] (4 bytes) per
103/// slot, 16 slots per line. Line-aligned for the same reason as
104/// [`VisitedLine`].
105#[repr(align(64))]
106struct TagLine([AtomicU32; TAGS_PER_LINE]);
107
108/// Cache-line-packed SIEVE metadata, split out of [`CacheEntry`].
109///
110/// Both arrays are indexed by slot and are *separate, line-aligned*
111/// allocations (ADR 0033 acceptance: "visited/tag metadata is laid out
112/// in separate cache-line-aligned arrays"). Because the elements are
113/// atomics, the hit path mutates `visited` through a shared `&self`
114/// with no lock at all — satisfying the contract's "cache hits set
115/// visited without acquiring the per-shard write lock".
116///
117/// The arrays are sized to the shard `capacity`. In normal operation a
118/// slot index never reaches `capacity` (`insert` evicts before growing
119/// `entries`), so every access lands in range. The one pathological
120/// exception — a full cache whose every slot is pinned, where `insert`
121/// grows `entries` past `capacity` — is handled by the bounds guards
122/// below: an out-of-range slot reports "not visited" / `TAG_EMPTY`,
123/// which makes that emergency over-capacity entry the first eviction
124/// candidate once a slot frees. No panic, no unbounded metadata.
125struct ShardMeta {
126    visited: Box<[VisitedLine]>,
127    tag: Box<[TagLine]>,
128    capacity: usize,
129}
130
131impl ShardMeta {
132    fn new(capacity: usize) -> Self {
133        let visited = (0..capacity.div_ceil(CACHE_LINE))
134            .map(|_| VisitedLine(std::array::from_fn(|_| AtomicBool::new(false))))
135            .collect::<Vec<_>>()
136            .into_boxed_slice();
137        let tag = (0..capacity.div_ceil(TAGS_PER_LINE))
138            .map(|_| TagLine(std::array::from_fn(|_| AtomicU32::new(TAG_EMPTY))))
139            .collect::<Vec<_>>()
140            .into_boxed_slice();
141        Self {
142            visited,
143            tag,
144            capacity,
145        }
146    }
147
148    /// Lock-free SIEVE hit mark. Benign-race by contract (ADR 0033): a
149    /// concurrent eviction clearing this same bit only costs one extra
150    /// SIEVE cycle. `Relaxed` is sufficient — the bit carries no
151    /// happens-before obligation toward any other state.
152    #[inline]
153    fn mark_visited(&self, slot: usize) {
154        if let Some(b) = self.visited_bit(slot) {
155            b.store(true, Ordering::Relaxed);
156        }
157    }
158
159    #[inline]
160    fn is_visited(&self, slot: usize) -> bool {
161        self.visited_bit(slot)
162            .map(|b| b.load(Ordering::Relaxed))
163            .unwrap_or(false)
164    }
165
166    /// Clear the visited bit. Structural (called from the eviction hand
167    /// under the per-shard locks), but the store itself is a relaxed
168    /// atomic so it composes with the lock-free hit mark.
169    #[inline]
170    fn clear_visited(&self, slot: usize) {
171        if let Some(b) = self.visited_bit(slot) {
172            b.store(false, Ordering::Relaxed);
173        }
174    }
175
176    /// The page id currently tagged at `slot`, or [`TAG_EMPTY`].
177    #[inline]
178    fn tag(&self, slot: usize) -> u32 {
179        self.tag_slot(slot)
180            .map(|t| t.load(Ordering::Relaxed))
181            .unwrap_or(TAG_EMPTY)
182    }
183
184    /// Bind a slot to a page and reset its visited bit. Structural:
185    /// the caller holds the per-shard write lock that serialises slot
186    /// ownership.
187    #[inline]
188    fn occupy(&self, slot: usize, page_id: u32) {
189        if let Some(t) = self.tag_slot(slot) {
190            t.store(page_id, Ordering::Relaxed);
191        }
192        self.clear_visited(slot);
193    }
194
195    /// Release a slot. Structural; caller holds the write lock.
196    #[inline]
197    fn vacate(&self, slot: usize) {
198        if let Some(t) = self.tag_slot(slot) {
199            t.store(TAG_EMPTY, Ordering::Relaxed);
200        }
201        self.clear_visited(slot);
202    }
203
204    /// Reset all metadata to the empty state (used by `clear`).
205    fn reset(&self) {
206        for line in self.visited.iter() {
207            for b in line.0.iter() {
208                b.store(false, Ordering::Relaxed);
209            }
210        }
211        for line in self.tag.iter() {
212            for t in line.0.iter() {
213                t.store(TAG_EMPTY, Ordering::Relaxed);
214            }
215        }
216    }
217
218    #[inline]
219    fn visited_bit(&self, slot: usize) -> Option<&AtomicBool> {
220        if slot >= self.capacity {
221            return None;
222        }
223        self.visited
224            .get(slot / CACHE_LINE)
225            .map(|line| &line.0[slot % CACHE_LINE])
226    }
227
228    #[inline]
229    fn tag_slot(&self, slot: usize) -> Option<&AtomicU32> {
230        if slot >= self.capacity {
231            return None;
232        }
233        self.tag
234            .get(slot / TAGS_PER_LINE)
235            .map(|line| &line.0[slot % TAGS_PER_LINE])
236    }
237}
238
239/// Cache statistics
240#[derive(Debug, Default, Clone)]
241pub struct CacheStats {
242    /// Number of cache hits
243    pub hits: u64,
244    /// Number of cache misses
245    pub misses: u64,
246    /// Number of evictions
247    pub evictions: u64,
248    /// Number of dirty page writebacks
249    pub writebacks: u64,
250}
251
252impl CacheStats {
253    /// Calculate hit rate (0.0 to 1.0)
254    pub fn hit_rate(&self) -> f64 {
255        let total = self.hits + self.misses;
256        if total == 0 {
257            0.0
258        } else {
259            self.hits as f64 / total as f64
260        }
261    }
262}
263
264/// SIEVE-based page cache
265///
266/// Thread-safe page cache using the SIEVE eviction algorithm.
267pub struct PageCacheShard {
268    /// Maximum number of pages to cache
269    capacity: usize,
270    /// Publish index, slots and FIFO changes together. Hits do not take this lock.
271    structure: Mutex<()>,
272    /// Page ID -> Entry index mapping
273    index: RwLock<HashMap<u32, usize>>,
274    /// FIFO queue of page IDs for eviction order
275    fifo: Mutex<VecDeque<u32>>,
276    /// Cache entries (indexed by slot)
277    entries: RwLock<Vec<Option<CacheEntry>>>,
278    /// Cache-line-packed SIEVE metadata (`visited` bits + slot `tag`s),
279    /// kept out of `entries` so the hit path can mark `visited` with a
280    /// lock-free relaxed atomic store. ADR 0033.
281    meta: ShardMeta,
282    /// Free slots
283    free_slots: Mutex<Vec<usize>>,
284    /// SIEVE eviction hand position
285    hand: Mutex<usize>,
286    /// Cache statistics
287    stats: Mutex<CacheStats>,
288    /// Dirty images this shard has given up to its caller. Counted before the
289    /// image stops being a hit, so a miss that reads it unchanged afterwards
290    /// knows no dirty image was on its way to the file meanwhile.
291    dirty_evictions: AtomicU64,
292}
293
294impl PageCacheShard {
295    /// Create a new page cache with specified capacity
296    pub fn new(capacity: usize) -> Self {
297        let capacity = capacity.max(MIN_CACHE_CAPACITY);
298
299        Self {
300            capacity,
301            structure: Mutex::new(()),
302            index: RwLock::new(HashMap::with_capacity(capacity)),
303            fifo: Mutex::new(VecDeque::with_capacity(capacity)),
304            entries: RwLock::new(Vec::with_capacity(capacity)),
305            meta: ShardMeta::new(capacity),
306            free_slots: Mutex::new(Vec::new()),
307            hand: Mutex::new(0),
308            stats: Mutex::new(CacheStats::default()),
309            dirty_evictions: AtomicU64::new(0),
310        }
311    }
312
313    /// Create a page cache with default capacity
314    pub fn with_default_capacity() -> Self {
315        Self::new(DEFAULT_CACHE_CAPACITY)
316    }
317
318    /// Dirty images evicted so far. See [`PageCache::dirty_evictions`].
319    pub fn dirty_evictions(&self) -> u64 {
320        self.dirty_evictions.load(Ordering::SeqCst)
321    }
322
323    /// Get the current number of cached pages
324    pub fn len(&self) -> usize {
325        cache_read(&self.index).len()
326    }
327
328    /// Check if cache is empty
329    pub fn is_empty(&self) -> bool {
330        self.len() == 0
331    }
332
333    /// Get cache capacity
334    pub fn capacity(&self) -> usize {
335        self.capacity
336    }
337
338    /// Get cache statistics
339    pub fn stats(&self) -> CacheStats {
340        cache_lock(&self.stats).clone()
341    }
342
343    /// Reset statistics
344    pub fn reset_stats(&self) {
345        *cache_lock(&self.stats) = CacheStats::default();
346    }
347
348    /// Get a page from cache
349    ///
350    /// Returns None if page is not in cache (cache miss).
351    /// On hit, marks the page as visited (SIEVE).
352    pub fn get(&self, page_id: u32) -> Option<Page> {
353        // Check if page is in cache
354        let index = cache_read(&self.index);
355        let slot = match index.get(&page_id) {
356            Some(&s) => s,
357            None => {
358                drop(index);
359                // Cache miss
360                cache_lock(&self.stats).misses += 1;
361                return None;
362            }
363        };
364        drop(index);
365
366        #[cfg(test)]
367        tests::after_slot_lookup();
368
369        // Lock-free hit path (ADR 0033). Clone the page under a *read*
370        // lock — never a write lock — then set the SIEVE `visited` bit
371        // with a single relaxed atomic store on the separate
372        // cache-line-packed metadata array. The hit path acquires no
373        // write lock and never touches `pin_count`/`dirty` (those live
374        // in `CacheEntry` behind the write lock and are mutated only by
375        // structural operations). Dropping the per-hit write-lock
376        // upgrade is the whole point: hot-loop reads of an
377        // already-cached page (e.g. BTree inserts hammering the
378        // rightmost leaf) no longer serialise on the entries writer.
379        let entries = cache_read(&self.entries);
380        if let Some(entry) = entries
381            .get(slot)
382            .and_then(|e| e.as_ref())
383            .filter(|entry| entry.page_id == page_id)
384        {
385            let page = entry.page.clone();
386            drop(entries);
387
388            // Mark visited lock-free. Confirm the slot still tags this
389            // page id first: if a racing eviction repurposed the slot
390            // we simply skip the mark (benign — at worst one extra
391            // SIEVE cycle, never a wrong-page write). The tag check
392            // never changes hit/miss accounting; the requested page was
393            // validated under the entries lock, so this is a hit.
394            if self.meta.tag(slot) == page_id {
395                self.meta.mark_visited(slot);
396            }
397
398            cache_lock(&self.stats).hits += 1;
399
400            Some(page)
401        } else {
402            cache_lock(&self.stats).misses += 1;
403            None
404        }
405    }
406
407    /// Insert a page into cache
408    ///
409    /// May trigger eviction if cache is full.
410    /// Returns the evicted page (if dirty) that needs to be written back.
411    pub fn insert(&self, page_id: u32, page: Page) -> Option<Page> {
412        self.insert_inner(page_id, page, false, true)
413    }
414
415    fn insert_inner(
416        &self,
417        page_id: u32,
418        page: Page,
419        dirty: bool,
420        replace_existing: bool,
421    ) -> Option<Page> {
422        let _structure = cache_lock(&self.structure);
423        // Check if already in cache
424        {
425            let index = cache_read(&self.index);
426            if let Some(&slot) = index.get(&page_id) {
427                drop(index);
428
429                // Update existing entry under the write lock; the
430                // SIEVE visited bit lives in the separate metadata
431                // array and is set lock-free (matches the prior
432                // behaviour of marking a re-inserted page visited).
433                let mut entries = cache_write(&self.entries);
434                if let Some(Some(entry)) = entries.get_mut(slot) {
435                    if replace_existing {
436                        entry.page = page;
437                        entry.dirty |= dirty;
438                    }
439                }
440                drop(entries);
441                self.meta.mark_visited(slot);
442                return None;
443            }
444        }
445
446        // Need to insert new entry
447        let mut evicted = None;
448
449        // Check if we need to evict before getting free_slots lock
450        let current_len = self.len();
451        if current_len >= self.capacity {
452            // Need to evict first (no locks held)
453            evicted = self.evict();
454        }
455
456        // Find or create a slot
457        let slot = {
458            let mut free_slots = cache_lock(&self.free_slots);
459            if let Some(slot) = free_slots.pop() {
460                slot
461            } else {
462                drop(free_slots);
463                // Add a new slot
464                let mut entries = cache_write(&self.entries);
465                let slot = entries.len();
466                entries.push(None);
467                slot
468            }
469        };
470
471        // Insert entry
472        {
473            let mut entries = cache_write(&self.entries);
474
475            // Ensure slot exists
476            while entries.len() <= slot {
477                entries.push(None);
478            }
479
480            entries[slot] = Some(CacheEntry::new(page_id, page, dirty));
481        }
482
483        // Update index
484        {
485            let mut index = cache_write(&self.index);
486            index.insert(page_id, slot);
487        }
488
489        // Bind the metadata slot to this page (tag = page_id, visited
490        // reset). Structural: ordered after the entry/index writes that
491        // the per-shard write lock serialises.
492        self.meta.occupy(slot, page_id);
493
494        // Add to FIFO
495        {
496            let mut fifo = cache_lock(&self.fifo);
497            fifo.push_back(page_id);
498        }
499
500        evicted
501    }
502
503    /// Publish a changed image and its dirty state for pager writes.
504    pub fn insert_dirty(&self, page_id: u32, page: Page) -> Option<Page> {
505        let evicted = self.insert_inner(page_id, page, true, true);
506        #[cfg(test)]
507        tests::after_insert_publish();
508        evicted
509    }
510
511    /// Complete a disk read without replacing an image installed meanwhile.
512    pub fn insert_if_absent(&self, page_id: u32, page: Page) -> Option<Page> {
513        self.insert_inner(page_id, page, false, false)
514    }
515
516    /// Evict a page using SIEVE algorithm
517    ///
518    /// Returns the evicted page if it was dirty.
519    fn evict(&self) -> Option<Page> {
520        let mut fifo = cache_lock(&self.fifo);
521        let mut hand = cache_lock(&self.hand);
522
523        if fifo.is_empty() {
524            return None;
525        }
526
527        let fifo_len = fifo.len();
528        let mut attempts = 0;
529
530        // Sweep from hand position
531        loop {
532            if attempts >= fifo_len * 2 {
533                // Couldn't find anything to evict (all pinned?)
534                return None;
535            }
536
537            // Wrap around
538            if *hand >= fifo_len {
539                *hand = 0;
540            }
541
542            let page_id = fifo[*hand];
543            attempts += 1;
544
545            // Get entry slot
546            let slot = {
547                let index = cache_read(&self.index);
548                match index.get(&page_id) {
549                    Some(&s) => s,
550                    None => {
551                        // Page was removed, skip
552                        *hand += 1;
553                        continue;
554                    }
555                }
556            };
557
558            // Check entry. `pin_count`/`dirty` are read under the
559            // entries lock; the SIEVE `visited` bit is read from the
560            // separate atomic metadata array.
561            let should_evict = {
562                let entries = cache_read(&self.entries);
563                match entries.get(slot).and_then(|e| e.as_ref()) {
564                    Some(entry) => {
565                        if entry.pin_count > 0 {
566                            // Pinned, can't evict
567                            false
568                        } else if self.meta.is_visited(slot) {
569                            // Clear visited bit, skip (SIEVE)
570                            false
571                        } else {
572                            // Can evict
573                            true
574                        }
575                    }
576                    None => {
577                        *hand += 1;
578                        continue;
579                    }
580                }
581            };
582
583            if !should_evict {
584                // Clear visited bit lock-free (no entries write lock
585                // needed — `visited` is no longer part of `CacheEntry`).
586                self.meta.clear_visited(slot);
587                *hand += 1;
588                continue;
589            }
590
591            // Evict this entry. Contract guard (ADR 0033): the eviction
592            // hand must never select a pinned page. We re-check under
593            // the write lock — the only place `pin_count` is read for
594            // the eviction decision and the place it must hold.
595            #[cfg(test)]
596            tests::before_evict_take();
597            let (evicted_page, dirty) = {
598                let mut entries = cache_write(&self.entries);
599                let Some(entry) = entries.get(slot).and_then(|e| e.as_ref()) else {
600                    *hand += 1;
601                    continue;
602                };
603                // A pin or write may have arrived after candidate selection.
604                // Revalidate while taking the exact image, in release builds too.
605                if entry.pin_count > 0 {
606                    *hand += 1;
607                    continue;
608                }
609                assert_eq!(
610                    entry.page_id, page_id,
611                    "invariant: eviction owns the indexed slot"
612                );
613                let entry = entries[slot].take().expect("validated cache candidate");
614                if entry.dirty {
615                    // Still under the lock a hit reads through.
616                    self.dirty_evictions.fetch_add(1, Ordering::SeqCst);
617                }
618                (entry.page, entry.dirty)
619            };
620
621            // Release the metadata slot (tag -> empty, visited -> false).
622            self.meta.vacate(slot);
623
624            // Remove from index
625            {
626                let mut index = cache_write(&self.index);
627                index.remove(&page_id);
628            }
629
630            // Remove from FIFO
631            fifo.remove(*hand);
632
633            // Add slot to free list
634            {
635                let mut free_slots = cache_lock(&self.free_slots);
636                free_slots.push(slot);
637            }
638
639            // Update stats
640            {
641                let mut stats = cache_lock(&self.stats);
642                stats.evictions += 1;
643                if dirty {
644                    stats.writebacks += 1;
645                }
646            }
647
648            // Return evicted page if dirty
649            if dirty {
650                return Some(evicted_page);
651            } else {
652                return None;
653            }
654        }
655    }
656
657    /// Mark a page as dirty
658    pub fn mark_dirty(&self, page_id: u32) {
659        let index = cache_read(&self.index);
660        if let Some(&slot) = index.get(&page_id) {
661            drop(index);
662
663            #[cfg(test)]
664            tests::after_slot_lookup();
665
666            let mut entries = cache_write(&self.entries);
667            if let Some(Some(entry)) = entries.get_mut(slot) {
668                if entry.page_id == page_id {
669                    entry.dirty = true;
670                }
671            }
672        }
673    }
674
675    /// Mark a page as clean
676    pub fn mark_clean(&self, page_id: u32) {
677        let index = cache_read(&self.index);
678        if let Some(&slot) = index.get(&page_id) {
679            drop(index);
680
681            #[cfg(test)]
682            tests::after_slot_lookup();
683
684            let mut entries = cache_write(&self.entries);
685            if let Some(Some(entry)) = entries.get_mut(slot) {
686                if entry.page_id == page_id {
687                    entry.dirty = false;
688                }
689            }
690        }
691    }
692
693    /// Pin a page (prevent eviction)
694    pub fn pin(&self, page_id: u32) -> bool {
695        let index = cache_read(&self.index);
696        if let Some(&slot) = index.get(&page_id) {
697            drop(index);
698
699            #[cfg(test)]
700            tests::after_slot_lookup();
701
702            let mut entries = cache_write(&self.entries);
703            if let Some(Some(entry)) = entries.get_mut(slot) {
704                if entry.page_id == page_id {
705                    entry.pin_count += 1;
706                    return true;
707                }
708            }
709        }
710        false
711    }
712
713    /// Unpin a page
714    pub fn unpin(&self, page_id: u32) -> bool {
715        let index = cache_read(&self.index);
716        if let Some(&slot) = index.get(&page_id) {
717            drop(index);
718
719            #[cfg(test)]
720            tests::after_slot_lookup();
721
722            let mut entries = cache_write(&self.entries);
723            if let Some(Some(entry)) = entries.get_mut(slot) {
724                if entry.page_id == page_id && entry.pin_count > 0 {
725                    entry.pin_count -= 1;
726                    return true;
727                }
728            }
729        }
730        false
731    }
732
733    /// Remove a page from cache
734    pub fn remove(&self, page_id: u32) -> Option<Page> {
735        let _structure = cache_lock(&self.structure);
736        // Get and remove from index
737        let slot = {
738            let mut index = cache_write(&self.index);
739            index.remove(&page_id)?
740        };
741
742        // Remove entry
743        let entry = {
744            let mut entries = cache_write(&self.entries);
745            entries.get_mut(slot).and_then(|e| e.take())
746        };
747
748        // Release the metadata slot.
749        self.meta.vacate(slot);
750
751        // Remove from FIFO
752        {
753            let mut fifo = cache_lock(&self.fifo);
754            fifo.retain(|&id| id != page_id);
755        }
756
757        // Add slot to free list
758        {
759            let mut free_slots = cache_lock(&self.free_slots);
760            free_slots.push(slot);
761        }
762
763        entry.map(|e| e.page)
764    }
765
766    /// Flush all dirty pages
767    ///
768    /// Returns an iterator of (page_id, page) for dirty pages.
769    pub fn flush_dirty(&self) -> Vec<(u32, Page)> {
770        let mut dirty_pages = Vec::new();
771
772        let index = cache_read(&self.index);
773        let entries = cache_read(&self.entries);
774
775        for (&page_id, &slot) in index.iter() {
776            if let Some(Some(entry)) = entries.get(slot) {
777                if entry.dirty {
778                    dirty_pages.push((page_id, entry.page.clone()));
779                }
780            }
781        }
782
783        drop(entries);
784        drop(index);
785
786        // Mark all as clean
787        for (page_id, _) in &dirty_pages {
788            self.mark_clean(*page_id);
789        }
790
791        let count = dirty_pages.len();
792        cache_lock(&self.stats).writebacks += count as u64;
793
794        dirty_pages
795    }
796
797    /// Snapshot and clear one dirty image under the same entry lock. A later
798    /// writer must leave its replacement dirty, even while this image flushes.
799    fn take_dirty_page(&self, page_id: u32) -> Option<Page> {
800        let index = cache_read(&self.index);
801        let slot = *index.get(&page_id)?;
802        let mut entries = cache_write(&self.entries);
803        let entry = entries.get_mut(slot)?.as_mut()?;
804        if !entry.dirty {
805            return None;
806        }
807        let page = entry.page.clone();
808        entry.dirty = false;
809        drop(entries);
810        drop(index);
811        cache_lock(&self.stats).writebacks += 1;
812        Some(page)
813    }
814
815    /// Bounded counterpart of `flush_dirty` used by the background
816    /// writer. Snapshots up to `max` dirty pages, marks them clean,
817    /// and returns the (page_id, page) pairs for the caller to
818    /// persist via the pager. Clamps to the current dirty set —
819    /// returning fewer than `max` simply means we're caught up.
820    pub fn flush_some_dirty(&self, max: usize) -> Vec<(u32, Page)> {
821        if max == 0 {
822            return Vec::new();
823        }
824        let mut dirty_pages = Vec::with_capacity(max);
825
826        let index = cache_read(&self.index);
827        let entries = cache_read(&self.entries);
828
829        for (&page_id, &slot) in index.iter() {
830            if dirty_pages.len() >= max {
831                break;
832            }
833            if let Some(Some(entry)) = entries.get(slot) {
834                if entry.dirty {
835                    dirty_pages.push((page_id, entry.page.clone()));
836                }
837            }
838        }
839
840        drop(entries);
841        drop(index);
842
843        for (page_id, _) in &dirty_pages {
844            self.mark_clean(*page_id);
845        }
846
847        let count = dirty_pages.len();
848        cache_lock(&self.stats).writebacks += count as u64;
849
850        dirty_pages
851    }
852
853    /// Count dirty pages currently in the cache. Used by the
854    /// background writer to compute an adaptive flush budget.
855    pub fn dirty_count(&self) -> usize {
856        let index = cache_read(&self.index);
857        let entries = cache_read(&self.entries);
858        let mut count = 0;
859        for (_, &slot) in index.iter() {
860            if let Some(Some(entry)) = entries.get(slot) {
861                if entry.dirty {
862                    count += 1;
863                }
864            }
865        }
866        count
867    }
868
869    /// Clear all entries from cache
870    pub fn clear(&self) {
871        let _structure = cache_lock(&self.structure);
872        let mut index = cache_write(&self.index);
873        let mut entries = cache_write(&self.entries);
874        let mut fifo = cache_lock(&self.fifo);
875        let mut free_slots = cache_lock(&self.free_slots);
876
877        index.clear();
878        entries.clear();
879        fifo.clear();
880        free_slots.clear();
881        self.meta.reset();
882        *cache_lock(&self.hand) = 0;
883    }
884
885    /// Check if a page is in cache
886    pub fn contains(&self, page_id: u32) -> bool {
887        cache_read(&self.index).contains_key(&page_id)
888    }
889
890    /// Get all cached page IDs
891    pub fn page_ids(&self) -> Vec<u32> {
892        cache_read(&self.index).keys().copied().collect()
893    }
894
895    /// Snapshot IDs without cloning images or clearing their dirty flags.
896    fn dirty_page_ids(&self, max: usize) -> Vec<u32> {
897        let index = cache_read(&self.index);
898        let entries = cache_read(&self.entries);
899        index
900            .iter()
901            .filter_map(|(&page_id, &slot)| {
902                let entry = entries.get(slot)?.as_ref()?;
903                entry.dirty.then_some(page_id)
904            })
905            .take(max)
906            .collect()
907    }
908}
909
910impl Default for PageCacheShard {
911    fn default() -> Self {
912        Self::with_default_capacity()
913    }
914}
915
916/// Number of independent `PageCacheShard`s inside a `PageCache`. Must
917/// be a power of two so `page_id & (NUM_SHARDS - 1)` is a valid shard
918/// index. 8 was picked to cover typical bench concurrency (16 workers)
919/// without making each shard's own SIEVE queue too small; bumping to
920/// 16 is safe if profiling ever shows shard-level contention.
921const NUM_SHARDS: usize = 8;
922
923/// Sharded page cache.
924///
925/// Routes each `page_id` to one of at most `NUM_SHARDS` independent
926/// [`PageCacheShard`]s by the low bits of the id. Readers and writers
927/// for disjoint pages hit different shards and do not contend on the
928/// shard-internal RwLocks/Mutexes. Each shard runs its own SIEVE
929/// eviction loop over its share of the requested slots; hot/cold
930/// asymmetry across shards is accepted in exchange for the
931/// contention win. Tiny budgets use fewer shards so one requested page
932/// remains one physical page slot.
933pub struct PageCache {
934    shards: Box<[PageCacheShard]>,
935    capacity: usize,
936}
937
938impl PageCache {
939    pub fn new(capacity: usize) -> Self {
940        let shard_count = (capacity / MIN_CACHE_CAPACITY)
941            .max(1)
942            .next_power_of_two()
943            .min(NUM_SHARDS);
944        let per_shard = capacity.div_ceil(shard_count).max(MIN_CACHE_CAPACITY);
945        let total = per_shard * shard_count;
946        let shards: Vec<PageCacheShard> = (0..shard_count)
947            .map(|_| PageCacheShard::new(per_shard))
948            .collect();
949        Self {
950            shards: shards.into_boxed_slice(),
951            capacity: total,
952        }
953    }
954
955    pub fn with_default_capacity() -> Self {
956        Self::new(DEFAULT_CACHE_CAPACITY)
957    }
958
959    #[inline]
960    fn shard_for(&self, page_id: u32) -> &PageCacheShard {
961        &self.shards[(page_id as usize) & (self.shards.len() - 1)]
962    }
963
964    pub fn len(&self) -> usize {
965        self.shards.iter().map(|s| s.len()).sum()
966    }
967
968    pub fn is_empty(&self) -> bool {
969        self.shards.iter().all(|s| s.is_empty())
970    }
971
972    pub fn capacity(&self) -> usize {
973        self.capacity
974    }
975
976    pub fn stats(&self) -> CacheStats {
977        let mut agg = CacheStats::default();
978        for s in self.shards.iter() {
979            let cs = s.stats();
980            agg.hits += cs.hits;
981            agg.misses += cs.misses;
982            agg.evictions += cs.evictions;
983            agg.writebacks += cs.writebacks;
984        }
985        agg
986    }
987
988    pub fn reset_stats(&self) {
989        for s in self.shards.iter() {
990            s.reset_stats();
991        }
992    }
993
994    pub fn get(&self, page_id: u32) -> Option<Page> {
995        self.shard_for(page_id).get(page_id)
996    }
997
998    /// Dirty images evicted so far. Each is the only copy of its page's
999    /// newest image until its caller has written it, so a reader that takes a
1000    /// page from the file compares this count before and after.
1001    pub fn dirty_evictions(&self) -> u64 {
1002        self.shards
1003            .iter()
1004            .map(PageCacheShard::dirty_evictions)
1005            .sum()
1006    }
1007
1008    pub fn insert(&self, page_id: u32, page: Page) -> Option<Page> {
1009        self.shard_for(page_id).insert(page_id, page)
1010    }
1011
1012    pub fn insert_dirty(&self, page_id: u32, page: Page) -> Option<Page> {
1013        self.shard_for(page_id).insert_dirty(page_id, page)
1014    }
1015
1016    pub fn insert_if_absent(&self, page_id: u32, page: Page) -> Option<Page> {
1017        self.shard_for(page_id).insert_if_absent(page_id, page)
1018    }
1019
1020    pub fn mark_dirty(&self, page_id: u32) {
1021        self.shard_for(page_id).mark_dirty(page_id)
1022    }
1023
1024    pub fn mark_clean(&self, page_id: u32) {
1025        self.shard_for(page_id).mark_clean(page_id)
1026    }
1027
1028    pub fn pin(&self, page_id: u32) -> bool {
1029        self.shard_for(page_id).pin(page_id)
1030    }
1031
1032    pub fn unpin(&self, page_id: u32) -> bool {
1033        self.shard_for(page_id).unpin(page_id)
1034    }
1035
1036    pub fn remove(&self, page_id: u32) -> Option<Page> {
1037        self.shard_for(page_id).remove(page_id)
1038    }
1039
1040    pub fn contains(&self, page_id: u32) -> bool {
1041        self.shard_for(page_id).contains(page_id)
1042    }
1043
1044    pub fn flush_dirty(&self) -> Vec<(u32, Page)> {
1045        let mut out = Vec::new();
1046        for s in self.shards.iter() {
1047            out.extend(s.flush_dirty());
1048        }
1049        out
1050    }
1051
1052    /// Snapshot only the requested dirty images, bounding payload copies by
1053    /// the caller's batch size rather than the full cache capacity.
1054    pub fn flush_dirty_pages(&self, page_ids: &[u32]) -> Vec<(u32, Page)> {
1055        let mut pages = Vec::with_capacity(page_ids.len());
1056        for &page_id in page_ids {
1057            if let Some(page) = self.shard_for(page_id).take_dirty_page(page_id) {
1058                pages.push((page_id, page));
1059            }
1060        }
1061        pages
1062    }
1063
1064    pub(crate) fn flush_dirty_page(&self, page_id: u32) -> Option<Page> {
1065        self.shard_for(page_id).take_dirty_page(page_id)
1066    }
1067
1068    pub fn flush_some_dirty(&self, max: usize) -> Vec<(u32, Page)> {
1069        if max == 0 {
1070            return Vec::new();
1071        }
1072        let mut out = Vec::with_capacity(max);
1073        for s in self.shards.iter() {
1074            if out.len() >= max {
1075                break;
1076            }
1077            let budget = max - out.len();
1078            out.extend(s.flush_some_dirty(budget));
1079        }
1080        out
1081    }
1082
1083    pub fn dirty_count(&self) -> usize {
1084        self.shards.iter().map(|s| s.dirty_count()).sum()
1085    }
1086
1087    pub fn clear(&self) {
1088        for s in self.shards.iter() {
1089            s.clear();
1090        }
1091    }
1092
1093    pub fn page_ids(&self) -> Vec<u32> {
1094        let mut out = Vec::with_capacity(self.len());
1095        for s in self.shards.iter() {
1096            out.extend(s.page_ids());
1097        }
1098        out
1099    }
1100
1101    /// Clean entries must not split a small dirty set into many I/O batches.
1102    pub fn dirty_page_ids(&self, max: usize) -> Vec<u32> {
1103        let mut ids = Vec::new();
1104        for shard in self.shards.iter() {
1105            if ids.len() == max {
1106                break;
1107            }
1108            ids.extend(shard.dirty_page_ids(max - ids.len()));
1109        }
1110        ids
1111    }
1112}
1113
1114impl Default for PageCache {
1115    fn default() -> Self {
1116        Self::with_default_capacity()
1117    }
1118}
1119
1120#[cfg(test)]
1121mod tests {
1122    use super::*;
1123    use crate::storage::page::PageType;
1124
1125    thread_local! {
1126        static SLOT_LOOKUP_HOOK: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
1127            const { std::cell::RefCell::new(None) };
1128        static EVICT_TAKE_HOOK: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
1129            const { std::cell::RefCell::new(None) };
1130        static INSERT_PUBLISH_HOOK: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
1131            const { std::cell::RefCell::new(None) };
1132    }
1133
1134    pub(super) fn after_slot_lookup() {
1135        let hook = SLOT_LOOKUP_HOOK.with(|slot| slot.borrow_mut().take());
1136        if let Some(hook) = hook {
1137            hook();
1138        }
1139    }
1140
1141    pub(super) fn before_evict_take() {
1142        let hook = EVICT_TAKE_HOOK.with(|slot| slot.borrow_mut().take());
1143        if let Some(hook) = hook {
1144            hook();
1145        }
1146    }
1147
1148    pub(super) fn after_insert_publish() {
1149        let hook = INSERT_PUBLISH_HOOK.with(|slot| slot.borrow_mut().take());
1150        if let Some(hook) = hook {
1151            hook();
1152        }
1153    }
1154
1155    #[test]
1156    fn cache_publish_read_miss_does_not_replace_a_newer_dirty_image() {
1157        let cache = PageCacheShard::new(2);
1158        let mut delayed_read = make_page(0);
1159        delayed_read.as_bytes_mut()[100] = 0x11;
1160        let mut current = make_page(0);
1161        current.as_bytes_mut()[100] = 0x22;
1162        cache.insert_dirty(0, current);
1163        cache.insert_if_absent(0, delayed_read);
1164        assert_eq!(cache.get(0).expect("current image").as_bytes()[100], 0x22);
1165        assert_eq!(cache.dirty_count(), 1, "read cleared the current writer");
1166    }
1167
1168    #[test]
1169    fn cache_publish_dirty_image_before_eviction_is_possible() {
1170        use std::sync::{mpsc, Arc};
1171        use std::time::Duration;
1172        let cache = Arc::new(PageCacheShard::new(2));
1173        cache.insert(0, make_page(0));
1174        cache.insert(1, make_page(1));
1175        let (published, publication_done) = mpsc::channel();
1176        let (resume, resumed) = mpsc::channel();
1177        let writer_cache = Arc::clone(&cache);
1178        let writer = std::thread::spawn(move || {
1179            INSERT_PUBLISH_HOOK.with(|slot| {
1180                *slot.borrow_mut() = Some(Box::new(move || {
1181                    published.send(()).expect("notify image publication");
1182                    resumed
1183                        .recv_timeout(Duration::from_secs(5))
1184                        .expect("resume writer");
1185                }));
1186            });
1187            let mut page = make_page(2);
1188            page.as_bytes_mut()[100] = 0x42;
1189            writer_cache.insert_dirty(2, page)
1190        });
1191        publication_done
1192            .recv_timeout(Duration::from_secs(5))
1193            .expect("writer published page 2");
1194        let evicted = [
1195            cache.insert_if_absent(3, make_page(3)),
1196            cache.insert_if_absent(4, make_page(4)),
1197        ];
1198        resume.send(()).expect("resume after read pressure");
1199        assert!(writer.join().expect("writer finishes").is_none());
1200        let image = evicted
1201            .into_iter()
1202            .flatten()
1203            .find(|page| page.page_id() == 2)
1204            .expect("concurrent disk reads must preserve the new dirty image for writeback");
1205        assert_eq!(image.as_bytes()[100], 0x42);
1206    }
1207
1208    fn make_page(id: u32) -> Page {
1209        Page::new(PageType::BTreeLeaf, id)
1210    }
1211
1212    #[test]
1213    fn requested_small_cache_does_not_allocate_all_shards() {
1214        for capacity in [1, 2, 4, 8, 10_000] {
1215            assert_eq!(PageCache::new(capacity).capacity(), capacity);
1216        }
1217    }
1218
1219    #[test]
1220    fn cache_hit_cannot_return_a_replacement_page_after_slot_reuse() {
1221        use std::sync::{mpsc, Arc};
1222        use std::time::Duration;
1223
1224        let cache = Arc::new(PageCacheShard::new(2));
1225        cache.insert(0, make_page(0));
1226        cache.insert(1, make_page(1));
1227        let (looked_up, lookup_done) = mpsc::channel();
1228        let (resume, resumed) = mpsc::channel();
1229        let reader_cache = Arc::clone(&cache);
1230        let reader = std::thread::spawn(move || {
1231            SLOT_LOOKUP_HOOK.with(|slot| {
1232                *slot.borrow_mut() = Some(Box::new(move || {
1233                    looked_up.send(()).expect("notify slot lookup");
1234                    resumed
1235                        .recv_timeout(Duration::from_secs(5))
1236                        .expect("resume reader after eviction");
1237                }));
1238            });
1239            reader_cache.get(0)
1240        });
1241        lookup_done
1242            .recv_timeout(Duration::from_secs(5))
1243            .expect("reader resolved original page slot");
1244        cache.insert(2, make_page(2));
1245        assert!(!cache.contains(0), "fixture must evict the original page");
1246        resume.send(()).expect("resume original page reader");
1247        let observed = reader.join().expect("reader must finish");
1248        assert!(
1249            observed.is_none(),
1250            "evicted page 0 became a hit for replacement page {:?}",
1251            observed.map(|page| page.page_id())
1252        );
1253        assert_eq!(cache.get(2).expect("replacement retained").page_id(), 2);
1254        assert_eq!(cache.stats().misses, 1);
1255    }
1256
1257    #[test]
1258    fn cache_slot_reuse_preserves_replacement_pins_and_dirty_state() {
1259        use std::sync::{mpsc, Arc};
1260        use std::time::Duration;
1261        #[derive(Clone, Copy, Debug)]
1262        enum Action {
1263            Pin,
1264            Unpin,
1265            MarkDirty,
1266            MarkClean,
1267        }
1268        for action in [
1269            Action::Pin,
1270            Action::Unpin,
1271            Action::MarkDirty,
1272            Action::MarkClean,
1273        ] {
1274            let cache = Arc::new(PageCacheShard::new(2));
1275            cache.insert(0, make_page(0));
1276            cache.insert(1, make_page(1));
1277            let (looked_up, lookup_done) = mpsc::channel();
1278            let (resume, resumed) = mpsc::channel();
1279            let worker_cache = Arc::clone(&cache);
1280            let worker = std::thread::spawn(move || {
1281                SLOT_LOOKUP_HOOK.with(|slot| {
1282                    *slot.borrow_mut() = Some(Box::new(move || {
1283                        looked_up.send(()).expect("notify lookup");
1284                        resumed
1285                            .recv_timeout(Duration::from_secs(5))
1286                            .expect("resume stale lookup");
1287                    }));
1288                });
1289                match action {
1290                    Action::Pin => worker_cache.pin(0),
1291                    Action::Unpin => worker_cache.unpin(0),
1292                    Action::MarkDirty => {
1293                        worker_cache.mark_dirty(0);
1294                        false
1295                    }
1296                    Action::MarkClean => {
1297                        worker_cache.mark_clean(0);
1298                        false
1299                    }
1300                }
1301            });
1302            lookup_done
1303                .recv_timeout(Duration::from_secs(5))
1304                .expect("lookup original slot");
1305            cache.insert(2, make_page(2));
1306            if matches!(action, Action::Unpin) {
1307                assert!(cache.pin(2));
1308            }
1309            if matches!(action, Action::MarkClean) {
1310                cache.mark_dirty(2);
1311            }
1312            resume.send(()).expect("resume worker");
1313            let changed = worker.join().expect("worker finishes");
1314            assert!(!changed, "{action:?} targeted a replacement page");
1315            let index = cache_read(&cache.index);
1316            let entries = cache_read(&cache.entries);
1317            let entry = entries[index[&2]].as_ref().expect("replacement");
1318            assert_eq!(
1319                entry.pin_count,
1320                usize::from(matches!(action, Action::Unpin)),
1321                "{action:?}"
1322            );
1323            assert_eq!(
1324                entry.dirty,
1325                matches!(action, Action::MarkClean),
1326                "{action:?}"
1327            );
1328        }
1329    }
1330
1331    #[test]
1332    fn cache_eviction_rechecks_pins_and_dirty_writes_before_removing_a_candidate() {
1333        use std::sync::{mpsc, Arc};
1334        use std::time::Duration;
1335        for pin in [false, true] {
1336            let cache = Arc::new(PageCacheShard::new(2));
1337            cache.insert(0, make_page(0));
1338            cache.insert(1, make_page(1));
1339            let (selected, selection_done) = mpsc::channel();
1340            let (resume, resumed) = mpsc::channel();
1341            let writer_cache = Arc::clone(&cache);
1342            let writer = std::thread::spawn(move || {
1343                EVICT_TAKE_HOOK.with(|slot| {
1344                    *slot.borrow_mut() = Some(Box::new(move || {
1345                        selected.send(()).expect("notify candidate");
1346                        resumed
1347                            .recv_timeout(Duration::from_secs(5))
1348                            .expect("resume eviction");
1349                    }));
1350                });
1351                writer_cache.insert(2, make_page(2))
1352            });
1353            selection_done
1354                .recv_timeout(Duration::from_secs(5))
1355                .expect("selected page 0");
1356            if pin {
1357                assert!(cache.pin(0));
1358            } else {
1359                cache.mark_dirty(0);
1360            }
1361            resume.send(()).expect("resume selected eviction");
1362            let writeback = writer
1363                .join()
1364                .expect("eviction must respect a concurrent pin");
1365            if pin {
1366                assert!(cache.contains(0), "pinned candidate was evicted");
1367                assert!(writeback.is_none());
1368            } else {
1369                assert_eq!(
1370                    writeback
1371                        .expect("new dirty image must be written back")
1372                        .page_id(),
1373                    0
1374                );
1375                assert_eq!(cache.stats().writebacks, 1);
1376            }
1377        }
1378    }
1379
1380    #[test]
1381    fn cache_concurrent_same_page_insertions_do_not_retain_unindexed_slots() {
1382        use std::sync::{Arc, Barrier};
1383        let cache = Arc::new(PageCacheShard::new(4));
1384        for cycle in 0..100 {
1385            let start = Arc::new(Barrier::new(4));
1386            let workers: Vec<_> = (0..4)
1387                .map(|_| {
1388                    let cache = Arc::clone(&cache);
1389                    let start = Arc::clone(&start);
1390                    std::thread::spawn(move || {
1391                        start.wait();
1392                        for round in 0..2000 {
1393                            let id = round % 8;
1394                            cache.insert(id, make_page(id));
1395                        }
1396                    })
1397                })
1398                .collect();
1399            for worker in workers {
1400                worker.join().expect("concurrent insertion");
1401            }
1402            let index = cache_read(&cache.index);
1403            let entries = cache_read(&cache.entries);
1404            assert!(index.len() <= cache.capacity());
1405            assert!(
1406                entries.len() <= cache.capacity(),
1407                "retained slot metadata grew past capacity"
1408            );
1409            assert_eq!(
1410                entries.iter().filter(|entry| entry.is_some()).count(),
1411                index.len(),
1412                "unindexed pages retained"
1413            );
1414            assert_eq!(
1415                cache_lock(&cache.fifo).len(),
1416                index.len(),
1417                "duplicate FIFO identities retained"
1418            );
1419            assert_eq!(
1420                cache_lock(&cache.free_slots).len(),
1421                entries.len() - index.len(),
1422                "unused slots lost at cycle {cycle}"
1423            );
1424        }
1425    }
1426
1427    #[test]
1428    fn cache_key_identity_remains_independent_of_the_payload_header() {
1429        // Cache callers, including the existing concurrency workload, may reuse
1430        // a page image under distinct keys. Slot ownership is the index identity.
1431        let cache = PageCacheShard::new(2);
1432        cache.insert(42, make_page(0));
1433        assert_eq!(cache.get(42).expect("requested cache key").page_id(), 0);
1434        assert!(cache.pin(42));
1435        assert!(cache.unpin(42));
1436        cache.mark_dirty(42);
1437        assert_eq!(cache.dirty_count(), 1);
1438        cache.mark_clean(42);
1439        assert_eq!(cache.dirty_count(), 0);
1440    }
1441
1442    #[test]
1443    fn test_cache_basic() {
1444        let cache = PageCacheShard::new(100);
1445
1446        assert!(cache.is_empty());
1447        assert_eq!(cache.capacity(), 100);
1448
1449        // Insert
1450        cache.insert(1, make_page(1));
1451        assert_eq!(cache.len(), 1);
1452        assert!(cache.contains(1));
1453
1454        // Get
1455        let page = cache.get(1);
1456        assert!(page.is_some());
1457
1458        // Miss
1459        let page = cache.get(999);
1460        assert!(page.is_none());
1461    }
1462
1463    #[test]
1464    fn test_cache_eviction() {
1465        let cache = PageCacheShard::new(4);
1466
1467        // Fill cache
1468        for i in 0..4 {
1469            cache.insert(i, make_page(i));
1470        }
1471
1472        assert_eq!(cache.len(), 4);
1473
1474        // Insert one more, should trigger eviction
1475        cache.insert(100, make_page(100));
1476
1477        // One of the original pages should be evicted
1478        assert_eq!(cache.len(), 4);
1479        assert!(cache.contains(100));
1480    }
1481
1482    #[test]
1483    fn test_cache_sieve_visited() {
1484        let cache = PageCacheShard::new(4);
1485
1486        // Fill cache
1487        for i in 0..4 {
1488            cache.insert(i, make_page(i));
1489        }
1490
1491        // Access page 0 (marks as visited)
1492        cache.get(0);
1493
1494        // Insert new page, should evict non-visited first
1495        cache.insert(100, make_page(100));
1496
1497        // Page 0 should still be there (was visited)
1498        assert!(cache.contains(0));
1499        assert!(cache.contains(100));
1500    }
1501
1502    #[test]
1503    fn test_cache_dirty() {
1504        let cache = PageCacheShard::new(100);
1505
1506        cache.insert(1, make_page(1));
1507        cache.mark_dirty(1);
1508
1509        let dirty = cache.flush_dirty();
1510        assert_eq!(dirty.len(), 1);
1511        assert_eq!(dirty[0].0, 1);
1512
1513        // Should be clean now
1514        let dirty = cache.flush_dirty();
1515        assert_eq!(dirty.len(), 0);
1516    }
1517
1518    #[test]
1519    fn test_cache_pin() {
1520        let cache = PageCacheShard::new(2);
1521
1522        cache.insert(1, make_page(1));
1523        cache.insert(2, make_page(2));
1524
1525        // Pin page 1
1526        assert!(cache.pin(1));
1527
1528        // Fill cache to trigger eviction
1529        cache.insert(3, make_page(3));
1530
1531        // Page 1 should still be there (pinned)
1532        assert!(cache.contains(1));
1533
1534        // Unpin
1535        assert!(cache.unpin(1));
1536    }
1537
1538    #[test]
1539    fn test_cache_remove() {
1540        let cache = PageCacheShard::new(100);
1541
1542        cache.insert(1, make_page(1));
1543        assert!(cache.contains(1));
1544
1545        let removed = cache.remove(1);
1546        assert!(removed.is_some());
1547        assert!(!cache.contains(1));
1548    }
1549
1550    #[test]
1551    fn test_cache_stats() {
1552        let cache = PageCacheShard::new(100);
1553
1554        cache.insert(1, make_page(1));
1555
1556        // Hit
1557        cache.get(1);
1558        cache.get(1);
1559
1560        // Miss
1561        cache.get(999);
1562
1563        let stats = cache.stats();
1564        assert_eq!(stats.hits, 2);
1565        assert_eq!(stats.misses, 1);
1566        assert!((stats.hit_rate() - 0.666).abs() < 0.01);
1567    }
1568
1569    #[test]
1570    fn test_cache_clear() {
1571        let cache = PageCacheShard::new(100);
1572
1573        for i in 0..50 {
1574            cache.insert(i, make_page(i));
1575        }
1576
1577        assert_eq!(cache.len(), 50);
1578
1579        cache.clear();
1580        assert!(cache.is_empty());
1581    }
1582
1583    #[test]
1584    fn test_cache_update_existing() {
1585        let cache = PageCacheShard::new(100);
1586
1587        let mut page1 = make_page(1);
1588        page1.as_bytes_mut()[100] = 0xAA;
1589        cache.insert(1, page1);
1590
1591        let mut page1_updated = make_page(1);
1592        page1_updated.as_bytes_mut()[100] = 0xBB;
1593        cache.insert(1, page1_updated);
1594
1595        // Should still only have one entry
1596        assert_eq!(cache.len(), 1);
1597
1598        // Should have updated value
1599        let retrieved = cache.get(1).unwrap();
1600        assert_eq!(retrieved.as_bytes()[100], 0xBB);
1601    }
1602
1603    #[test]
1604    fn test_cache_recovers_after_index_lock_poisoning() {
1605        let cache = std::sync::Arc::new(PageCacheShard::new(8));
1606        let poison_target = std::sync::Arc::clone(&cache);
1607        let _ = std::thread::spawn(move || {
1608            let _guard = poison_target
1609                .index
1610                .write()
1611                .expect("index lock should be acquired");
1612            panic!("poison index lock");
1613        })
1614        .join();
1615
1616        cache.insert(1, make_page(1));
1617        assert!(cache.contains(1));
1618        assert!(cache.get(1).is_some());
1619    }
1620
1621    #[test]
1622    fn test_cache_recovers_after_stats_lock_poisoning() {
1623        let cache = std::sync::Arc::new(PageCacheShard::new(8));
1624        let poison_target = std::sync::Arc::clone(&cache);
1625        let _ = std::thread::spawn(move || {
1626            let _guard = poison_target
1627                .stats
1628                .lock()
1629                .expect("stats lock should be acquired");
1630            panic!("poison stats lock");
1631        })
1632        .join();
1633
1634        assert!(cache.get(999).is_none());
1635        assert_eq!(cache.stats().misses, 1);
1636        cache.reset_stats();
1637        assert_eq!(cache.stats().misses, 0);
1638    }
1639
1640    /// ADR 0033: the SIEVE `visited`/`tag` metadata lives in its own
1641    /// cache-line-packed, line-aligned arrays — separate from the
1642    /// lock-protected `CacheEntry`. Assert the line types are exactly
1643    /// one 64-byte line and 64-byte aligned (so the boxed backing
1644    /// buffers start on a line boundary and never false-share), and
1645    /// that `CacheEntry` no longer carries the visited bit.
1646    #[test]
1647    fn test_metadata_layout_is_cache_line_packed() {
1648        assert_eq!(std::mem::align_of::<VisitedLine>(), CACHE_LINE);
1649        assert_eq!(std::mem::size_of::<VisitedLine>(), CACHE_LINE);
1650        assert_eq!(std::mem::align_of::<TagLine>(), CACHE_LINE);
1651        assert_eq!(std::mem::size_of::<TagLine>(), CACHE_LINE);
1652
1653        // The metadata arrays are distinct allocations from `entries`.
1654        let meta = ShardMeta::new(200);
1655        // Densely packed: 64 visited bits per line, 16 tags per line.
1656        assert_eq!(meta.visited.len(), 200usize.div_ceil(64));
1657        assert_eq!(meta.tag.len(), 200usize.div_ceil(16));
1658
1659        // occupy/vacate round-trip through the tag array.
1660        meta.occupy(5, 42);
1661        assert_eq!(meta.tag(5), 42);
1662        assert!(!meta.is_visited(5));
1663        meta.mark_visited(5);
1664        assert!(meta.is_visited(5));
1665        meta.vacate(5);
1666        assert_eq!(meta.tag(5), TAG_EMPTY);
1667        assert!(!meta.is_visited(5));
1668    }
1669
1670    /// ADR 0033: a cache hit sets the SIEVE `visited` bit on the
1671    /// separate metadata array (no write-lock upgrade), and that bit
1672    /// drives eviction exactly as before — a hit page survives one
1673    /// eviction sweep while an un-hit page is evicted first.
1674    #[test]
1675    fn test_hit_sets_visited_and_preserves_sieve_policy() {
1676        let cache = PageCacheShard::new(4);
1677        for i in 0..4 {
1678            cache.insert(i, make_page(i));
1679        }
1680
1681        // Hit pages 0 and 1 (lock-free visited mark via metadata array).
1682        assert!(cache.get(0).is_some());
1683        assert!(cache.get(1).is_some());
1684
1685        // Insert two more: SIEVE evicts the un-hit 2 and 3 first.
1686        cache.insert(10, make_page(10));
1687        cache.insert(11, make_page(11));
1688
1689        assert!(cache.contains(0), "hit page 0 must survive");
1690        assert!(cache.contains(1), "hit page 1 must survive");
1691        assert!(cache.contains(10));
1692        assert!(cache.contains(11));
1693        assert!(!cache.contains(2));
1694        assert!(!cache.contains(3));
1695    }
1696
1697    /// ADR 0033 acceptance: under concurrent hits + eviction, no pinned
1698    /// page is ever evicted, and dirty pages are never silently lost —
1699    /// every dirty page that leaves the cache is returned for
1700    /// writeback. Stress/loom-style: many threads hammer hits while
1701    /// other threads drive insertions (and thus the eviction hand).
1702    #[test]
1703    fn test_concurrent_hits_never_evict_pinned_or_lose_dirty() {
1704        use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
1705        use std::sync::Arc;
1706
1707        const CAP: u32 = 64;
1708        const PINNED: u32 = 8; // pages 0..8 stay pinned for the whole run
1709        const DIRTY: u32 = 8; // pages 8..16 are dirty
1710        const HITTERS: usize = 6;
1711        const INSERTERS: usize = 4;
1712        const ROUNDS: usize = 4_000;
1713
1714        let cache = Arc::new(PageCacheShard::new(CAP as usize));
1715        for i in 0..CAP {
1716            cache.insert(i, make_page(i));
1717        }
1718        for p in 0..PINNED {
1719            assert!(cache.pin(p), "pin {p}");
1720        }
1721        for p in PINNED..PINNED + DIRTY {
1722            cache.mark_dirty(p);
1723        }
1724
1725        // Count dirty pages handed back by insert() so we can prove no
1726        // dirty data is silently dropped.
1727        let dirty_written_back = Arc::new(AtomicUsize::new(0));
1728        let stop = Arc::new(AtomicBool::new(false));
1729
1730        // Hitters: loop on the lock-free visited path until signalled.
1731        let mut hitters = Vec::with_capacity(HITTERS);
1732        for h in 0..HITTERS {
1733            let cache = Arc::clone(&cache);
1734            let stop = Arc::clone(&stop);
1735            hitters.push(std::thread::spawn(move || {
1736                let mut id = (h as u32) % CAP;
1737                while !stop.load(Ordering::Relaxed) {
1738                    let _ = cache.get(id);
1739                    id = (id + 1) % CAP;
1740                }
1741            }));
1742        }
1743
1744        // Inserters: bounded churn that drives the eviction hand.
1745        let mut inserters = Vec::with_capacity(INSERTERS);
1746        for w in 0..INSERTERS {
1747            let cache = Arc::clone(&cache);
1748            let dirty_written_back = Arc::clone(&dirty_written_back);
1749            inserters.push(std::thread::spawn(move || {
1750                let base = 1_000 + (w as u32) * 1_000_000;
1751                for i in 0..ROUNDS {
1752                    let id = base + i as u32;
1753                    if cache.insert(id, make_page(id)).is_some() {
1754                        // insert only returns Some for a dirty victim.
1755                        dirty_written_back.fetch_add(1, Ordering::Relaxed);
1756                    }
1757                    // Invariant checked mid-storm: pinned pages are
1758                    // never evicted.
1759                    for p in 0..PINNED {
1760                        assert!(
1761                            cache.contains(p),
1762                            "pinned page {p} was evicted under concurrency"
1763                        );
1764                    }
1765                }
1766            }));
1767        }
1768
1769        // Inserters finish their bounded work; then stop the hitters.
1770        for h in inserters {
1771            h.join()
1772                .expect("inserter thread panicked (invariant broke)");
1773        }
1774        stop.store(true, Ordering::Relaxed);
1775        for h in hitters {
1776            h.join().expect("hitter thread panicked (invariant broke)");
1777        }
1778
1779        // Pinned pages survived the entire storm.
1780        for p in 0..PINNED {
1781            assert!(cache.contains(p), "pinned page {p} missing after storm");
1782        }
1783
1784        // Dirty accounting: a dirty page still in the cache, plus any
1785        // dirty victims handed back for writeback, must conserve the
1786        // original dirty set — no dirty page silently vanished.
1787        let dirty_resident = (PINNED..PINNED + DIRTY)
1788            .filter(|&p| cache.contains(p))
1789            .count();
1790        assert!(
1791            dirty_resident + dirty_written_back.load(Ordering::Relaxed) >= DIRTY as usize,
1792            "dirty pages lost: resident={dirty_resident} written_back={}",
1793            dirty_written_back.load(Ordering::Relaxed)
1794        );
1795
1796        // Note: we deliberately do NOT assert `len <= CAP`. The
1797        // pre-existing fine-grained-lock `insert` checks length and
1798        // evicts in separate steps, so concurrent inserters can
1799        // transiently push a shard past capacity. ShardMeta's bounds
1800        // guards make that overflow safe (over-capacity slots report
1801        // "not visited" / TAG_EMPTY and drain first); enforcing a hard
1802        // cap is out of scope for this lock-free-hit change.
1803    }
1804
1805    /// Legacy single-lock baseline used as a regression check for the
1806    /// sharded `PageCache`. Mirrors the pre-shard cache shape: a single
1807    /// `RwLock<HashMap<u32, Page>>` so every mutation serializes on one
1808    /// writer. We only need the surface used by the concurrency test
1809    /// (`insert` / `get`); keeping it minimal avoids accidentally
1810    /// drifting toward the sharded design and silently flattening the
1811    /// regression signal.
1812    mod legacy_baseline {
1813        use super::Page;
1814        use std::collections::HashMap;
1815        use std::sync::RwLock;
1816
1817        pub struct LegacyPageCache {
1818            entries: RwLock<HashMap<u32, Page>>,
1819        }
1820
1821        impl LegacyPageCache {
1822            pub fn new(_capacity: usize) -> Self {
1823                Self {
1824                    entries: RwLock::new(HashMap::new()),
1825                }
1826            }
1827
1828            pub fn insert(&self, page_id: u32, page: Page) {
1829                let mut entries = self.entries.write().unwrap();
1830                entries.insert(page_id, page);
1831            }
1832
1833            pub fn get(&self, page_id: u32) -> Option<Page> {
1834                let entries = self.entries.read().unwrap();
1835                entries.get(&page_id).cloned()
1836            }
1837        }
1838    }
1839
1840    /// Workload shared by both the sharded and legacy runs of the
1841    /// concurrency property test below. Each worker churns through its
1842    /// own disjoint `page_id` range so any contention seen between
1843    /// workers is purely lock-induced, not data-induced.
1844    fn run_workload<F>(workers: usize, ops_per_worker: usize, run: F) -> std::time::Duration
1845    where
1846        F: Fn(u32, &Page) + Send + Sync + 'static + Clone,
1847    {
1848        use std::sync::Arc;
1849        use std::time::Instant;
1850
1851        let run = Arc::new(run);
1852        let start = Instant::now();
1853        let mut handles = Vec::with_capacity(workers);
1854        for w in 0..workers {
1855            let run = Arc::clone(&run);
1856            handles.push(std::thread::spawn(move || {
1857                let base = (w as u32) * 1_000_000;
1858                let page = make_page(0);
1859                for i in 0..ops_per_worker {
1860                    let id = base + (i as u32);
1861                    run(id, &page);
1862                }
1863            }));
1864        }
1865        for h in handles {
1866            h.join().unwrap();
1867        }
1868        start.elapsed()
1869    }
1870
1871    #[test]
1872    fn test_sharded_cache_scales_concurrently() {
1873        // Property: with disjoint page_id ranges, 10 workers should
1874        // beat 1 worker by a meaningful factor on the sharded cache,
1875        // and the sharded cache should beat the legacy single-lock
1876        // baseline at 10 workers (since the baseline serializes every
1877        // mutation through one global RwLock).
1878        //
1879        // We assert "sub-linear scaling" in a deliberately loose form
1880        // (parallel < 7x serial) so CI flakiness on busy runners
1881        // doesn't false-positive. The legacy comparison is the
1882        // stronger regression signal.
1883        use std::sync::Arc;
1884
1885        const WORKERS: usize = 10;
1886        const OPS: usize = 5_000;
1887        const CAPACITY: usize = 200_000;
1888
1889        // Sharded: 1 worker baseline.
1890        let sharded = Arc::new(PageCache::new(CAPACITY));
1891        let s1 = Arc::clone(&sharded);
1892        let sharded_serial = run_workload(1, OPS * WORKERS, move |id, page| {
1893            s1.insert(id, page.clone());
1894            let _ = s1.get(id);
1895        });
1896
1897        // Sharded: WORKERS parallel.
1898        let sharded = Arc::new(PageCache::new(CAPACITY));
1899        let s2 = Arc::clone(&sharded);
1900        let sharded_parallel = run_workload(WORKERS, OPS, move |id, page| {
1901            s2.insert(id, page.clone());
1902            let _ = s2.get(id);
1903        });
1904
1905        // Legacy: WORKERS parallel.
1906        let legacy = Arc::new(legacy_baseline::LegacyPageCache::new(CAPACITY));
1907        let l2 = Arc::clone(&legacy);
1908        let legacy_parallel = run_workload(WORKERS, OPS, move |id, page| {
1909            l2.insert(id, page.clone());
1910            let _ = l2.get(id);
1911        });
1912
1913        eprintln!(
1914            "page_cache concurrency: sharded 1w={:?} sharded {}w={:?} legacy {}w={:?}",
1915            sharded_serial, WORKERS, sharded_parallel, WORKERS, legacy_parallel
1916        );
1917
1918        // Sub-linear scaling: parallel must not be worse than ~7x the
1919        // serial run. Linear (no scaling) would be ~10x.
1920        assert!(
1921            sharded_parallel.as_nanos() < sharded_serial.as_nanos() * 7,
1922            "sharded cache did not scale: 1w={:?} {}w={:?}",
1923            sharded_serial,
1924            WORKERS,
1925            sharded_parallel
1926        );
1927
1928        // Regression check: sharded must beat the legacy single-lock
1929        // baseline at WORKERS workers. We give the legacy a generous
1930        // 1.2x cushion so a noisy CI box doesn't flip the assertion
1931        // when both designs are within noise (would itself indicate a
1932        // sharding regression worth investigating).
1933        assert!(
1934            sharded_parallel.as_nanos() * 12 < legacy_parallel.as_nanos() * 10,
1935            "sharded cache did not beat legacy baseline: sharded {}w={:?} legacy {}w={:?}",
1936            WORKERS,
1937            sharded_parallel,
1938            WORKERS,
1939            legacy_parallel
1940        );
1941    }
1942}