Skip to main content

drep/llm/
cache.rs

1//! Content-addressed cache for LLM responses.
2//!
3//! Two choices make cache hits follow the call paths the gate actually takes:
4//!
5//! - **The key is content-only, never commit-aware.** Hashing content
6//!   invalidates precisely when the content changes; including the commit SHA
7//!   would force a miss on unchanged files after every commit, which is the
8//!   exact case the cache exists to serve.
9//! - **One file per entry, the value is the JSON.** No sidecar metadata file.
10//!   The key is the filename, so nothing has to be re-validated on read except
11//!   age. If the entry is corrupt, unreadable, or expired, the read returns
12//!   `None` and the caller re-queries and overwrites. A cache is an
13//!   optimisation; it must not be able to take the gate down.
14//!
15//! ## Storage layout
16//!
17//! `root/<first two hex chars>/<full hex>.json`. Sharding keeps directories
18//! from growing to tens of thousands of entries (a flat `root/<hex>.json`
19//! layout would do the same for `readdir`, but `ls`-ing the cache to debug
20//! it would take seconds).
21//!
22//! ## Key composition
23//!
24//! `blake3` over the six inputs, each length-prefixed with an 8-byte
25//! big-endian length. Length prefixing rules out the
26//! `key("ab", "c", ...)` vs `key("a", "bc", ...)` collision that a separator
27//! byte cannot guarantee once `content` or `system_prompt` is allowed to
28//! contain that byte. `temperature` uses Rust's shortest round-tripping
29//! representation, so equal values hash alike without collapsing neighboring
30//! `f32` values.
31//!
32//! **The backend identity is part of the key, not just the model.** A model name is
33//! not a globally unique identity: the canonical failover pair is one open
34//! model served from a local runtime and from a cloud provider, which name it
35//! identically. Keyed on the model alone, the fallback's answer lands where the
36//! head would look for its own - so a later run with the head restored is
37//! served a response it never produced, which is the exact defect the
38//! per-provider key exists to prevent.
39//!
40//! ## Defaults
41//!
42//! 30 days TTL, 256 MiB max bytes.
43
44use std::path::{Path, PathBuf};
45use std::time::{Duration, SystemTime};
46use std::{fs, io::Write};
47
48use serde_json::Value;
49use thiserror::Error;
50
51/// A cache key: the blake3 hex digest of the six key inputs.
52///
53/// The inner `String` is exactly 64 lower-case ASCII hex characters because
54/// `blake3::Hash::to_hex` always emits 64 hex chars. Tests rely on this to
55/// compute the on-disk path by hand.
56#[derive(Clone, Debug, PartialEq, Eq, Hash)]
57pub struct CacheKey(String);
58
59impl CacheKey {
60    /// The hex digest. Test-only path construction uses this.
61    pub(crate) fn as_hex(&self) -> &str {
62        &self.0
63    }
64}
65
66/// What can go wrong at write time.
67///
68/// Reads are infallible by design: a corrupt or missing entry is a miss, not
69/// an error, so `get` returns `Option<Value>`. The caller treats write
70/// failures as non-fatal (log and continue); only the path to disk, the
71/// serialisation, the directory creation, and eviction need error variants.
72#[derive(Debug, Error)]
73pub enum CacheError {
74    /// The shard directory could not be created on `put`.
75    #[error("could not create cache shard {0}: {1}")]
76    CreateShard(PathBuf, std::io::Error),
77    /// Serialising the value to JSON failed. Should be unreachable for
78    /// values produced by `serde_json` itself, but the type permits any
79    /// `Value`, so the error path exists.
80    #[error("could not serialise cache entry {0}: {1}")]
81    Serialize(String, serde_json::Error),
82    /// Writing the JSON file failed (disk full, permissions, race with
83    /// concurrent eviction).
84    #[error("could not write cache entry {0}: {1}")]
85    Write(PathBuf, std::io::Error),
86    /// Reading the cache directory during eviction failed.
87    #[error("could not read cache directory: {0}")]
88    Walk(std::io::Error),
89    /// Removing an entry during eviction failed.
90    #[error("could not remove cache entry {0}: {1}")]
91    Remove(PathBuf, std::io::Error),
92}
93
94/// The cache: a directory tree of one JSON file per entry, keyed by blake3
95/// digest of the six prompt and backend inputs.
96///
97/// Built once per process and shared across the analyzer; every method takes
98/// `&self` so `Cache` can live behind an `Arc` if a future caller needs it.
99#[derive(Debug, Clone)]
100pub struct Cache {
101    root: PathBuf,
102    ttl: Duration,
103    max_bytes: u64,
104}
105
106impl Cache {
107    /// Build a cache rooted at `root`. Creates `root` if absent; a creation
108    /// failure is swallowed (the next `put` will surface it).
109    pub fn new(root: PathBuf, ttl_days: u64, max_bytes: u64) -> Self {
110        let _ = std::fs::create_dir_all(&root);
111        Self {
112            root,
113            ttl: Duration::from_secs(ttl_days.saturating_mul(86_400)),
114            max_bytes,
115        }
116    }
117
118    /// The conventional location: `directories::ProjectDirs::cache_dir()`,
119    /// falling back to `.drep-cache` in the cwd when the platform has no
120    /// cache directory. Returned as a relative path on the fallback branch
121    /// so the caller can resolve it against whatever cwd they choose.
122    pub fn default_root() -> PathBuf {
123        if let Some(dirs) = directories::ProjectDirs::from("dev", "slb350", "drep") {
124            return dirs.cache_dir().to_path_buf();
125        }
126        PathBuf::from(".drep-cache")
127    }
128
129    /// Compute the key for
130    /// `(system_prompt, content, backend, model, request_shape, temperature)`.
131    ///
132    /// Deliberately does NOT consult `self`: the key is content-only, so two
133    /// `Cache` instances at different roots produce the same key for the
134    /// same inputs. That is what criterion 7 asserts and what makes the
135    /// cache portable across CI runs.
136    ///
137    /// `request_shape` is in the key because one endpoint can serve the same model
138    /// over both wire formats - `api.minimax.io` publishes `/v1` and
139    /// `/anthropic/v1` for `MiniMax-M3` - and the two are different requests
140    /// with different reasoning handling. Keying without it files one
141    /// protocol's answer where the other looks for its own, which is the same
142    /// defect that put `endpoint` in the key.
143    pub fn key(
144        &self,
145        system_prompt: &str,
146        content: &str,
147        backend: &str,
148        model: &str,
149        request_shape: &str,
150        temperature: Option<f32>,
151    ) -> CacheKey {
152        let mut hasher = blake3::Hasher::new();
153        write_field(&mut hasher, system_prompt.as_bytes());
154        write_field(&mut hasher, content.as_bytes());
155        write_field(&mut hasher, backend.as_bytes());
156        write_field(&mut hasher, model.as_bytes());
157        write_field(&mut hasher, request_shape.as_bytes());
158        // `{:?}` on an ordinary finite `f32` is the shortest string that
159        // round-trips, so values such as `0.2` and `0.20` share a key while
160        // neighboring finite values do not. Config validation excludes NaN;
161        // signed zero is harmlessly allowed to retain its distinct spelling.
162        //
163        // This replaced `{:.6}`, whose comment claimed six decimal places were
164        // finer than `f32`'s resolution. They are not: `f32` has ~7 significant
165        // digits, not 7 decimal places, so near 1.0 its ulp is ~1.2e-7 while
166        // six decimals steps by 1e-6 - coarser, and able to collapse two
167        // genuinely different temperatures onto one key.
168        //
169        // An unset temperature is a *different request* from any set one - the
170        // field is absent and the server picks - so it gets a sentinel that no
171        // formatted float can collide with, rather than being folded onto some
172        // stand-in value.
173        let temp_str = match temperature {
174            Some(value) => format!("{value:?}"),
175            None => "unset".to_string(),
176        };
177        write_field(&mut hasher, temp_str.as_bytes());
178        CacheKey(hasher.finalize().to_hex().to_string())
179    }
180
181    /// Read the entry at `key`, or `None` if absent, expired, unreadable, or
182    /// unparseable. Reads never fail.
183    ///
184    /// An expired entry is removed opportunistically; a corrupt or
185    /// unreadable entry is left in place so the next read has another chance
186    /// (transient I/O is more likely than persistent corruption, and a
187    /// half-deleted cache is worse than a slightly redundant one).
188    pub fn get(&self, key: &CacheKey) -> Option<Value> {
189        let path = self.entry_path(key);
190        let meta = std::fs::metadata(&path).ok()?;
191        let mtime = meta.modified().ok()?;
192        // A future mtime (clock skew, manual planting) makes
193        // `duration_since` return `Err`. Treat that as age zero rather
194        // than propagating the error: the entry is well within TTL,
195        // and the alternative would silently turn every clock-skewed
196        // cache into a miss.
197        let age = SystemTime::now()
198            .duration_since(mtime)
199            .unwrap_or(Duration::ZERO);
200        if age > self.ttl {
201            // Expired. Removing is best-effort: a stale entry is no worse
202            // than a missing one, but failing to remove is not worth a Result.
203            let _ = std::fs::remove_file(&path);
204            return None;
205        }
206        let bytes = std::fs::read(&path).ok()?;
207        serde_json::from_slice(&bytes).ok()
208    }
209
210    /// Write `value` to disk under `key`.
211    ///
212    /// Creates the shard directory on demand so the very first `put` into a
213    /// fresh cache does not need a separate bootstrap step.
214    pub fn put(&self, key: &CacheKey, value: &Value) -> Result<(), CacheError> {
215        let path = self.entry_path(key);
216        let parent = path.parent().ok_or_else(|| {
217            CacheError::Write(
218                path.clone(),
219                std::io::Error::new(
220                    std::io::ErrorKind::InvalidInput,
221                    "cache entry path has no shard directory",
222                ),
223            )
224        })?;
225        fs::create_dir_all(parent).map_err(|e| CacheError::CreateShard(parent.to_path_buf(), e))?;
226        let bytes = serde_json::to_vec(value)
227            .map_err(|e| CacheError::Serialize(key.as_hex().to_owned(), e))?;
228        let mut temporary = tempfile::NamedTempFile::new_in(parent)
229            .map_err(|e| CacheError::Write(path.clone(), e))?;
230        temporary
231            .write_all(&bytes)
232            .map_err(|e| CacheError::Write(path.clone(), e))?;
233        temporary
234            .persist(&path)
235            .map_err(|e| CacheError::Write(path.clone(), e.error))?;
236        Ok(())
237    }
238
239    /// Walk the tree, evicting the oldest entries (by mtime) until the
240    /// total size is at or under `max_bytes`. Returns the number of bytes
241    /// freed; `0` when no eviction was needed.
242    pub fn evict_if_needed(&self) -> Result<u64, CacheError> {
243        let mut entries = self.collect_entries()?;
244        let total: u64 = entries.iter().map(|e| e.size).sum();
245        if total <= self.max_bytes {
246            return Ok(0);
247        }
248        entries.sort_by_key(|e| e.mtime);
249        let mut current = total;
250        let mut freed = 0u64;
251        for entry in entries {
252            if current <= self.max_bytes {
253                break;
254            }
255            std::fs::remove_file(&entry.path)
256                .map_err(|e| CacheError::Remove(entry.path.clone(), e))?;
257            current = current.saturating_sub(entry.size);
258            freed = freed.saturating_add(entry.size);
259        }
260        Ok(freed)
261    }
262
263    /// Compute the on-disk path for `key`.
264    ///
265    /// `pub(crate)` so the test suite can construct the same path to plant
266    /// an expired mtime or to write a corrupt body for the miss-on-bad-data
267    /// criterion.
268    pub(crate) fn entry_path(&self, key: &CacheKey) -> PathBuf {
269        let hex = key.as_hex();
270        // blake3::Hash::to_hex always produces 64 ASCII hex chars, so the
271        // `..2` slice is safe by construction.
272        let shard = &hex[..2];
273        self.root.join(shard).join(format!("{hex}.json"))
274    }
275
276    /// Walk every entry under `root` and return `(path, mtime, size)`.
277    ///
278    /// Skips the shard-directories' own metadata (no file under them, no
279    /// entry). Entries we cannot stat are skipped silently: a transient
280    /// stat failure should not abort eviction when the tree still has
281    /// deletable members.
282    fn collect_entries(&self) -> Result<Vec<CacheEntry>, CacheError> {
283        let mut out = Vec::new();
284        let shards = std::fs::read_dir(&self.root).map_err(CacheError::Walk)?;
285        for shard in shards {
286            let Ok(shard) = shard else { continue };
287            // Only descend into the two-hex-char directories. Anything else -
288            // a stray file the user dropped in the cache root, or a directory
289            // that is not one of ours - is ignored, so nothing outside the
290            // layout this module writes can be evicted.
291            //
292            // The name check is load-bearing, not decorative. `is_dir()` alone
293            // was what the code did while this comment claimed otherwise, which
294            // meant `evict_if_needed` - the one destructive path here - would
295            // happily delete files out of *any* directory someone had placed
296            // under the cache root.
297            let file_type = match shard.file_type() {
298                Ok(ft) => ft,
299                Err(_) => continue,
300            };
301            if !file_type.is_dir() {
302                continue;
303            }
304            if !is_shard_name(&shard.file_name()) {
305                continue;
306            }
307            let shard_path = shard.path();
308            let shard_name = shard.file_name();
309            let entries = match std::fs::read_dir(&shard_path) {
310                Ok(e) => e,
311                Err(_) => continue,
312            };
313            for entry in entries {
314                let entry = match entry {
315                    Ok(e) => e,
316                    Err(_) => continue,
317                };
318                if !is_entry_name(&shard_name, &entry.file_name()) {
319                    continue;
320                }
321                let path = entry.path();
322                let file_type = match entry.file_type() {
323                    Ok(file_type) => file_type,
324                    Err(_) => continue,
325                };
326                if !file_type.is_file() {
327                    continue;
328                }
329                let meta = match entry.metadata() {
330                    Ok(m) => m,
331                    Err(_) => continue,
332                };
333                if !meta.is_file() {
334                    continue;
335                }
336                // Falling back to UNIX_EPOCH on a failed `modified()` means
337                // the entry sorts first in eviction - i.e., it would be
338                // evicted first. That is the safe direction: a cache that
339                // evicts an unreadable entry loses a redundant file, not
340                // correctness.
341                let mtime = meta.modified().unwrap_or(SystemTime::UNIX_EPOCH);
342                let size = meta.len();
343                out.push(CacheEntry { path, mtime, size });
344            }
345        }
346        Ok(out)
347    }
348}
349
350impl Cache {
351    /// The cache root directory. `pub(crate)` for tests that need to assert
352    /// sharding / shard creation.
353    #[allow(dead_code)]
354    pub(crate) fn root(&self) -> &Path {
355        &self.root
356    }
357}
358
359/// One entry on disk, pre-computed for the eviction walk.
360struct CacheEntry {
361    path: PathBuf,
362    mtime: SystemTime,
363    size: u64,
364}
365
366/// Whether `name` is one of this module's shard directories.
367///
368/// Exactly two lower-case hex characters, which is what [`Cache::entry_path`]
369/// produces from a blake3 digest. Written against the same alphabet rather than
370/// a looser "two characters" check, so a directory named `ab` is a shard and
371/// one named `zz` or `AB` is not.
372fn is_shard_name(name: &std::ffi::OsStr) -> bool {
373    name.to_str().is_some_and(|name| is_lower_hex(name, 2))
374}
375
376/// Whether `name` has the exact form written by [`Cache::entry_path`] for
377/// `shard`: 64 lower-case hexadecimal digest characters plus `.json`, with
378/// the digest beginning with the parent shard name.
379fn is_entry_name(shard: &std::ffi::OsStr, name: &std::ffi::OsStr) -> bool {
380    let (Some(shard), Some(name)) = (shard.to_str(), name.to_str()) else {
381        return false;
382    };
383    let Some(digest) = name.strip_suffix(".json") else {
384        return false;
385    };
386    digest.starts_with(shard) && is_lower_hex(digest, 64)
387}
388
389fn is_lower_hex(value: &str, expected_len: usize) -> bool {
390    value.len() == expected_len
391        && value
392            .bytes()
393            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
394}
395
396/// Write a length-prefixed field to the hasher.
397///
398/// Length-prefixing rules out boundary collisions (`("ab","c")` vs
399/// `("a","bc")`) without depending on any byte that cannot appear in the
400/// payload. The length is a fixed 8-byte big-endian `u64`, so a single
401/// field can be at most `u64::MAX` bytes long - far longer than any real
402/// prompt.
403fn write_field(hasher: &mut blake3::Hasher, bytes: &[u8]) {
404    let len = u64::try_from(bytes.len()).expect("prompt field longer than u64::MAX bytes");
405    hasher.update(&len.to_be_bytes());
406    hasher.update(bytes);
407}
408
409#[cfg(test)]
410mod tests;