Skip to main content

rete_core/
block_cache.rs

1//! A read-through **block cache** over any [`RangeReader`] — the client-side
2//! half of lazy range serving (SPEC.md §9).
3//!
4//! The engine faults small, scattered byte ranges (a dictionary chunk here, an
5//! index tile there). Issued one-for-one against a high-latency remote, that is
6//! many round trips. This wrapper fetches fixed-size, **block-aligned** spans
7//! instead of exact ranges and caches them, so:
8//!
9//! - nearby reads coalesce into a few block fetches,
10//! - repeated reads (and the header re-read) are free, and
11//! - it needs only plain single-range `Range: bytes=a-b` support — so it speeds
12//!   up reads from **any** object store (S3, GCS, Azure, a CDN) that has no
13//!   multi-range / `multipart/byteranges` support at all.
14//!
15//! The trade is a little over-fetch (whole blocks) for far fewer requests — the
16//! right call on a latency-bound link. Missing blocks for one access are fetched
17//! through [`RangeReader::read_many`], so a backend that *does* support
18//! multi-range collapses them further still; the two optimizations compose.
19//!
20//! Residency is **bounded**: past a byte cap (default [`DEFAULT_CACHE_CAP`],
21//! overridable with [`BlockCacheReader::with_cache_cap`]) the least-recently
22//! touched blocks are evicted after each read. Without the cap, a wide scan of a
23//! multi-GB remote file would grow the cache toward the whole file — on 32-bit
24//! wasm (a 4 GiB address space shared with the decompressed tiles and dictionary
25//! chunks) that is an out-of-memory crash, not a slowdown.
26
27use crate::reader::RangeReader;
28use std::collections::{BTreeSet, HashMap, HashSet};
29use std::sync::{Arc, Condvar, Mutex};
30
31/// Default block size: 64 KiB — large enough to swallow a dictionary chunk or an
32/// index tile in one fetch, small enough to keep over-fetch modest.
33pub const DEFAULT_BLOCK: u64 = 64 * 1024;
34
35/// Default cap on resident cached bytes: 256 MiB. Large enough that a working
36/// set (the tiles + dictionary chunks a query family touches) stays warm; small
37/// enough that a full sweep of a multi-GB file leaves plenty of the 32-bit wasm
38/// address space for the decompressed structures built on top of these bytes.
39/// At the auto-tuned 128–512 KiB block sizes this is 512–2048 resident blocks,
40/// so the eviction scan is trivial.
41pub const DEFAULT_CACHE_CAP: u64 = 256 * 1024 * 1024;
42
43/// Pick a [`BlockCacheReader`] block size from the file length: bigger files get
44/// bigger blocks so a remote query makes far fewer (but larger) round trips —
45/// 128 KiB ≤ 10 MB, 256 KiB ≤ 100 MB, 512 KiB above. The over-fetch is modest
46/// next to the round-trip latency it saves on a high-latency link (S3/CDN). Shared
47/// by the CLI and the wasm client so both size identically; the file length is
48/// known for free from the opening `HEAD` / `Content-Range`.
49pub fn auto_block(len: u64) -> u64 {
50    const MB: u64 = 1 << 20;
51    // The reader coalesces byte-adjacent missing blocks into one request, so a
52    // large block buys little on a contiguous read — it only over-fetches the
53    // *scattered* faults that dominate a selective query (a dictionary chunk is
54    // 64 KiB; a 512 KiB block dragged in 8× the bytes). Keep the block near the
55    // chunk size; nearby-but-not-adjacent faults still merge when they share a
56    // block, and the bigger tier for huge files trades a little over-fetch for
57    // fewer round trips on the biggest scans.
58    let mult: u64 = if len > 100 * MB {
59        2 // 128 KiB
60    } else {
61        1 // 64 KiB
62    };
63    mult * DEFAULT_BLOCK
64}
65
66/// What a cached block costs against the cap: its allocation's real size
67/// (`Arc` header included, rounded to the allocator's class), not its length —
68/// a 128 KiB block occupies 160 KiB under jemalloc.
69fn charge(data: &Arc<[u8]>) -> u64 {
70    crate::chunk_cache::alloc_footprint(data.len() as u64 + 16)
71}
72
73/// One resident block: its bytes plus the last-touch stamp eviction orders by.
74struct CacheEntry {
75    data: Arc<[u8]>,
76    stamp: u64,
77}
78
79/// The cache state behind one mutex: resident blocks, their total byte size,
80/// and the monotonic access counter that makes eviction least-recently-used.
81struct CacheState {
82    map: HashMap<u64, CacheEntry>,
83    used: u64,
84    tick: u64,
85    /// Blocks a reader is fetching right now: a concurrent reader that wants
86    /// one waits for it ([`BlockCacheReader::landed`]) instead of fetching the
87    /// same bytes a second time.
88    in_flight: HashSet<u64>,
89}
90
91pub struct BlockCacheReader<R> {
92    inner: R,
93    block: u64,
94    len: u64,
95    cap: u64,
96    cache: Mutex<CacheState>,
97    /// Signalled whenever a fetch lands (or fails) and clears its in-flight
98    /// marks.
99    landed: Condvar,
100}
101
102impl<R: RangeReader> BlockCacheReader<R> {
103    /// Wrap `inner`, fetching `block`-aligned blocks (clamped to ≥ 4 KiB) and
104    /// keeping at most [`DEFAULT_CACHE_CAP`] bytes of them resident.
105    pub fn new(inner: R, block: u64) -> Self {
106        let len = inner.len();
107        Self {
108            inner,
109            block: block.max(4096),
110            len,
111            cap: DEFAULT_CACHE_CAP,
112            cache: Mutex::new(CacheState {
113                map: HashMap::new(),
114                used: 0,
115                tick: 0,
116                in_flight: HashSet::new(),
117            }),
118            landed: Condvar::new(),
119        }
120    }
121
122    /// Override the resident-byte cap. The cap is enforced *between* reads: a
123    /// single read spanning more than `cap` bytes of blocks is still served
124    /// exactly (its blocks are resident while it assembles) and the cache is
125    /// trimmed back under the cap right after. `u64::MAX` disables eviction.
126    pub fn with_cache_cap(mut self, cap: u64) -> Self {
127        self.cap = cap;
128        self
129    }
130
131    /// Bytes currently resident in the cache (for stats and tests).
132    pub fn cached_bytes(&self) -> u64 {
133        self.cache.lock().unwrap().used
134    }
135
136    /// Does the inner reader already hold `[offset, offset+len)` in memory?
137    fn held(&self, offset: u64, len: u64) -> bool {
138        offset
139            .checked_add(len)
140            .is_some_and(|e| e <= self.inner.resident_prefix())
141    }
142
143    fn bounds(&self, offset: u64, len: u64) -> std::io::Result<()> {
144        if offset.checked_add(len).is_none_or(|e| e > self.len) {
145            // Name the numbers: this fires when a read the file's own layout
146            // demands overruns the length the transport reported, and the two
147            // disagreeing values are the whole diagnosis (issue #95: a host
148            // advertised its gzip size, 58 MB, for a 71 MB file).
149            return Err(std::io::Error::new(
150                std::io::ErrorKind::UnexpectedEof,
151                format!(
152                    "range out of bounds: read {offset}+{len} exceeds the reported resource length {} — \
153                     the file's layout expects more bytes than the length probe found \
154                     (a host serving a compressed Content-Length can cause this)",
155                    self.len
156                ),
157            ));
158        }
159        Ok(())
160    }
161
162    /// Fetch and cache every block index in `want` that isn't resident, issuing
163    /// the missing ones as coalesced spans through `read_many`. Already-resident
164    /// wanted blocks get their recency stamp refreshed.
165    fn ensure(&self, want: &BTreeSet<u64>) -> std::io::Result<()> {
166        // Resident blocks are touched; blocks another reader is fetching are
167        // waited for, not fetched again (a parallel open walks two containers
168        // at once and both often want the next block); the rest are claimed.
169        let (missing, others): (Vec<u64>, Vec<u64>) = {
170            let mut st = self.cache.lock().unwrap();
171            st.tick += 1;
172            let tick = st.tick;
173            let mut missing = Vec::new();
174            let mut others = Vec::new();
175            for &b in want {
176                if let Some(e) = st.map.get_mut(&b) {
177                    e.stamp = tick;
178                } else if st.in_flight.contains(&b) {
179                    others.push(b);
180                } else {
181                    missing.push(b);
182                }
183            }
184            for &b in &missing {
185                st.in_flight.insert(b);
186            }
187            (missing, others)
188        };
189        let fetched = self.fetch_claimed(&missing);
190        if !others.is_empty() {
191            let mut st = self.cache.lock().unwrap();
192            while others.iter().any(|b| st.in_flight.contains(b)) {
193                st = self.landed.wait(st).unwrap();
194            }
195            // A block the other reader failed to fetch is read directly by
196            // `assemble`: correctness never depends on residency.
197        }
198        fetched
199    }
200
201    /// Fetch the blocks this reader claimed in [`ensure`](Self::ensure), cache
202    /// them, and clear their in-flight marks whatever the outcome.
203    fn fetch_claimed(&self, missing: &[u64]) -> std::io::Result<()> {
204        if missing.is_empty() {
205            return Ok(());
206        }
207        let r = self.fetch_missing(missing);
208        let mut st = self.cache.lock().unwrap();
209        for b in missing {
210            st.in_flight.remove(b);
211        }
212        drop(st);
213        self.landed.notify_all();
214        r
215    }
216
217    fn fetch_missing(&self, missing: &[u64]) -> std::io::Result<()> {
218        // Coalesce consecutive block indices into one span each.
219        let mut spans: Vec<(u64, u64)> = Vec::new();
220        let mut runs: Vec<(u64, u64)> = Vec::new();
221        let mut i = 0;
222        while i < missing.len() {
223            let first = missing[i];
224            let mut last = first;
225            let mut j = i + 1;
226            while j < missing.len() && missing[j] == last + 1 {
227                last = missing[j];
228                j += 1;
229            }
230            let off = first * self.block;
231            let end = ((last + 1) * self.block).min(self.len);
232            spans.push((off, end - off));
233            runs.push((first, last));
234            i = j;
235        }
236        let blobs = self.inner.read_many(&spans)?;
237        if blobs.len() != spans.len() {
238            return Err(std::io::Error::other("block fetch returned wrong count"));
239        }
240        // A blob of any other length than its span is not that span: caching
241        // a short one would hand the parsers a silently truncated block.
242        if let Some(((o, l), b)) = spans
243            .iter()
244            .zip(&blobs)
245            .find(|((_, l), b)| b.len() as u64 != *l)
246        {
247            return Err(std::io::Error::new(
248                std::io::ErrorKind::UnexpectedEof,
249                format!("block fetch at {o} returned {} bytes, not {l}", b.len()),
250            ));
251        }
252        let mut st = self.cache.lock().unwrap();
253        st.tick += 1;
254        let tick = st.tick;
255        for (&(first, last), blob) in runs.iter().zip(blobs.into_iter()) {
256            let span_start = first * self.block;
257            for b in first..=last {
258                let lo = (b * self.block - span_start) as usize;
259                let hi = ((((b + 1) * self.block).min(self.len)) - span_start) as usize;
260                let hi = hi.min(blob.len());
261                let lo = lo.min(hi);
262                let data: Arc<[u8]> = Arc::from(&blob[lo..hi]);
263                st.used += charge(&data);
264                if let Some(old) = st.map.insert(b, CacheEntry { data, stamp: tick }) {
265                    st.used -= charge(&old.data); // concurrent double-fetch
266                }
267            }
268        }
269        Ok(())
270    }
271
272    /// Evict least-recently-touched blocks until the resident total fits the
273    /// cap. Called after a read has assembled its bytes, so nothing in flight
274    /// depends on what gets dropped.
275    ///
276    /// Once over the cap it evicts down to 7/8 of it, not just under it:
277    /// finding the least-recent blocks sorts the whole map, and a full cache
278    /// (every read of a long export) used to pay that sort on every single
279    /// read. The slack amortizes one sort over ~1/8 of the cache's turnover
280    /// (only once the cache holds 32+ blocks, so a tiny cache stays exact LRU).
281    fn trim(&self) {
282        let mut st = self.cache.lock().unwrap();
283        if st.used <= self.cap {
284            return;
285        }
286        let slack = if self.cap / 8 >= 4 * self.block {
287            self.cap / 8
288        } else {
289            0
290        };
291        let target = self.cap - slack;
292        let mut order: Vec<(u64, u64)> = st.map.iter().map(|(&b, e)| (e.stamp, b)).collect();
293        order.sort_unstable();
294        for (_, b) in order {
295            if st.used <= target {
296                break;
297            }
298            if let Some(e) = st.map.remove(&b) {
299                st.used -= charge(&e.data);
300            }
301        }
302    }
303
304    /// Copy `[offset, offset+len)` out of the cache. The needed blocks are
305    /// cloned out under one short lock; a block missing here (evicted by a
306    /// concurrent reader's trim between `ensure` and this call) is re-read
307    /// directly from the inner reader — correctness never depends on residency.
308    fn assemble(&self, offset: u64, len: u64) -> std::io::Result<Vec<u8>> {
309        let first = offset / self.block;
310        let last = (offset + len - 1) / self.block;
311        let resident: Vec<Option<Arc<[u8]>>> = {
312            let st = self.cache.lock().unwrap();
313            (first..=last)
314                .map(|b| st.map.get(&b).map(|e| e.data.clone()))
315                .collect()
316        };
317        let mut out = Vec::with_capacity(len as usize);
318        let mut pos = offset;
319        let end = offset + len;
320        while pos < end {
321            let b = pos / self.block;
322            let block_start = b * self.block;
323            let within = (pos - block_start) as usize;
324            let fetched: Vec<u8>;
325            let blk: &[u8] = match &resident[(b - first) as usize] {
326                Some(data) => data,
327                None => {
328                    let blen = ((b + 1) * self.block).min(self.len) - block_start;
329                    fetched = self.inner.read_at(block_start, blen)?;
330                    &fetched
331                }
332            };
333            let take = ((end - pos) as usize).min(blk.len().saturating_sub(within));
334            if take == 0 {
335                break;
336            }
337            out.extend_from_slice(&blk[within..within + take]);
338            pos += take as u64;
339        }
340        if out.len() as u64 != len {
341            return Err(std::io::Error::new(
342                std::io::ErrorKind::UnexpectedEof,
343                format!("short read: {} of {len} bytes at {offset}", out.len()),
344            ));
345        }
346        Ok(out)
347    }
348}
349
350impl<R: RangeReader> RangeReader for BlockCacheReader<R> {
351    fn len(&self) -> u64 {
352        self.len
353    }
354
355    fn concurrency(&self) -> usize {
356        self.inner.concurrency()
357    }
358
359    fn resident_prefix(&self) -> u64 {
360        self.inner.resident_prefix()
361    }
362
363    fn read_at(&self, offset: u64, len: u64) -> std::io::Result<Vec<u8>> {
364        if len == 0 {
365            return Ok(Vec::new());
366        }
367        self.bounds(offset, len)?;
368        // Bytes the inner reader already holds (an HTTP open's first read) are
369        // no fetch: asking it for the block-aligned span around them would
370        // re-read them, and the rest of the block, in a request of its own.
371        if self.held(offset, len) {
372            return self.inner.read_at(offset, len);
373        }
374        let want: BTreeSet<u64> = (offset / self.block..=(offset + len - 1) / self.block).collect();
375        self.ensure(&want)?;
376        let out = self.assemble(offset, len)?;
377        self.trim();
378        Ok(out)
379    }
380
381    fn read_many(&self, ranges: &[(u64, u64)]) -> std::io::Result<Vec<Vec<u8>>> {
382        let mut want = BTreeSet::new();
383        for &(o, l) in ranges {
384            if l == 0 {
385                continue;
386            }
387            self.bounds(o, l)?;
388            if self.held(o, l) {
389                continue;
390            }
391            for b in o / self.block..=(o + l - 1) / self.block {
392                want.insert(b);
393            }
394        }
395        self.ensure(&want)?;
396        let out = ranges
397            .iter()
398            .map(|&(o, l)| {
399                if l == 0 {
400                    Ok(Vec::new())
401                } else if self.held(o, l) {
402                    self.inner.read_at(o, l)
403                } else {
404                    self.assemble(o, l)
405                }
406            })
407            .collect::<std::io::Result<Vec<_>>>()?;
408        self.trim();
409        Ok(out)
410    }
411}
412
413#[cfg(test)]
414mod tests {
415    use super::*;
416    use crate::reader::PrefixReader;
417    use crate::reader::{CountingReader, SliceReader};
418
419    /// An HTTP open already holds the file's first bytes: a read inside them
420    /// is served as it is, not by fetching the block-aligned span around it.
421    #[test]
422    fn reads_inside_the_inner_prefix_fetch_no_block() {
423        let data: Vec<u8> = (0..100_000u32).map(|i| i as u8).collect();
424        let prefix: Arc<[u8]> = Arc::from(&data[..4096]);
425        let counting = Arc::new(CountingReader::new(SliceReader::new(&data)));
426        let r = BlockCacheReader::new(PrefixReader::new(counting.clone(), prefix), 16 * 1024);
427        assert_eq!(r.read_at(0, 4096).unwrap(), data[..4096]);
428        assert_eq!(r.read_many(&[(10, 100)]).unwrap()[0], data[10..110]);
429        assert_eq!(counting.requests(), 0);
430        // Past the prefix the block is fetched whole, as before.
431        assert_eq!(r.read_at(5000, 10).unwrap(), data[5000..5010]);
432        assert_eq!(counting.requests(), 1);
433        assert_eq!(counting.bytes_read(), 16 * 1024);
434    }
435
436    #[test]
437    fn caches_blocks_and_serves_exact_bytes() {
438        let data: Vec<u8> = (0..100_000u32).map(|i| i as u8).collect();
439        let counting = Arc::new(CountingReader::new(SliceReader::new(&data)));
440        let r = BlockCacheReader::new(counting.clone(), 16 * 1024);
441
442        // many small scattered reads inside the first few blocks
443        for off in [10u64, 200, 5000, 16_500, 17_000, 33_000, 33_100] {
444            assert_eq!(
445                r.read_at(off, 32).unwrap(),
446                data[off as usize..off as usize + 32]
447            );
448        }
449        // exact bytes returned, but the 7 logical reads touched only 3 blocks
450        // (0,1,2) → at most 3 physical fetches, not 7.
451        assert!(
452            counting.requests() <= 3,
453            "physical fetches: {}",
454            counting.requests()
455        );
456
457        // a repeat read is fully cached → no new fetch
458        let before = counting.requests();
459        assert_eq!(r.read_at(200, 16).unwrap(), data[200..216]);
460        assert_eq!(counting.requests(), before);
461    }
462
463    #[test]
464    fn read_many_fetches_missing_blocks_once() {
465        let data: Vec<u8> = (0..200_000u32).map(|i| (i * 7) as u8).collect();
466        let counting = Arc::new(CountingReader::new(SliceReader::new(&data)));
467        let r = BlockCacheReader::new(counting.clone(), 32 * 1024);
468        let ranges = [(0u64, 8u64), (40_000, 16), (40_050, 16), (130_000, 64)];
469        let out = r.read_many(&ranges).unwrap();
470        for (&(o, l), got) in ranges.iter().zip(&out) {
471            assert_eq!(got, &data[o as usize..(o + l) as usize]);
472        }
473        // 4 ranges over blocks {0, 1, 4} → ≤ 3 physical fetches.
474        assert!(
475            counting.requests() <= 3,
476            "physical: {}",
477            counting.requests()
478        );
479    }
480
481    /// A slow reader that counts its reads.
482    struct Slow(Vec<u8>, std::sync::atomic::AtomicUsize);
483    impl RangeReader for Slow {
484        fn len(&self) -> u64 {
485            self.0.len() as u64
486        }
487        fn read_at(&self, offset: u64, len: u64) -> std::io::Result<Vec<u8>> {
488            self.1.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
489            std::thread::sleep(std::time::Duration::from_millis(30));
490            Ok(self.0[offset as usize..(offset + len) as usize].to_vec())
491        }
492    }
493
494    /// Readers that want the same block at the same time fetch it once: the
495    /// others wait for it to land (a parallel open walks two containers at
496    /// once, and both used to fetch, and count, the next block).
497    #[test]
498    fn concurrent_readers_fetch_a_block_once() {
499        let r = BlockCacheReader::new(Slow(vec![3u8; 100_000], Default::default()), 4096);
500        std::thread::scope(|s| {
501            for _ in 0..6 {
502                s.spawn(|| assert_eq!(r.read_at(5000, 100).unwrap(), vec![3u8; 100]));
503            }
504        });
505        assert_eq!(r.inner.1.load(std::sync::atomic::Ordering::SeqCst), 1);
506    }
507
508    /// A reader that answers every range one byte short (audit fix 9).
509    struct Short(Vec<u8>);
510    impl RangeReader for Short {
511        fn len(&self) -> u64 {
512            self.0.len() as u64
513        }
514        fn read_at(&self, offset: u64, len: u64) -> std::io::Result<Vec<u8>> {
515            let end = (offset + len).saturating_sub(1) as usize;
516            Ok(self.0[offset as usize..end].to_vec())
517        }
518    }
519
520    /// A short blob from the inner reader is an error, never a short block
521    /// cached and handed out as if it were the range.
522    #[test]
523    fn a_short_blob_is_refused_not_cached() {
524        let r = BlockCacheReader::new(Short(vec![9u8; 10_000]), 4096);
525        let err = r.read_at(100, 50).unwrap_err();
526        assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof, "{err}");
527        assert!(r.read_many(&[(0, 10), (5000, 10)]).is_err());
528    }
529
530    #[test]
531    fn out_of_bounds_errors() {
532        let data = vec![0u8; 1000];
533        let r = BlockCacheReader::new(SliceReader::new(&data), 8192);
534        assert!(r.read_at(990, 20).is_err());
535    }
536
537    /// A sweep far wider than the cap must stay under the cap after every read
538    /// while still returning exact bytes — the unbounded-growth regression.
539    #[test]
540    fn eviction_caps_resident_bytes_and_keeps_reads_exact() {
541        let data: Vec<u8> = (0..1_000_000u32).map(|i| (i * 31) as u8).collect();
542        let counting = Arc::new(CountingReader::new(SliceReader::new(&data)));
543        // 64 KiB cap over 8 KiB blocks = at most 8 resident blocks.
544        let cap = 64 * 1024;
545        let r = BlockCacheReader::new(counting.clone(), 8192).with_cache_cap(cap);
546        for off in (0..1_000_000u64 - 64).step_by(37_777) {
547            assert_eq!(
548                r.read_at(off, 64).unwrap(),
549                data[off as usize..off as usize + 64]
550            );
551            assert!(
552                r.cached_bytes() <= cap,
553                "resident {} > cap {cap}",
554                r.cached_bytes()
555            );
556        }
557    }
558
559    /// Eviction is least-recently-used: re-touching a block protects it, the
560    /// stalest block goes first, and an evicted block re-fetches exactly once.
561    #[test]
562    fn eviction_is_lru() {
563        let data: Vec<u8> = (0..64 * 1024u32).map(|i| i as u8).collect();
564        let counting = Arc::new(CountingReader::new(SliceReader::new(&data)));
565        // Cap = exactly 2 blocks of 8 KiB (as charged).
566        let two = 2 * charge(&Arc::from(vec![0u8; 8192]));
567        let r = BlockCacheReader::new(counting.clone(), 8192).with_cache_cap(two);
568        let block = |i: u64| i * 8192;
569        r.read_at(block(0), 16).unwrap(); // cache {0}
570        r.read_at(block(1), 16).unwrap(); // cache {0,1}
571        r.read_at(block(0), 16).unwrap(); // touch 0 → 1 is now the LRU
572
573        let before = counting.requests();
574        r.read_at(block(2), 16).unwrap(); // fetches 2, evicts 1, keeps 0
575        assert_eq!(counting.requests(), before + 1);
576
577        let before = counting.requests();
578        r.read_at(block(0), 16).unwrap(); // still resident → no fetch
579        assert_eq!(
580            counting.requests(),
581            before,
582            "recently-touched block evicted"
583        );
584
585        let before = counting.requests();
586        r.read_at(block(1), 16).unwrap(); // was evicted → exactly one refetch
587        assert_eq!(counting.requests(), before + 1);
588    }
589
590    /// One read spanning more blocks than the cap allows must still return the
591    /// exact bytes (blocks are resident while the read assembles) and the cache
592    /// must be trimmed back under the cap immediately after.
593    #[test]
594    fn request_larger_than_cap_reads_exactly_then_trims() {
595        let data: Vec<u8> = (0..256 * 1024u32).map(|i| (i * 7) as u8).collect();
596        let cap = 16 * 1024;
597        let r = BlockCacheReader::new(SliceReader::new(&data), 8192).with_cache_cap(cap);
598        let (off, len) = (1000usize, 96 * 1024usize); // 6× the cap
599        let out = r.read_at(off as u64, len as u64).unwrap();
600        assert_eq!(out, &data[off..off + len]);
601        assert!(
602            r.cached_bytes() <= cap,
603            "resident {} > cap {cap} after the read",
604            r.cached_bytes()
605        );
606    }
607}