Skip to main content

aft_store/
cache.rs

1//! One byte-budgeted cache of verified segment blocks, shared by every open
2//! segment.
3//!
4//! Segments are read with positioned reads, never memory maps: a mapped file
5//! cannot be deleted on Windows, a file truncated under a mapping crashes the
6//! process on Unix, and mapped pages would escape AFT's memory accounting. The
7//! cache holds each block only after its checksum verified, so a cached block
8//! is always good bytes, and its size is the data layer's resident read memory.
9
10use std::collections::{BTreeMap, HashMap};
11use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
12use std::sync::{Arc, Mutex, RwLock};
13
14use crate::segment::BLOCK_LEN;
15
16/// A process-wide id for one open segment file. Blocks are keyed by it, so a
17/// closed and reopened segment never sees another file's blocks.
18#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
19pub(crate) struct FileToken(u64);
20
21impl FileToken {
22    pub(crate) fn next() -> Self {
23        static NEXT: AtomicU64 = AtomicU64::new(1);
24        Self(NEXT.fetch_add(1, Ordering::Relaxed))
25    }
26}
27
28#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
29pub(crate) struct BlockKey {
30    pub(crate) file: FileToken,
31    pub(crate) section: u32,
32    pub(crate) block: u64,
33}
34
35/// Counters for the memory census and health reports.
36#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
37pub struct CacheStats {
38    /// The configured budget in bytes.
39    pub budget_bytes: usize,
40    /// Bytes of block data held right now.
41    pub resident_bytes: usize,
42    /// Blocks held right now.
43    pub blocks: usize,
44    pub hits: u64,
45    pub misses: u64,
46    pub evictions: u64,
47}
48
49/// Verified segment blocks, evicted least recently used first once their
50/// total size passes the budget.
51///
52/// A build's resolver threads read the same segments at once, and one lock
53/// for every hit made each hit wait for all the others (12 threads: 4.9 us
54/// per hit, against 0.1 us for one thread). So the cache is split into
55/// shards by block, each with its own lock, its own share of the budget and
56/// its own use order, and a hit takes only its shard's read lock: it stamps
57/// the block's last use atomically and leaves the use order alone. The
58/// order catches up at eviction, which moves a block it finds used since it
59/// was listed instead of evicting it. Eviction is therefore least recently
60/// used within a shard; a small cache keeps one shard, so its order is
61/// exact.
62#[derive(Debug)]
63pub struct BlockCache {
64    budget: AtomicUsize,
65    resize: Mutex<()>,
66    shards: Box<[Shard]>,
67}
68
69/// Aligned to a cache line (128 bytes covers every target AFT builds for),
70/// so one shard's lock traffic never moves its neighbour's line.
71#[derive(Debug)]
72#[repr(align(128))]
73struct Shard {
74    budget: AtomicUsize,
75    /// Stamps of use, increasing; every touch and insert takes a new one,
76    /// so no two blocks share a stamp.
77    clock: AtomicU64,
78    hits: AtomicU64,
79    misses: AtomicU64,
80    state: RwLock<State>,
81}
82
83/// The most shards a cache splits into.
84const MAX_SHARDS: usize = 32;
85/// The fewest blocks a shard's budget holds: below that, a shard would
86/// evict blocks a read is still using.
87const MIN_SHARD_BLOCKS: usize = 64;
88
89#[derive(Debug, Default)]
90struct State {
91    entries: HashMap<BlockKey, Entry>,
92    /// Entries by the stamp they were listed under, the first the next
93    /// candidate for eviction. A hit does not move its entry here; eviction
94    /// moves an entry whose last use is newer than its listing.
95    by_use: BTreeMap<u64, BlockKey>,
96    resident: usize,
97    evictions: u64,
98}
99
100#[derive(Debug)]
101struct Entry {
102    bytes: Arc<[u8]>,
103    /// The stamp of the entry's last use, written by hits under the read
104    /// lock.
105    used_at: AtomicU64,
106    /// The stamp `by_use` lists the entry under.
107    listed_at: u64,
108}
109
110impl BlockCache {
111    /// A cache holding at most `budget_bytes` of block data.
112    ///
113    /// # Panics
114    ///
115    /// If the budget is smaller than one block: such a cache could not hold
116    /// the block a read is waiting for.
117    #[must_use]
118    pub fn new(budget_bytes: usize) -> Self {
119        assert!(
120            budget_bytes >= BLOCK_LEN,
121            "block cache budget {budget_bytes} is below one block ({BLOCK_LEN} bytes)"
122        );
123        let count = (budget_bytes / (MIN_SHARD_BLOCKS * BLOCK_LEN)).clamp(1, MAX_SHARDS);
124        // Every shard's budget is at least one block, and together they are
125        // exactly the cache's budget.
126        let share = budget_bytes / count;
127        let shards = (0..count)
128            .map(|index| Shard {
129                budget: AtomicUsize::new(if index == 0 {
130                    budget_bytes - share * (count - 1)
131                } else {
132                    share
133                }),
134                clock: AtomicU64::new(0),
135                hits: AtomicU64::new(0),
136                misses: AtomicU64::new(0),
137                state: RwLock::default(),
138            })
139            .collect();
140        Self {
141            budget: AtomicUsize::new(budget_bytes),
142            resize: Mutex::new(()),
143            shards,
144        }
145    }
146
147    /// Resize without invalidating blocks readers already hold. Each shard
148    /// keeps its identity; a shrink releases at most 64 entries per lock hold.
149    /// The budget must still allow at least one block per existing shard.
150    pub fn set_budget(&self, bytes: usize) {
151        assert!(bytes >= self.shards.len() * BLOCK_LEN);
152        let _resize = self
153            .resize
154            .lock()
155            .expect("block cache resize lock poisoned");
156        if self.budget.load(Ordering::Acquire) == bytes {
157            return;
158        }
159        let share = bytes / self.shards.len();
160        for (index, shard) in self.shards.iter().enumerate() {
161            let budget = if index == 0 {
162                bytes - share * (self.shards.len() - 1)
163            } else {
164                share
165            };
166            shard.budget.store(budget, Ordering::Release);
167            loop {
168                let mut state = shard.write();
169                for _ in 0..64 {
170                    if state.resident <= budget {
171                        break;
172                    }
173                    // A shrink need not preserve recency: removing one entry
174                    // directly bounds work even while readers stamp hot blocks.
175                    let Some((_, key)) = state.by_use.first_key_value() else {
176                        break;
177                    };
178                    let key = *key;
179                    state.remove(key);
180                    state.evictions += 1;
181                }
182                let done = state.resident <= budget;
183                drop(state);
184                if done {
185                    break;
186                }
187                std::thread::yield_now();
188            }
189        }
190        self.budget.store(bytes, Ordering::Release);
191    }
192
193    #[must_use]
194    pub fn stats(&self) -> CacheStats {
195        let mut stats = CacheStats {
196            budget_bytes: self.budget.load(Ordering::Acquire),
197            ..CacheStats::default()
198        };
199        for shard in &*self.shards {
200            let state = shard.read();
201            stats.resident_bytes += state.resident;
202            stats.blocks += state.entries.len();
203            stats.hits += shard.hits.load(Ordering::Relaxed);
204            stats.misses += shard.misses.load(Ordering::Relaxed);
205            stats.evictions += state.evictions;
206        }
207        stats
208    }
209
210    /// The cached block for `key`, or the block `load` returns, which is then
211    /// cached. `load` runs without the cache lock held, so a slow read never
212    /// blocks other readers; two threads missing the same block may both load
213    /// it, and the second keeps the first one's copy.
214    pub(crate) fn get_or_load<E>(
215        &self,
216        key: BlockKey,
217        load: impl FnOnce() -> Result<Arc<[u8]>, E>,
218    ) -> Result<Arc<[u8]>, E> {
219        let shard = self.shard(key);
220        if let Some(bytes) = shard.read().touch(key, &shard.clock) {
221            shard.hits.fetch_add(1, Ordering::Relaxed);
222            return Ok(bytes);
223        }
224        shard.misses.fetch_add(1, Ordering::Relaxed);
225        let loaded = load()?;
226        let mut state = shard.write();
227        if let Some(bytes) = state.touch(key, &shard.clock) {
228            return Ok(bytes);
229        }
230        state.insert(key, Arc::clone(&loaded), &shard.clock);
231        // A resize may have lowered the budget before its bounded eviction
232        // pass reaches this shard. Leave the remaining shrink to that pass.
233        for _ in 0..64 {
234            if state.resident <= shard.budget.load(Ordering::Acquire) {
235                break;
236            }
237            state.evict_oldest();
238        }
239        Ok(loaded)
240    }
241
242    /// Drops every block of one file, so a closed segment's memory is
243    /// released at once rather than waiting for eviction.
244    pub(crate) fn forget(&self, file: FileToken) {
245        for shard in &*self.shards {
246            let mut state = shard.write();
247            let doomed: Vec<BlockKey> = state
248                .entries
249                .keys()
250                .filter(|key| key.file == file)
251                .copied()
252                .collect();
253            for key in doomed {
254                state.remove(key);
255            }
256        }
257    }
258
259    /// The bytes the cache holds in memory, measured as [`crate::heap`]
260    /// describes: every cached block in its shared allocation, and the two
261    /// tables that find a block and order blocks by use. `None` while
262    /// another thread holds the cache's lock: the memory census never waits
263    /// for it.
264    #[must_use]
265    pub fn memory_bytes(&self) -> Option<usize> {
266        let mut seen = crate::heap::Seen::new();
267        let mut total = std::mem::size_of_val(&*self.shards);
268        for shard in &*self.shards {
269            let state = match shard.state.try_read() {
270                Ok(state) => state,
271                Err(std::sync::TryLockError::Poisoned(poisoned)) => poisoned.into_inner(),
272                Err(std::sync::TryLockError::WouldBlock) => return None,
273            };
274            total += crate::heap::HeapBytes::heap_bytes(&state.entries, &mut seen)
275                + crate::heap::HeapBytes::heap_bytes(&state.by_use, &mut seen);
276        }
277        Some(total)
278    }
279
280    /// The shard holding `key`: a mix of the key's parts, so neighbouring
281    /// blocks of one section spread over the shards.
282    fn shard(&self, key: BlockKey) -> &Shard {
283        let mixed = key.file.0.wrapping_mul(0x9E37_79B9_7F4A_7C15)
284            ^ u64::from(key.section).wrapping_mul(0xC2B2_AE3D_27D4_EB4F)
285            ^ key.block.wrapping_mul(0x1656_67B1_9E37_79F9);
286        let index = usize::try_from((mixed >> 32) % self.shards.len() as u64)
287            .expect("a shard index fits in usize");
288        &self.shards[index]
289    }
290}
291
292impl Shard {
293    fn read(&self) -> std::sync::RwLockReadGuard<'_, State> {
294        self.state.read().expect("block cache lock poisoned")
295    }
296
297    fn write(&self) -> std::sync::RwLockWriteGuard<'_, State> {
298        self.state.write().expect("block cache lock poisoned")
299    }
300}
301
302impl State {
303    /// The cached block for `key`, stamped as used now. Needs only the read
304    /// lock.
305    fn touch(&self, key: BlockKey, clock: &AtomicU64) -> Option<Arc<[u8]>> {
306        let entry = self.entries.get(&key)?;
307        let now = clock.fetch_add(1, Ordering::Relaxed) + 1;
308        entry.used_at.fetch_max(now, Ordering::Relaxed);
309        Some(Arc::clone(&entry.bytes))
310    }
311
312    fn insert(&mut self, key: BlockKey, bytes: Arc<[u8]>, clock: &AtomicU64) {
313        let now = clock.fetch_add(1, Ordering::Relaxed) + 1;
314        self.resident += bytes.len();
315        self.by_use.insert(now, key);
316        self.entries.insert(
317            key,
318            Entry {
319                bytes,
320                used_at: AtomicU64::new(now),
321                listed_at: now,
322            },
323        );
324    }
325
326    /// Evicts the least recently used block. A block used since it was
327    /// listed is listed again under its last use instead, until the first
328    /// listed block is one nothing used since.
329    fn evict_oldest(&mut self) {
330        while let Some((listed, key)) = self.by_use.pop_first() {
331            let Some(entry) = self.entries.get_mut(&key) else {
332                continue;
333            };
334            let used = entry.used_at.load(Ordering::Relaxed);
335            if used > listed {
336                entry.listed_at = used;
337                self.by_use.insert(used, key);
338                continue;
339            }
340            if let Some(entry) = self.entries.remove(&key) {
341                self.resident -= entry.bytes.len();
342                self.evictions += 1;
343            }
344            return;
345        }
346    }
347
348    fn remove(&mut self, key: BlockKey) {
349        if let Some(entry) = self.entries.remove(&key) {
350            self.by_use.remove(&entry.listed_at);
351            self.resident -= entry.bytes.len();
352        }
353    }
354}
355
356crate::heap_bytes_none!(FileToken, BlockKey);
357impl crate::heap::HeapBytes for Entry {
358    fn heap_bytes(&self, seen: &mut crate::heap::Seen) -> usize {
359        // The stamps are plain integers; only the block owns heap memory.
360        let Self {
361            bytes,
362            used_at: _,
363            listed_at: _,
364        } = self;
365        crate::heap::HeapBytes::heap_bytes(bytes, seen)
366    }
367}
368
369#[cfg(test)]
370mod tests {
371    use super::*;
372
373    fn key(file: FileToken, block: u64) -> BlockKey {
374        BlockKey {
375            file,
376            section: 0,
377            block,
378        }
379    }
380
381    fn block(fill: u8) -> Arc<[u8]> {
382        Arc::from(vec![fill; BLOCK_LEN])
383    }
384
385    #[test]
386    fn memory_counts_every_block_and_the_tables_that_find_them() {
387        let cache = BlockCache::new(4 * BLOCK_LEN);
388        // An empty cache holds only its shards.
389        let shards = std::mem::size_of_val(&*cache.shards);
390        assert_eq!(cache.memory_bytes(), Some(shards));
391        let file = FileToken::next();
392        for index in 0..3 {
393            cache
394                .get_or_load(key(file, index), || Ok::<_, ()>(block(1)))
395                .unwrap();
396        }
397        let measured = cache.memory_bytes().unwrap();
398        let blocks = shards + 3 * (crate::heap::COUNTS + BLOCK_LEN);
399        assert!(measured > blocks, "{measured} <= {blocks}");
400        assert!(
401            measured < blocks + 2048,
402            "tables of three entries: {measured}"
403        );
404        let _held = cache.shards[0].write();
405        assert_eq!(
406            cache.memory_bytes(),
407            None,
408            "a held lock is never waited for"
409        );
410    }
411
412    #[test]
413    fn hits_skip_the_loader_and_misses_cache_the_result() {
414        let cache = BlockCache::new(4 * BLOCK_LEN);
415        let file = FileToken::next();
416        let first = cache
417            .get_or_load(key(file, 0), || Ok::<_, ()>(block(7)))
418            .unwrap();
419        let again = cache
420            .get_or_load(key(file, 0), || -> Result<Arc<[u8]>, ()> {
421                panic!("a cached block must not be loaded again")
422            })
423            .unwrap();
424        assert!(Arc::ptr_eq(&first, &again));
425        let stats = cache.stats();
426        assert_eq!((stats.hits, stats.misses, stats.blocks), (1, 1, 1));
427        assert_eq!(stats.resident_bytes, BLOCK_LEN);
428    }
429
430    #[test]
431    fn a_failed_load_caches_nothing() {
432        let cache = BlockCache::new(BLOCK_LEN);
433        let file = FileToken::next();
434        assert_eq!(cache.get_or_load(key(file, 0), || Err("torn")), Err("torn"));
435        assert_eq!(cache.stats().blocks, 0);
436        assert_eq!(cache.stats().resident_bytes, 0);
437    }
438
439    #[test]
440    fn the_least_recently_used_block_is_evicted_first() {
441        let cache = BlockCache::new(2 * BLOCK_LEN);
442        let file = FileToken::next();
443        for index in 0..2 {
444            cache
445                .get_or_load(key(file, index), || Ok::<_, ()>(block(1)))
446                .unwrap();
447        }
448        // Block 0 is used again, so block 1 is now the oldest.
449        cache
450            .get_or_load(key(file, 0), || -> Result<Arc<[u8]>, ()> {
451                panic!("block 0 is cached")
452            })
453            .unwrap();
454        cache
455            .get_or_load(key(file, 2), || Ok::<_, ()>(block(2)))
456            .unwrap();
457        let stats = cache.stats();
458        assert_eq!((stats.blocks, stats.evictions), (2, 1));
459        assert!(stats.resident_bytes <= stats.budget_bytes);
460        let mut reloaded = false;
461        cache
462            .get_or_load(key(file, 1), || {
463                reloaded = true;
464                Ok::<_, ()>(block(1))
465            })
466            .unwrap();
467        assert!(
468            reloaded,
469            "block 1 was the oldest and should have been evicted"
470        );
471    }
472
473    #[test]
474    fn forgetting_a_file_releases_only_its_blocks() {
475        let cache = BlockCache::new(8 * BLOCK_LEN);
476        let (closed, open) = (FileToken::next(), FileToken::next());
477        for index in 0..3 {
478            cache
479                .get_or_load(key(closed, index), || Ok::<_, ()>(block(1)))
480                .unwrap();
481        }
482        cache
483            .get_or_load(key(open, 0), || Ok::<_, ()>(block(2)))
484            .unwrap();
485        cache.forget(closed);
486        let stats = cache.stats();
487        assert_eq!(stats.blocks, 1);
488        assert_eq!(stats.resident_bytes, BLOCK_LEN);
489    }
490
491    #[test]
492    fn a_sharded_cache_keeps_its_whole_budget_and_releases_a_file_from_every_shard() {
493        let cache = BlockCache::new(4 * MIN_SHARD_BLOCKS * BLOCK_LEN);
494        assert_eq!(cache.shards.len(), 4);
495        assert_eq!(
496            cache
497                .shards
498                .iter()
499                .map(|shard| shard.budget.load(Ordering::Acquire))
500                .sum::<usize>(),
501            cache.budget.load(Ordering::Acquire)
502        );
503        let (closed, open) = (FileToken::next(), FileToken::next());
504        let loads = 6 * MIN_SHARD_BLOCKS as u64;
505        for index in 0..loads {
506            cache
507                .get_or_load(key(open, index), || Ok::<_, ()>(block(1)))
508                .unwrap();
509            let stats = cache.stats();
510            assert!(
511                stats.resident_bytes <= stats.budget_bytes,
512                "{stats:?} after {index}"
513            );
514        }
515        let stats = cache.stats();
516        assert_eq!(stats.misses, loads);
517        assert!(stats.evictions > 0, "{stats:?}");
518        // Each shard is full, so the blocks held are close to the budget.
519        assert!(stats.blocks > 3 * MIN_SHARD_BLOCKS, "{stats:?}");
520        // The block loaded last is still held.
521        cache
522            .get_or_load(key(open, loads - 1), || -> Result<Arc<[u8]>, ()> {
523                panic!("the newest block is cached")
524            })
525            .unwrap();
526
527        for index in 0..32 {
528            cache
529                .get_or_load(key(closed, index), || Ok::<_, ()>(block(2)))
530                .unwrap();
531        }
532        let before = cache.stats().blocks;
533        cache.forget(closed);
534        let after = cache.stats();
535        assert_eq!(after.blocks, before - 32, "{after:?}");
536        for shard in &*cache.shards {
537            assert!(shard.read().entries.keys().all(|key| key.file != closed));
538        }
539    }
540
541    /// Hits under read locks while other threads load and evict: every read
542    /// gets its own block's bytes, and the budget holds throughout.
543    #[test]
544    fn concurrent_loads_and_hits_return_their_own_blocks_within_the_budget() {
545        let cache = Arc::new(BlockCache::new(2 * MIN_SHARD_BLOCKS * BLOCK_LEN));
546        let file = FileToken::next();
547        // Three times what the cache holds, so loads keep evicting.
548        let blocks = 6 * MIN_SHARD_BLOCKS as u64;
549        std::thread::scope(|scope| {
550            for thread in 0..8u64 {
551                let cache = Arc::clone(&cache);
552                scope.spawn(move || {
553                    let mut index = thread * 31;
554                    for _ in 0..4_000 {
555                        index = (index + 97) % blocks;
556                        let fill = (index % 251) as u8;
557                        let bytes = cache
558                            .get_or_load(key(file, index), || Ok::<_, ()>(block(fill)))
559                            .unwrap();
560                        assert!(bytes.iter().all(|byte| *byte == fill), "block {index}");
561                    }
562                });
563            }
564        });
565        let stats = cache.stats();
566        assert!(stats.resident_bytes <= stats.budget_bytes, "{stats:?}");
567        assert_eq!(stats.resident_bytes, stats.blocks * BLOCK_LEN, "{stats:?}");
568        assert!(stats.evictions > 0 && stats.hits > 0, "{stats:?}");
569        for shard in &*cache.shards {
570            let state = shard.read();
571            // Every entry is listed exactly once, under its own stamp.
572            assert_eq!(state.by_use.len(), state.entries.len());
573            for (listed, key) in &state.by_use {
574                assert_eq!(state.entries[key].listed_at, *listed);
575            }
576        }
577    }
578
579    #[test]
580    fn cache_shrink_while_readers_are_active_preserves_their_blocks() {
581        let cache = Arc::new(BlockCache::new(4 * MIN_SHARD_BLOCKS * BLOCK_LEN));
582        let file = FileToken::next();
583        for index in 0..256 {
584            cache
585                .get_or_load(key(file, index), || Ok::<_, ()>(block(index as u8)))
586                .unwrap();
587        }
588        let held = cache
589            .get_or_load(key(file, 0), || Ok::<_, ()>(block(0)))
590            .unwrap();
591        let started = std::sync::Barrier::new(5);
592        let finish = std::sync::atomic::AtomicBool::new(false);
593        std::thread::scope(|scope| {
594            for reader in 0..4 {
595                let cache = &cache;
596                let started = &started;
597                let finish = &finish;
598                scope.spawn(move || {
599                    started.wait();
600                    let mut index = reader;
601                    while !finish.load(Ordering::Acquire) {
602                        index = (index + 7) % 256;
603                        let bytes = cache
604                            .get_or_load(key(file, index), || Ok::<_, ()>(block(index as u8)))
605                            .unwrap();
606                        assert!(bytes.iter().all(|byte| *byte == index as u8));
607                    }
608                });
609            }
610            started.wait();
611            cache.set_budget(4 * BLOCK_LEN);
612            finish.store(true, Ordering::Release);
613        });
614        assert!(held.iter().all(|byte| *byte == 0));
615        let stats = cache.stats();
616        assert_eq!(stats.budget_bytes, 4 * BLOCK_LEN);
617        assert!(stats.resident_bytes <= stats.budget_bytes, "{stats:?}");
618        assert!(stats.evictions > 0);
619        cache.set_budget(8 * BLOCK_LEN);
620        assert_eq!(cache.stats().budget_bytes, 8 * BLOCK_LEN);
621    }
622
623    #[test]
624    fn a_small_cache_keeps_one_shard() {
625        assert_eq!(BlockCache::new(BLOCK_LEN).shards.len(), 1);
626        assert_eq!(
627            BlockCache::new(2 * MIN_SHARD_BLOCKS * BLOCK_LEN - 1)
628                .shards
629                .len(),
630            1
631        );
632        assert_eq!(BlockCache::new(1 << 40).shards.len(), MAX_SHARDS);
633    }
634
635    /// Measures warm hits from many threads at once, as a build's resolver
636    /// threads read the same segments: run with `--ignored --nocapture` in a
637    /// release build to compare cache designs.
638    #[test]
639    #[ignore = "measurement; prints nanoseconds per hit"]
640    fn measure_concurrent_warm_hits() {
641        let cache = Arc::new(BlockCache::new(256 << 20));
642        let file = FileToken::next();
643        let blocks = 1024;
644        for index in 0..blocks {
645            cache
646                .get_or_load(key(file, index), || Ok::<_, ()>(block(1)))
647                .unwrap();
648        }
649        for threads in [1usize, 4, 12] {
650            let hits_per_thread = 400_000u64;
651            let started = std::time::Instant::now();
652            std::thread::scope(|scope| {
653                for thread in 0..threads {
654                    let cache = Arc::clone(&cache);
655                    scope.spawn(move || {
656                        let mut index = thread as u64 * 7919;
657                        for _ in 0..hits_per_thread {
658                            index = (index + 2_654_435_761) % blocks;
659                            let bytes = cache
660                                .get_or_load(key(file, index), || -> Result<Arc<[u8]>, ()> {
661                                    panic!("every block is cached")
662                                })
663                                .unwrap();
664                            std::hint::black_box(bytes);
665                        }
666                    });
667                }
668            });
669            let elapsed = started.elapsed();
670            println!(
671                "threads={threads} wall_ms={} ns_per_hit_per_thread={:.0}",
672                elapsed.as_millis(),
673                elapsed.as_nanos() as f64 / hits_per_thread as f64
674            );
675        }
676    }
677
678    #[test]
679    #[should_panic(expected = "below one block")]
680    fn a_budget_below_one_block_is_refused() {
681        let _cache = BlockCache::new(BLOCK_LEN - 1);
682    }
683}