Skip to main content

sail_cache/
memory.rs

1//! The in-memory tier: a bounded, least-recently-used map from keys to
2//! replies, in front of the disk tier (ADR 0015).
3//!
4//! A slot is either:
5//! - **on disk**: its bytes were read from a verified disk entry, or were
6//!   written to one, and the slot remembers that file's [`FileStamp`]. The
7//!   owner serves it only while the file still has that stamp, so a memory
8//!   hit is always byte-identical to what the disk tier holds; or
9//! - **pending**: a `PUT` whose disk write is queued (write-behind). No
10//!   entry file exists for the key yet. Once the write finishes the slot
11//!   becomes *on disk* with the new file's stamp, or is dropped if the write
12//!   failed or found another entry already there.
13//!
14//! This module only keeps the map; the daemon applies those rules.
15
16use std::collections::{BTreeMap, HashMap};
17use std::sync::{Arc, Mutex, MutexGuard};
18
19use sail_key::QueryKey;
20use serde::{Deserialize, Serialize};
21
22use crate::{Effort, FileStamp};
23
24/// Bytes charged for each slot on top of its reply.
25pub const SLOT_OVERHEAD: u64 = 128;
26
27/// A cached reply with the effort its entry records.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct Value {
30    /// The verification namespace, checked before serving.
31    pub mode: String,
32    /// The exact reply bytes.
33    pub reply: Vec<u8>,
34    /// The entry's recorded effort, for `check-sat` replies.
35    pub effort: Option<Effort>,
36}
37
38impl Value {
39    fn cost(&self) -> u64 {
40        u64::try_from(self.reply.len()).unwrap_or(u64::MAX) + SLOT_OVERHEAD
41    }
42}
43
44/// Where a slot's bytes stand relative to disk.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum State {
47    /// Identical to the entry file with this stamp.
48    OnDisk(FileStamp),
49    /// Queued for writing; no entry file yet.
50    Pending,
51}
52
53#[derive(Debug)]
54struct Slot {
55    value: Arc<Value>,
56    state: State,
57    tick: u64,
58}
59
60#[derive(Debug, Default)]
61struct Inner {
62    slots: HashMap<[u8; 32], Slot>,
63    /// Least recently used first.
64    order: BTreeMap<u64, [u8; 32]>,
65    tick: u64,
66    bytes: u64,
67    pending: u64,
68}
69
70impl Inner {
71    /// The next recency tick. The counter is a lifetime operation count, so
72    /// at exhaustion the held slots are renumbered densely in their current
73    /// order instead of overflowing (#474): recency order is preserved and
74    /// nothing panics while the tier lock is held.
75    fn next_tick(&mut self) -> u64 {
76        if let Some(tick) = self.tick.checked_add(1) {
77            self.tick = tick;
78            return tick;
79        }
80        self.renumber();
81        self.tick = self.tick.saturating_add(1);
82        self.tick
83    }
84
85    /// Reassigns ticks `1..=n` to the held slots, least recently used first.
86    fn renumber(&mut self) {
87        let order = std::mem::take(&mut self.order);
88        let mut tick = 0u64;
89        for key in order.into_values() {
90            if let Some(slot) = self.slots.get_mut(&key) {
91                tick = tick.saturating_add(1);
92                slot.tick = tick;
93                self.order.insert(tick, key);
94            }
95        }
96        self.tick = tick;
97    }
98
99    fn remove(&mut self, key: &[u8; 32]) {
100        if let Some(slot) = self.slots.remove(key) {
101            self.order.remove(&slot.tick);
102            self.bytes = self.bytes.saturating_sub(slot.value.cost());
103            if slot.state == State::Pending {
104                self.pending = self.pending.saturating_sub(1);
105            }
106        }
107    }
108
109    fn insert(&mut self, key: [u8; 32], value: Arc<Value>, state: State, capacity: u64) {
110        self.remove(&key);
111        let tick = self.next_tick();
112        self.bytes += value.cost();
113        if state == State::Pending {
114            self.pending += 1;
115        }
116        self.slots.insert(key, Slot { value, state, tick });
117        self.order.insert(tick, key);
118        while self.bytes > capacity {
119            let Some((_, oldest)) = self.order.pop_first() else {
120                break;
121            };
122            // `remove` looks the tick up again; it is already gone from
123            // `order`, which is harmless.
124            self.remove(&oldest);
125        }
126    }
127}
128
129/// Counters describing the tier's contents.
130#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
131pub struct MemoryStats {
132    /// The configured budget in bytes (0: the tier is off).
133    pub capacity_bytes: u64,
134    /// Slots held.
135    pub entries: u64,
136    /// Bytes charged for them (replies plus [`SLOT_OVERHEAD`] each).
137    pub bytes: u64,
138    /// Slots whose disk write is still queued.
139    pub pending: u64,
140}
141
142/// The in-memory tier.
143#[derive(Debug)]
144pub struct MemoryTier {
145    capacity: u64,
146    inner: Mutex<Inner>,
147}
148
149impl MemoryTier {
150    /// A tier holding at most `capacity` bytes (0 turns it off).
151    #[must_use]
152    pub fn new(capacity: u64) -> Self {
153        Self {
154            capacity,
155            inner: Mutex::new(Inner::default()),
156        }
157    }
158
159    fn lock(&self) -> Option<MutexGuard<'_, Inner>> {
160        // A poisoned lock means a thread panicked mid-update: treat the
161        // tier as empty from then on (every lookup is a miss).
162        self.inner.lock().ok()
163    }
164
165    /// Whether `value` is small enough to hold: at most a quarter of the
166    /// budget, so one large reply cannot flush the whole tier.
167    fn admits(&self, value: &Value) -> bool {
168        self.capacity > 0 && value.cost() <= self.capacity / 4
169    }
170
171    /// The slot for `key`, marking it most recently used.
172    #[must_use]
173    pub fn lookup(&self, key: &QueryKey) -> Option<(Arc<Value>, State)> {
174        let mut inner = self.lock()?;
175        let tick = inner.next_tick();
176        let inner = &mut *inner;
177        let slot = inner.slots.get_mut(&key.0)?;
178        inner.order.remove(&slot.tick);
179        slot.tick = tick;
180        inner.order.insert(tick, key.0);
181        Some((Arc::clone(&slot.value), slot.state))
182    }
183
184    /// Holds `value`, read from or written to the entry file with `stamp`,
185    /// replacing any slot for `key`.
186    pub fn insert_on_disk(&self, key: &QueryKey, value: Arc<Value>, stamp: FileStamp) {
187        if !self.admits(&value) {
188            self.remove(key);
189            return;
190        }
191        if let Some(mut inner) = self.lock() {
192            inner.insert(key.0, value, State::OnDisk(stamp), self.capacity);
193        }
194    }
195
196    /// Holds `value` as pending, unless `key` already has a slot or the
197    /// value is too large. Returns whether it was inserted.
198    pub fn insert_pending(&self, key: &QueryKey, value: Arc<Value>) -> bool {
199        if !self.admits(&value) {
200            return false;
201        }
202        let Some(mut inner) = self.lock() else {
203            return false;
204        };
205        if inner.slots.contains_key(&key.0) {
206            return false;
207        }
208        inner.insert(key.0, value, State::Pending, self.capacity);
209        true
210    }
211
212    /// Records the end of `value`'s disk write: with `Some(stamp)` the slot
213    /// becomes on-disk with that stamp; with `None` (the write failed, or
214    /// another entry was already there) it is dropped. Only a pending slot
215    /// still holding this very `value` is affected.
216    pub fn settle(&self, key: &QueryKey, value: &Arc<Value>, stamp: Option<FileStamp>) {
217        let Some(mut inner) = self.lock() else {
218            return;
219        };
220        let mine = inner
221            .slots
222            .get(&key.0)
223            .is_some_and(|s| s.state == State::Pending && Arc::ptr_eq(&s.value, value));
224        if !mine {
225            return;
226        }
227        match stamp {
228            Some(stamp) => {
229                inner.pending = inner.pending.saturating_sub(1);
230                if let Some(slot) = inner.slots.get_mut(&key.0) {
231                    slot.state = State::OnDisk(stamp);
232                }
233            }
234            None => inner.remove(&key.0),
235        }
236    }
237
238    /// Drops `key`'s slot if it still holds `value`.
239    pub fn remove_if(&self, key: &QueryKey, value: &Arc<Value>) {
240        if let Some(mut inner) = self.lock() {
241            let same = inner
242                .slots
243                .get(&key.0)
244                .is_some_and(|s| Arc::ptr_eq(&s.value, value));
245            if same {
246                inner.remove(&key.0);
247            }
248        }
249    }
250
251    /// Drops `key`'s slot.
252    pub fn remove(&self, key: &QueryKey) {
253        if let Some(mut inner) = self.lock() {
254            inner.remove(&key.0);
255        }
256    }
257
258    /// The tier's counters.
259    #[must_use]
260    pub fn stats(&self) -> MemoryStats {
261        let (entries, bytes, pending) = self.lock().map_or((0, 0, 0), |i| {
262            (
263                u64::try_from(i.slots.len()).unwrap_or(u64::MAX),
264                i.bytes,
265                i.pending,
266            )
267        });
268        MemoryStats {
269            capacity_bytes: self.capacity,
270            entries,
271            bytes,
272            pending,
273        }
274    }
275}
276
277#[cfg(test)]
278mod tests {
279    use super::*;
280
281    fn val(n: usize, b: u8) -> Arc<Value> {
282        Arc::new(Value {
283            mode: "default".to_owned(),
284            reply: vec![b; n],
285            effort: None,
286        })
287    }
288
289    fn stamp() -> FileStamp {
290        match std::fs::metadata(std::env::temp_dir()) {
291            Ok(m) => FileStamp::of(&m),
292            Err(e) => unreachable!("no temp dir: {e}"),
293        }
294    }
295
296    #[test]
297    fn evicts_least_recently_used_within_budget() {
298        // Room for five 100-byte replies.
299        let t = MemoryTier::new(5 * (100 + SLOT_OVERHEAD) + 10);
300        for i in 0..5u8 {
301            t.insert_on_disk(&QueryKey([i; 32]), val(100, i), stamp());
302        }
303        // Touch key 0, so key 1 is the oldest.
304        assert!(t.lookup(&QueryKey([0; 32])).is_some());
305        t.insert_on_disk(&QueryKey([5; 32]), val(100, 5), stamp());
306        assert!(t.lookup(&QueryKey([1; 32])).is_none());
307        for i in [0u8, 2, 3, 4, 5] {
308            assert!(t.lookup(&QueryKey([i; 32])).is_some(), "{i}");
309        }
310        let s = t.stats();
311        assert_eq!(s.entries, 5);
312        assert!(s.bytes <= s.capacity_bytes);
313    }
314
315    #[test]
316    fn exhausted_tick_renumbers_without_panicking_or_losing_order() {
317        // #474: the lifetime tick at u64::MAX must neither overflow (a panic
318        // under the tier lock) nor wrap (making a fresh touch look oldest).
319        let t = MemoryTier::new(5 * (100 + SLOT_OVERHEAD) + 10);
320        for i in 0..5u8 {
321            t.insert_on_disk(&QueryKey([i; 32]), val(100, i), stamp());
322        }
323        assert_eq!(t.stats().entries, 5);
324        if let Ok(mut inner) = t.inner.lock() {
325            inner.tick = u64::MAX;
326        }
327        // A miss and a hit at exhaustion: key 0 becomes most recent.
328        assert!(t.lookup(&QueryKey([9; 32])).is_none());
329        assert!(t.lookup(&QueryKey([0; 32])).is_some());
330        if let Ok(inner) = t.inner.lock() {
331            assert!(inner.tick < 10, "ticks were renumbered: {}", inner.tick);
332            assert_eq!(inner.order.len(), 5);
333        }
334        // Key 1 is now the oldest and is the one evicted.
335        t.insert_on_disk(&QueryKey([5; 32]), val(100, 5), stamp());
336        assert!(t.lookup(&QueryKey([1; 32])).is_none());
337        for i in [0u8, 2, 3, 4, 5] {
338            assert!(t.lookup(&QueryKey([i; 32])).is_some(), "{i}");
339        }
340    }
341
342    #[test]
343    fn off_and_oversized_values_are_not_held() {
344        let off = MemoryTier::new(0);
345        off.insert_on_disk(&QueryKey([1; 32]), val(1, 1), stamp());
346        assert!(!off.insert_pending(&QueryKey([2; 32]), val(1, 1)));
347        assert_eq!(off.stats().entries, 0);
348        let small = MemoryTier::new(1000);
349        assert!(!small.insert_pending(&QueryKey([2; 32]), val(500, 1)));
350        assert!(small.insert_pending(&QueryKey([2; 32]), val(10, 1)));
351    }
352
353    #[test]
354    fn pending_slots_settle_only_for_their_own_value() {
355        let t = MemoryTier::new(1 << 20);
356        let k = QueryKey([5; 32]);
357        let (a, b) = (val(10, b'a'), val(10, b'b'));
358        assert!(t.insert_pending(&k, Arc::clone(&a)));
359        // A second pending insert for the key is refused.
360        assert!(!t.insert_pending(&k, Arc::clone(&b)));
361        assert_eq!(t.stats().pending, 1);
362        // Settling another value does nothing.
363        t.settle(&k, &b, None);
364        assert!(matches!(t.lookup(&k), Some((_, State::Pending))));
365        t.settle(&k, &a, Some(stamp()));
366        assert!(matches!(t.lookup(&k), Some((_, State::OnDisk(_)))));
367        assert_eq!(t.stats().pending, 0);
368        // A failed write drops the pending slot.
369        let k2 = QueryKey([6; 32]);
370        assert!(t.insert_pending(&k2, Arc::clone(&b)));
371        t.settle(&k2, &b, None);
372        assert!(t.lookup(&k2).is_none());
373        // A disk read replaces a pending slot; the late settle is ignored.
374        let k3 = QueryKey([7; 32]);
375        assert!(t.insert_pending(&k3, Arc::clone(&a)));
376        t.insert_on_disk(&k3, Arc::clone(&b), stamp());
377        t.settle(&k3, &a, None);
378        assert!(t.lookup(&k3).is_some_and(|(v, _)| Arc::ptr_eq(&v, &b)));
379        t.remove_if(&k3, &a);
380        assert!(t.lookup(&k3).is_some());
381        t.remove_if(&k3, &b);
382        assert!(t.lookup(&k3).is_none());
383    }
384}