Skip to main content

lean_ctx/core/cache/
entry.rs

1use std::collections::HashMap;
2use std::sync::OnceLock;
3use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
4use std::time::{Duration, Instant, SystemTime};
5
6/// Process-global monotonic base for encoding `Instant`s into an `AtomicU64`.
7/// Stored as milliseconds since this base, which is sufficient resolution for
8/// LRU/RRF eviction recency while allowing lock-free access on cache hits.
9fn instant_base() -> Instant {
10    static BASE: OnceLock<Instant> = OnceLock::new();
11    *BASE.get_or_init(Instant::now)
12}
13
14fn encode_instant(i: Instant) -> u64 {
15    i.saturating_duration_since(instant_base()).as_millis() as u64
16}
17
18fn decode_instant(ms: u64) -> Instant {
19    instant_base() + Duration::from_millis(ms)
20}
21
22pub(super) fn normalize_key(path: &str) -> String {
23    crate::core::pathutil::normalize_tool_path(path)
24}
25
26/// Built-in default token budget for the in-memory read cache.
27/// 2M covers ~100 typical source files, reducing premature eviction
28/// before re-reads occur. RAM-pressure eviction via EvictionOrchestrator
29/// provides an independent safety net regardless of this budget.
30pub(crate) const DEFAULT_CACHE_MAX_TOKENS: usize = 2_000_000;
31
32/// Pure resolver for the read-cache token budget. `env` (the raw
33/// `LEAN_CTX_CACHE_MAX_TOKENS` value) wins when it parses to a positive integer,
34/// then the `configured` `[core] cache_max_tokens`, else
35/// [`DEFAULT_CACHE_MAX_TOKENS`]. A `0` (or unparseable env) in either source
36/// means "use the default". Split out so the precedence is unit-testable without
37/// touching the global env or config.
38pub(super) fn resolve_cache_max_tokens(env: Option<&str>, configured: usize) -> usize {
39    if let Some(raw) = env
40        && let Ok(n) = raw.trim().parse::<usize>()
41        && n > 0
42    {
43        return n;
44    }
45    if configured > 0 {
46        configured
47    } else {
48        DEFAULT_CACHE_MAX_TOKENS
49    }
50}
51
52/// Resolved token budget for the read cache. `LEAN_CTX_CACHE_MAX_TOKENS` wins
53/// (env-first keeps the hot eviction path cheap for power users), then
54/// `[core] cache_max_tokens` in config.toml, else [`DEFAULT_CACHE_MAX_TOKENS`].
55/// Shared with `eviction_orchestrator` so both eviction rails read one budget.
56pub(crate) fn max_cache_tokens() -> usize {
57    resolve_cache_max_tokens(
58        std::env::var("LEAN_CTX_CACHE_MAX_TOKENS").ok().as_deref(),
59        crate::core::config::Config::load().cache_max_tokens,
60    )
61}
62
63/// A cached file read: zstd-compressed content, hash, token count, and access metadata.
64///
65/// `read_count` and `last_access` use interior mutability (atomics) so cache
66/// hits can be recorded under a shared (read) lock — parallel reads of distinct
67/// files no longer serialize on a global write lock.
68#[derive(Debug)]
69pub struct CacheEntry {
70    pub(super) compressed_content: Vec<u8>,
71    pub hash: String,
72    pub line_count: usize,
73    pub original_tokens: usize,
74    read_count: AtomicU32,
75    pub path: String,
76    last_access: AtomicU64,
77    pub stored_mtime: Option<SystemTime>,
78    /// Mode-specific compressed outputs (e.g. "map", "signatures") cached to avoid re-parsing.
79    pub compressed_outputs: HashMap<String, String>,
80    /// Whether full (uncompressed) content was already delivered for this hash.
81    /// Prevents cache-stub loops when upgrading from compressed to full mode.
82    pub full_content_delivered: bool,
83    /// Conversation id that received the full content (see
84    /// [`crate::core::conversation`]). The `[unchanged]` stub is only valid for
85    /// a re-read from this same conversation; `None` means delivered without a
86    /// known conversation context (legacy / hooks absent).
87    pub delivered_conversation: Option<String>,
88    /// Last read mode used for this file (for auto-escalation on edit failure).
89    pub last_mode: String,
90}
91
92const ZSTD_LEVEL: i32 = 3;
93
94fn zstd_compress(data: &str) -> Vec<u8> {
95    zstd::encode_all(data.as_bytes(), ZSTD_LEVEL).unwrap_or_else(|_| data.as_bytes().to_vec())
96}
97
98fn zstd_decompress(data: &[u8]) -> Option<String> {
99    zstd::decode_all(data)
100        .ok()
101        .and_then(|v| String::from_utf8(v).ok())
102}
103
104impl CacheEntry {
105    /// Creates a new entry with zstd-compressed content.
106    pub fn new(
107        content: &str,
108        hash: String,
109        line_count: usize,
110        original_tokens: usize,
111        path: String,
112        stored_mtime: Option<SystemTime>,
113    ) -> Self {
114        let compressed_content = zstd_compress(content);
115        Self {
116            compressed_content,
117            hash,
118            line_count,
119            original_tokens,
120            read_count: AtomicU32::new(1),
121            path,
122            last_access: AtomicU64::new(encode_instant(Instant::now())),
123            stored_mtime,
124            compressed_outputs: HashMap::new(),
125            full_content_delivered: false,
126            delivered_conversation: None,
127            last_mode: String::new(),
128        }
129    }
130
131    /// Current read count (lock-free).
132    pub fn read_count(&self) -> u32 {
133        self.read_count.load(Ordering::Relaxed)
134    }
135
136    /// Atomically increments the read count and returns the new value (lock-free).
137    pub fn bump_read_count(&self) -> u32 {
138        self.read_count.fetch_add(1, Ordering::Relaxed) + 1
139    }
140
141    /// Overwrites the read count (used by `store` and tests).
142    pub fn set_read_count(&self, n: u32) {
143        self.read_count.store(n, Ordering::Relaxed);
144    }
145
146    /// Last access time, decoded from the atomic millisecond offset.
147    pub fn last_access(&self) -> Instant {
148        decode_instant(self.last_access.load(Ordering::Relaxed))
149    }
150
151    /// Marks the entry as accessed now (lock-free).
152    pub fn touch(&self) {
153        self.last_access
154            .store(encode_instant(Instant::now()), Ordering::Relaxed);
155    }
156
157    /// Overwrites the last-access time (used by tests and eviction setup).
158    pub fn set_last_access(&self, when: Instant) {
159        self.last_access
160            .store(encode_instant(when), Ordering::Relaxed);
161    }
162
163    /// Decompresses and returns the full file content.
164    pub fn content(&self) -> Option<String> {
165        zstd_decompress(&self.compressed_content)
166    }
167
168    /// Replaces the stored content with new zstd-compressed data.
169    pub fn set_content(&mut self, content: &str) {
170        self.compressed_content = zstd_compress(content);
171    }
172
173    /// Approximate RAM usage of the compressed content in bytes.
174    pub fn compressed_size(&self) -> usize {
175        self.compressed_content.len()
176    }
177}
178
179/// Result of a cache store operation, indicating whether it was a hit or new entry.
180#[derive(Debug, Clone)]
181pub struct StoreResult {
182    pub line_count: usize,
183    pub original_tokens: usize,
184    pub read_count: u32,
185    pub was_hit: bool,
186    /// Whether full content was previously delivered for this cache entry.
187    pub full_content_delivered: bool,
188}
189
190impl CacheEntry {
191    /// Computes a legacy eviction score blending recency, frequency, and size.
192    pub fn eviction_score_legacy(&self, now: Instant) -> f64 {
193        let elapsed = now
194            .checked_duration_since(self.last_access())
195            .unwrap_or_default()
196            .as_secs_f64();
197        let recency = 1.0 / (1.0 + elapsed.sqrt());
198        let frequency = (self.read_count() as f64 + 1.0).ln();
199        let size_value = (self.original_tokens as f64 + 1.0).ln();
200        recency * 0.4 + frequency * 0.3 + size_value * 0.3
201    }
202
203    pub fn get_compressed(&self, mode_key: &str) -> Option<&String> {
204        self.compressed_outputs.get(mode_key)
205    }
206
207    pub fn set_compressed(&mut self, mode_key: &str, output: String) {
208        const MAX_COMPRESSED_VARIANTS: usize = 3;
209        if self.compressed_outputs.len() >= MAX_COMPRESSED_VARIANTS
210            && !self.compressed_outputs.contains_key(mode_key)
211            && let Some(oldest_key) = self.compressed_outputs.keys().next().cloned()
212        {
213            self.compressed_outputs.remove(&oldest_key);
214        }
215        self.compressed_outputs.insert(mode_key.to_string(), output);
216    }
217
218    pub fn mark_full_delivered(&mut self, conversation: Option<String>) {
219        self.full_content_delivered = true;
220        self.delivered_conversation = conversation;
221    }
222}
223
224const RRF_K: f64 = 60.0;
225
226/// Hebbian protection added to an entry's RRF eviction score per unit of
227/// association strength with the currently-active working set (#3). Files that
228/// are read together resist eviction together ("fire together, wire together").
229/// Deterministic: a fixed multiplier, no sampling.
230pub(super) const HEBBIAN_PROTECT_WEIGHT: f64 = 0.05;
231/// Size of the "active working set" (most-recently-accessed entries) against
232/// which Hebbian association is measured during eviction.
233pub(super) const HEBBIAN_ACTIVE_SET: usize = 8;
234
235/// Compute Reciprocal Rank Fusion eviction scores for a batch of cache entries.
236/// Each signal (recency, frequency, size) produces an independent ranking.
237/// The final score is the sum of `1/(k + rank)` across all signals.
238/// Higher score = more valuable = keep longer.
239pub fn eviction_scores_rrf(entries: &[(&String, &CacheEntry)], now: Instant) -> Vec<(String, f64)> {
240    if entries.is_empty() {
241        return Vec::new();
242    }
243
244    let n = entries.len();
245
246    let mut recency_order: Vec<usize> = (0..n).collect();
247    recency_order.sort_by(|&a, &b| {
248        let elapsed_a = now
249            .checked_duration_since(entries[a].1.last_access())
250            .unwrap_or_default()
251            .as_secs_f64();
252        let elapsed_b = now
253            .checked_duration_since(entries[b].1.last_access())
254            .unwrap_or_default()
255            .as_secs_f64();
256        elapsed_a
257            .partial_cmp(&elapsed_b)
258            .unwrap_or(std::cmp::Ordering::Equal)
259    });
260
261    let mut frequency_order: Vec<usize> = (0..n).collect();
262    frequency_order.sort_by(|&a, &b| entries[b].1.read_count().cmp(&entries[a].1.read_count()));
263
264    let mut size_order: Vec<usize> = (0..n).collect();
265    size_order.sort_by(|&a, &b| {
266        entries[b]
267            .1
268            .original_tokens
269            .cmp(&entries[a].1.original_tokens)
270    });
271
272    let mut recency_ranks = vec![0usize; n];
273    let mut frequency_ranks = vec![0usize; n];
274    let mut size_ranks = vec![0usize; n];
275
276    for (rank, &idx) in recency_order.iter().enumerate() {
277        recency_ranks[idx] = rank;
278    }
279    for (rank, &idx) in frequency_order.iter().enumerate() {
280        frequency_ranks[idx] = rank;
281    }
282    for (rank, &idx) in size_order.iter().enumerate() {
283        size_ranks[idx] = rank;
284    }
285
286    entries
287        .iter()
288        .enumerate()
289        .map(|(i, (path, _))| {
290            let score = 1.0 / (RRF_K + recency_ranks[i] as f64)
291                + 1.0 / (RRF_K + frequency_ranks[i] as f64)
292                + 1.0 / (RRF_K + size_ranks[i] as f64);
293            ((*path).clone(), score)
294        })
295        .collect()
296}
297
298/// Add the Hebbian co-access bonus (#3) to RRF eviction scores in place. A
299/// higher score means "keep longer", so co-accessed entries are protected.
300pub(super) fn apply_hebbian_bonus(scores: &mut [(String, f64)], bonus: &HashMap<String, f64>) {
301    if bonus.is_empty() {
302        return;
303    }
304    for s in scores.iter_mut() {
305        if let Some(b) = bonus.get(&s.0) {
306            s.1 += *b;
307        }
308    }
309}
310
311/// Aggregated cache statistics: hits, reads, and token savings.
312///
313/// Counters are atomic so they can be updated on the read-locked cache-hit
314/// fast path without taking a write lock.
315#[derive(Debug, Default)]
316pub struct CacheStats {
317    pub(super) total_reads: AtomicU64,
318    pub(super) cache_hits: AtomicU64,
319    pub(super) total_original_tokens: AtomicU64,
320    pub(super) total_sent_tokens: AtomicU64,
321    pub(super) files_tracked: AtomicU64,
322}
323
324impl CacheStats {
325    /// Total number of read operations recorded.
326    pub fn total_reads(&self) -> u64 {
327        self.total_reads.load(Ordering::Relaxed)
328    }
329
330    /// Total number of cache hits recorded.
331    pub fn cache_hits(&self) -> u64 {
332        self.cache_hits.load(Ordering::Relaxed)
333    }
334
335    /// Sum of original (uncompressed) token counts across all reads.
336    pub fn total_original_tokens(&self) -> u64 {
337        self.total_original_tokens.load(Ordering::Relaxed)
338    }
339
340    /// Sum of tokens actually sent to the model.
341    pub fn total_sent_tokens(&self) -> u64 {
342        self.total_sent_tokens.load(Ordering::Relaxed)
343    }
344
345    /// Number of distinct files currently tracked.
346    pub fn files_tracked(&self) -> u64 {
347        self.files_tracked.load(Ordering::Relaxed)
348    }
349
350    /// Returns the cache hit rate as a percentage (0–100).
351    pub fn hit_rate(&self) -> f64 {
352        let total = self.total_reads();
353        if total == 0 {
354            return 0.0;
355        }
356        (self.cache_hits() as f64 / total as f64) * 100.0
357    }
358
359    /// Returns the total number of tokens saved by cache hits.
360    pub fn tokens_saved(&self) -> u64 {
361        self.total_original_tokens()
362            .saturating_sub(self.total_sent_tokens())
363    }
364
365    /// Returns the savings as a percentage of total original tokens.
366    pub fn savings_percent(&self) -> f64 {
367        let original = self.total_original_tokens();
368        if original == 0 {
369            return 0.0;
370        }
371        (self.tokens_saved() as f64 / original as f64) * 100.0
372    }
373}
374
375/// A block shared across multiple files, identified by its canonical source.
376#[derive(Clone, Debug)]
377pub struct SharedBlock {
378    pub canonical_path: String,
379    pub canonical_ref: String,
380    pub start_line: usize,
381    pub end_line: usize,
382    pub content: String,
383}