Skip to main content

lean_ctx/core/cache/
session.rs

1use std::collections::HashMap;
2use std::sync::atomic::Ordering;
3use std::time::Instant;
4
5use super::entry::{
6    CacheEntry, CacheStats, HEBBIAN_ACTIVE_SET, HEBBIAN_PROTECT_WEIGHT, SharedBlock, StoreResult,
7    apply_hebbian_bonus, eviction_scores_rrf, max_cache_tokens, normalize_key,
8};
9use super::validation::{compute_md5, is_cache_entry_stale_verified};
10use crate::core::tokens::count_tokens;
11
12/// #1287: delivery state of one compressed render variant. `Absent` = no such
13/// variant cached; `UnknownConversation` = stored without a resolvable
14/// conversation id (the variant stub must not be served — unknown delivery is
15/// never treated as "stub allowed"); `Conversation` = provably delivered to
16/// that conversation.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum VariantDelivery {
19    Absent,
20    UnknownConversation,
21    Conversation(String),
22}
23
24pub(crate) const DEFAULT_FULL_DEGRADATION_THRESHOLD: u32 = 2;
25
26pub(crate) fn full_degradation_threshold() -> u32 {
27    std::env::var("LCTX_FULL_DEGRADATION_THRESHOLD")
28        .ok()
29        .and_then(|value| value.trim().parse().ok())
30        .filter(|&threshold| threshold > 0)
31        .unwrap_or(DEFAULT_FULL_DEGRADATION_THRESHOLD)
32}
33
34/// In-memory file cache with segmented LRU eviction (probationary vs protected),
35/// file references, and cross-file dedup.
36pub struct SessionCache {
37    entries: HashMap<String, CacheEntry>,
38    file_refs: HashMap<String, String>,
39    next_ref: usize,
40    stats: CacheStats,
41    shared_blocks: Vec<SharedBlock>,
42    /// Hebbian co-access matrix (#3): tracks which files are read together so
43    /// eviction can protect co-accessed clusters. Updated on `store`, consulted
44    /// during eviction.
45    co_access: crate::core::hebbian_cache::CoAccessMatrix,
46}
47
48impl Default for SessionCache {
49    fn default() -> Self {
50        Self::new()
51    }
52}
53
54impl SessionCache {
55    /// Creates an empty session cache with default stats.
56    pub fn new() -> Self {
57        Self {
58            entries: HashMap::new(),
59            file_refs: HashMap::new(),
60            next_ref: 1,
61            shared_blocks: Vec::new(),
62            stats: CacheStats::default(),
63            co_access: crate::core::hebbian_cache::CoAccessMatrix::new(),
64        }
65    }
66
67    /// Record that `path` was accessed, strengthening its Hebbian association
68    /// with other files read in the same burst window (#3). Called on every
69    /// `store`; co-access boundaries are flushed via `flush_co_access`.
70    pub fn record_co_access(&mut self, path: &str) {
71        let key = normalize_key(path);
72        self.co_access
73            .record_access(crate::core::hebbian_cache::path_hash(&key));
74    }
75
76    /// Close the current co-access burst so its associations are committed.
77    /// Call at the end of a logical tool call (post-dispatch).
78    pub fn flush_co_access(&mut self) {
79        self.co_access.end_burst();
80    }
81
82    /// Widen the co-access burst window. Test-only: lets a test keep several
83    /// `store()` calls in one burst without depending on them landing inside
84    /// the real-time 500ms window (a scheduling-jitter flake under parallel
85    /// test execution).
86    #[cfg(test)]
87    pub fn set_co_access_burst_window(&mut self, window: std::time::Duration) {
88        self.co_access.set_burst_window(window);
89    }
90
91    /// Per-entry Hebbian eviction bonus (#3): each cached entry that is
92    /// co-accessed with the recently-active working set earns a positive bonus
93    /// that is added to its RRF score, so clustered files survive eviction
94    /// together. Deterministic (no sampling); ticks the activation registry when
95    /// any association actually influences the decision.
96    pub(crate) fn hebbian_eviction_bonus(&self) -> HashMap<String, f64> {
97        use crate::core::hebbian_cache::path_hash;
98        if self.entries.is_empty() {
99            return HashMap::new();
100        }
101        let mut by_recency: Vec<(&String, Instant)> = self
102            .entries
103            .iter()
104            .map(|(k, e)| (k, e.last_access()))
105            .collect();
106        by_recency.sort_by_key(|(_, t)| std::cmp::Reverse(*t));
107        let active: Vec<u64> = by_recency
108            .iter()
109            .take(HEBBIAN_ACTIVE_SET)
110            .map(|(k, _)| path_hash(k))
111            .collect();
112
113        let mut out = HashMap::new();
114        for k in self.entries.keys() {
115            let h = path_hash(k);
116            // Exclude self so an entry never "protects itself".
117            let peers: Vec<u64> = active.iter().copied().filter(|&a| a != h).collect();
118            let strength = self.co_access.association_strength(h, &peers);
119            if strength > 0.0 {
120                out.insert(k.clone(), f64::from(strength) * HEBBIAN_PROTECT_WEIGHT);
121            }
122        }
123        if !out.is_empty() {
124            crate::core::introspect::tick("hebbian_cache");
125        }
126        out
127    }
128
129    /// Returns or assigns a short file reference label (F1, F2, ...) for the given path.
130    pub fn get_file_ref(&mut self, path: &str) -> String {
131        let key = normalize_key(path);
132        if let Some(r) = self.file_refs.get(&key) {
133            return r.clone();
134        }
135        let r = format!("F{}", self.next_ref);
136        self.next_ref += 1;
137        self.file_refs.insert(key, r.clone());
138        r
139    }
140
141    /// Returns the file reference label for a path without assigning a new one.
142    pub fn get_file_ref_readonly(&self, path: &str) -> Option<String> {
143        self.file_refs.get(&normalize_key(path)).cloned()
144    }
145
146    /// Looks up a cached entry by file path.
147    pub fn get(&self, path: &str) -> Option<&CacheEntry> {
148        self.entries.get(&normalize_key(path))
149    }
150
151    /// Mutable lookup of a cached entry by file path.
152    pub fn get_mut(&mut self, path: &str) -> Option<&mut CacheEntry> {
153        self.entries.get_mut(&normalize_key(path))
154    }
155
156    /// Retrieves the full (uncompressed) content for a file path, if cached.
157    /// Used by the CCR (Compress-Cache-Retrieve) mechanism.
158    pub fn get_full_content(&self, path: &str) -> Option<String> {
159        self.entries
160            .get(&normalize_key(path))
161            .and_then(CacheEntry::content)
162    }
163
164    /// Staleness-safe accessor for the *current* full content and its token
165    /// count: returns the cached copy when it is still fresh, or a fresh disk
166    /// re-read when the cached copy is stale (mtime/hash changed since it was
167    /// cached). Returns `None` when there is no cache entry, or the entry is
168    /// stale and the file can no longer be read.
169    ///
170    /// Cross-agent / retrieve paths (`ctx_retrieve`, `ctx_share`) MUST use this
171    /// instead of [`get_full_content`](Self::get_full_content): serving the raw
172    /// cached copy hands an agent a version that may no longer match disk — e.g.
173    /// a handover file edited between two agents — silently feeding it stale
174    /// context. Validation uses the entry's stored absolute `path`, because a
175    /// caller's `path` may be relative and resolve against a different CWD.
176    pub fn current_full_content(&self, path: &str) -> Option<(String, usize)> {
177        let entry = self.entries.get(&normalize_key(path))?;
178        if is_cache_entry_stale_verified(&entry.path, entry.stored_mtime, &entry.hash)
179            && let Ok(fresh) = crate::core::io_boundary::read_file_lossy(&entry.path)
180        {
181            // Cache is behind disk → serve the current bytes. If the file is now
182            // unreadable (deleted/permission), fall through to the cached copy:
183            // last-known content beats nothing, and that fall-through is not the
184            // staleness bug (it only fires when there is no current content).
185            let tokens = count_tokens(&fresh);
186            return Some((fresh, tokens));
187        }
188        Some((entry.content()?, entry.original_tokens))
189    }
190
191    /// Records a cache hit, updates access stats, and emits a cache-hit event.
192    ///
193    /// Takes `&self`: the hit counters use interior-mutable atomics, so this
194    /// runs under a shared (read) lock and lets parallel reads of different
195    /// files proceed concurrently instead of serializing on a write lock.
196    pub fn record_cache_hit(&self, path: &str) -> Option<&CacheEntry> {
197        let key = normalize_key(path);
198        let ref_label = self
199            .file_refs
200            .get(&key)
201            .cloned()
202            .unwrap_or_else(|| "F?".to_string());
203        let entry = self.entries.get(&key)?;
204        let new_count = entry.bump_read_count();
205        entry.touch();
206        self.stats.total_reads.fetch_add(1, Ordering::Relaxed);
207        self.stats.cache_hits.fetch_add(1, Ordering::Relaxed);
208        self.stats
209            .total_original_tokens
210            .fetch_add(entry.original_tokens as u64, Ordering::Relaxed);
211        let hit_msg = format!("{ref_label} cached {new_count}t {}L", entry.line_count);
212        let sent_tokens = count_tokens(&hit_msg) as u64;
213        self.stats
214            .total_sent_tokens
215            .fetch_add(sent_tokens, Ordering::Relaxed);
216        crate::core::events::emit_cache_hit(
217            path,
218            (entry.original_tokens as u64).saturating_sub(sent_tokens),
219        );
220        Some(entry)
221    }
222
223    /// Stores file content in the cache; returns a hit if content hash matches.
224    pub fn store(&mut self, path: &str, content: &str) -> StoreResult {
225        let key = normalize_key(path);
226        // #3: feed the Hebbian co-access matrix on every read so eviction can
227        // later protect files that are habitually read together.
228        self.co_access
229            .record_access(crate::core::hebbian_cache::path_hash(&key));
230        let hash = compute_md5(content);
231        let line_count = content.lines().count();
232        let original_tokens = count_tokens(content);
233        let stored_mtime = std::fs::metadata(path).and_then(|m| m.modified()).ok();
234        let now = Instant::now();
235
236        self.stats.total_reads.fetch_add(1, Ordering::Relaxed);
237        self.stats
238            .total_original_tokens
239            .fetch_add(original_tokens as u64, Ordering::Relaxed);
240
241        if let Some(existing) = self.entries.get_mut(&key) {
242            existing.set_last_access(now);
243            if stored_mtime.is_some() {
244                existing.stored_mtime = stored_mtime;
245            }
246            if existing.hash == hash {
247                let new_count = existing.bump_read_count();
248                self.stats.cache_hits.fetch_add(1, Ordering::Relaxed);
249                let hit_msg = format!(
250                    "{} cached {new_count}t {}L",
251                    self.file_refs.get(&key).unwrap_or(&"F?".to_string()),
252                    existing.line_count,
253                );
254                let sent_tokens = count_tokens(&hit_msg) as u64;
255                self.stats
256                    .total_sent_tokens
257                    .fetch_add(sent_tokens, Ordering::Relaxed);
258                return StoreResult {
259                    line_count: existing.line_count,
260                    original_tokens: existing.original_tokens,
261                    read_count: new_count,
262                    was_hit: true,
263                    full_content_delivered: existing.full_content_delivered,
264                };
265            }
266            existing.clear_compressed_outputs();
267            existing.set_content(content);
268            existing.hash = hash;
269            existing.line_count = line_count;
270            existing.original_tokens = original_tokens;
271            let new_count = existing.bump_read_count();
272            existing.full_content_delivered = false;
273            existing.delivered_conversation = None;
274            existing.last_mode.clear();
275            if stored_mtime.is_some() {
276                existing.stored_mtime = stored_mtime;
277            }
278            self.stats
279                .total_sent_tokens
280                .fetch_add(original_tokens as u64, Ordering::Relaxed);
281            return StoreResult {
282                line_count,
283                original_tokens,
284                read_count: new_count,
285                was_hit: false,
286                full_content_delivered: false,
287            };
288        }
289
290        self.evict_if_needed(original_tokens);
291        self.get_file_ref(&key);
292
293        let entry = CacheEntry::new(
294            content,
295            hash,
296            line_count,
297            original_tokens,
298            key.clone(),
299            stored_mtime,
300        );
301
302        self.entries.insert(key, entry);
303        self.stats.files_tracked.fetch_add(1, Ordering::Relaxed);
304        self.stats
305            .total_sent_tokens
306            .fetch_add(original_tokens as u64, Ordering::Relaxed);
307        StoreResult {
308            line_count,
309            original_tokens,
310            read_count: 1,
311            was_hit: false,
312            full_content_delivered: false,
313        }
314    }
315
316    /// Returns the sum of original token counts across all cached entries.
317    pub fn total_cached_tokens(&self) -> usize {
318        self.entries.values().map(|e| e.original_tokens).sum()
319    }
320
321    /// Evict until cache fits within token budget using RRF (Reciprocal Rank Fusion).
322    /// Combines recency, frequency, and size signals to evict least-valuable entries first.
323    pub fn evict_if_needed(&mut self, incoming_tokens: usize) {
324        let max_tokens = max_cache_tokens();
325        let current = self.total_cached_tokens();
326        if current + incoming_tokens <= max_tokens {
327            return;
328        }
329
330        let now = Instant::now();
331        let all: Vec<(&String, &CacheEntry)> = self.entries.iter().collect();
332        let mut scores = eviction_scores_rrf(&all, now);
333        apply_hebbian_bonus(&mut scores, &self.hebbian_eviction_bonus());
334        // Sort ascending: lowest RRF score = least valuable = evict first
335        scores.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
336
337        let mut freed = 0usize;
338        let mut redelivered = 0u64;
339        let target = (current + incoming_tokens).saturating_sub(max_tokens);
340
341        for (path, _score) in &scores {
342            if freed >= target {
343                break;
344            }
345            if let Some(entry) = self.entries.remove(path) {
346                freed += entry.original_tokens;
347                if entry.full_content_delivered {
348                    redelivered += 1;
349                }
350                self.file_refs.remove(path);
351            }
352        }
353        crate::core::cache_telemetry::record_eviction(redelivered);
354    }
355
356    /// Returns all cached entries as (path, entry) pairs.
357    pub fn get_all_entries(&self) -> Vec<(&String, &CacheEntry)> {
358        self.entries.iter().collect()
359    }
360
361    /// Returns a reference to the aggregated cache statistics.
362    pub fn get_stats(&self) -> &CacheStats {
363        &self.stats
364    }
365
366    /// Returns the path-to-file-ref mapping (e.g. "/src/main.rs" → "F1").
367    pub fn file_ref_map(&self) -> &HashMap<String, String> {
368        &self.file_refs
369    }
370
371    /// Replaces the cross-file shared blocks used for deduplication.
372    pub fn set_shared_blocks(&mut self, blocks: Vec<SharedBlock>) {
373        self.shared_blocks = blocks;
374    }
375
376    /// Returns the current set of cross-file shared blocks.
377    pub fn get_shared_blocks(&self) -> &[SharedBlock] {
378        &self.shared_blocks
379    }
380
381    /// Replace shared blocks in content with cross-file references.
382    pub fn apply_dedup(&self, path: &str, content: &str) -> Option<String> {
383        if self.shared_blocks.is_empty() {
384            return None;
385        }
386        let refs: Vec<&SharedBlock> = self
387            .shared_blocks
388            .iter()
389            .filter(|b| b.canonical_path != path && content.contains(&b.content))
390            .collect();
391        if refs.is_empty() {
392            return None;
393        }
394        let mut result = content.to_string();
395        for block in refs {
396            result = result.replacen(
397                &block.content,
398                &format!(
399                    "[= {}:{}-{}]",
400                    block.canonical_ref, block.start_line, block.end_line
401                ),
402                1,
403            );
404        }
405        Some(result)
406    }
407
408    /// Removes a file from the cache, forcing a fresh read on next access.
409    pub fn invalidate(&mut self, path: &str) -> bool {
410        self.entries.remove(&normalize_key(path)).is_some()
411    }
412
413    /// #1287: which conversation first received the given compressed variant,
414    /// WITHOUT recording hit statistics — the caller decides between stub and
415    /// payload delivery and records accordingly.
416    pub fn compressed_delivered_conversation(&self, path: &str, mode_key: &str) -> VariantDelivery {
417        match self
418            .entries
419            .get(&normalize_key(path))
420            .and_then(|entry| entry.compressed_delivered_conversation(mode_key))
421        {
422            None => VariantDelivery::Absent,
423            Some(None) => VariantDelivery::UnknownConversation,
424            Some(Some(conversation)) => VariantDelivery::Conversation(conversation.to_string()),
425        }
426    }
427
428    /// Returns a cached compressed output for a given file and mode key.
429    /// Counts as a cache hit — the caller avoids a full disk read + recompression.
430    pub fn get_compressed(&self, path: &str, mode_key: &str) -> Option<&String> {
431        let key = normalize_key(path);
432        let entry = self.entries.get(&key)?;
433        let result = entry.get_compressed(mode_key)?;
434        entry.bump_read_count();
435        entry.touch();
436        self.stats.total_reads.fetch_add(1, Ordering::Relaxed);
437        self.stats.cache_hits.fetch_add(1, Ordering::Relaxed);
438        self.stats
439            .total_original_tokens
440            .fetch_add(entry.original_tokens as u64, Ordering::Relaxed);
441        let sent = count_tokens(result);
442        self.stats
443            .total_sent_tokens
444            .fetch_add(sent as u64, Ordering::Relaxed);
445        crate::core::events::emit_cache_hit(
446            path,
447            (entry.original_tokens as u64).saturating_sub(sent as u64),
448        );
449        crate::core::stats::record_reread(entry.original_tokens.saturating_sub(sent));
450        Some(result)
451    }
452
453    pub fn was_compressed_variant_evicted(&self, path: &str, mode_key: &str) -> bool {
454        self.entries
455            .get(&normalize_key(path))
456            .is_some_and(|entry| entry.was_compressed_variant_evicted(mode_key))
457    }
458
459    /// Marks that full (uncompressed) content was delivered for this file,
460    /// tagging it with the current conversation so a later re-read only serves
461    /// the `[unchanged]` stub to the same conversation (see
462    /// `crate::core::conversation`).
463    pub fn mark_full_delivered(&mut self, path: &str) {
464        let conversation = crate::core::conversation::current_conversation_id();
465        let key = normalize_key(path);
466        let file_ref = self.file_refs.get(&key).cloned();
467        if let Some(entry) = self.entries.get_mut(&key) {
468            entry.mark_full_delivered(conversation.clone());
469            // Write-through to the persistent stub index so an unchanged re-read
470            // in the same conversation survives a daemon restart / idle clear
471            // (#955). `record` ignores None-conversation deliveries.
472            crate::core::read_stub_index::record(crate::core::read_stub_index::StubRecord::new(
473                key.clone(),
474                entry.hash.clone(),
475                entry.stored_mtime,
476                entry.line_count,
477                file_ref.unwrap_or_default(),
478                conversation,
479            ));
480        }
481    }
482
483    /// Stores a compressed output for a given file and mode key.
484    pub fn set_compressed(&mut self, path: &str, mode_key: &str, output: String) {
485        if let Some(entry) = self.entries.get_mut(&normalize_key(path)) {
486            entry.set_compressed(mode_key, output);
487        }
488    }
489
490    /// Resets `full_content_delivered` for all entries without removing them.
491    /// Used after host context compaction — forces re-delivery on next read
492    /// while preserving compressed content and file refs.
493    pub fn reset_delivery_flags(&mut self) -> usize {
494        let mut count = 0;
495        for entry in self.entries.values_mut() {
496            if entry.full_content_delivered {
497                entry.full_content_delivered = false;
498                count += 1;
499            }
500        }
501        count
502    }
503
504    /// Returns whether full content was previously delivered for this path.
505    pub fn is_full_delivered(&self, path: &str) -> bool {
506        self.entries
507            .get(&normalize_key(path))
508            .is_some_and(|e| e.full_content_delivered)
509    }
510
511    /// Returns the last successful read mode for an entry, if one was recorded.
512    pub fn last_mode(&self, path: &str) -> Option<String> {
513        self.entries
514            .get(&normalize_key(path))
515            .map(|entry| entry.last_mode.clone())
516            .filter(|mode| !mode.is_empty())
517    }
518
519    /// Counts entries that have full content delivered — i.e. those that would
520    /// serve a cheap `[unchanged]` stub and therefore force a full re-delivery
521    /// if dropped. Used by re-delivery telemetry at clear/eviction sites.
522    pub fn count_full_delivered(&self) -> usize {
523        self.entries
524            .values()
525            .filter(|e| e.full_content_delivered)
526            .count()
527    }
528
529    /// Removes all compressed output variants (map, signatures, etc.) from every entry,
530    /// keeping the full zstd-compressed content intact. Returns the number of entries trimmed.
531    pub fn trim_compressed_outputs(&mut self) -> usize {
532        let mut trimmed = 0;
533        for entry in self.entries.values_mut() {
534            if entry.evict_compressed_outputs() {
535                trimmed += 1;
536            }
537        }
538        trimmed
539    }
540
541    /// Evicts all entries that have been read at most once (probationary).
542    /// Returns the number of entries removed.
543    pub fn evict_probationary(&mut self) -> usize {
544        let to_remove: Vec<String> = self
545            .entries
546            .iter()
547            .filter(|(_, e)| e.read_count() <= 1)
548            .map(|(k, _)| k.clone())
549            .collect();
550        let count = to_remove.len();
551        let mut redelivered = 0u64;
552        for key in &to_remove {
553            if self
554                .entries
555                .remove(key)
556                .is_some_and(|e| e.full_content_delivered)
557            {
558                redelivered += 1;
559            }
560            self.file_refs.remove(key);
561        }
562        crate::core::cache_telemetry::record_eviction(redelivered);
563        count
564    }
565
566    /// Evicts entries via RRF scoring until total tokens are at or below `target_tokens`.
567    pub fn evict_to_budget(&mut self, target_tokens: usize) {
568        let current = self.total_cached_tokens();
569        if current <= target_tokens {
570            return;
571        }
572        let now = Instant::now();
573        let all: Vec<(&String, &CacheEntry)> = self.entries.iter().collect();
574        let mut scores = eviction_scores_rrf(&all, now);
575        apply_hebbian_bonus(&mut scores, &self.hebbian_eviction_bonus());
576        scores.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
577
578        let mut freed = 0usize;
579        let mut redelivered = 0u64;
580        let target_free = current.saturating_sub(target_tokens);
581        for (path, _score) in &scores {
582            if freed >= target_free {
583                break;
584            }
585            if let Some(entry) = self.entries.remove(path) {
586                freed += entry.original_tokens;
587                if entry.full_content_delivered {
588                    redelivered += 1;
589                }
590                self.file_refs.remove(path);
591            }
592        }
593        crate::core::cache_telemetry::record_eviction(redelivered);
594    }
595
596    /// Estimates the approximate heap memory usage in bytes.
597    pub fn approximate_bytes(&self) -> usize {
598        let entries_bytes: usize = self
599            .entries
600            .values()
601            .map(|e| {
602                e.compressed_content.len()
603                    + e.hash.len()
604                    + e.path.len()
605                    + e.compressed_outputs
606                        .iter()
607                        .map(|(k, v)| k.len() + v.len())
608                        .sum::<usize>()
609                    + 128 // fixed overhead per entry
610            })
611            .sum();
612        let refs_bytes: usize = self.file_refs.iter().map(|(k, v)| k.len() + v.len()).sum();
613        let blocks_bytes: usize = self
614            .shared_blocks
615            .iter()
616            .map(|b| b.canonical_path.len() + b.canonical_ref.len() + b.content.len() + 32)
617            .sum();
618        entries_bytes + refs_bytes + blocks_bytes
619    }
620
621    const MAX_SHARED_BLOCKS: usize = 100;
622
623    /// Trims shared blocks to a maximum count, keeping the most recent.
624    pub fn trim_shared_blocks(&mut self) {
625        if self.shared_blocks.len() > Self::MAX_SHARED_BLOCKS {
626            let excess = self.shared_blocks.len() - Self::MAX_SHARED_BLOCKS;
627            self.shared_blocks.drain(..excess);
628        }
629    }
630
631    /// Clears all cached entries, file refs, and resets stats. Returns the number of entries removed.
632    pub fn clear(&mut self) -> usize {
633        let count = self.entries.len();
634        self.entries.clear();
635        self.file_refs.clear();
636        self.shared_blocks.clear();
637        self.next_ref = 1;
638        self.stats = CacheStats::default();
639        count
640    }
641}