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