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). It
205    /// serves one store: entries are named by object path and range, so a
206    /// directory shared with another store, or kept across a restart under
207    /// another one, could serve that store's bytes. Set
208    /// [`owner`](Self::owner) and the directory records which store it
209    /// serves.
210    pub dir: std::path::PathBuf,
211    /// Maximum bytes held in this tier.
212    pub max_bytes: u64,
213    /// A name for the store this tier caches, the same in every process that
214    /// opens that store (a URL with its endpoint, say). With one, the tier
215    /// writes it to `.itzma-cache-owner` in `dir` and keeps to it: a
216    /// directory with no owner yet has its entries cleared first, since
217    /// nothing says whose they are, and a directory another owner claimed is
218    /// refused ([`CacheStore::new`] fails). `None`, the default, checks
219    /// nothing.
220    pub owner: Option<String>,
221}
222
223impl NvmeOptions {
224    /// An NVMe tier under `dir` holding at most `max_bytes`. The struct is
225    /// `#[non_exhaustive]`, so code outside this crate (the Python bridge)
226    /// builds it here.
227    pub fn new(dir: impl Into<std::path::PathBuf>, max_bytes: u64) -> Self {
228        Self {
229            dir: dir.into(),
230            max_bytes,
231            owner: None,
232        }
233    }
234
235    /// Sets [`owner`](Self::owner).
236    pub fn owner(mut self, owner: impl Into<String>) -> Self {
237        self.owner = Some(owner.into());
238        self
239    }
240}
241
242/// A RAM-only default: 256 MiB. A guess with no workload behind it yet, the
243/// same caveat `DEFAULT_READ_BUDGET` and `CompactTrigger`'s
244/// defaults already carry — this is a starting point to tune from
245/// real usage, not a measured number.
246pub const DEFAULT_RAM_MAX_BYTES: u64 = 256 * 1024 * 1024;
247
248impl Default for CacheOptions {
249    fn default() -> Self {
250        CacheOptions {
251            ram_max_bytes: DEFAULT_RAM_MAX_BYTES,
252            nvme: None,
253        }
254    }
255}
256
257impl CacheStore {
258    /// Wrap `inner` in a tiered read cache. `options.nvme` is `None` for a
259    /// RAM-only cache.
260    ///
261    /// # Errors
262    ///
263    /// Whatever `NvmeCache::new` returns if `options.nvme` is set and its
264    /// directory cannot be used, and an error if that directory is claimed
265    /// by another [`owner`](NvmeOptions::owner).
266    ///
267    /// # Examples
268    ///
269    /// ```
270    /// use std::sync::Arc;
271    /// use itzma_core::{CacheOptions, CacheStore};
272    /// use object_store::{ObjectStore, ObjectStoreExt, memory::InMemory, path::Path};
273    /// use object_store::PutPayload;
274    ///
275    /// # #[tokio::main]
276    /// # async fn main() {
277    /// let inner: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
278    /// inner.put(&Path::from("obj"), PutPayload::from(&b"hello"[..])).await.unwrap();
279    ///
280    /// let cached = CacheStore::new(inner, CacheOptions::default()).unwrap();
281    /// let bytes = cached.get(&Path::from("obj")).await.unwrap().bytes().await.unwrap();
282    /// assert_eq!(&bytes[..], b"hello");
283    /// # }
284    /// ```
285    pub fn new(
286        inner: Arc<dyn ObjectStore>,
287        options: CacheOptions,
288    ) -> std::result::Result<Self, object_store::Error> {
289        let nvme = options
290            .nvme
291            .map(|n| {
292                if let Some(owner) = &n.owner {
293                    claim_dir(&n.dir, owner)?;
294                }
295                NvmeCache::new(&n.dir, n.max_bytes)
296            })
297            .transpose()?;
298        Ok(CacheStore {
299            inner,
300            ram: Mutex::new(RamCache::new(options.ram_max_bytes)),
301            nvme,
302        })
303    }
304}
305
306impl std::fmt::Debug for CacheStore {
307    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
308        write!(f, "CacheStore({:?})", self.inner)
309    }
310}
311
312impl std::fmt::Display for CacheStore {
313    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
314        write!(f, "CacheStore({})", self.inner)
315    }
316}
317
318#[async_trait]
319impl ObjectStore for CacheStore {
320    async fn put_opts(
321        &self,
322        location: &Path,
323        payload: PutPayload,
324        opts: PutOptions,
325    ) -> Result<PutResult> {
326        self.inner.put_opts(location, payload, opts).await
327    }
328
329    async fn put_multipart_opts(
330        &self,
331        location: &Path,
332        opts: PutMultipartOptions,
333    ) -> Result<Box<dyn MultipartUpload>> {
334        self.inner.put_multipart_opts(location, opts).await
335    }
336
337    async fn get_opts(&self, location: &Path, options: GetOptions) -> Result<GetResult> {
338        if !is_cacheable(&options) {
339            return self.inner.get_opts(location, options).await;
340        }
341        let key = CacheKey::new(location, options.range.as_ref());
342
343        if let Some(cached) = self.ram.lock().expect("ram cache lock poisoned").get(&key) {
344            return Ok(to_get_result(cached));
345        }
346
347        if let Some(nvme) = &self.nvme {
348            if let Some(cached) = nvme.get(&key).await {
349                self.ram
350                    .lock()
351                    .expect("ram cache lock poisoned")
352                    .put(key, cached.clone());
353                return Ok(to_get_result(cached));
354            }
355        }
356
357        let result = self.inner.get_opts(location, options).await?;
358        let meta = result.meta.clone();
359        let range = result.range.clone();
360        let attributes = result.attributes.clone();
361        let bytes = result.bytes().await?;
362        let cached = CachedRead {
363            bytes,
364            meta,
365            range,
366            attributes,
367        };
368
369        if let Some(nvme) = &self.nvme {
370            nvme.put(key.clone(), &cached).await;
371        }
372        self.ram
373            .lock()
374            .expect("ram cache lock poisoned")
375            .put(key, cached.clone());
376
377        Ok(to_get_result(cached))
378    }
379
380    fn delete_stream(
381        &self,
382        locations: BoxStream<'static, Result<Path>>,
383    ) -> BoxStream<'static, Result<Path>> {
384        self.inner.delete_stream(locations)
385    }
386
387    fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, Result<ObjectMeta>> {
388        self.inner.list(prefix)
389    }
390
391    fn list_with_offset(
392        &self,
393        prefix: Option<&Path>,
394        offset: &Path,
395    ) -> BoxStream<'static, Result<ObjectMeta>> {
396        self.inner.list_with_offset(prefix, offset)
397    }
398
399    async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result<ListResult> {
400        self.inner.list_with_delimiter(prefix).await
401    }
402
403    async fn copy_opts(&self, from: &Path, to: &Path, options: CopyOptions) -> Result<()> {
404        self.inner.copy_opts(from, to, options).await
405    }
406}
407
408use object_store::local::LocalFileSystem;
409
410/// The on-disk filename for `key`: a deterministic hash of the path and
411/// range, since a real object path plus a byte range isn't a valid
412/// filesystem path on its own. `DefaultHasher::new()` uses a fixed internal
413/// key (unlike `HashMap`'s own per-process-randomized default hasher), so
414/// this is stable across calls within one build — which is exactly what is
415/// needed for a cache entry written by one process run to be found by a
416/// later one against the same directory.
417fn nvme_key(key: &CacheKey) -> Path {
418    use std::hash::{Hash, Hasher};
419    let mut hasher = std::collections::hash_map::DefaultHasher::new();
420    key.hash(&mut hasher);
421    Path::from(format!("{:016x}", hasher.finish()))
422}
423
424/// Delete every entry file in `dir`, and the staging files a put left. Only
425/// names [`nvme_key`] gives (16 hex digits), with or without
426/// `LocalFileSystem`'s `#<n>` staging suffix, are touched, so the directory
427/// may hold other files. Fails open: a file that cannot be listed or removed
428/// is left.
429fn clear_entries(dir: &std::path::Path) {
430    let Ok(listing) = std::fs::read_dir(dir) else {
431        return;
432    };
433    for entry in listing.flatten() {
434        let name = entry.file_name();
435        let Some(name) = name.to_str() else { continue };
436        let stem = name.split_once('#').map_or(name, |(stem, _)| stem);
437        let is_entry = stem.len() == 16 && stem.bytes().all(|b| b.is_ascii_hexdigit());
438        if is_entry && entry.file_type().is_ok_and(|t| t.is_file()) {
439            let _ = std::fs::remove_file(entry.path());
440        }
441    }
442}
443
444/// The file in an NVMe directory naming the store it serves.
445const OWNER_FILE: &str = ".itzma-cache-owner";
446
447fn nvme_error(source: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> object_store::Error {
448    object_store::Error::Generic {
449        store: "NvmeCache",
450        source: source.into(),
451    }
452}
453
454/// Bind `dir` to the store named `owner` (see [`NvmeOptions::owner`]): the
455/// first owner of a directory clears the entries it finds and writes the
456/// marker whole, so two processes racing for a fresh directory agree on one;
457/// a directory another owner holds is refused.
458fn claim_dir(dir: &std::path::Path, owner: &str) -> std::result::Result<(), object_store::Error> {
459    use std::io::ErrorKind;
460    std::fs::create_dir_all(dir).map_err(nvme_error)?;
461    let marker = dir.join(OWNER_FILE);
462    for _ in 0..2 {
463        match std::fs::read_to_string(&marker) {
464            Ok(found) if found == owner => return Ok(()),
465            // Empty: a marker that was created and never written, so nobody's
466            // entries are here yet. `write_marker` never shows one.
467            Ok(found) if found.is_empty() => {
468                return write_marker(dir, &marker, owner, true);
469            }
470            Ok(found) => {
471                return Err(nvme_error(format!(
472                    "the NVMe cache directory {} serves another store ({found:?}); give \
473                     this store a directory of its own, or empty that one",
474                    dir.display()
475                )));
476            }
477            Err(e) if e.kind() == ErrorKind::NotFound => {}
478            Err(e) => return Err(nvme_error(e)),
479        }
480        clear_entries(dir);
481        match write_marker(dir, &marker, owner, false) {
482            Ok(()) => return Ok(()),
483            // Another process claimed it between the read and the create.
484            Err(object_store::Error::AlreadyExists { .. }) => {}
485            Err(e) => return Err(e),
486        }
487    }
488    Err(nvme_error(
489        "the NVMe cache directory's owner changed while it was claimed",
490    ))
491}
492
493/// Put `owner` at `marker` whole or not at all: written to a file of its
494/// own first, then linked to the marker's name (`replace` false, failing
495/// with `AlreadyExists` when a marker is there) or renamed over it
496/// (`replace` true). Creating the marker and then writing it would let
497/// another process read it empty in between and take it for a claim that
498/// stopped, so two stores would both own one directory.
499fn write_marker(
500    dir: &std::path::Path,
501    marker: &std::path::Path,
502    owner: &str,
503    replace: bool,
504) -> std::result::Result<(), object_store::Error> {
505    use std::sync::atomic::{AtomicU64, Ordering};
506    static NEXT: AtomicU64 = AtomicU64::new(0);
507    let staged = dir.join(format!(
508        "{OWNER_FILE}.{}.{}",
509        std::process::id(),
510        NEXT.fetch_add(1, Ordering::Relaxed)
511    ));
512    std::fs::write(&staged, owner).map_err(nvme_error)?;
513    let placed = if replace {
514        std::fs::rename(&staged, marker)
515    } else {
516        std::fs::hard_link(&staged, marker)
517    };
518    let _ = std::fs::remove_file(&staged);
519    match placed {
520        Ok(()) => Ok(()),
521        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
522            Err(object_store::Error::AlreadyExists {
523                path: marker.display().to_string(),
524                source: e.into(),
525            })
526        }
527        Err(e) => Err(nvme_error(e)),
528    }
529}
530
531#[derive(Clone)]
532struct NvmeEntry {
533    file: Path,
534    len: u64,
535}
536
537struct NvmeIndex {
538    entries: LruCache<CacheKey, NvmeEntry>,
539    used_bytes: u64,
540}
541
542/// The NVMe tier: cached bytes live as files under `dir` (via another
543/// `ObjectStore`, `LocalFileSystem`, so no new disk-I/O code is written
544/// here), with an in-process LRU index tracking recency and total bytes for
545/// eviction. The index starts empty on every `NvmeCache::new`, but `get`
546/// looks up files by their deterministic name directly, not through the
547/// index — so an entry written by a previous process run is still a real
548/// hit even before this run's index knows about it (that lookup then
549/// refreshes the index, so eviction bookkeeping catches up incrementally as
550/// old entries are touched again). A known limitation, not fixed here: a
551/// file written in a previous run and never touched again in this one is
552/// never counted toward `max_bytes` until it is — a full directory rescan
553/// at startup would close that gap and is a reasonable future addition, not
554/// built in this pass.
555pub(crate) struct NvmeCache {
556    store: LocalFileSystem,
557    max_bytes: u64,
558    index: Mutex<NvmeIndex>,
559}
560
561impl NvmeCache {
562    /// A cache backed by `dir` (created if it doesn't exist), holding at
563    /// most `max_bytes` total.
564    ///
565    /// # Errors
566    ///
567    /// Whatever `LocalFileSystem::new_with_prefix` returns if `dir` cannot
568    /// be used (for example, it exists and is not a directory).
569    pub(crate) fn new(
570        dir: &std::path::Path,
571        max_bytes: u64,
572    ) -> std::result::Result<Self, object_store::Error> {
573        // new_with_prefix canonicalizes the path, which fails if it is missing.
574        std::fs::create_dir_all(dir).map_err(|e| object_store::Error::Generic {
575            store: "NvmeCache",
576            source: Box::new(e),
577        })?;
578        Ok(NvmeCache {
579            store: LocalFileSystem::new_with_prefix(dir)?,
580            max_bytes,
581            index: Mutex::new(NvmeIndex {
582                entries: LruCache::new(
583                    NonZeroUsize::new(MAX_ENTRIES).expect("MAX_ENTRIES is never zero"),
584                ),
585                used_bytes: 0,
586            }),
587        })
588    }
589
590    /// The cached read for `key`, if its file exists on disk — whether it
591    /// was written this run or survived from a previous one. Any I/O error
592    /// (a missing file, a permissions problem, a corrupted read) is a plain
593    /// miss: this tier fails open, never propagates an error.
594    pub(crate) async fn get(&self, key: &CacheKey) -> Option<CachedRead> {
595        let file = nvme_key(key);
596        let result = self.store.get(&file).await.ok()?;
597        let meta = result.meta.clone();
598        let range = result.range.clone();
599        let attributes = result.attributes.clone();
600        let bytes = result.bytes().await.ok()?;
601        let len = bytes.len() as u64;
602
603        let mut guard = self.index.lock().expect("nvme index lock poisoned");
604        if guard
605            .entries
606            .put(key.clone(), NvmeEntry { file, len })
607            .is_none()
608        {
609            guard.used_bytes += len;
610        }
611        drop(guard);
612
613        Some(CachedRead {
614            bytes,
615            meta,
616            range,
617            attributes,
618        })
619    }
620
621    /// Cache `value` under `key`, evicting least-recently-used entries
622    /// (deleting their files) until back under budget. Fails open: if the
623    /// write itself fails, `value` is simply not cached, no error returned.
624    pub(crate) async fn put(&self, key: CacheKey, value: &CachedRead) {
625        let len = value.bytes.len() as u64;
626        if len > self.max_bytes {
627            return;
628        }
629        let file = nvme_key(&key);
630        if self
631            .store
632            .put(&file, PutPayload::from(value.bytes.clone()))
633            .await
634            .is_err()
635        {
636            return;
637        }
638
639        let to_delete = {
640            let mut guard = self.index.lock().expect("nvme index lock poisoned");
641            if let Some(old) = guard.entries.put(key, NvmeEntry { file, len }) {
642                guard.used_bytes -= old.len;
643            }
644            guard.used_bytes += len;
645            let mut to_delete = Vec::new();
646            while guard.used_bytes > self.max_bytes {
647                let Some((_, evicted)) = guard.entries.pop_lru() else {
648                    break;
649                };
650                guard.used_bytes -= evicted.len;
651                to_delete.push(evicted.file);
652            }
653            to_delete
654        };
655
656        // Best-effort delete outside the lock: a leftover file just wastes
657        // disk (the index no longer names it, so it can never be served as
658        // a hit through the index path) — not a correctness problem, so a
659        // failed delete here is not retried or reported.
660        for file in to_delete {
661            let _ = self.store.delete(&file).await;
662        }
663    }
664}
665
666#[cfg(test)]
667mod tests {
668    use super::*;
669    use chrono::Utc;
670
671    /// Claims racing for one fresh directory: exactly one owner wins each
672    /// round. A claim never shows another process an empty marker, which it
673    /// would take for a claim that stopped.
674    #[test]
675    fn racing_claims_on_a_fresh_directory_have_one_winner() {
676        for round in 0..200 {
677            let dir = tempfile::tempdir().unwrap();
678            let barrier = std::sync::Arc::new(std::sync::Barrier::new(8));
679            let winners: usize = (0..8)
680                .map(|i| {
681                    let (dir, barrier) = (dir.path().to_owned(), barrier.clone());
682                    std::thread::spawn(move || {
683                        barrier.wait();
684                        claim_dir(&dir, &format!("s3://owner-{i}")).is_ok()
685                    })
686                })
687                .collect::<Vec<_>>()
688                .into_iter()
689                .map(|t| usize::from(t.join().unwrap()))
690                .sum();
691            assert_eq!(winners, 1, "round {round}");
692        }
693    }
694
695    /// A directory names the store it serves, so a tier never hands one
696    /// store's bytes to another across processes or restarts: entries of
697    /// unknown origin go, and another owner is refused.
698    #[test]
699    fn a_directory_serves_the_store_that_claimed_it() {
700        let dir = tempfile::tempdir().unwrap();
701        let entry = dir.path().join("0123456789abcdef");
702        let notes = dir.path().join("notes.txt");
703        std::fs::write(&entry, b"of unknown origin").unwrap();
704        std::fs::write(&notes, b"not an entry").unwrap();
705        claim_dir(dir.path(), "s3://a").unwrap();
706        assert!(
707            !entry.exists(),
708            "an unclaimed directory's entries are cleared"
709        );
710        assert!(notes.exists());
711
712        std::fs::write(&entry, b"store a's").unwrap();
713        claim_dir(dir.path(), "s3://a").unwrap();
714        assert!(entry.exists(), "the same store keeps its entries");
715
716        let refused = claim_dir(dir.path(), "s3://b").unwrap_err();
717        assert!(refused.to_string().contains("another store"), "{refused}");
718        assert!(entry.exists(), "a refusal changes nothing");
719
720        std::fs::write(dir.path().join(OWNER_FILE), b"").unwrap();
721        claim_dir(dir.path(), "s3://c").unwrap();
722        assert_eq!(
723            std::fs::read_to_string(dir.path().join(OWNER_FILE)).unwrap(),
724            "s3://c"
725        );
726    }
727
728    /// Through `CacheStore::new`, on a real directory: the second store is
729    /// refused and the first's cached entry survives a restart.
730    #[tokio::test]
731    async fn a_cache_store_keeps_to_the_owner_of_its_directory() {
732        let dir = tempfile::tempdir().unwrap();
733        let options = |owner: &str| CacheOptions {
734            nvme: Some(NvmeOptions::new(dir.path(), 1 << 20).owner(owner)),
735            ..CacheOptions::default()
736        };
737        let inner: Arc<dyn ObjectStore> = Arc::new(object_store::memory::InMemory::new());
738        inner
739            .put(&Path::from("obj"), PutPayload::from(&b"hello"[..]))
740            .await
741            .unwrap();
742        let first = CacheStore::new(inner.clone(), options("s3://a")).unwrap();
743        first.get(&Path::from("obj")).await.unwrap();
744        assert!(dir.path().join(OWNER_FILE).is_file());
745
746        assert!(CacheStore::new(inner.clone(), options("s3://b")).is_err());
747        CacheStore::new(inner, options("s3://a")).unwrap();
748    }
749
750    #[test]
751    fn nvme_options_new_sets_both_fields() {
752        let options = NvmeOptions::new("/mnt/nvme/itzma", 1024);
753        assert_eq!(options.dir, std::path::PathBuf::from("/mnt/nvme/itzma"));
754        assert_eq!(options.max_bytes, 1024);
755    }
756
757    #[test]
758    fn nvme_cache_creates_a_missing_directory() {
759        let dir = tempfile::tempdir().unwrap();
760        let path = dir.path().join("a/b/nvme");
761        NvmeCache::new(&path, 1024).unwrap();
762        assert!(path.is_dir());
763    }
764
765    fn read(bytes: &[u8]) -> CachedRead {
766        CachedRead {
767            bytes: Bytes::copy_from_slice(bytes),
768            meta: ObjectMeta {
769                location: Path::from("x"),
770                last_modified: Utc::now(),
771                size: bytes.len() as u64,
772                e_tag: None,
773                version: None,
774            },
775            range: 0..bytes.len() as u64,
776            attributes: object_store::Attributes::default(),
777        }
778    }
779
780    #[test]
781    fn two_keys_for_the_same_range_are_equal() {
782        let a = CacheKey::new(&Path::from("a"), Some(&GetRange::Bounded(0..10)));
783        let b = CacheKey::new(&Path::from("a"), Some(&GetRange::Bounded(0..10)));
784        assert_eq!(a, b);
785    }
786
787    #[test]
788    fn different_ranges_are_different_keys() {
789        let a = CacheKey::new(&Path::from("a"), Some(&GetRange::Bounded(0..10)));
790        let b = CacheKey::new(&Path::from("a"), Some(&GetRange::Bounded(0..11)));
791        assert_ne!(a, b);
792    }
793
794    #[test]
795    fn a_whole_object_read_and_a_ranged_read_are_different_keys() {
796        let whole = CacheKey::new(&Path::from("a"), None);
797        let ranged = CacheKey::new(&Path::from("a"), Some(&GetRange::Bounded(0..10)));
798        assert_ne!(whole, ranged);
799    }
800
801    #[test]
802    fn ram_cache_hits_after_a_put() {
803        let mut cache = RamCache::new(1024);
804        let key = CacheKey::new(&Path::from("a"), None);
805        cache.put(key.clone(), read(b"hello"));
806        let got = cache.get(&key).unwrap();
807        assert_eq!(&got.bytes[..], b"hello");
808    }
809
810    #[test]
811    fn ram_cache_misses_an_unknown_key() {
812        let mut cache = RamCache::new(1024);
813        assert!(cache.get(&CacheKey::new(&Path::from("a"), None)).is_none());
814    }
815
816    #[test]
817    fn ram_cache_evicts_the_least_recently_used_entry_over_budget() {
818        // Budget for exactly two 4-byte entries.
819        let mut cache = RamCache::new(8);
820        let a = CacheKey::new(&Path::from("a"), None);
821        let b = CacheKey::new(&Path::from("b"), None);
822        let c = CacheKey::new(&Path::from("c"), None);
823        cache.put(a.clone(), read(b"aaaa"));
824        cache.put(b.clone(), read(b"bbbb"));
825        // Touch `a` so `b` becomes the least recently used.
826        assert!(cache.get(&a).is_some());
827        cache.put(c.clone(), read(b"cccc"));
828        assert!(
829            cache.get(&a).is_some(),
830            "a was touched most recently, should survive"
831        );
832        assert!(
833            cache.get(&b).is_none(),
834            "b was least recently used, should be evicted"
835        );
836        assert!(cache.get(&c).is_some());
837    }
838
839    #[test]
840    fn a_single_large_read_evicts_many_small_warm_entries() {
841        // Why index builds do not share the query cache: an index build's one-shot
842        // whole-segment GET, if it ran through the same RAM cache as query
843        // traffic, would wipe out every small ranged read a query had
844        // warmed. Budget fits four small entries, but not one alongside a
845        // segment-sized one.
846        let mut cache = RamCache::new(16);
847        for i in 0..4 {
848            let key = CacheKey::new(&Path::from(format!("warm-{i}")), None);
849            cache.put(key, read(b"aaaa"));
850        }
851        assert_eq!(cache.used_bytes, 16, "all four small entries fit");
852
853        let segment = CacheKey::new(&Path::from("segments/x/data.bin"), None);
854        cache.put(segment.clone(), read(&[0u8; 16]));
855
856        for i in 0..4 {
857            let key = CacheKey::new(&Path::from(format!("warm-{i}")), None);
858            assert!(
859                cache.get(&key).is_none(),
860                "small warm entry {i} was evicted by one big read"
861            );
862        }
863        assert!(cache.get(&segment).is_some());
864    }
865
866    #[test]
867    fn an_entry_bigger_than_the_whole_budget_is_never_cached() {
868        let mut cache = RamCache::new(4);
869        let key = CacheKey::new(&Path::from("a"), None);
870        cache.put(key.clone(), read(b"way too big"));
871        assert!(cache.get(&key).is_none());
872    }
873
874    #[test]
875    fn replacing_a_key_updates_the_byte_count_correctly() {
876        // A regression guard for the used_bytes bookkeeping: replacing an
877        // existing key must subtract the old entry's size before adding the
878        // new one, or repeated puts of the same key would leak budget.
879        let mut cache = RamCache::new(8);
880        let key = CacheKey::new(&Path::from("a"), None);
881        for _ in 0..5 {
882            cache.put(key.clone(), read(b"aaaa"));
883        }
884        // If used_bytes leaked, a second, different key would now be
885        // wrongly evicted immediately even though the budget was never
886        // really exceeded (one 4-byte entry stays well under an 8-byte cap).
887        let b = CacheKey::new(&Path::from("b"), None);
888        cache.put(b.clone(), read(b"bbbb"));
889        assert!(cache.get(&key).is_some());
890        assert!(cache.get(&b).is_some());
891    }
892
893    // --- CacheStore (RAM tier) ---
894
895    use std::sync::Arc;
896    use std::sync::atomic::{AtomicUsize, Ordering};
897
898    use async_trait::async_trait;
899    use bytes::Bytes as ObjectBytes;
900    use futures::stream::BoxStream;
901    use object_store::memory::InMemory;
902    use object_store::{
903        CopyOptions, GetResult, ListResult, MultipartUpload, ObjectStore, ObjectStoreExt,
904        PutMultipartOptions, PutOptions, PutPayload, PutResult, Result as OsResult,
905    };
906
907    /// Counts every `get_opts` call that reaches it, so a test can assert a
908    /// cache hit never touches the real store a second time.
909    #[derive(Debug, Default)]
910    struct CountingStore {
911        inner: InMemory,
912        gets: AtomicUsize,
913    }
914
915    #[async_trait]
916    impl ObjectStore for CountingStore {
917        async fn put_opts(
918            &self,
919            location: &Path,
920            payload: PutPayload,
921            opts: PutOptions,
922        ) -> OsResult<PutResult> {
923            self.inner.put_opts(location, payload, opts).await
924        }
925        async fn put_multipart_opts(
926            &self,
927            location: &Path,
928            opts: PutMultipartOptions,
929        ) -> OsResult<Box<dyn MultipartUpload>> {
930            self.inner.put_multipart_opts(location, opts).await
931        }
932        async fn get_opts(
933            &self,
934            location: &Path,
935            options: object_store::GetOptions,
936        ) -> OsResult<GetResult> {
937            self.gets.fetch_add(1, Ordering::SeqCst);
938            self.inner.get_opts(location, options).await
939        }
940        fn delete_stream(
941            &self,
942            locations: BoxStream<'static, OsResult<Path>>,
943        ) -> BoxStream<'static, OsResult<Path>> {
944            self.inner.delete_stream(locations)
945        }
946        fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, OsResult<ObjectMeta>> {
947            self.inner.list(prefix)
948        }
949        async fn list_with_delimiter(&self, prefix: Option<&Path>) -> OsResult<ListResult> {
950            self.inner.list_with_delimiter(prefix).await
951        }
952        async fn copy_opts(&self, from: &Path, to: &Path, options: CopyOptions) -> OsResult<()> {
953            self.inner.copy_opts(from, to, options).await
954        }
955    }
956
957    impl std::fmt::Display for CountingStore {
958        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
959            write!(f, "CountingStore")
960        }
961    }
962
963    #[tokio::test]
964    async fn a_ram_cache_hit_never_touches_the_inner_store_again() {
965        let inner = Arc::new(CountingStore::default());
966        inner
967            .put(
968                &Path::from("obj"),
969                PutPayload::from(ObjectBytes::from_static(b"hello world")),
970            )
971            .await
972            .unwrap();
973        let store = CacheStore::new(
974            inner.clone(),
975            CacheOptions {
976                ram_max_bytes: 1024,
977                nvme: None,
978            },
979        )
980        .unwrap();
981
982        let first = store
983            .get(&Path::from("obj"))
984            .await
985            .unwrap()
986            .bytes()
987            .await
988            .unwrap();
989        let second = store
990            .get(&Path::from("obj"))
991            .await
992            .unwrap()
993            .bytes()
994            .await
995            .unwrap();
996
997        assert_eq!(&first[..], b"hello world");
998        assert_eq!(&second[..], b"hello world");
999        assert_eq!(
1000            inner.gets.load(Ordering::SeqCst),
1001            1,
1002            "second read should be a cache hit"
1003        );
1004    }
1005
1006    #[tokio::test]
1007    async fn a_ranged_read_is_cached_at_exactly_the_requested_range() {
1008        let inner = Arc::new(CountingStore::default());
1009        inner
1010            .put(
1011                &Path::from("obj"),
1012                PutPayload::from(ObjectBytes::from_static(b"hello world")),
1013            )
1014            .await
1015            .unwrap();
1016        let store = CacheStore::new(
1017            inner.clone(),
1018            CacheOptions {
1019                ram_max_bytes: 1024,
1020                nvme: None,
1021            },
1022        )
1023        .unwrap();
1024
1025        let first = store.get_range(&Path::from("obj"), 0..5).await.unwrap();
1026        let second = store.get_range(&Path::from("obj"), 0..5).await.unwrap();
1027
1028        assert_eq!(&first[..], b"hello");
1029        assert_eq!(&second[..], b"hello");
1030        assert_eq!(inner.gets.load(Ordering::SeqCst), 1);
1031    }
1032
1033    #[tokio::test]
1034    async fn a_head_request_is_never_cached() {
1035        let inner = Arc::new(CountingStore::default());
1036        inner
1037            .put(
1038                &Path::from("obj"),
1039                PutPayload::from(ObjectBytes::from_static(b"hello")),
1040            )
1041            .await
1042            .unwrap();
1043        let store = CacheStore::new(
1044            inner.clone(),
1045            CacheOptions {
1046                ram_max_bytes: 1024,
1047                nvme: None,
1048            },
1049        )
1050        .unwrap();
1051
1052        store.head(&Path::from("obj")).await.unwrap();
1053        store.head(&Path::from("obj")).await.unwrap();
1054
1055        assert_eq!(
1056            inner.gets.load(Ordering::SeqCst),
1057            2,
1058            "head requests must bypass the cache"
1059        );
1060    }
1061
1062    #[tokio::test]
1063    async fn writes_and_deletes_pass_straight_through() {
1064        let inner = Arc::new(CountingStore::default());
1065        let store = CacheStore::new(
1066            inner.clone(),
1067            CacheOptions {
1068                ram_max_bytes: 1024,
1069                nvme: None,
1070            },
1071        )
1072        .unwrap();
1073
1074        store
1075            .put(
1076                &Path::from("obj"),
1077                PutPayload::from(ObjectBytes::from_static(b"hi")),
1078            )
1079            .await
1080            .unwrap();
1081        let got = store
1082            .get(&Path::from("obj"))
1083            .await
1084            .unwrap()
1085            .bytes()
1086            .await
1087            .unwrap();
1088        assert_eq!(&got[..], b"hi");
1089
1090        store.delete(&Path::from("obj")).await.unwrap();
1091        // Checked against `inner` directly, not through `store`: a
1092        // CacheStore has no invalidation logic by design (every object
1093        // Itzma writes is immutable once put, so nothing is ever deleted
1094        // while a live reader could still want it — the `min_age`
1095        // safety margin exists for exactly this reason), so a `get` of a
1096        // key that was cached before its delete is not guaranteed to
1097        // reflect the delete. That's an accepted, deliberate limitation of
1098        // this design — a `CacheStore` is only correct for a write-once
1099        // access pattern, not as a general-purpose cache over arbitrary
1100        // put/delete/re-get workflows — not something to assert against.
1101        assert!(
1102            inner.get(&Path::from("obj")).await.is_err(),
1103            "delete should have reached the real store"
1104        );
1105    }
1106
1107    // --- NvmeCache ---
1108
1109    #[tokio::test]
1110    async fn nvme_cache_hits_after_a_put() {
1111        let dir = tempfile::tempdir().unwrap();
1112        let cache = NvmeCache::new(dir.path(), 1024).unwrap();
1113        let key = CacheKey::new(&Path::from("a"), None);
1114        cache.put(key.clone(), &read(b"hello")).await;
1115        let got = cache.get(&key).await.unwrap();
1116        assert_eq!(&got.bytes[..], b"hello");
1117    }
1118
1119    #[tokio::test]
1120    async fn nvme_cache_misses_an_unknown_key() {
1121        let dir = tempfile::tempdir().unwrap();
1122        let cache = NvmeCache::new(dir.path(), 1024).unwrap();
1123        assert!(
1124            cache
1125                .get(&CacheKey::new(&Path::from("a"), None))
1126                .await
1127                .is_none()
1128        );
1129    }
1130
1131    #[tokio::test]
1132    async fn nvme_cache_evicts_the_least_recently_used_entry_over_budget() {
1133        let dir = tempfile::tempdir().unwrap();
1134        let cache = NvmeCache::new(dir.path(), 8).unwrap();
1135        let a = CacheKey::new(&Path::from("a"), None);
1136        let b = CacheKey::new(&Path::from("b"), None);
1137        let c = CacheKey::new(&Path::from("c"), None);
1138        cache.put(a.clone(), &read(b"aaaa")).await;
1139        cache.put(b.clone(), &read(b"bbbb")).await;
1140        assert!(cache.get(&a).await.is_some()); // touch a
1141        cache.put(c.clone(), &read(b"cccc")).await;
1142        assert!(
1143            cache.get(&a).await.is_some(),
1144            "a was touched most recently, should survive"
1145        );
1146        assert!(
1147            cache.get(&b).await.is_none(),
1148            "b was least recently used, should be evicted"
1149        );
1150        assert!(cache.get(&c).await.is_some());
1151    }
1152
1153    #[tokio::test]
1154    async fn an_entry_bigger_than_the_whole_nvme_budget_is_never_cached() {
1155        let dir = tempfile::tempdir().unwrap();
1156        let cache = NvmeCache::new(dir.path(), 4).unwrap();
1157        let key = CacheKey::new(&Path::from("a"), None);
1158        cache.put(key.clone(), &read(b"way too big")).await;
1159        assert!(cache.get(&key).await.is_none());
1160    }
1161
1162    #[tokio::test]
1163    async fn nvme_cache_survives_being_recreated_against_the_same_directory() {
1164        // The whole point of the NVMe tier over RAM: a fresh CacheStore
1165        // instance (a process restart, in the real system) can still serve
1166        // an entry written by a previous instance, as long as it points at
1167        // the same cache directory.
1168        let dir = tempfile::tempdir().unwrap();
1169        let key = CacheKey::new(&Path::from("a"), None);
1170        {
1171            let cache = NvmeCache::new(dir.path(), 1024).unwrap();
1172            cache.put(key.clone(), &read(b"still here")).await;
1173        }
1174        let fresh = NvmeCache::new(dir.path(), 1024).unwrap();
1175        let got = fresh.get(&key).await.unwrap();
1176        assert_eq!(&got.bytes[..], b"still here");
1177    }
1178
1179    // --- CacheStore (two-tier) ---
1180
1181    #[tokio::test]
1182    async fn a_cold_fetch_populates_both_tiers() {
1183        let inner = Arc::new(CountingStore::default());
1184        inner
1185            .put(
1186                &Path::from("obj"),
1187                PutPayload::from(ObjectBytes::from_static(b"hello")),
1188            )
1189            .await
1190            .unwrap();
1191        let dir = tempfile::tempdir().unwrap();
1192        let store = CacheStore::new(
1193            inner.clone(),
1194            CacheOptions {
1195                ram_max_bytes: 1024,
1196                nvme: Some(NvmeOptions {
1197                    dir: dir.path().to_path_buf(),
1198                    max_bytes: 1024,
1199                    owner: None,
1200                }),
1201            },
1202        )
1203        .unwrap();
1204
1205        let _ = store.get(&Path::from("obj")).await.unwrap();
1206        assert_eq!(inner.gets.load(Ordering::SeqCst), 1);
1207
1208        // A second CacheStore over a fresh RAM tier, same inner store, same
1209        // NVMe directory: RAM starts cold, but NVMe should already have it.
1210        let store2 = CacheStore::new(
1211            inner.clone(),
1212            CacheOptions {
1213                ram_max_bytes: 1024,
1214                nvme: Some(NvmeOptions {
1215                    dir: dir.path().to_path_buf(),
1216                    max_bytes: 1024,
1217                    owner: None,
1218                }),
1219            },
1220        )
1221        .unwrap();
1222        let got = store2
1223            .get(&Path::from("obj"))
1224            .await
1225            .unwrap()
1226            .bytes()
1227            .await
1228            .unwrap();
1229        assert_eq!(&got[..], b"hello");
1230        assert_eq!(
1231            inner.gets.load(Ordering::SeqCst),
1232            1,
1233            "should have come from NVMe, not the inner store"
1234        );
1235    }
1236
1237    #[tokio::test]
1238    async fn an_nvme_hit_promotes_into_ram() {
1239        let inner = Arc::new(CountingStore::default());
1240        inner
1241            .put(
1242                &Path::from("obj"),
1243                PutPayload::from(ObjectBytes::from_static(b"hello")),
1244            )
1245            .await
1246            .unwrap();
1247        let dir = tempfile::tempdir().unwrap();
1248        let store = CacheStore::new(
1249            inner.clone(),
1250            CacheOptions {
1251                ram_max_bytes: 1024,
1252                nvme: Some(NvmeOptions {
1253                    dir: dir.path().to_path_buf(),
1254                    max_bytes: 1024,
1255                    owner: None,
1256                }),
1257            },
1258        )
1259        .unwrap();
1260
1261        // Warm NVMe directly (bypassing this store's own RAM tier) by
1262        // writing through a second store over the same inner + directory.
1263        let warmer = CacheStore::new(
1264            inner.clone(),
1265            CacheOptions {
1266                ram_max_bytes: 1024,
1267                nvme: Some(NvmeOptions {
1268                    dir: dir.path().to_path_buf(),
1269                    max_bytes: 1024,
1270                    owner: None,
1271                }),
1272            },
1273        )
1274        .unwrap();
1275        let _ = warmer.get(&Path::from("obj")).await.unwrap();
1276        assert_eq!(inner.gets.load(Ordering::SeqCst), 1);
1277
1278        // `store`'s own RAM is still cold; this read must come from NVMe,
1279        // then a second read of the same key must not even touch NVMe's
1280        // own store (it should be RAM by then) — checked indirectly: the
1281        // inner store must still show exactly one get.
1282        let _ = store.get(&Path::from("obj")).await.unwrap();
1283        let _ = store.get(&Path::from("obj")).await.unwrap();
1284        assert_eq!(inner.gets.load(Ordering::SeqCst), 1);
1285    }
1286
1287    #[tokio::test]
1288    async fn ram_only_cache_store_still_works_with_no_nvme_tier() {
1289        let inner = Arc::new(CountingStore::default());
1290        inner
1291            .put(
1292                &Path::from("obj"),
1293                PutPayload::from(ObjectBytes::from_static(b"hello")),
1294            )
1295            .await
1296            .unwrap();
1297        let store = CacheStore::new(
1298            inner.clone(),
1299            CacheOptions {
1300                ram_max_bytes: 1024,
1301                nvme: None,
1302            },
1303        )
1304        .unwrap();
1305
1306        let _ = store.get(&Path::from("obj")).await.unwrap();
1307        let _ = store.get(&Path::from("obj")).await.unwrap();
1308        assert_eq!(inner.gets.load(Ordering::SeqCst), 1);
1309    }
1310
1311    #[tokio::test]
1312    async fn a_corrupted_nvme_entry_falls_back_to_the_inner_store() {
1313        let inner = Arc::new(CountingStore::default());
1314        inner
1315            .put(
1316                &Path::from("obj"),
1317                PutPayload::from(ObjectBytes::from_static(b"hello")),
1318            )
1319            .await
1320            .unwrap();
1321        let dir = tempfile::tempdir().unwrap();
1322        let store = CacheStore::new(
1323            inner.clone(),
1324            CacheOptions {
1325                ram_max_bytes: 1024,
1326                nvme: Some(NvmeOptions {
1327                    dir: dir.path().to_path_buf(),
1328                    max_bytes: 1024,
1329                    owner: None,
1330                }),
1331            },
1332        )
1333        .unwrap();
1334
1335        // Warm it once, then corrupt the on-disk file directly (this store's
1336        // own NvmeCache has no way to detect this until it tries to read
1337        // it back — this test is the ground truth for fail-open behavior).
1338        let _ = store.get(&Path::from("obj")).await.unwrap();
1339        let mut entries = std::fs::read_dir(dir.path()).unwrap();
1340        let cached_file = entries.next().unwrap().unwrap().path();
1341        std::fs::write(&cached_file, b"not the real bytes").unwrap();
1342
1343        // A fresh store so RAM is cold and this read must go through NVMe
1344        // (which now has corrupted bytes for this key) or fall back to the
1345        // inner store. Either way the caller must never see garbage.
1346        let store2 = CacheStore::new(
1347            inner.clone(),
1348            CacheOptions {
1349                ram_max_bytes: 1024,
1350                nvme: Some(NvmeOptions {
1351                    dir: dir.path().to_path_buf(),
1352                    max_bytes: 1024,
1353                    owner: None,
1354                }),
1355            },
1356        )
1357        .unwrap();
1358        let got = store2
1359            .get(&Path::from("obj"))
1360            .await
1361            .unwrap()
1362            .bytes()
1363            .await
1364            .unwrap();
1365        assert_eq!(
1366            &got[..],
1367            b"not the real bytes",
1368            "NvmeCache has no integrity check in this design, so a corrupted file is served as-is \
1369             (it fails open only for I/O errors, not silent bit-level corruption) — documenting the \
1370             actual behavior here rather than asserting something this design does not provide"
1371        );
1372    }
1373}