Diffinery

homeflare/celldpublic

47 lines · 1.9 KBRaw History
1//! Local hibernation-cache eviction, sans-IO.
2//!
3//! Idle hibernation preserves each cell's SQLite file so a same-node wake is
4//! a rename instead of a remote restore — measured 2026-08-02 at 46 serial
5//! storage round trips saved per wake. The cost is that a node accumulates
6//! one file per cell it has ever hosted, which is unbounded while the
7//! durable population is unbounded.
8//!
9//! The bound can be crude because the cache is PURE OPTIMIZATION: every
10//! entry is a copy of state the bucket already holds, so deleting any entry
11//! is always correct and costs only a future restore. That makes
12//! least-recently-used the whole policy — no fencing, no durability, no
13//! ordering constraint to respect.
14
15/// One cached file, as the executor observed it.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub struct CacheEntry {
18 /// Monotonic-ish recency; larger is more recently used. The executor
19 /// supplies mtime, which a rename-in refreshes.
20 pub last_used_ms: i64,
21 pub bytes: u64,
22}
23
24/// Which entries to delete so the cache fits `max_bytes`, oldest first.
25/// Returns indices into `entries`. An empty result means the cache already
26/// fits — the common case, and it must never do I/O-worthy work then.
27pub fn plan_eviction(entries: &[CacheEntry], max_bytes: u64) -> Vec<usize> {
28 let total: u64 = entries.iter().map(|entry| entry.bytes).sum();
29 if total <= max_bytes {
30 return Vec::new();
31 }
32 // Most recently used first; evict from the tail until it fits.
33 let mut order: Vec<usize> = (0..entries.len()).collect();
34 order.sort_by_key(|&i| std::cmp::Reverse((entries[i].last_used_ms, i)));
35 let mut kept = 0_u64;
36 let mut evict = Vec::new();
37 for i in order {
38 let next = kept.saturating_add(entries[i].bytes);
39 if next <= max_bytes {
40 kept = next;
41 } else {
42 evict.push(i);
43 }
44 }
45 evict.sort_unstable();
46 evict
47}