Skip to main content

itzma_core/
cache.rs

1//! A tiered read cache: a `CacheStore` wraps the real
2//! `ObjectStore` and serves repeat reads from RAM, then local NVMe, before
3//! falling through to a real fetch.
4//!
5//! Cache correctness is close to free here: every object Itzma writes is
6//! immutable once put (a WAL object, a segment, an index object), so there
7//! is no invalidation logic anywhere in this module, only eviction.
8
9use std::num::NonZeroUsize;
10use std::ops::Range;
11
12use bytes::Bytes;
13use lru::LruCache;
14use object_store::path::Path;
15use object_store::{GetRange, ObjectMeta};
16
17/// What one cache entry is keyed on: the object's path and, if the read was
18/// ranged, exactly which range was requested. Two reads of the same
19/// `(path, range)` on an immutable object always return the same bytes, so
20/// the raw requested range (not the range resolved against the object's
21/// size) is a stable, correct key — no need to resolve `Offset`/`Suffix`
22/// against a size before checking the cache.
23#[derive(Debug, Clone, PartialEq, Eq, Hash)]
24pub(crate) struct CacheKey {
25    path: Path,
26    range: Option<RangeSpec>,
27}
28
29impl CacheKey {
30    /// The key for a read of `path`, optionally restricted to `range`
31    /// (`None` for a whole-object read).
32    pub(crate) fn new(path: &Path, range: Option<&GetRange>) -> Self {
33        CacheKey {
34            path: path.clone(),
35            range: range.map(RangeSpec::from),
36        }
37    }
38}
39
40/// `GetRange` mirrors this exactly, but derives `PartialEq`/`Eq`/`Clone`
41/// only, not `Hash` — this is the same three variants, hashable, so
42/// `CacheKey` can be used as a map key.
43#[derive(Debug, Clone, PartialEq, Eq, Hash)]
44enum RangeSpec {
45    Bounded(u64, u64),
46    Offset(u64),
47    Suffix(u64),
48}
49
50impl From<&GetRange> for RangeSpec {
51    fn from(range: &GetRange) -> Self {
52        match range {
53            GetRange::Bounded(r) => RangeSpec::Bounded(r.start, r.end),
54            GetRange::Offset(o) => RangeSpec::Offset(*o),
55            GetRange::Suffix(s) => RangeSpec::Suffix(*s),
56        }
57    }
58}
59
60/// One cached read: its bytes, plus the metadata needed to reconstruct a
61/// `GetResult` that looks exactly like a real fetch to the caller.
62/// `GetResult::extensions` is not part of this (and not reconstructed on a
63/// hit) — it's implementation-specific, ephemeral, per-request context
64/// (HTTP middleware state), not real object metadata worth caching.
65#[derive(Debug, Clone)]
66pub(crate) struct CachedRead {
67    pub(crate) bytes: Bytes,
68    pub(crate) meta: ObjectMeta,
69    pub(crate) range: Range<u64>,
70    pub(crate) attributes: object_store::Attributes,
71}
72
73impl CachedRead {
74    fn len(&self) -> u64 {
75        self.bytes.len() as u64
76    }
77}
78
79/// An entry-count cap for the underlying `LruCache`, high enough that
80/// `used_bytes` is always the real limiter in practice (no realistic
81/// workload caches this many distinct byte ranges before running out of
82/// budget first) — `usize::MAX` itself overflows a capacity calculation
83/// inside `lru`'s hashbrown-backed table on construction, found by actually
84/// running the tests below, not anticipated up front.
85const MAX_ENTRIES: usize = 10_000_000;
86
87/// A byte-budgeted, in-process LRU cache. `lru::LruCache` bounds by entry
88/// count, not bytes — object sizes here vary from a few bytes (a WAL
89/// fence) to megabytes (a segment data object), so this tracks total bytes
90/// itself and evicts the least-recently-used entry whenever a `put` would
91/// go over `max_bytes`.
92pub(crate) struct RamCache {
93    entries: LruCache<CacheKey, CachedRead>,
94    max_bytes: u64,
95    used_bytes: u64,
96}
97
98impl RamCache {
99    /// A new, empty cache holding at most `max_bytes` total.
100    pub(crate) fn new(max_bytes: u64) -> Self {
101        RamCache {
102            entries: LruCache::new(
103                NonZeroUsize::new(MAX_ENTRIES).expect("MAX_ENTRIES is never zero"),
104            ),
105            max_bytes,
106            used_bytes: 0,
107        }
108    }
109
110    /// The cached read for `key`, if present. Marks it most-recently-used.
111    pub(crate) fn get(&mut self, key: &CacheKey) -> Option<CachedRead> {
112        self.entries.get(key).cloned()
113    }
114
115    /// Cache `value` under `key`, evicting least-recently-used entries
116    /// until back under budget. An entry bigger than the whole budget is
117    /// never cached (it would just evict everything else and then itself).
118    pub(crate) fn put(&mut self, key: CacheKey, value: CachedRead) {
119        let len = value.len();
120        if len > self.max_bytes {
121            return;
122        }
123        if let Some(old) = self.entries.put(key, value) {
124            self.used_bytes -= old.len();
125        }
126        self.used_bytes += len;
127        while self.used_bytes > self.max_bytes {
128            let Some((_, evicted)) = self.entries.pop_lru() else {
129                break;
130            };
131            self.used_bytes -= evicted.len();
132        }
133    }
134}
135
136use std::sync::{Arc, Mutex};
137
138use async_trait::async_trait;
139use futures::StreamExt;
140use futures::stream::BoxStream;
141use object_store::{
142    CopyOptions, GetOptions, GetResult, GetResultPayload, ListResult, MultipartUpload, ObjectStore,
143    ObjectStoreExt, PutMultipartOptions, PutOptions, PutPayload, PutResult, Result,
144};
145
146/// Whether `options` is the simple, cacheable shape this store handles: no
147/// preconditions, no explicit version, not a HEAD-only request. Anything
148/// else bypasses the cache and goes straight to the real store — Itzma's
149/// own read call sites never send a conditional or versioned read, so this
150/// costs nothing in practice while keeping this cache's correctness bar low
151/// (a cached conditional read would need to re-check the precondition on
152/// every hit, which this design does not attempt).
153fn is_cacheable(options: &GetOptions) -> bool {
154    options.if_match.is_none()
155        && options.if_none_match.is_none()
156        && options.if_modified_since.is_none()
157        && options.if_unmodified_since.is_none()
158        && options.version.is_none()
159        && !options.head
160}
161
162fn to_get_result(cached: CachedRead) -> GetResult {
163    let CachedRead {
164        bytes,
165        meta,
166        range,
167        attributes,
168    } = cached;
169    GetResult {
170        payload: GetResultPayload::Stream(futures::stream::once(async move { Ok(bytes) }).boxed()),
171        meta,
172        range,
173        attributes,
174        extensions: Default::default(),
175    }
176}
177
178/// A read-through cache in front of a real `ObjectStore`: RAM first, then a
179/// local NVMe cache (if configured), then `inner`. Only reads are cached —
180/// `put`, `delete`, `list` and `copy` pass straight through, since every
181/// object here is immutable once written and there is nothing to
182/// invalidate, only capacity to manage.
183pub struct CacheStore {
184    inner: Arc<dyn ObjectStore>,
185    ram: Mutex<RamCache>,
186    nvme: Option<NvmeCache>,
187}
188
189/// How to size `CacheStore`'s tiers. `nvme` is optional — omit it for a
190/// RAM-only cache (tests, or a deployment with no local disk to spare).
191#[derive(Debug, Clone)]
192#[non_exhaustive]
193pub struct CacheOptions {
194    /// Maximum bytes held in the RAM tier.
195    pub ram_max_bytes: u64,
196    /// The local NVMe tier, if any.
197    pub nvme: Option<NvmeOptions>,
198}
199
200/// The local NVMe tier's settings.
201#[derive(Debug, Clone)]
202#[non_exhaustive]
203pub struct NvmeOptions {
204    /// Directory the cache's files live under (created if missing).
205    pub dir: std::path::PathBuf,
206    /// Maximum bytes held in this tier.
207    pub max_bytes: u64,
208}
209
210impl NvmeOptions {
211    /// An NVMe tier under `dir` holding at most `max_bytes`. The struct is
212    /// `#[non_exhaustive]`, so code outside this crate (the Python bridge)
213    /// builds it here.
214    pub fn new(dir: impl Into<std::path::PathBuf>, max_bytes: u64) -> Self {
215        Self {
216            dir: dir.into(),
217            max_bytes,
218        }
219    }
220}
221
222/// A RAM-only default: 256 MiB. A guess with no workload behind it yet, the
223/// same caveat `DEFAULT_READ_BUDGET` and `CompactTrigger`'s
224/// defaults already carry — this is a starting point to tune from
225/// real usage, not a measured number.
226pub const DEFAULT_RAM_MAX_BYTES: u64 = 256 * 1024 * 1024;
227
228impl Default for CacheOptions {
229    fn default() -> Self {
230        CacheOptions {
231            ram_max_bytes: DEFAULT_RAM_MAX_BYTES,
232            nvme: None,
233        }
234    }
235}
236
237impl CacheStore {
238    /// Wrap `inner` in a tiered read cache. `options.nvme` is `None` for a
239    /// RAM-only cache.
240    ///
241    /// # Errors
242    ///
243    /// Whatever `NvmeCache::new` returns if `options.nvme` is set and its
244    /// directory cannot be used.
245    ///
246    /// # Examples
247    ///
248    /// ```
249    /// use std::sync::Arc;
250    /// use itzma_core::{CacheOptions, CacheStore};
251    /// use object_store::{ObjectStore, ObjectStoreExt, memory::InMemory, path::Path};
252    /// use object_store::PutPayload;
253    ///
254    /// # #[tokio::main]
255    /// # async fn main() {
256    /// let inner: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
257    /// inner.put(&Path::from("obj"), PutPayload::from(&b"hello"[..])).await.unwrap();
258    ///
259    /// let cached = CacheStore::new(inner, CacheOptions::default()).unwrap();
260    /// let bytes = cached.get(&Path::from("obj")).await.unwrap().bytes().await.unwrap();
261    /// assert_eq!(&bytes[..], b"hello");
262    /// # }
263    /// ```
264    pub fn new(
265        inner: Arc<dyn ObjectStore>,
266        options: CacheOptions,
267    ) -> std::result::Result<Self, object_store::Error> {
268        let nvme = options
269            .nvme
270            .map(|n| NvmeCache::new(&n.dir, n.max_bytes))
271            .transpose()?;
272        Ok(CacheStore {
273            inner,
274            ram: Mutex::new(RamCache::new(options.ram_max_bytes)),
275            nvme,
276        })
277    }
278}
279
280impl std::fmt::Debug for CacheStore {
281    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
282        write!(f, "CacheStore({:?})", self.inner)
283    }
284}
285
286impl std::fmt::Display for CacheStore {
287    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
288        write!(f, "CacheStore({})", self.inner)
289    }
290}
291
292#[async_trait]
293impl ObjectStore for CacheStore {
294    async fn put_opts(
295        &self,
296        location: &Path,
297        payload: PutPayload,
298        opts: PutOptions,
299    ) -> Result<PutResult> {
300        self.inner.put_opts(location, payload, opts).await
301    }
302
303    async fn put_multipart_opts(
304        &self,
305        location: &Path,
306        opts: PutMultipartOptions,
307    ) -> Result<Box<dyn MultipartUpload>> {
308        self.inner.put_multipart_opts(location, opts).await
309    }
310
311    async fn get_opts(&self, location: &Path, options: GetOptions) -> Result<GetResult> {
312        if !is_cacheable(&options) {
313            return self.inner.get_opts(location, options).await;
314        }
315        let key = CacheKey::new(location, options.range.as_ref());
316
317        if let Some(cached) = self.ram.lock().expect("ram cache lock poisoned").get(&key) {
318            return Ok(to_get_result(cached));
319        }
320
321        if let Some(nvme) = &self.nvme {
322            if let Some(cached) = nvme.get(&key).await {
323                self.ram
324                    .lock()
325                    .expect("ram cache lock poisoned")
326                    .put(key, cached.clone());
327                return Ok(to_get_result(cached));
328            }
329        }
330
331        let result = self.inner.get_opts(location, options).await?;
332        let meta = result.meta.clone();
333        let range = result.range.clone();
334        let attributes = result.attributes.clone();
335        let bytes = result.bytes().await?;
336        let cached = CachedRead {
337            bytes,
338            meta,
339            range,
340            attributes,
341        };
342
343        if let Some(nvme) = &self.nvme {
344            nvme.put(key.clone(), &cached).await;
345        }
346        self.ram
347            .lock()
348            .expect("ram cache lock poisoned")
349            .put(key, cached.clone());
350
351        Ok(to_get_result(cached))
352    }
353
354    fn delete_stream(
355        &self,
356        locations: BoxStream<'static, Result<Path>>,
357    ) -> BoxStream<'static, Result<Path>> {
358        self.inner.delete_stream(locations)
359    }
360
361    fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, Result<ObjectMeta>> {
362        self.inner.list(prefix)
363    }
364
365    fn list_with_offset(
366        &self,
367        prefix: Option<&Path>,
368        offset: &Path,
369    ) -> BoxStream<'static, Result<ObjectMeta>> {
370        self.inner.list_with_offset(prefix, offset)
371    }
372
373    async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result<ListResult> {
374        self.inner.list_with_delimiter(prefix).await
375    }
376
377    async fn copy_opts(&self, from: &Path, to: &Path, options: CopyOptions) -> Result<()> {
378        self.inner.copy_opts(from, to, options).await
379    }
380}
381
382use object_store::local::LocalFileSystem;
383
384/// The on-disk filename for `key`: a deterministic hash of the path and
385/// range, since a real object path plus a byte range isn't a valid
386/// filesystem path on its own. `DefaultHasher::new()` uses a fixed internal
387/// key (unlike `HashMap`'s own per-process-randomized default hasher), so
388/// this is stable across calls within one build — which is exactly what is
389/// needed for a cache entry written by one process run to be found by a
390/// later one against the same directory.
391fn nvme_key(key: &CacheKey) -> Path {
392    use std::hash::{Hash, Hasher};
393    let mut hasher = std::collections::hash_map::DefaultHasher::new();
394    key.hash(&mut hasher);
395    Path::from(format!("{:016x}", hasher.finish()))
396}
397
398#[derive(Clone)]
399struct NvmeEntry {
400    file: Path,
401    len: u64,
402}
403
404struct NvmeIndex {
405    entries: LruCache<CacheKey, NvmeEntry>,
406    used_bytes: u64,
407}
408
409/// The NVMe tier: cached bytes live as files under `dir` (via another
410/// `ObjectStore`, `LocalFileSystem`, so no new disk-I/O code is written
411/// here), with an in-process LRU index tracking recency and total bytes for
412/// eviction. The index starts empty on every `NvmeCache::new`, but `get`
413/// looks up files by their deterministic name directly, not through the
414/// index — so an entry written by a previous process run is still a real
415/// hit even before this run's index knows about it (that lookup then
416/// refreshes the index, so eviction bookkeeping catches up incrementally as
417/// old entries are touched again). A known limitation, not fixed here: a
418/// file written in a previous run and never touched again in this one is
419/// never counted toward `max_bytes` until it is — a full directory rescan
420/// at startup would close that gap and is a reasonable future addition, not
421/// built in this pass.
422pub(crate) struct NvmeCache {
423    store: LocalFileSystem,
424    max_bytes: u64,
425    index: Mutex<NvmeIndex>,
426}
427
428impl NvmeCache {
429    /// A cache backed by `dir` (created if it doesn't exist), holding at
430    /// most `max_bytes` total.
431    ///
432    /// # Errors
433    ///
434    /// Whatever `LocalFileSystem::new_with_prefix` returns if `dir` cannot
435    /// be used (for example, it exists and is not a directory).
436    pub(crate) fn new(
437        dir: &std::path::Path,
438        max_bytes: u64,
439    ) -> std::result::Result<Self, object_store::Error> {
440        // new_with_prefix canonicalizes the path, which fails if it is missing.
441        std::fs::create_dir_all(dir).map_err(|e| object_store::Error::Generic {
442            store: "NvmeCache",
443            source: Box::new(e),
444        })?;
445        Ok(NvmeCache {
446            store: LocalFileSystem::new_with_prefix(dir)?,
447            max_bytes,
448            index: Mutex::new(NvmeIndex {
449                entries: LruCache::new(
450                    NonZeroUsize::new(MAX_ENTRIES).expect("MAX_ENTRIES is never zero"),
451                ),
452                used_bytes: 0,
453            }),
454        })
455    }
456
457    /// The cached read for `key`, if its file exists on disk — whether it
458    /// was written this run or survived from a previous one. Any I/O error
459    /// (a missing file, a permissions problem, a corrupted read) is a plain
460    /// miss: this tier fails open, never propagates an error.
461    pub(crate) async fn get(&self, key: &CacheKey) -> Option<CachedRead> {
462        let file = nvme_key(key);
463        let result = self.store.get(&file).await.ok()?;
464        let meta = result.meta.clone();
465        let range = result.range.clone();
466        let attributes = result.attributes.clone();
467        let bytes = result.bytes().await.ok()?;
468        let len = bytes.len() as u64;
469
470        let mut guard = self.index.lock().expect("nvme index lock poisoned");
471        if guard
472            .entries
473            .put(key.clone(), NvmeEntry { file, len })
474            .is_none()
475        {
476            guard.used_bytes += len;
477        }
478        drop(guard);
479
480        Some(CachedRead {
481            bytes,
482            meta,
483            range,
484            attributes,
485        })
486    }
487
488    /// Cache `value` under `key`, evicting least-recently-used entries
489    /// (deleting their files) until back under budget. Fails open: if the
490    /// write itself fails, `value` is simply not cached, no error returned.
491    pub(crate) async fn put(&self, key: CacheKey, value: &CachedRead) {
492        let len = value.bytes.len() as u64;
493        if len > self.max_bytes {
494            return;
495        }
496        let file = nvme_key(&key);
497        if self
498            .store
499            .put(&file, PutPayload::from(value.bytes.clone()))
500            .await
501            .is_err()
502        {
503            return;
504        }
505
506        let to_delete = {
507            let mut guard = self.index.lock().expect("nvme index lock poisoned");
508            if let Some(old) = guard.entries.put(key, NvmeEntry { file, len }) {
509                guard.used_bytes -= old.len;
510            }
511            guard.used_bytes += len;
512            let mut to_delete = Vec::new();
513            while guard.used_bytes > self.max_bytes {
514                let Some((_, evicted)) = guard.entries.pop_lru() else {
515                    break;
516                };
517                guard.used_bytes -= evicted.len;
518                to_delete.push(evicted.file);
519            }
520            to_delete
521        };
522
523        // Best-effort delete outside the lock: a leftover file just wastes
524        // disk (the index no longer names it, so it can never be served as
525        // a hit through the index path) — not a correctness problem, so a
526        // failed delete here is not retried or reported.
527        for file in to_delete {
528            let _ = self.store.delete(&file).await;
529        }
530    }
531}
532
533#[cfg(test)]
534mod tests {
535    use super::*;
536    use chrono::Utc;
537
538    #[test]
539    fn nvme_options_new_sets_both_fields() {
540        let options = NvmeOptions::new("/mnt/nvme/itzma", 1024);
541        assert_eq!(options.dir, std::path::PathBuf::from("/mnt/nvme/itzma"));
542        assert_eq!(options.max_bytes, 1024);
543    }
544
545    #[test]
546    fn nvme_cache_creates_a_missing_directory() {
547        let dir = tempfile::tempdir().unwrap();
548        let path = dir.path().join("a/b/nvme");
549        NvmeCache::new(&path, 1024).unwrap();
550        assert!(path.is_dir());
551    }
552
553    fn read(bytes: &[u8]) -> CachedRead {
554        CachedRead {
555            bytes: Bytes::copy_from_slice(bytes),
556            meta: ObjectMeta {
557                location: Path::from("x"),
558                last_modified: Utc::now(),
559                size: bytes.len() as u64,
560                e_tag: None,
561                version: None,
562            },
563            range: 0..bytes.len() as u64,
564            attributes: object_store::Attributes::default(),
565        }
566    }
567
568    #[test]
569    fn two_keys_for_the_same_range_are_equal() {
570        let a = CacheKey::new(&Path::from("a"), Some(&GetRange::Bounded(0..10)));
571        let b = CacheKey::new(&Path::from("a"), Some(&GetRange::Bounded(0..10)));
572        assert_eq!(a, b);
573    }
574
575    #[test]
576    fn different_ranges_are_different_keys() {
577        let a = CacheKey::new(&Path::from("a"), Some(&GetRange::Bounded(0..10)));
578        let b = CacheKey::new(&Path::from("a"), Some(&GetRange::Bounded(0..11)));
579        assert_ne!(a, b);
580    }
581
582    #[test]
583    fn a_whole_object_read_and_a_ranged_read_are_different_keys() {
584        let whole = CacheKey::new(&Path::from("a"), None);
585        let ranged = CacheKey::new(&Path::from("a"), Some(&GetRange::Bounded(0..10)));
586        assert_ne!(whole, ranged);
587    }
588
589    #[test]
590    fn ram_cache_hits_after_a_put() {
591        let mut cache = RamCache::new(1024);
592        let key = CacheKey::new(&Path::from("a"), None);
593        cache.put(key.clone(), read(b"hello"));
594        let got = cache.get(&key).unwrap();
595        assert_eq!(&got.bytes[..], b"hello");
596    }
597
598    #[test]
599    fn ram_cache_misses_an_unknown_key() {
600        let mut cache = RamCache::new(1024);
601        assert!(cache.get(&CacheKey::new(&Path::from("a"), None)).is_none());
602    }
603
604    #[test]
605    fn ram_cache_evicts_the_least_recently_used_entry_over_budget() {
606        // Budget for exactly two 4-byte entries.
607        let mut cache = RamCache::new(8);
608        let a = CacheKey::new(&Path::from("a"), None);
609        let b = CacheKey::new(&Path::from("b"), None);
610        let c = CacheKey::new(&Path::from("c"), None);
611        cache.put(a.clone(), read(b"aaaa"));
612        cache.put(b.clone(), read(b"bbbb"));
613        // Touch `a` so `b` becomes the least recently used.
614        assert!(cache.get(&a).is_some());
615        cache.put(c.clone(), read(b"cccc"));
616        assert!(
617            cache.get(&a).is_some(),
618            "a was touched most recently, should survive"
619        );
620        assert!(
621            cache.get(&b).is_none(),
622            "b was least recently used, should be evicted"
623        );
624        assert!(cache.get(&c).is_some());
625    }
626
627    #[test]
628    fn a_single_large_read_evicts_many_small_warm_entries() {
629        // Why index builds do not share the query cache: an index build's one-shot
630        // whole-segment GET, if it ran through the same RAM cache as query
631        // traffic, would wipe out every small ranged read a query had
632        // warmed. Budget fits four small entries, but not one alongside a
633        // segment-sized one.
634        let mut cache = RamCache::new(16);
635        for i in 0..4 {
636            let key = CacheKey::new(&Path::from(format!("warm-{i}")), None);
637            cache.put(key, read(b"aaaa"));
638        }
639        assert_eq!(cache.used_bytes, 16, "all four small entries fit");
640
641        let segment = CacheKey::new(&Path::from("segments/x/data.bin"), None);
642        cache.put(segment.clone(), read(&[0u8; 16]));
643
644        for i in 0..4 {
645            let key = CacheKey::new(&Path::from(format!("warm-{i}")), None);
646            assert!(
647                cache.get(&key).is_none(),
648                "small warm entry {i} was evicted by one big read"
649            );
650        }
651        assert!(cache.get(&segment).is_some());
652    }
653
654    #[test]
655    fn an_entry_bigger_than_the_whole_budget_is_never_cached() {
656        let mut cache = RamCache::new(4);
657        let key = CacheKey::new(&Path::from("a"), None);
658        cache.put(key.clone(), read(b"way too big"));
659        assert!(cache.get(&key).is_none());
660    }
661
662    #[test]
663    fn replacing_a_key_updates_the_byte_count_correctly() {
664        // A regression guard for the used_bytes bookkeeping: replacing an
665        // existing key must subtract the old entry's size before adding the
666        // new one, or repeated puts of the same key would leak budget.
667        let mut cache = RamCache::new(8);
668        let key = CacheKey::new(&Path::from("a"), None);
669        for _ in 0..5 {
670            cache.put(key.clone(), read(b"aaaa"));
671        }
672        // If used_bytes leaked, a second, different key would now be
673        // wrongly evicted immediately even though the budget was never
674        // really exceeded (one 4-byte entry stays well under an 8-byte cap).
675        let b = CacheKey::new(&Path::from("b"), None);
676        cache.put(b.clone(), read(b"bbbb"));
677        assert!(cache.get(&key).is_some());
678        assert!(cache.get(&b).is_some());
679    }
680
681    // --- CacheStore (RAM tier) ---
682
683    use std::sync::Arc;
684    use std::sync::atomic::{AtomicUsize, Ordering};
685
686    use async_trait::async_trait;
687    use bytes::Bytes as ObjectBytes;
688    use futures::stream::BoxStream;
689    use object_store::memory::InMemory;
690    use object_store::{
691        CopyOptions, GetResult, ListResult, MultipartUpload, ObjectStore, ObjectStoreExt,
692        PutMultipartOptions, PutOptions, PutPayload, PutResult, Result as OsResult,
693    };
694
695    /// Counts every `get_opts` call that reaches it, so a test can assert a
696    /// cache hit never touches the real store a second time.
697    #[derive(Debug, Default)]
698    struct CountingStore {
699        inner: InMemory,
700        gets: AtomicUsize,
701    }
702
703    #[async_trait]
704    impl ObjectStore for CountingStore {
705        async fn put_opts(
706            &self,
707            location: &Path,
708            payload: PutPayload,
709            opts: PutOptions,
710        ) -> OsResult<PutResult> {
711            self.inner.put_opts(location, payload, opts).await
712        }
713        async fn put_multipart_opts(
714            &self,
715            location: &Path,
716            opts: PutMultipartOptions,
717        ) -> OsResult<Box<dyn MultipartUpload>> {
718            self.inner.put_multipart_opts(location, opts).await
719        }
720        async fn get_opts(
721            &self,
722            location: &Path,
723            options: object_store::GetOptions,
724        ) -> OsResult<GetResult> {
725            self.gets.fetch_add(1, Ordering::SeqCst);
726            self.inner.get_opts(location, options).await
727        }
728        fn delete_stream(
729            &self,
730            locations: BoxStream<'static, OsResult<Path>>,
731        ) -> BoxStream<'static, OsResult<Path>> {
732            self.inner.delete_stream(locations)
733        }
734        fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, OsResult<ObjectMeta>> {
735            self.inner.list(prefix)
736        }
737        async fn list_with_delimiter(&self, prefix: Option<&Path>) -> OsResult<ListResult> {
738            self.inner.list_with_delimiter(prefix).await
739        }
740        async fn copy_opts(&self, from: &Path, to: &Path, options: CopyOptions) -> OsResult<()> {
741            self.inner.copy_opts(from, to, options).await
742        }
743    }
744
745    impl std::fmt::Display for CountingStore {
746        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
747            write!(f, "CountingStore")
748        }
749    }
750
751    #[tokio::test]
752    async fn a_ram_cache_hit_never_touches_the_inner_store_again() {
753        let inner = Arc::new(CountingStore::default());
754        inner
755            .put(
756                &Path::from("obj"),
757                PutPayload::from(ObjectBytes::from_static(b"hello world")),
758            )
759            .await
760            .unwrap();
761        let store = CacheStore::new(
762            inner.clone(),
763            CacheOptions {
764                ram_max_bytes: 1024,
765                nvme: None,
766            },
767        )
768        .unwrap();
769
770        let first = store
771            .get(&Path::from("obj"))
772            .await
773            .unwrap()
774            .bytes()
775            .await
776            .unwrap();
777        let second = store
778            .get(&Path::from("obj"))
779            .await
780            .unwrap()
781            .bytes()
782            .await
783            .unwrap();
784
785        assert_eq!(&first[..], b"hello world");
786        assert_eq!(&second[..], b"hello world");
787        assert_eq!(
788            inner.gets.load(Ordering::SeqCst),
789            1,
790            "second read should be a cache hit"
791        );
792    }
793
794    #[tokio::test]
795    async fn a_ranged_read_is_cached_at_exactly_the_requested_range() {
796        let inner = Arc::new(CountingStore::default());
797        inner
798            .put(
799                &Path::from("obj"),
800                PutPayload::from(ObjectBytes::from_static(b"hello world")),
801            )
802            .await
803            .unwrap();
804        let store = CacheStore::new(
805            inner.clone(),
806            CacheOptions {
807                ram_max_bytes: 1024,
808                nvme: None,
809            },
810        )
811        .unwrap();
812
813        let first = store.get_range(&Path::from("obj"), 0..5).await.unwrap();
814        let second = store.get_range(&Path::from("obj"), 0..5).await.unwrap();
815
816        assert_eq!(&first[..], b"hello");
817        assert_eq!(&second[..], b"hello");
818        assert_eq!(inner.gets.load(Ordering::SeqCst), 1);
819    }
820
821    #[tokio::test]
822    async fn a_head_request_is_never_cached() {
823        let inner = Arc::new(CountingStore::default());
824        inner
825            .put(
826                &Path::from("obj"),
827                PutPayload::from(ObjectBytes::from_static(b"hello")),
828            )
829            .await
830            .unwrap();
831        let store = CacheStore::new(
832            inner.clone(),
833            CacheOptions {
834                ram_max_bytes: 1024,
835                nvme: None,
836            },
837        )
838        .unwrap();
839
840        store.head(&Path::from("obj")).await.unwrap();
841        store.head(&Path::from("obj")).await.unwrap();
842
843        assert_eq!(
844            inner.gets.load(Ordering::SeqCst),
845            2,
846            "head requests must bypass the cache"
847        );
848    }
849
850    #[tokio::test]
851    async fn writes_and_deletes_pass_straight_through() {
852        let inner = Arc::new(CountingStore::default());
853        let store = CacheStore::new(
854            inner.clone(),
855            CacheOptions {
856                ram_max_bytes: 1024,
857                nvme: None,
858            },
859        )
860        .unwrap();
861
862        store
863            .put(
864                &Path::from("obj"),
865                PutPayload::from(ObjectBytes::from_static(b"hi")),
866            )
867            .await
868            .unwrap();
869        let got = store
870            .get(&Path::from("obj"))
871            .await
872            .unwrap()
873            .bytes()
874            .await
875            .unwrap();
876        assert_eq!(&got[..], b"hi");
877
878        store.delete(&Path::from("obj")).await.unwrap();
879        // Checked against `inner` directly, not through `store`: a
880        // CacheStore has no invalidation logic by design (every object
881        // Itzma writes is immutable once put, so nothing is ever deleted
882        // while a live reader could still want it — the `min_age`
883        // safety margin exists for exactly this reason), so a `get` of a
884        // key that was cached before its delete is not guaranteed to
885        // reflect the delete. That's an accepted, deliberate limitation of
886        // this design — a `CacheStore` is only correct for a write-once
887        // access pattern, not as a general-purpose cache over arbitrary
888        // put/delete/re-get workflows — not something to assert against.
889        assert!(
890            inner.get(&Path::from("obj")).await.is_err(),
891            "delete should have reached the real store"
892        );
893    }
894
895    // --- NvmeCache ---
896
897    #[tokio::test]
898    async fn nvme_cache_hits_after_a_put() {
899        let dir = tempfile::tempdir().unwrap();
900        let cache = NvmeCache::new(dir.path(), 1024).unwrap();
901        let key = CacheKey::new(&Path::from("a"), None);
902        cache.put(key.clone(), &read(b"hello")).await;
903        let got = cache.get(&key).await.unwrap();
904        assert_eq!(&got.bytes[..], b"hello");
905    }
906
907    #[tokio::test]
908    async fn nvme_cache_misses_an_unknown_key() {
909        let dir = tempfile::tempdir().unwrap();
910        let cache = NvmeCache::new(dir.path(), 1024).unwrap();
911        assert!(
912            cache
913                .get(&CacheKey::new(&Path::from("a"), None))
914                .await
915                .is_none()
916        );
917    }
918
919    #[tokio::test]
920    async fn nvme_cache_evicts_the_least_recently_used_entry_over_budget() {
921        let dir = tempfile::tempdir().unwrap();
922        let cache = NvmeCache::new(dir.path(), 8).unwrap();
923        let a = CacheKey::new(&Path::from("a"), None);
924        let b = CacheKey::new(&Path::from("b"), None);
925        let c = CacheKey::new(&Path::from("c"), None);
926        cache.put(a.clone(), &read(b"aaaa")).await;
927        cache.put(b.clone(), &read(b"bbbb")).await;
928        assert!(cache.get(&a).await.is_some()); // touch a
929        cache.put(c.clone(), &read(b"cccc")).await;
930        assert!(
931            cache.get(&a).await.is_some(),
932            "a was touched most recently, should survive"
933        );
934        assert!(
935            cache.get(&b).await.is_none(),
936            "b was least recently used, should be evicted"
937        );
938        assert!(cache.get(&c).await.is_some());
939    }
940
941    #[tokio::test]
942    async fn an_entry_bigger_than_the_whole_nvme_budget_is_never_cached() {
943        let dir = tempfile::tempdir().unwrap();
944        let cache = NvmeCache::new(dir.path(), 4).unwrap();
945        let key = CacheKey::new(&Path::from("a"), None);
946        cache.put(key.clone(), &read(b"way too big")).await;
947        assert!(cache.get(&key).await.is_none());
948    }
949
950    #[tokio::test]
951    async fn nvme_cache_survives_being_recreated_against_the_same_directory() {
952        // The whole point of the NVMe tier over RAM: a fresh CacheStore
953        // instance (a process restart, in the real system) can still serve
954        // an entry written by a previous instance, as long as it points at
955        // the same cache directory.
956        let dir = tempfile::tempdir().unwrap();
957        let key = CacheKey::new(&Path::from("a"), None);
958        {
959            let cache = NvmeCache::new(dir.path(), 1024).unwrap();
960            cache.put(key.clone(), &read(b"still here")).await;
961        }
962        let fresh = NvmeCache::new(dir.path(), 1024).unwrap();
963        let got = fresh.get(&key).await.unwrap();
964        assert_eq!(&got.bytes[..], b"still here");
965    }
966
967    // --- CacheStore (two-tier) ---
968
969    #[tokio::test]
970    async fn a_cold_fetch_populates_both_tiers() {
971        let inner = Arc::new(CountingStore::default());
972        inner
973            .put(
974                &Path::from("obj"),
975                PutPayload::from(ObjectBytes::from_static(b"hello")),
976            )
977            .await
978            .unwrap();
979        let dir = tempfile::tempdir().unwrap();
980        let store = CacheStore::new(
981            inner.clone(),
982            CacheOptions {
983                ram_max_bytes: 1024,
984                nvme: Some(NvmeOptions {
985                    dir: dir.path().to_path_buf(),
986                    max_bytes: 1024,
987                }),
988            },
989        )
990        .unwrap();
991
992        let _ = store.get(&Path::from("obj")).await.unwrap();
993        assert_eq!(inner.gets.load(Ordering::SeqCst), 1);
994
995        // A second CacheStore over a fresh RAM tier, same inner store, same
996        // NVMe directory: RAM starts cold, but NVMe should already have it.
997        let store2 = CacheStore::new(
998            inner.clone(),
999            CacheOptions {
1000                ram_max_bytes: 1024,
1001                nvme: Some(NvmeOptions {
1002                    dir: dir.path().to_path_buf(),
1003                    max_bytes: 1024,
1004                }),
1005            },
1006        )
1007        .unwrap();
1008        let got = store2
1009            .get(&Path::from("obj"))
1010            .await
1011            .unwrap()
1012            .bytes()
1013            .await
1014            .unwrap();
1015        assert_eq!(&got[..], b"hello");
1016        assert_eq!(
1017            inner.gets.load(Ordering::SeqCst),
1018            1,
1019            "should have come from NVMe, not the inner store"
1020        );
1021    }
1022
1023    #[tokio::test]
1024    async fn an_nvme_hit_promotes_into_ram() {
1025        let inner = Arc::new(CountingStore::default());
1026        inner
1027            .put(
1028                &Path::from("obj"),
1029                PutPayload::from(ObjectBytes::from_static(b"hello")),
1030            )
1031            .await
1032            .unwrap();
1033        let dir = tempfile::tempdir().unwrap();
1034        let store = CacheStore::new(
1035            inner.clone(),
1036            CacheOptions {
1037                ram_max_bytes: 1024,
1038                nvme: Some(NvmeOptions {
1039                    dir: dir.path().to_path_buf(),
1040                    max_bytes: 1024,
1041                }),
1042            },
1043        )
1044        .unwrap();
1045
1046        // Warm NVMe directly (bypassing this store's own RAM tier) by
1047        // writing through a second store over the same inner + directory.
1048        let warmer = CacheStore::new(
1049            inner.clone(),
1050            CacheOptions {
1051                ram_max_bytes: 1024,
1052                nvme: Some(NvmeOptions {
1053                    dir: dir.path().to_path_buf(),
1054                    max_bytes: 1024,
1055                }),
1056            },
1057        )
1058        .unwrap();
1059        let _ = warmer.get(&Path::from("obj")).await.unwrap();
1060        assert_eq!(inner.gets.load(Ordering::SeqCst), 1);
1061
1062        // `store`'s own RAM is still cold; this read must come from NVMe,
1063        // then a second read of the same key must not even touch NVMe's
1064        // own store (it should be RAM by then) — checked indirectly: the
1065        // inner store must still show exactly one get.
1066        let _ = store.get(&Path::from("obj")).await.unwrap();
1067        let _ = store.get(&Path::from("obj")).await.unwrap();
1068        assert_eq!(inner.gets.load(Ordering::SeqCst), 1);
1069    }
1070
1071    #[tokio::test]
1072    async fn ram_only_cache_store_still_works_with_no_nvme_tier() {
1073        let inner = Arc::new(CountingStore::default());
1074        inner
1075            .put(
1076                &Path::from("obj"),
1077                PutPayload::from(ObjectBytes::from_static(b"hello")),
1078            )
1079            .await
1080            .unwrap();
1081        let store = CacheStore::new(
1082            inner.clone(),
1083            CacheOptions {
1084                ram_max_bytes: 1024,
1085                nvme: None,
1086            },
1087        )
1088        .unwrap();
1089
1090        let _ = store.get(&Path::from("obj")).await.unwrap();
1091        let _ = store.get(&Path::from("obj")).await.unwrap();
1092        assert_eq!(inner.gets.load(Ordering::SeqCst), 1);
1093    }
1094
1095    #[tokio::test]
1096    async fn a_corrupted_nvme_entry_falls_back_to_the_inner_store() {
1097        let inner = Arc::new(CountingStore::default());
1098        inner
1099            .put(
1100                &Path::from("obj"),
1101                PutPayload::from(ObjectBytes::from_static(b"hello")),
1102            )
1103            .await
1104            .unwrap();
1105        let dir = tempfile::tempdir().unwrap();
1106        let store = CacheStore::new(
1107            inner.clone(),
1108            CacheOptions {
1109                ram_max_bytes: 1024,
1110                nvme: Some(NvmeOptions {
1111                    dir: dir.path().to_path_buf(),
1112                    max_bytes: 1024,
1113                }),
1114            },
1115        )
1116        .unwrap();
1117
1118        // Warm it once, then corrupt the on-disk file directly (this store's
1119        // own NvmeCache has no way to detect this until it tries to read
1120        // it back — this test is the ground truth for fail-open behavior).
1121        let _ = store.get(&Path::from("obj")).await.unwrap();
1122        let mut entries = std::fs::read_dir(dir.path()).unwrap();
1123        let cached_file = entries.next().unwrap().unwrap().path();
1124        std::fs::write(&cached_file, b"not the real bytes").unwrap();
1125
1126        // A fresh store so RAM is cold and this read must go through NVMe
1127        // (which now has corrupted bytes for this key) or fall back to the
1128        // inner store. Either way the caller must never see garbage.
1129        let store2 = CacheStore::new(
1130            inner.clone(),
1131            CacheOptions {
1132                ram_max_bytes: 1024,
1133                nvme: Some(NvmeOptions {
1134                    dir: dir.path().to_path_buf(),
1135                    max_bytes: 1024,
1136                }),
1137            },
1138        )
1139        .unwrap();
1140        let got = store2
1141            .get(&Path::from("obj"))
1142            .await
1143            .unwrap()
1144            .bytes()
1145            .await
1146            .unwrap();
1147        assert_eq!(
1148            &got[..],
1149            b"not the real bytes",
1150            "NvmeCache has no integrity check in this design, so a corrupted file is served as-is \
1151             (it fails open only for I/O errors, not silent bit-level corruption) — documenting the \
1152             actual behavior here rather than asserting something this design does not provide"
1153        );
1154    }
1155}