lean_ctx/core/cache/
entry.rs1use std::collections::HashMap;
2use std::sync::OnceLock;
3use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
4use std::time::{Duration, Instant, SystemTime};
5
6fn 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
26pub(crate) const DEFAULT_CACHE_MAX_TOKENS: usize = 2_000_000;
31
32pub(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
52pub(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#[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 pub compressed_outputs: HashMap<String, String>,
80 pub full_content_delivered: bool,
83 pub delivered_conversation: Option<String>,
88 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 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 pub fn read_count(&self) -> u32 {
133 self.read_count.load(Ordering::Relaxed)
134 }
135
136 pub fn bump_read_count(&self) -> u32 {
138 self.read_count.fetch_add(1, Ordering::Relaxed) + 1
139 }
140
141 pub fn set_read_count(&self, n: u32) {
143 self.read_count.store(n, Ordering::Relaxed);
144 }
145
146 pub fn last_access(&self) -> Instant {
148 decode_instant(self.last_access.load(Ordering::Relaxed))
149 }
150
151 pub fn touch(&self) {
153 self.last_access
154 .store(encode_instant(Instant::now()), Ordering::Relaxed);
155 }
156
157 pub fn set_last_access(&self, when: Instant) {
159 self.last_access
160 .store(encode_instant(when), Ordering::Relaxed);
161 }
162
163 pub fn content(&self) -> Option<String> {
165 zstd_decompress(&self.compressed_content)
166 }
167
168 pub fn set_content(&mut self, content: &str) {
170 self.compressed_content = zstd_compress(content);
171 }
172
173 pub fn compressed_size(&self) -> usize {
175 self.compressed_content.len()
176 }
177}
178
179#[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 pub full_content_delivered: bool,
188}
189
190impl CacheEntry {
191 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
226pub(super) const HEBBIAN_PROTECT_WEIGHT: f64 = 0.05;
231pub(super) const HEBBIAN_ACTIVE_SET: usize = 8;
234
235pub 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
298pub(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#[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 pub fn total_reads(&self) -> u64 {
327 self.total_reads.load(Ordering::Relaxed)
328 }
329
330 pub fn cache_hits(&self) -> u64 {
332 self.cache_hits.load(Ordering::Relaxed)
333 }
334
335 pub fn total_original_tokens(&self) -> u64 {
337 self.total_original_tokens.load(Ordering::Relaxed)
338 }
339
340 pub fn total_sent_tokens(&self) -> u64 {
342 self.total_sent_tokens.load(Ordering::Relaxed)
343 }
344
345 pub fn files_tracked(&self) -> u64 {
347 self.files_tracked.load(Ordering::Relaxed)
348 }
349
350 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 pub fn tokens_saved(&self) -> u64 {
361 self.total_original_tokens()
362 .saturating_sub(self.total_sent_tokens())
363 }
364
365 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#[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}