Skip to main content

sail_cache/
lib.rs

1//! Tiered result cache. Status: the local disk tier (ADR 0011), the
2//! in-memory tier ([`memory`]), disk maintenance ([`maint`]: summaries,
3//! integrity checks, eviction and clearing) and the shared tier of signed
4//! entries ([`shared`], ADR 0017).
5//!
6//! An entry maps a v2 query key (ADR 0008) to the exact reply bytes the
7//! pinned solver produced for that command. Each entry is one file,
8//! `<root>/v2/<k0k1>/<key>`, holding a JSON header line followed by the reply
9//! bytes. Writes are atomic: a temporary file, then a rename. A read checks
10//! that the stored key matches and that the reply hash matches. Any problem
11//! is a miss: the entry is removed and the caller falls back to the solver.
12#![forbid(unsafe_code)]
13
14pub mod maint;
15pub mod memory;
16pub mod pack;
17mod persist;
18pub mod shared;
19
20use std::path::{Path, PathBuf};
21use std::sync::atomic::{AtomicU64, Ordering};
22use std::time::{Duration, SystemTime};
23
24use sail_key::{QueryKey, sha256};
25use serde::{Deserialize, Serialize};
26
27/// Sequence number for temporary file names.
28static TMP_SEQ: AtomicU64 = AtomicU64::new(0);
29
30/// Format version of entry files.
31pub const ENTRY_VERSION: u32 = 2;
32
33/// Metadata stored with each reply.
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35pub struct Meta {
36    /// Verification namespace; older entries belong to default mode.
37    #[serde(default = "default_mode")]
38    pub mode: String,
39    /// Entry format version.
40    pub entry_version: u32,
41    /// The key, as hex.
42    pub key: String,
43    /// SHA-256 of the reply bytes, as hex.
44    pub reply_sha256: String,
45    /// The command the reply answers, for example `check-sat`.
46    pub command: String,
47    /// Solver identity summary: `name version sha256 platform`.
48    pub solver: String,
49    /// Unix time the entry was stored.
50    pub stored_unix: u64,
51    /// How the result was established (charter rule 7).
52    pub provenance: String,
53    /// Solver effort for `check-sat` replies (ADR 0009): `limit`, `used`,
54    /// and `reason` for `unknown` answers.
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub effort: Option<Effort>,
57}
58
59fn default_mode() -> String {
60    "default".to_owned()
61}
62
63/// Provenance and namespace for an explicitly scoped cache store.
64pub struct StoreContext<'a> {
65    /// Exact solver identity summary.
66    pub solver: &'a str,
67    /// How the reply was established.
68    pub provenance: &'a str,
69    /// Verification namespace.
70    pub mode: &'a str,
71}
72
73/// Solver effort for a `check-sat` reply (ADR 0009).
74#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
75pub struct Effort {
76    /// The `:rlimit` in force (0 means unlimited).
77    pub limit: Option<u64>,
78    /// Resource units used.
79    pub used: Option<u64>,
80    /// The `reason-unknown` reply, for `unknown` answers.
81    pub reason: Option<String>,
82}
83
84pub(crate) fn hex(bytes: &[u8]) -> String {
85    use std::fmt::Write as _;
86    bytes.iter().fold(String::with_capacity(64), |mut s, b| {
87        let _ = write!(s, "{b:02x}");
88        s
89    })
90}
91
92/// How long an entry's access time may lag behind its last use. Reads touch
93/// an entry's access time at most this often, so `gc` can evict the least
94/// recently used entries without a write on every hit.
95pub const TOUCH_INTERVAL: Duration = Duration::from_secs(60);
96
97/// The identity of one entry file on disk: device, inode, length and
98/// modification time.
99///
100/// Entries are only ever created by renaming a fresh temporary file into
101/// place, so a different entry at the same path has a different inode. An
102/// in-place rewrite changes the modification time. The in-memory tier
103/// serves a reply only while its file still has the stamp it had when the
104/// reply was read from it or written to it.
105#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
106pub struct FileStamp {
107    dev: u64,
108    ino: u64,
109    len: u64,
110    mtime_ns: i128,
111}
112
113impl FileStamp {
114    /// The stamp of the file `meta` describes.
115    #[must_use]
116    pub fn of(meta: &std::fs::Metadata) -> Self {
117        #[cfg(unix)]
118        {
119            use std::os::unix::fs::MetadataExt as _;
120            Self {
121                dev: meta.dev(),
122                ino: meta.ino(),
123                len: meta.len(),
124                mtime_ns: i128::from(meta.mtime()) * 1_000_000_000 + i128::from(meta.mtime_nsec()),
125            }
126        }
127        #[cfg(not(unix))]
128        {
129            let mtime_ns = meta
130                .modified()
131                .ok()
132                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
133                .map_or(0, |d| i128::try_from(d.as_nanos()).unwrap_or(i128::MAX));
134            Self {
135                dev: 0,
136                ino: 0,
137                len: meta.len(),
138                mtime_ns,
139            }
140        }
141    }
142}
143
144/// A valid entry read from disk.
145#[derive(Debug, Clone, PartialEq, Eq)]
146pub struct Stored {
147    /// The entry's header.
148    pub meta: Meta,
149    /// The exact reply bytes.
150    pub reply: Vec<u8>,
151    /// The stamp of the file the entry was read from.
152    pub stamp: FileStamp,
153}
154
155/// What [`DiskCache::put_stamped`] did.
156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157pub enum PutOutcome {
158    /// The entry was written; its file has this stamp.
159    Written(FileStamp),
160    /// An entry for the key already existed and was left alone.
161    Exists,
162}
163
164/// Why an entry file is not a valid entry.
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
166#[serde(rename_all = "kebab-case")]
167pub enum Problem {
168    /// The file cannot be read.
169    Unreadable,
170    /// There is no header line, or it is not valid JSON for a header.
171    BadHeader,
172    /// The header has another entry format version.
173    WrongVersion,
174    /// The header names a different key from the file name.
175    KeyMismatch,
176    /// The reply does not hash to the header's `reply_sha256`.
177    HashMismatch,
178    /// The reply does not have the shape its command requires.
179    BadShape,
180    /// A directory where an entry file should be.
181    Directory,
182    /// A file whose name is not a key, or a directory that is not a key
183    /// prefix.
184    Stray,
185    /// A temporary file older than [`STALE_TEMP`]: left by an interrupted
186    /// write.
187    StaleTemp,
188}
189
190impl Problem {
191    /// A short name for reports.
192    #[must_use]
193    pub fn name(self) -> &'static str {
194        match self {
195            Self::Unreadable => "unreadable",
196            Self::BadHeader => "bad-header",
197            Self::WrongVersion => "wrong-version",
198            Self::KeyMismatch => "key-mismatch",
199            Self::HashMismatch => "hash-mismatch",
200            Self::BadShape => "bad-shape",
201            Self::Directory => "directory",
202            Self::Stray => "stray",
203            Self::StaleTemp => "stale-temp",
204        }
205    }
206}
207
208/// How old a temporary file must be before maintenance treats it as left
209/// over from an interrupted write and removes it. Younger ones may belong
210/// to a write in progress.
211pub const STALE_TEMP: Duration = Duration::from_secs(3600);
212
213/// Whether `reply` has the shape the solver gives for a command named
214/// `command` (the name stored in the header). This is the coarse,
215/// name-only form of the shim's shape check (ADR 0011): the header keeps
216/// the command's name, not its text, so for example an `echo` reply is only
217/// checked to end a line. Every reply must be exactly one complete response
218/// frame: two concatenated forms would add a reply to a session's stream.
219#[must_use]
220pub fn shape_ok(command: &str, reply: &[u8]) -> bool {
221    if !sail_smtlib::split::is_single_response(reply) {
222        return false;
223    }
224    let body = reply.trim_ascii();
225    match command {
226        "check-sat" | "check-sat-assuming" | "check-sat-using" => {
227            matches!(body, b"sat" | b"unsat" | b"unknown")
228        }
229        "echo" => reply.ends_with(b"\n"),
230        "get-info" => body.starts_with(b"(:") && body.ends_with(b")"),
231        _ => !body.is_empty() && !body.starts_with(b"(error"),
232    }
233}
234
235/// Parses and checks entry file contents against the key named `key` (hex).
236/// The header must parse, name `key`, carry this format version and hash
237/// the reply correctly.
238///
239/// # Errors
240///
241/// The first problem found.
242pub fn parse_entry(data: &[u8], key: &str) -> Result<(Meta, Vec<u8>), Problem> {
243    let (header, payload) =
244        sail_acceptance::cache_record::split_record(data).ok_or(Problem::BadHeader)?;
245    let meta: Meta = serde_json::from_slice(header).map_err(|_| Problem::BadHeader)?;
246    let reply = payload.to_vec();
247    let computed = hex(&sha256(&reply));
248    let version = meta.entry_version;
249    let recorded_key = meta.key.as_bytes().to_vec();
250    let recorded_digest = meta.reply_sha256.as_bytes().to_vec();
251    sail_acceptance::query::RecoveryRecord::new(meta, reply, version, recorded_key, recorded_digest)
252        .recover(ENTRY_VERSION, key.as_bytes(), computed.as_bytes())
253        .map_err(|rejection| match rejection {
254            sail_acceptance::query::RecoveryRejection::WrongVersion => Problem::WrongVersion,
255            sail_acceptance::query::RecoveryRejection::KeyMismatch => Problem::KeyMismatch,
256            sail_acceptance::query::RecoveryRejection::HashMismatch => Problem::HashMismatch,
257        })
258}
259
260/// Whether `meta`'s access time is missing or older than [`TOUCH_INTERVAL`].
261fn access_stale(meta: &std::fs::Metadata) -> bool {
262    meta.accessed()
263        .ok()
264        .and_then(|a| SystemTime::now().duration_since(a).ok())
265        .is_none_or(|age| age >= TOUCH_INTERVAL)
266}
267
268/// Sets `file`'s access time to now if it is older than [`TOUCH_INTERVAL`].
269/// Only the access time changes, so the file's [`FileStamp`] does not.
270/// Failures are ignored: a missed touch only makes `gc` think the entry is
271/// older than it is.
272fn touch_if_stale(file: &std::fs::File, meta: &std::fs::Metadata) {
273    if access_stale(meta) {
274        let _ = file.set_times(std::fs::FileTimes::new().set_accessed(SystemTime::now()));
275    }
276}
277
278/// The local disk tier.
279#[derive(Debug, Clone)]
280pub struct DiskCache {
281    root: PathBuf,
282}
283
284impl DiskCache {
285    /// A cache rooted at `root` (created on first write).
286    #[must_use]
287    pub fn new(root: impl Into<PathBuf>) -> Self {
288        Self { root: root.into() }
289    }
290
291    /// The cache root.
292    #[must_use]
293    pub fn root(&self) -> &Path {
294        &self.root
295    }
296
297    /// The directory holding every entry, `<root>/v2`.
298    #[must_use]
299    pub fn entries_dir(&self) -> PathBuf {
300        self.root.join("v2")
301    }
302
303    /// The path of `key`'s entry file.
304    #[must_use]
305    pub fn entry_path(&self, key: &QueryKey) -> PathBuf {
306        let k = key.to_string();
307        self.entries_dir().join(k.get(..2).unwrap_or("xx")).join(k)
308    }
309
310    /// The reply stored for `key`, if there is a valid entry.
311    #[must_use]
312    pub fn get(&self, key: &QueryKey) -> Option<(Meta, Vec<u8>)> {
313        self.get_stamped(key).map(|s| (s.meta, s.reply))
314    }
315
316    /// The entry stored for `key`, if valid, with the stamp of the file it
317    /// was read from. A hit refreshes the file's access time (at most once
318    /// per [`TOUCH_INTERVAL`]). An invalid entry file is removed.
319    #[must_use]
320    pub fn get_stamped(&self, key: &QueryKey) -> Option<Stored> {
321        use std::io::Read as _;
322        let path = self.entry_path(key);
323        let mut file = std::fs::File::open(&path).ok()?;
324        let meta = file.metadata().ok()?;
325        if !meta.is_file() {
326            // A directory or other non-file: a miss. `verify` reports it.
327            return None;
328        }
329        let mut data = Vec::with_capacity(usize::try_from(meta.len()).unwrap_or(0));
330        let parsed = file
331            .read_to_end(&mut data)
332            .ok()
333            .and_then(|_| parse_entry(&data, &key.to_string()).ok());
334        let Some((m, reply)) = parsed else {
335            // Corrupt or foreign entry: drop it; the caller re-solves.
336            let _ = std::fs::remove_file(&path);
337            return None;
338        };
339        touch_if_stale(&file, &meta);
340        Some(Stored {
341            meta: m,
342            reply,
343            stamp: FileStamp::of(&meta),
344        })
345    }
346
347    /// The stamp of `key`'s entry file as it is now, if it is a file. The
348    /// caller is about to serve this entry from memory, so the access time
349    /// is refreshed if it is older than [`TOUCH_INTERVAL`], for `gc`.
350    #[must_use]
351    pub fn stamp_for_hit(&self, key: &QueryKey) -> Option<FileStamp> {
352        let path = self.entry_path(key);
353        let meta = std::fs::metadata(&path).ok()?;
354        if !meta.is_file() {
355            return None;
356        }
357        if access_stale(&meta)
358            && let Ok(f) = std::fs::File::open(&path)
359        {
360            touch_if_stale(&f, &meta);
361        }
362        Some(FileStamp::of(&meta))
363    }
364
365    /// Whether an entry file exists for `key` (valid or not).
366    #[must_use]
367    pub fn contains(&self, key: &QueryKey) -> bool {
368        self.entry_path(key).is_file()
369    }
370
371    /// Stores `reply` for `key`. Existing entries are left alone: content
372    /// addressing means they hold the same answer.
373    ///
374    /// # Errors
375    ///
376    /// I/O errors creating or writing the entry.
377    pub fn put(
378        &self,
379        key: &QueryKey,
380        reply: &[u8],
381        command: &str,
382        solver: &str,
383        provenance: &str,
384        effort: Option<&Effort>,
385    ) -> std::io::Result<()> {
386        self.put_stamped(key, reply, command, solver, provenance, effort)
387            .map(|_| ())
388    }
389
390    /// [`DiskCache::put`], reporting whether the entry was written and, if
391    /// so, the stamp of the file now at the entry's path.
392    ///
393    /// # Errors
394    ///
395    /// I/O errors creating or writing the entry.
396    pub fn put_stamped(
397        &self,
398        key: &QueryKey,
399        reply: &[u8],
400        command: &str,
401        solver: &str,
402        provenance: &str,
403        effort: Option<&Effort>,
404    ) -> std::io::Result<PutOutcome> {
405        self.put_scoped(
406            key,
407            reply,
408            command,
409            &StoreContext {
410                solver,
411                provenance,
412                mode: "default",
413            },
414            effort,
415        )
416    }
417
418    /// Stores an entry with explicit provenance and verification namespace.
419    ///
420    /// # Errors
421    ///
422    /// I/O errors creating or writing the entry.
423    pub fn put_scoped(
424        &self,
425        key: &QueryKey,
426        reply: &[u8],
427        command: &str,
428        context: &StoreContext<'_>,
429        effort: Option<&Effort>,
430    ) -> std::io::Result<PutOutcome> {
431        let path = self.entry_path(key);
432        if path.is_file() {
433            return Ok(PutOutcome::Exists);
434        }
435        let dir = path.parent().unwrap_or(&self.root).to_path_buf();
436        std::fs::create_dir_all(&dir)?;
437        let meta = Meta {
438            mode: context.mode.to_owned(),
439            entry_version: ENTRY_VERSION,
440            key: key.to_string(),
441            reply_sha256: hex(&sha256(reply)),
442            command: command.to_owned(),
443            solver: context.solver.to_owned(),
444            stored_unix: SystemTime::now()
445                .duration_since(std::time::UNIX_EPOCH)
446                .map_or(0, |d| d.as_secs()),
447            provenance: context.provenance.to_owned(),
448            effort: effort.cloned(),
449        };
450        // Unique per write: two writers may store the same key at once, and
451        // must not write into the same temporary file.
452        let seq = TMP_SEQ.fetch_add(1, Ordering::Relaxed);
453        let tmp = dir.join(format!(".tmp-{}-{seq}-{key}", std::process::id()));
454        // The shared transaction retains exclusive creation and never removes
455        // a preexisting temporary name. Its receipt establishes write-call
456        // sequencing, not truthful solver origin or durable filesystem state.
457        persist::write_record(&tmp, &path, &meta, reply).map(PutOutcome::Written)
458    }
459}
460
461#[cfg(test)]
462mod tests {
463    use super::*;
464
465    fn scratch(name: &str) -> PathBuf {
466        let d = std::env::temp_dir().join(format!("sail-cache-test-{}-{name}", std::process::id()));
467        let _ = std::fs::remove_dir_all(&d);
468        d
469    }
470
471    #[test]
472    fn shape_requires_exactly_one_response_frame() {
473        assert!(super::shape_ok("get-info", b"(:name \"Z3\")\n"));
474        assert!(super::shape_ok("check-sat", b"unsat\n"));
475        assert!(!super::shape_ok(
476            "get-info",
477            b"(:name \"Z3\")(:evil \"extra\")\n"
478        ));
479        assert!(!super::shape_ok("check-sat", b"unsat\nsat\n"));
480        assert!(!super::shape_ok("get-model", b"(model)\n(model)\n"));
481        assert!(!super::shape_ok("echo", b"a\nb\n"));
482    }
483
484    #[test]
485    fn round_trips_exact_bytes() {
486        let c = DiskCache::new(scratch("rt"));
487        let k = QueryKey([1; 32]);
488        assert!(c.get(&k).is_none());
489        let reply = b"(model\n  (define-fun x () Int 1)\n)\n\x00\xff";
490        assert!(
491            c.put(&k, reply, "get-model", "z3", "pinned-solver", None)
492                .is_ok()
493        );
494        let (meta, got) = c.get(&k).unwrap_or_default_for_test();
495        assert_eq!(got, reply);
496        assert_eq!(meta.command, "get-model");
497        let _ = std::fs::remove_dir_all(c.root());
498    }
499
500    #[test]
501    fn entries_without_session_silence_evidence_are_rejected() {
502        let c = DiskCache::new(scratch("legacy-stderr"));
503        let k = QueryKey([19; 32]);
504        assert!(
505            c.put(&k, b"unsat\n", "check-sat", "z3", "pinned-solver", None)
506                .is_ok()
507        );
508        let data = std::fs::read(c.entry_path(&k)).unwrap_or_default();
509        let end = data.iter().position(|&b| b == b'\n').unwrap_or(0);
510        let mut header: serde_json::Value =
511            serde_json::from_slice(&data[..end]).unwrap_or_default();
512        header["entry_version"] = 1.into();
513        let mut old = serde_json::to_vec(&header).unwrap_or_default();
514        old.extend_from_slice(&data[end..]);
515        assert!(matches!(
516            parse_entry(&old, &k.to_string()),
517            Err(Problem::WrongVersion)
518        ));
519        let _ = std::fs::remove_dir_all(c.root());
520    }
521
522    #[test]
523    fn corrupt_entries_are_misses_and_removed() {
524        let c = DiskCache::new(scratch("corrupt"));
525        let k = QueryKey([2; 32]);
526        assert!(
527            c.put(&k, b"unsat\n", "check-sat", "z3", "pinned-solver", None)
528                .is_ok()
529        );
530        let path = c.entry_path(&k);
531        let mut data = std::fs::read(&path).unwrap_or_default();
532        if let Some(last) = data.last_mut() {
533            *last ^= 1;
534        }
535        assert!(std::fs::write(&path, &data).is_ok());
536        assert!(c.get(&k).is_none());
537        assert!(!path.exists());
538        // An entry filed under the wrong key is also a miss.
539        let other = QueryKey([3; 32]);
540        assert!(
541            c.put(&k, b"sat\n", "check-sat", "z3", "pinned-solver", None)
542                .is_ok()
543        );
544        assert!(std::fs::create_dir_all(c.entry_path(&other).parent().unwrap_or(c.root())).is_ok());
545        assert!(std::fs::copy(c.entry_path(&k), c.entry_path(&other)).is_ok());
546        assert!(c.get(&other).is_none());
547        let _ = std::fs::remove_dir_all(c.root());
548    }
549
550    #[test]
551    fn concurrent_puts_of_one_key_leave_a_valid_entry() {
552        // Statistics replies for one key differ in their timing figures, so
553        // racing writers store different bytes. Each must write its own
554        // temporary file, or the renamed entry can mix them.
555        let c = DiskCache::new(scratch("race"));
556        let k = QueryKey([4; 32]);
557        for round in 0..40 {
558            let _ = std::fs::remove_file(c.entry_path(&k));
559            let barrier = std::sync::Barrier::new(8);
560            std::thread::scope(|s| {
561                for t in 0..8u8 {
562                    let (c, barrier) = (&c, &barrier);
563                    s.spawn(move || {
564                        let reply = vec![b'a' + t; 4096 * (usize::from(t) + 1)];
565                        barrier.wait();
566                        let _ = c.put(&k, &reply, "get-info", "z3", "pinned-solver", None);
567                    });
568                }
569            });
570            let got = c.get(&k).map(|(_, r)| r);
571            assert!(
572                got.as_ref()
573                    .is_some_and(|r| r.iter().all(|&b| Some(&b) == r.first())),
574                "round {round}: no valid entry"
575            );
576        }
577        let _ = std::fs::remove_dir_all(c.root());
578    }
579
580    #[cfg(unix)]
581    #[test]
582    fn put_refuses_a_preexisting_temporary_name() {
583        // #412: a symlink at the next temporary name must not be followed
584        // (truncating its target), renamed into place, or removed.
585        let c = DiskCache::new(scratch("tmp-symlink"));
586        let k = QueryKey([5; 32]);
587        let dir = c.entry_path(&k).parent().map(Path::to_path_buf);
588        let dir = dir.unwrap_or_else(|| c.root().to_path_buf());
589        assert!(std::fs::create_dir_all(&dir).is_ok());
590        let target = c.root().join("owned-by-someone-else");
591        assert!(std::fs::write(&target, b"sentinel").is_ok());
592        let seq = TMP_SEQ.load(Ordering::Relaxed);
593        // Other tests in this process may take sequence numbers concurrently,
594        // so plant the link at a run of upcoming names.
595        let links: Vec<PathBuf> = (seq..seq + 64)
596            .map(|n| dir.join(format!(".tmp-{}-{n}-{k}", std::process::id())))
597            .collect();
598        for l in &links {
599            assert!(std::os::unix::fs::symlink(&target, l).is_ok());
600        }
601        let mut refused = false;
602        for _ in 0..64 {
603            match c.put(&k, b"unsat\n", "check-sat", "z3", "pinned-solver", None) {
604                Err(e) => {
605                    assert_eq!(e.kind(), std::io::ErrorKind::AlreadyExists);
606                    refused = true;
607                }
608                Ok(()) => break,
609            }
610        }
611        assert!(refused, "a preexisting temporary name must be refused");
612        assert_eq!(
613            std::fs::read(&target).ok().as_deref(),
614            Some(&b"sentinel"[..])
615        );
616        let entry = c.entry_path(&k);
617        assert!(
618            std::fs::symlink_metadata(&entry).map_or(true, |m| !m.file_type().is_symlink()),
619            "the entry must never be a renamed symlink"
620        );
621        assert!(
622            links
623                .iter()
624                .all(|l| std::fs::symlink_metadata(l).is_ok_and(|m| m.file_type().is_symlink())),
625            "a name this writer did not create must not be removed"
626        );
627        let _ = std::fs::remove_dir_all(c.root());
628    }
629
630    trait OrDefault {
631        fn unwrap_or_default_for_test(self) -> (Meta, Vec<u8>);
632    }
633
634    impl OrDefault for Option<(Meta, Vec<u8>)> {
635        fn unwrap_or_default_for_test(self) -> (Meta, Vec<u8>) {
636            match self {
637                Some(x) => x,
638                None => unreachable!("expected a cache hit"),
639            }
640        }
641    }
642}