Skip to main content

sail_cache/
maint.rs

1//! Disk-tier maintenance: listing, summaries, integrity checks, eviction
2//! and clearing (ADR 0015).
3//!
4//! Every operation here is safe to run while a daemon serves and writes the
5//! same cache:
6//! - entries are only ever removed whole, never edited, so a reader sees a
7//!   complete entry or no entry;
8//! - a removed entry is a miss, which costs a re-solve, never correctness;
9//! - temporary files younger than [`STALE_TEMP`] are never touched, because
10//!   they may belong to a write in progress.
11
12use std::collections::BTreeMap;
13use std::path::{Path, PathBuf};
14use std::time::SystemTime;
15
16use sail_key::QueryKey;
17use serde::{Deserialize, Serialize};
18
19use crate::{DiskCache, Meta, Problem, STALE_TEMP, parse_entry, shape_ok};
20
21/// What a file under `<root>/v2` is.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum FileKind {
24    /// Named by a key, in its prefix directory.
25    Entry(QueryKey),
26    /// A key-named directory where an entry file should be.
27    EntryDirectory,
28    /// A temporary file of a write (`.tmp-*`).
29    Temp,
30    /// Anything else.
31    Stray,
32}
33
34/// One file (or misplaced directory) under `<root>/v2`.
35#[derive(Debug, Clone)]
36pub struct Listed {
37    /// Its path.
38    pub path: PathBuf,
39    /// What it is.
40    pub kind: FileKind,
41    /// Its size in bytes.
42    pub bytes: u64,
43    /// The later of its access and modification times: when it was last
44    /// used, as far as the cache knows.
45    pub used: SystemTime,
46}
47
48/// Parses a 64-character lowercase hex key.
49#[must_use]
50pub fn parse_key(hex: &str) -> Option<QueryKey> {
51    if hex.len() != 64 || hex.bytes().any(|b| !matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
52        return None;
53    }
54    let mut k = [0u8; 32];
55    for (i, b) in k.iter_mut().enumerate() {
56        *b = u8::from_str_radix(hex.get(2 * i..2 * i + 2)?, 16).ok()?;
57    }
58    Some(QueryKey(k))
59}
60
61fn last_used(meta: &std::fs::Metadata) -> SystemTime {
62    let m = meta.modified().unwrap_or(SystemTime::UNIX_EPOCH);
63    let a = meta.accessed().unwrap_or(SystemTime::UNIX_EPOCH);
64    m.max(a)
65}
66
67fn listed(path: PathBuf, kind: FileKind, meta: &std::fs::Metadata) -> Listed {
68    Listed {
69        path,
70        kind,
71        bytes: meta.len(),
72        used: last_used(meta),
73    }
74}
75
76fn is_prefix_dir(name: &str) -> bool {
77    name.len() == 2 && name.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
78}
79
80impl DiskCache {
81    /// Every file under `<root>/v2`, classified. Files that vanish while
82    /// listing are skipped.
83    #[must_use]
84    pub fn list(&self) -> Vec<Listed> {
85        let mut out = Vec::new();
86        let Ok(dirs) = std::fs::read_dir(self.entries_dir()) else {
87            return out;
88        };
89        for d in dirs.flatten() {
90            let path = d.path();
91            let name = d.file_name().to_string_lossy().into_owned();
92            let Ok(meta) = std::fs::symlink_metadata(&path) else {
93                continue;
94            };
95            if !meta.is_dir() || !is_prefix_dir(&name) {
96                out.push(listed(path, FileKind::Stray, &meta));
97                continue;
98            }
99            let Ok(files) = std::fs::read_dir(&path) else {
100                continue;
101            };
102            for f in files.flatten() {
103                let fpath = f.path();
104                let fname = f.file_name().to_string_lossy().into_owned();
105                let Ok(fmeta) = std::fs::symlink_metadata(&fpath) else {
106                    continue;
107                };
108                let key = parse_key(&fname).filter(|_| fname.starts_with(name.as_str()));
109                let kind = match key {
110                    Some(k) if fmeta.is_file() => FileKind::Entry(k),
111                    Some(_) if fmeta.is_dir() => FileKind::EntryDirectory,
112                    _ if fname.starts_with(".tmp-") && fmeta.is_file() => FileKind::Temp,
113                    _ => FileKind::Stray,
114                };
115                out.push(listed(fpath, kind, &fmeta));
116            }
117        }
118        out.sort_by(|a, b| a.path.cmp(&b.path));
119        out
120    }
121
122    /// Entry files and their total size, without reading them.
123    #[must_use]
124    pub fn usage(&self) -> Usage {
125        let mut u = Usage::default();
126        for l in self.list() {
127            if matches!(l.kind, FileKind::Entry(_)) {
128                u.entries += 1;
129                u.bytes += l.bytes;
130            }
131        }
132        u
133    }
134
135    /// Fully checks the entry file at `path` for `key`: integrity (header,
136    /// key, hash) and the shape of the reply for its command.
137    ///
138    /// # Errors
139    ///
140    /// The first problem found.
141    pub fn check_file(path: &Path, key: &QueryKey) -> Result<(Meta, Vec<u8>), Problem> {
142        let data = std::fs::read(path).map_err(|_| Problem::Unreadable)?;
143        let (meta, reply) = parse_entry(&data, &key.to_string())?;
144        if !shape_ok(&meta.command, &reply) {
145            return Err(Problem::BadShape);
146        }
147        Ok((meta, reply))
148    }
149
150    /// The problem with a listed file, if any: `None` for a valid entry or
151    /// a temporary file that may still be in use.
152    fn problem(l: &Listed, now: SystemTime) -> Option<Problem> {
153        match l.kind {
154            FileKind::Entry(k) => Self::check_file(&l.path, &k).err(),
155            FileKind::EntryDirectory => Some(Problem::Directory),
156            FileKind::Temp => now
157                .duration_since(l.used)
158                .is_ok_and(|age| age >= STALE_TEMP)
159                .then_some(Problem::StaleTemp),
160            FileKind::Stray => Some(Problem::Stray),
161        }
162    }
163
164    /// Summarizes the cache: entries and bytes by command, `unknown`
165    /// answers and their recorded effort, and files that are not valid
166    /// entries. Reads every entry; removes nothing.
167    #[must_use]
168    pub fn summarize(&self) -> Summary {
169        let mut s = Summary::default();
170        let mut fractions = Vec::new();
171        for l in self.list() {
172            let FileKind::Entry(k) = l.kind else {
173                match l.kind {
174                    FileKind::Temp => s.temp_files += 1,
175                    _ => s.invalid += 1,
176                }
177                continue;
178            };
179            let Ok((meta, reply)) = Self::check_file(&l.path, &k) else {
180                // Vanished or invalid: the next read removes it.
181                if l.path.exists() {
182                    s.invalid += 1;
183                }
184                continue;
185            };
186            s.entries += 1;
187            s.bytes += l.bytes;
188            let by = s.by_command.entry(meta.command.clone()).or_default();
189            by.entries += 1;
190            by.bytes += l.bytes;
191            if meta.command.starts_with("check-sat") && reply.trim_ascii() == b"unknown" {
192                let unknown = &mut s.unknown;
193                unknown.entries += 1;
194                match meta.effort {
195                    Some(e) => {
196                        unknown.with_effort += 1;
197                        let reason = e.reason.clone().unwrap_or_else(|| "(none)".to_owned());
198                        *unknown.by_reason.entry(reason).or_default() += 1;
199                        if let (Some(used), Some(limit)) = (e.used, e.limit)
200                            && limit > 0
201                        {
202                            #[allow(clippy::cast_precision_loss, reason = "a ratio for display")]
203                            fractions.push(used as f64 / limit as f64);
204                            if used.saturating_mul(2) <= limit {
205                                unknown.within_half_limit += 1;
206                            }
207                        }
208                    }
209                    None => {
210                        *unknown
211                            .by_reason
212                            .entry("(no effort)".to_owned())
213                            .or_default() += 1;
214                    }
215                }
216            }
217        }
218        fractions.sort_by(f64::total_cmp);
219        if let (Some(&min), Some(&max)) = (fractions.first(), fractions.last()) {
220            s.unknown.used_fraction = Some(Spread {
221                min,
222                median: fractions.get(fractions.len() / 2).copied().unwrap_or(min),
223                max,
224            });
225        }
226        s
227    }
228
229    /// Checks every file under `<root>/v2`. With `remove`, deletes each bad
230    /// one. Temporary files younger than [`STALE_TEMP`] are skipped.
231    #[must_use]
232    pub fn verify(&self, remove: bool) -> VerifyReport {
233        let mut r = VerifyReport::default();
234        let now = SystemTime::now();
235        for l in self.list() {
236            if matches!(l.kind, FileKind::Entry(_)) {
237                r.checked += 1;
238            }
239            match Self::problem(&l, now) {
240                None if matches!(l.kind, FileKind::Entry(_)) => r.valid += 1,
241                None => {}
242                // A file that vanished mid-check was removed or replaced by
243                // someone else; it is not a finding.
244                Some(Problem::Unreadable) if !l.path.exists() => r.checked -= 1,
245                Some(problem) => {
246                    let removed = remove && remove_path(&l.path);
247                    if removed {
248                        r.removed += 1;
249                    }
250                    *r.by_problem.entry(problem.name().to_owned()).or_default() += 1;
251                    r.bad.push(BadFile {
252                        path: l.path.display().to_string(),
253                        problem,
254                        removed,
255                    });
256                }
257            }
258        }
259        r
260    }
261
262    /// Evicts the least recently used entries until entry files take at
263    /// most `max_bytes`, and removes temporary files older than
264    /// [`STALE_TEMP`]. "Used" is the later of a file's access time (which
265    /// the daemon refreshes on hits) and its modification time.
266    #[must_use]
267    pub fn gc(&self, max_bytes: u64) -> GcReport {
268        let now = SystemTime::now();
269        let mut entries = Vec::new();
270        let mut r = GcReport {
271            max_bytes,
272            ..GcReport::default()
273        };
274        for l in self.list() {
275            match l.kind {
276                FileKind::Entry(_) => {
277                    r.before.entries += 1;
278                    r.before.bytes += l.bytes;
279                    entries.push(l);
280                }
281                FileKind::Temp => {
282                    let stale = now
283                        .duration_since(l.used)
284                        .is_ok_and(|age| age >= STALE_TEMP);
285                    if stale && remove_path(&l.path) {
286                        r.temp_removed += 1;
287                    }
288                }
289                FileKind::EntryDirectory | FileKind::Stray => {}
290            }
291        }
292        // Oldest first; ties broken by path for determinism.
293        entries.sort_by(|a, b| a.used.cmp(&b.used).then_with(|| a.path.cmp(&b.path)));
294        let mut total = r.before.bytes;
295        for l in entries {
296            if total <= max_bytes {
297                break;
298            }
299            if remove_path(&l.path) {
300                r.evicted.entries += 1;
301                r.evicted.bytes += l.bytes;
302            }
303            total = total.saturating_sub(l.bytes);
304        }
305        r.after = Usage {
306            entries: r.before.entries - r.evicted.entries,
307            bytes: r.before.bytes - r.evicted.bytes,
308        };
309        r
310    }
311
312    /// Removes every entry. The entries directory is first renamed out of
313    /// the way, so entries disappear at once, then deleted. Returns the
314    /// number of entries there were.
315    ///
316    /// # Errors
317    ///
318    /// I/O errors renaming or deleting the directory.
319    pub fn clear(&self) -> std::io::Result<Usage> {
320        let usage = self.usage();
321        let dir = self.entries_dir();
322        if !dir.exists() {
323            return Ok(usage);
324        }
325        let nanos = SystemTime::now()
326            .duration_since(SystemTime::UNIX_EPOCH)
327            .map_or(0, |d| d.as_nanos());
328        let trash = self
329            .root()
330            .join(format!(".clear-{}-{nanos}", std::process::id()));
331        std::fs::rename(&dir, &trash)?;
332        std::fs::remove_dir_all(&trash)?;
333        Ok(usage)
334    }
335}
336
337fn remove_path(path: &Path) -> bool {
338    match std::fs::symlink_metadata(path) {
339        Ok(m) if m.is_dir() => std::fs::remove_dir_all(path).is_ok(),
340        Ok(_) => std::fs::remove_file(path).is_ok(),
341        Err(_) => false,
342    }
343}
344
345/// A count of entries and their bytes.
346#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
347pub struct Usage {
348    /// Entry files.
349    pub entries: u64,
350    /// Their total size.
351    pub bytes: u64,
352}
353
354/// Minimum, median and maximum of a set of values.
355#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
356pub struct Spread {
357    /// Smallest.
358    pub min: f64,
359    /// Median.
360    pub median: f64,
361    /// Largest.
362    pub max: f64,
363}
364
365/// Cached `check-sat` answers of `unknown` and their recorded effort
366/// (ADR 0009).
367#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
368pub struct UnknownSummary {
369    /// `unknown` entries.
370    pub entries: u64,
371    /// Those with recorded effort.
372    pub with_effort: u64,
373    /// Those that used at most half of a non-zero limit.
374    pub within_half_limit: u64,
375    /// Entries by `reason-unknown` reply.
376    pub by_reason: BTreeMap<String, u64>,
377    /// Effort used as a fraction of the limit, where both are known.
378    pub used_fraction: Option<Spread>,
379}
380
381/// What [`DiskCache::summarize`] found.
382#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
383pub struct Summary {
384    /// Valid entries.
385    pub entries: u64,
386    /// Their total size in bytes.
387    pub bytes: u64,
388    /// Valid entries by the command they answer.
389    pub by_command: BTreeMap<String, Usage>,
390    /// `unknown` answers.
391    pub unknown: UnknownSummary,
392    /// Files that are not valid entries (see `sail cache verify`).
393    pub invalid: u64,
394    /// Temporary files of writes (in progress, or left by a crash).
395    pub temp_files: u64,
396}
397
398/// One file [`DiskCache::verify`] rejected.
399#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
400pub struct BadFile {
401    /// Its path.
402    pub path: String,
403    /// What is wrong with it.
404    pub problem: Problem,
405    /// Whether it was removed.
406    pub removed: bool,
407}
408
409/// What [`DiskCache::verify`] found.
410#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
411pub struct VerifyReport {
412    /// Entry files checked.
413    pub checked: u64,
414    /// Those that passed.
415    pub valid: u64,
416    /// Every rejected file.
417    pub bad: Vec<BadFile>,
418    /// Rejected files by problem.
419    pub by_problem: BTreeMap<String, u64>,
420    /// Rejected files removed.
421    pub removed: u64,
422}
423
424/// What [`DiskCache::gc`] did.
425#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
426pub struct GcReport {
427    /// The budget.
428    pub max_bytes: u64,
429    /// Entries before.
430    pub before: Usage,
431    /// Entries evicted.
432    pub evicted: Usage,
433    /// Entries after.
434    pub after: Usage,
435    /// Stale temporary files removed.
436    pub temp_removed: u64,
437}
438
439#[cfg(test)]
440mod tests {
441    use super::*;
442    use std::fs::FileTimes;
443    use std::time::Duration;
444
445    fn scratch(name: &str) -> DiskCache {
446        let d = std::env::temp_dir().join(format!("sail-maint-{}-{name}", std::process::id()));
447        let _ = std::fs::remove_dir_all(&d);
448        DiskCache::new(d)
449    }
450
451    fn put(c: &DiskCache, i: u8, reply: &[u8], command: &str) -> QueryKey {
452        let k = QueryKey([i; 32]);
453        assert!(c.put(&k, reply, command, "", "pinned-solver", None).is_ok());
454        k
455    }
456
457    fn age(c: &DiskCache, k: &QueryKey, secs: u64) {
458        let t = SystemTime::now() - Duration::from_secs(secs);
459        let f = std::fs::File::options().write(true).open(c.entry_path(k));
460        assert!(
461            f.and_then(|f| f.set_times(FileTimes::new().set_accessed(t).set_modified(t)))
462                .is_ok()
463        );
464    }
465
466    #[test]
467    fn gc_evicts_least_recently_used_first() {
468        let c = scratch("gc");
469        // One complete response frame of 1000 bytes.
470        let reply = [vec![b'x'; 999], b"\n".to_vec()].concat();
471        let keys: Vec<QueryKey> = (0..6u8).map(|i| put(&c, i, &reply, "get-model")).collect();
472        // Entry i was last used 1000 - 100 i seconds ago; entry 0 is the
473        // oldest. Then a hit on entry 1 makes it the newest.
474        for (i, k) in keys.iter().enumerate() {
475            age(&c, k, 1000 - 100 * i as u64);
476        }
477        assert!(c.get(&keys[1]).is_some());
478        let size = c.usage().bytes / 6;
479        let r = c.gc(size * 3);
480        assert_eq!(r.evicted.entries, 3);
481        assert!(r.after.bytes <= size * 3);
482        let left: Vec<bool> = keys.iter().map(|k| c.entry_path(k).exists()).collect();
483        assert_eq!(left, [false, true, false, false, true, true]);
484        // Everything left is still valid.
485        assert_eq!(c.verify(false).bad.len(), 0);
486        assert_eq!(c.gc(0).after.entries, 0);
487        let _ = std::fs::remove_dir_all(c.root());
488    }
489
490    #[test]
491    fn verify_reports_and_removes_bad_files() {
492        let c = scratch("verify");
493        let good = put(&c, 1, b"unsat\n", "check-sat");
494        let shape = put(&c, 2, b"(error \"x\")\n", "check-sat");
495        let flipped = put(&c, 3, b"sat\n", "check-sat");
496        let p = c.entry_path(&flipped);
497        let mut data = std::fs::read(&p).unwrap_or_default();
498        if let Some(b) = data.last_mut() {
499            *b ^= 1;
500        }
501        assert!(std::fs::write(&p, data).is_ok());
502        let dir = c.entry_path(&good).parent().map(Path::to_path_buf);
503        let dir = dir.unwrap_or_default();
504        assert!(std::fs::write(dir.join("junk"), b"x").is_ok());
505        assert!(std::fs::write(dir.join(".tmp-1-2-x"), b"partial").is_ok());
506        let r = c.verify(false);
507        assert_eq!((r.checked, r.valid, r.bad.len()), (3, 1, 3));
508        assert_eq!(r.by_problem.get("bad-shape"), Some(&1));
509        assert_eq!(r.by_problem.get("hash-mismatch"), Some(&1));
510        assert_eq!(r.by_problem.get("stray"), Some(&1));
511        assert!(c.entry_path(&shape).exists());
512        let r = c.verify(true);
513        assert_eq!(r.removed, 3);
514        assert!(!c.entry_path(&shape).exists());
515        // The young temporary file is left alone.
516        assert!(dir.join(".tmp-1-2-x").exists());
517        let r = c.verify(false);
518        assert_eq!((r.checked, r.valid, r.bad.len()), (1, 1, 0));
519        let _ = std::fs::remove_dir_all(c.root());
520    }
521
522    #[test]
523    fn summarize_counts_commands_and_unknowns() {
524        let c = scratch("summary");
525        put(&c, 1, b"unsat\n", "check-sat");
526        put(&c, 2, b"hi\n", "echo");
527        for (i, used) in [(3u8, 10u64), (4, 90)] {
528            let k = QueryKey([i; 32]);
529            let effort = crate::Effort {
530                limit: Some(100),
531                used: Some(used),
532                reason: Some("(incomplete quantifiers)".to_owned()),
533            };
534            assert!(
535                c.put(&k, b"unknown\n", "check-sat", "", "p", Some(&effort))
536                    .is_ok()
537            );
538        }
539        let s = c.summarize();
540        assert_eq!(s.entries, 4);
541        assert_eq!(s.by_command.get("check-sat").map(|u| u.entries), Some(3));
542        assert_eq!(s.unknown.entries, 2);
543        assert_eq!(s.unknown.within_half_limit, 1);
544        assert_eq!(
545            s.unknown.by_reason.get("(incomplete quantifiers)"),
546            Some(&2)
547        );
548        assert!(s.unknown.used_fraction.is_some_and(|f| f.max > 0.8));
549        let cleared = c.clear();
550        assert_eq!(cleared.ok().map(|u| u.entries), Some(4));
551        assert_eq!(c.usage().entries, 0);
552        let _ = std::fs::remove_dir_all(c.root());
553    }
554}