Skip to main content

lean_ctx/core/cache/
validation.rs

1use md5::{Digest, Md5};
2use std::sync::atomic::{AtomicU64, Ordering};
3use std::time::SystemTime;
4
5/// The single terminal reuse classification for one eligible cacheable read.
6///
7/// A request can pass through several cache layers, but it must be counted in
8/// exactly one bucket.  In particular, a session-cache rendering that is later
9/// collapsed by kernel dedup is an [`UnchangedStub`](Self::UnchangedStub), not
10/// two independent hits.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum ReuseOutcome {
13    Cold,
14    DiskContentHit,
15    RenderCacheHit,
16    UnchangedStub,
17    CrossFileRef,
18    FreshBypass,
19    Stale,
20    VariantEvicted,
21    PolicyBypass,
22}
23
24impl ReuseOutcome {
25    const fn is_render_reuse(self) -> bool {
26        matches!(
27            self,
28            Self::RenderCacheHit | Self::UnchangedStub | Self::CrossFileRef
29        )
30    }
31
32    const fn is_ctx_read_eligible(self) -> bool {
33        !matches!(self, Self::FreshBypass | Self::PolicyBypass)
34    }
35}
36
37/// Snapshot for the three non-overlapping cache-reuse measurements.
38///
39/// `eligible_ctx_reads` intentionally excludes explicit fresh reads and
40/// policy-disabled cache reads: neither was allowed to reuse a rendering.
41#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
42pub struct ReuseSnapshot {
43    pub cold: u64,
44    pub disk_content_hits: u64,
45    pub render_cache_hits: u64,
46    pub unchanged_stubs: u64,
47    pub cross_file_refs: u64,
48    pub fresh_bypasses: u64,
49    pub stale: u64,
50    pub variant_evicted: u64,
51    pub policy_bypasses: u64,
52    pub eligible_ctx_reads: u64,
53    pub reused_renderings: u64,
54    pub eligible_search_reads: u64,
55}
56
57impl ReuseSnapshot {
58    /// Percentage of eligible `ctx_read`s served by an already-rendered result.
59    pub fn read_reuse_rate(&self) -> f64 {
60        rate(self.reused_renderings, self.eligible_ctx_reads)
61    }
62
63    /// Percentage of eligible search file reads served by `content_cache`.
64    pub fn disk_reuse_rate(&self) -> f64 {
65        rate(self.disk_content_hits, self.eligible_search_reads)
66    }
67}
68
69struct ReuseCounters {
70    cold: AtomicU64,
71    disk_content_hits: AtomicU64,
72    render_cache_hits: AtomicU64,
73    unchanged_stubs: AtomicU64,
74    cross_file_refs: AtomicU64,
75    fresh_bypasses: AtomicU64,
76    stale: AtomicU64,
77    variant_evicted: AtomicU64,
78    policy_bypasses: AtomicU64,
79    eligible_ctx_reads: AtomicU64,
80    reused_renderings: AtomicU64,
81    eligible_search_reads: AtomicU64,
82}
83
84impl ReuseCounters {
85    const fn new() -> Self {
86        Self {
87            cold: AtomicU64::new(0),
88            disk_content_hits: AtomicU64::new(0),
89            render_cache_hits: AtomicU64::new(0),
90            unchanged_stubs: AtomicU64::new(0),
91            cross_file_refs: AtomicU64::new(0),
92            fresh_bypasses: AtomicU64::new(0),
93            stale: AtomicU64::new(0),
94            variant_evicted: AtomicU64::new(0),
95            policy_bypasses: AtomicU64::new(0),
96            eligible_ctx_reads: AtomicU64::new(0),
97            reused_renderings: AtomicU64::new(0),
98            eligible_search_reads: AtomicU64::new(0),
99        }
100    }
101}
102
103static REUSE_COUNTERS: ReuseCounters = ReuseCounters::new();
104
105fn rate(numerator: u64, denominator: u64) -> f64 {
106    if denominator == 0 {
107        0.0
108    } else {
109        numerator as f64 * 100.0 / denominator as f64
110    }
111}
112
113fn bump_outcome(counters: &ReuseCounters, outcome: ReuseOutcome) {
114    let counter = match outcome {
115        ReuseOutcome::Cold => &counters.cold,
116        ReuseOutcome::DiskContentHit => &counters.disk_content_hits,
117        ReuseOutcome::RenderCacheHit => &counters.render_cache_hits,
118        ReuseOutcome::UnchangedStub => &counters.unchanged_stubs,
119        ReuseOutcome::CrossFileRef => &counters.cross_file_refs,
120        ReuseOutcome::FreshBypass => &counters.fresh_bypasses,
121        ReuseOutcome::Stale => &counters.stale,
122        ReuseOutcome::VariantEvicted => &counters.variant_evicted,
123        ReuseOutcome::PolicyBypass => &counters.policy_bypasses,
124    };
125    counter.fetch_add(1, Ordering::Relaxed);
126}
127
128fn record_ctx_read_outcome_into(counters: &ReuseCounters, outcome: ReuseOutcome) {
129    bump_outcome(counters, outcome);
130    if outcome.is_ctx_read_eligible() {
131        counters.eligible_ctx_reads.fetch_add(1, Ordering::Relaxed);
132        if outcome.is_render_reuse() {
133            counters.reused_renderings.fetch_add(1, Ordering::Relaxed);
134        }
135    }
136}
137
138/// Record exactly one terminal outcome for a completed `ctx_read`.
139pub fn record_ctx_read_outcome(outcome: ReuseOutcome) {
140    record_ctx_read_outcome_into(&REUSE_COUNTERS, outcome);
141}
142
143fn record_search_content_read_into(counters: &ReuseCounters, hit: bool) {
144    counters
145        .eligible_search_reads
146        .fetch_add(1, Ordering::Relaxed);
147    bump_outcome(
148        counters,
149        if hit {
150            ReuseOutcome::DiskContentHit
151        } else {
152            ReuseOutcome::Cold
153        },
154    );
155}
156
157/// Record exactly one content-cache outcome for one eligible search file read.
158pub fn record_search_content_read(hit: bool) {
159    record_search_content_read_into(&REUSE_COUNTERS, hit);
160}
161
162/// Return a lock-free point-in-time view of reuse counters.
163#[must_use]
164pub fn reuse_snapshot() -> ReuseSnapshot {
165    snapshot_from(&REUSE_COUNTERS)
166}
167
168fn snapshot_from(counters: &ReuseCounters) -> ReuseSnapshot {
169    ReuseSnapshot {
170        cold: counters.cold.load(Ordering::Relaxed),
171        disk_content_hits: counters.disk_content_hits.load(Ordering::Relaxed),
172        render_cache_hits: counters.render_cache_hits.load(Ordering::Relaxed),
173        unchanged_stubs: counters.unchanged_stubs.load(Ordering::Relaxed),
174        cross_file_refs: counters.cross_file_refs.load(Ordering::Relaxed),
175        fresh_bypasses: counters.fresh_bypasses.load(Ordering::Relaxed),
176        stale: counters.stale.load(Ordering::Relaxed),
177        variant_evicted: counters.variant_evicted.load(Ordering::Relaxed),
178        policy_bypasses: counters.policy_bypasses.load(Ordering::Relaxed),
179        eligible_ctx_reads: counters.eligible_ctx_reads.load(Ordering::Relaxed),
180        reused_renderings: counters.reused_renderings.load(Ordering::Relaxed),
181        eligible_search_reads: counters.eligible_search_reads.load(Ordering::Relaxed),
182    }
183}
184
185pub fn file_mtime(path: &str) -> Option<SystemTime> {
186    std::fs::metadata(path).and_then(|m| m.modified()).ok()
187}
188
189pub fn is_cache_entry_stale(path: &str, cached_mtime: Option<SystemTime>) -> bool {
190    let current = file_mtime(path);
191    match (cached_mtime, current) {
192        // Both unavailable (e.g. WSL DrvFS): can't tell → assume fresh (conservative).
193        (None, None) => false,
194        // One side missing: metadata changed or appeared/disappeared → stale.
195        (Some(_), None) | (None, Some(_)) => true,
196        // `!=`, not `>`: a *backward* mtime (git checkout, touch -t, snapshot
197        // restore) is just as much a content change as a forward one.
198        (Some(cached), Some(current)) => current != cached,
199    }
200}
201
202/// Files larger than this are not content-hashed for stub verification; the
203/// mtime check alone decides. Keeps the stub fast-path O(small-file-read).
204const VERIFY_HASH_CAP_BYTES: u64 = 8 * 1024 * 1024;
205
206fn cache_verify_enabled() -> bool {
207    std::env::var("LEAN_CTX_CACHE_VERIFY").map_or(true, |v| v != "0")
208}
209
210/// Staleness with content verification: like [`is_cache_entry_stale`], but when
211/// the mtime claims "unchanged", additionally compares the md5 of the on-disk
212/// content against the cached hash.
213///
214/// mtime alone cannot be trusted for *correctness*: same-second writes are
215/// invisible on coarse-granularity filesystems (HFS+ 1s, FAT 2s) and mtimes can
216/// be restored by tools. Serving an `[unchanged]` stub for changed content
217/// would silently mislead the agent — the worst failure mode a context layer
218/// can have. The extra disk read costs microseconds for typical source files;
219/// the stub's token savings are unaffected. Opt out: `LEAN_CTX_CACHE_VERIFY=0`.
220///
221/// Note: entries whose stored content differs from disk by design (e.g. secret
222/// redaction) hash differently and therefore never serve stubs — conservative
223/// and correct.
224pub fn is_cache_entry_stale_verified(
225    path: &str,
226    cached_mtime: Option<SystemTime>,
227    cached_hash: &str,
228) -> bool {
229    let mtime_stale = is_cache_entry_stale(path, cached_mtime);
230
231    if !mtime_stale && (cached_hash.is_empty() || !cache_verify_enabled()) {
232        return false;
233    }
234
235    if cached_hash.is_empty() {
236        return mtime_stale;
237    }
238
239    let Ok(meta) = std::fs::metadata(path) else {
240        return true;
241    };
242    if meta.len() > VERIFY_HASH_CAP_BYTES {
243        return mtime_stale;
244    }
245    match std::fs::read(path) {
246        Ok(bytes) => compute_md5(&String::from_utf8_lossy(&bytes)) != cached_hash,
247        Err(_) => true,
248    }
249}
250pub(super) fn compute_md5(content: &str) -> String {
251    let mut hasher = Md5::new();
252    hasher.update(content.as_bytes());
253    crate::core::agent_identity::hex_encode(&hasher.finalize())
254}
255
256#[cfg(test)]
257mod tests {
258    use super::{
259        ReuseCounters, ReuseOutcome, ReuseSnapshot, record_ctx_read_outcome_into,
260        record_search_content_read_into, snapshot_from,
261    };
262
263    #[test]
264    fn every_read_records_one_exclusive_terminal_outcome() {
265        let counters = ReuseCounters::new();
266        record_ctx_read_outcome_into(&counters, ReuseOutcome::RenderCacheHit);
267        record_ctx_read_outcome_into(&counters, ReuseOutcome::UnchangedStub);
268        record_ctx_read_outcome_into(&counters, ReuseOutcome::FreshBypass);
269        record_ctx_read_outcome_into(&counters, ReuseOutcome::PolicyBypass);
270        record_search_content_read_into(&counters, true);
271        record_search_content_read_into(&counters, false);
272
273        let snapshot = snapshot_from(&counters);
274        assert_eq!(snapshot.render_cache_hits, 1);
275        assert_eq!(snapshot.unchanged_stubs, 1);
276        assert_eq!(snapshot.fresh_bypasses, 1);
277        assert_eq!(snapshot.policy_bypasses, 1);
278        assert_eq!(snapshot.disk_content_hits, 1);
279        assert_eq!(snapshot.cold, 1);
280        assert_eq!(snapshot.eligible_ctx_reads, 2);
281        assert_eq!(snapshot.reused_renderings, 2);
282        assert_eq!(snapshot.eligible_search_reads, 2);
283    }
284
285    #[test]
286    fn reuse_rates_keep_read_and_disk_denominators_separate() {
287        let metrics = ReuseSnapshot {
288            reused_renderings: 3,
289            eligible_ctx_reads: 4,
290            disk_content_hits: 2,
291            eligible_search_reads: 5,
292            ..ReuseSnapshot::default()
293        };
294
295        assert_eq!(metrics.read_reuse_rate(), 75.0);
296        assert_eq!(metrics.disk_reuse_rate(), 40.0);
297    }
298
299    #[test]
300    fn only_render_reuse_outcomes_count_for_ctx_read_reuse() {
301        assert!(ReuseOutcome::RenderCacheHit.is_render_reuse());
302        assert!(ReuseOutcome::UnchangedStub.is_render_reuse());
303        assert!(ReuseOutcome::CrossFileRef.is_render_reuse());
304        assert!(!ReuseOutcome::DiskContentHit.is_render_reuse());
305        assert!(!ReuseOutcome::FreshBypass.is_render_reuse());
306        assert!(!ReuseOutcome::Stale.is_render_reuse());
307    }
308
309    #[test]
310    fn bypasses_are_not_eligible_for_read_reuse() {
311        assert!(!ReuseOutcome::FreshBypass.is_ctx_read_eligible());
312        assert!(!ReuseOutcome::PolicyBypass.is_ctx_read_eligible());
313        assert!(ReuseOutcome::Stale.is_ctx_read_eligible());
314    }
315
316    #[test]
317    fn stale_mtime_but_same_hash_is_not_stale() {
318        use std::io::Write;
319        let dir = tempfile::tempdir().unwrap();
320        let p = dir.path().join("poll.txt");
321        std::fs::write(&p, "terminal output line 1").unwrap();
322
323        let mtime1 = std::fs::metadata(&p).unwrap().modified().unwrap();
324        let hash = super::compute_md5("terminal output line 1");
325
326        std::thread::sleep(std::time::Duration::from_millis(50));
327        {
328            let mut f = std::fs::OpenOptions::new()
329                .write(true)
330                .truncate(true)
331                .open(&p)
332                .unwrap();
333            f.write_all(b"terminal output line 1").unwrap();
334        }
335        let mtime2 = std::fs::metadata(&p).unwrap().modified().unwrap();
336        assert_ne!(mtime1, mtime2, "mtime must differ after rewrite");
337
338        let stale = super::is_cache_entry_stale_verified(p.to_str().unwrap(), Some(mtime1), &hash);
339        assert!(
340            !stale,
341            "same content with different mtime must NOT be stale"
342        );
343    }
344
345    #[test]
346    fn stale_mtime_with_changed_content_is_stale() {
347        let dir = tempfile::tempdir().unwrap();
348        let p = dir.path().join("changed.txt");
349        std::fs::write(&p, "version 1").unwrap();
350
351        let mtime1 = std::fs::metadata(&p).unwrap().modified().unwrap();
352        let hash = super::compute_md5("version 1");
353
354        std::thread::sleep(std::time::Duration::from_millis(50));
355        std::fs::write(&p, "version 2 with new content").unwrap();
356
357        let stale = super::is_cache_entry_stale_verified(p.to_str().unwrap(), Some(mtime1), &hash);
358        assert!(stale, "changed content must be stale");
359    }
360
361    #[test]
362    fn same_mtime_same_hash_is_not_stale() {
363        let dir = tempfile::tempdir().unwrap();
364        let p = dir.path().join("stable.txt");
365        std::fs::write(&p, "stable content").unwrap();
366
367        let mtime = std::fs::metadata(&p).unwrap().modified().unwrap();
368        let hash = super::compute_md5("stable content");
369
370        let stale = super::is_cache_entry_stale_verified(p.to_str().unwrap(), Some(mtime), &hash);
371        assert!(!stale, "unchanged file must not be stale");
372    }
373
374    #[test]
375    fn empty_hash_falls_back_to_mtime_only() {
376        let dir = tempfile::tempdir().unwrap();
377        let p = dir.path().join("nohash.txt");
378        std::fs::write(&p, "content").unwrap();
379
380        let mtime = std::fs::metadata(&p).unwrap().modified().unwrap();
381        assert!(
382            !super::is_cache_entry_stale_verified(p.to_str().unwrap(), Some(mtime), ""),
383            "same mtime + empty hash = not stale"
384        );
385
386        std::thread::sleep(std::time::Duration::from_millis(50));
387        std::fs::write(&p, "content").unwrap();
388        assert!(
389            super::is_cache_entry_stale_verified(p.to_str().unwrap(), Some(mtime), ""),
390            "different mtime + empty hash = stale (no hash to rescue)"
391        );
392    }
393
394    #[test]
395    fn large_file_uses_mtime_only() {
396        let dir = tempfile::tempdir().unwrap();
397        let p = dir.path().join("big.txt");
398        let big = "x".repeat(9 * 1024 * 1024);
399        std::fs::write(&p, &big).unwrap();
400
401        let mtime = std::fs::metadata(&p).unwrap().modified().unwrap();
402        let hash = super::compute_md5(&big);
403
404        assert!(
405            !super::is_cache_entry_stale_verified(p.to_str().unwrap(), Some(mtime), &hash),
406            "same mtime on large file = not stale"
407        );
408
409        std::thread::sleep(std::time::Duration::from_millis(50));
410        std::fs::write(&p, &big).unwrap();
411        assert!(
412            super::is_cache_entry_stale_verified(p.to_str().unwrap(), Some(mtime), &hash),
413            "large files skip hash check even if content matches"
414        );
415    }
416
417    #[test]
418    fn deleted_file_is_stale() {
419        let dir = tempfile::tempdir().unwrap();
420        let p = dir.path().join("ephemeral.txt");
421        std::fs::write(&p, "temp").unwrap();
422
423        let mtime = std::fs::metadata(&p).unwrap().modified().unwrap();
424        let hash = super::compute_md5("temp");
425
426        std::fs::remove_file(&p).unwrap();
427
428        assert!(
429            super::is_cache_entry_stale_verified(p.to_str().unwrap(), Some(mtime), &hash),
430            "deleted file must be stale"
431        );
432    }
433
434    #[test]
435    fn empty_file_hash_matches_correctly() {
436        let dir = tempfile::tempdir().unwrap();
437        let p = dir.path().join("empty.txt");
438        std::fs::write(&p, "").unwrap();
439
440        let mtime = std::fs::metadata(&p).unwrap().modified().unwrap();
441        let hash = super::compute_md5("");
442
443        std::thread::sleep(std::time::Duration::from_millis(50));
444        std::fs::write(&p, "").unwrap();
445
446        assert!(
447            !super::is_cache_entry_stale_verified(p.to_str().unwrap(), Some(mtime), &hash),
448            "empty file rewritten with same content must not be stale"
449        );
450    }
451
452    #[test]
453    fn rapid_touch_cycles_stay_cached() {
454        let dir = tempfile::tempdir().unwrap();
455        let p = dir.path().join("rapid.txt");
456        let content = "rapid polling content that stays stable";
457        std::fs::write(&p, content).unwrap();
458
459        let mtime_initial = std::fs::metadata(&p).unwrap().modified().unwrap();
460        let hash = super::compute_md5(content);
461
462        for _ in 0..10 {
463            std::thread::sleep(std::time::Duration::from_millis(10));
464            std::fs::write(&p, content).unwrap();
465
466            let stale = super::is_cache_entry_stale_verified(
467                p.to_str().unwrap(),
468                Some(mtime_initial),
469                &hash,
470            );
471            assert!(
472                !stale,
473                "repeated rewrites of same content must never be stale"
474            );
475        }
476    }
477
478    #[test]
479    fn binary_content_hash_works() {
480        let dir = tempfile::tempdir().unwrap();
481        let p = dir.path().join("binary.bin");
482        let data: Vec<u8> = (0..=255).collect();
483        std::fs::write(&p, &data).unwrap();
484
485        let mtime = std::fs::metadata(&p).unwrap().modified().unwrap();
486        let hash = super::compute_md5(&String::from_utf8_lossy(&data));
487
488        std::thread::sleep(std::time::Duration::from_millis(50));
489        std::fs::write(&p, &data).unwrap();
490
491        assert!(
492            !super::is_cache_entry_stale_verified(p.to_str().unwrap(), Some(mtime), &hash),
493            "binary content with same bytes must not be stale"
494        );
495
496        let mut changed = data.clone();
497        changed[100] = 0;
498        std::fs::write(&p, &changed).unwrap();
499        assert!(
500            super::is_cache_entry_stale_verified(p.to_str().unwrap(), Some(mtime), &hash),
501            "binary content with 1 byte changed must be stale"
502        );
503    }
504}