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 (decided by `conversation_allows_stub` with no delivery id:
15/// served only when the caller has no conversation context either, #1909);
16/// `Conversation` = provably delivered to 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    ///
177    /// Either copy is handed out as a new delivery: it passes the context
178    /// gateway under the *current* policy, with the entry's path (G5, recovery
179    /// is re-authorized). `Some(Err(reason))` is content-free: the gateway
180    /// withholds the content.
181    pub fn current_full_content(&self, path: &str) -> Option<Result<(String, usize), String>> {
182        let entry = self.entries.get(&normalize_key(path))?;
183        let (text, tokens) =
184            if is_cache_entry_stale_verified(&entry.path, entry.stored_mtime, &entry.hash)
185                && let Ok(fresh) = crate::core::io_boundary::read_file_lossy(&entry.path)
186            {
187                // Cache is behind disk → serve the current bytes. If the file is now
188                // unreadable (deleted/permission), fall through to the cached copy:
189                // last-known content beats nothing, and that fall-through is not the
190                // staleness bug (it only fires when there is no current content).
191                (fresh, None)
192            } else {
193                (entry.content()?, Some(entry.original_tokens))
194            };
195        Some(
196            crate::core::context_admission::admit_source(&text, &entry.path, false)
197                .map(|admitted| {
198                    let tokens = tokens
199                        .filter(|_| admitted == text)
200                        .unwrap_or_else(|| count_tokens(&admitted));
201                    (admitted, tokens)
202                })
203                .map_err(|error| error.to_string()),
204        )
205    }
206
207    /// Records a cache hit, updates access stats, and emits a cache-hit event.
208    ///
209    /// Takes `&self`: the hit counters use interior-mutable atomics, so this
210    /// runs under a shared (read) lock and lets parallel reads of different
211    /// files proceed concurrently instead of serializing on a write lock.
212    pub fn record_cache_hit(&self, path: &str) -> Option<&CacheEntry> {
213        let key = normalize_key(path);
214        let ref_label = self
215            .file_refs
216            .get(&key)
217            .cloned()
218            .unwrap_or_else(|| "F?".to_string());
219        let entry = self.entries.get(&key)?;
220        let new_count = entry.bump_read_count();
221        entry.touch();
222        self.stats.total_reads.fetch_add(1, Ordering::Relaxed);
223        self.stats.cache_hits.fetch_add(1, Ordering::Relaxed);
224        self.stats
225            .total_original_tokens
226            .fetch_add(entry.original_tokens as u64, Ordering::Relaxed);
227        let hit_msg = format!("{ref_label} cached {new_count}t {}L", entry.line_count);
228        let sent_tokens = count_tokens(&hit_msg) as u64;
229        self.stats
230            .total_sent_tokens
231            .fetch_add(sent_tokens, Ordering::Relaxed);
232        crate::core::events::emit_cache_hit(
233            path,
234            (entry.original_tokens as u64).saturating_sub(sent_tokens),
235        );
236        Some(entry)
237    }
238
239    /// Stores file content in the cache; returns a hit if content hash matches.
240    pub fn store(&mut self, path: &str, content: &str) -> StoreResult {
241        let key = normalize_key(path);
242        // #3: feed the Hebbian co-access matrix on every read so eviction can
243        // later protect files that are habitually read together.
244        self.co_access
245            .record_access(crate::core::hebbian_cache::path_hash(&key));
246        let hash = compute_md5(content);
247        let line_count = content.lines().count();
248        let original_tokens = count_tokens(content);
249        let stored_mtime = std::fs::metadata(path).and_then(|m| m.modified()).ok();
250        let now = Instant::now();
251
252        self.stats.total_reads.fetch_add(1, Ordering::Relaxed);
253        self.stats
254            .total_original_tokens
255            .fetch_add(original_tokens as u64, Ordering::Relaxed);
256
257        if let Some(existing) = self.entries.get_mut(&key) {
258            existing.set_last_access(now);
259            if stored_mtime.is_some() {
260                existing.stored_mtime = stored_mtime;
261            }
262            if existing.hash == hash {
263                let new_count = existing.bump_read_count();
264                self.stats.cache_hits.fetch_add(1, Ordering::Relaxed);
265                let hit_msg = format!(
266                    "{} cached {new_count}t {}L",
267                    self.file_refs.get(&key).unwrap_or(&"F?".to_string()),
268                    existing.line_count,
269                );
270                let sent_tokens = count_tokens(&hit_msg) as u64;
271                self.stats
272                    .total_sent_tokens
273                    .fetch_add(sent_tokens, Ordering::Relaxed);
274                return StoreResult {
275                    line_count: existing.line_count,
276                    original_tokens: existing.original_tokens,
277                    read_count: new_count,
278                    was_hit: true,
279                    full_content_delivered: existing.full_content_delivered,
280                };
281            }
282            existing.clear_compressed_outputs();
283            existing.set_content(content);
284            existing.hash = hash;
285            existing.line_count = line_count;
286            existing.original_tokens = original_tokens;
287            let new_count = existing.bump_read_count();
288            existing.full_content_delivered = false;
289            existing.delivered_conversation = None;
290            existing.last_mode.clear();
291            if stored_mtime.is_some() {
292                existing.stored_mtime = stored_mtime;
293            }
294            self.stats
295                .total_sent_tokens
296                .fetch_add(original_tokens as u64, Ordering::Relaxed);
297            return StoreResult {
298                line_count,
299                original_tokens,
300                read_count: new_count,
301                was_hit: false,
302                full_content_delivered: false,
303            };
304        }
305
306        self.evict_if_needed(original_tokens);
307        self.get_file_ref(&key);
308
309        let entry = CacheEntry::new(
310            content,
311            hash,
312            line_count,
313            original_tokens,
314            key.clone(),
315            stored_mtime,
316        );
317
318        self.entries.insert(key, entry);
319        self.stats.files_tracked.fetch_add(1, Ordering::Relaxed);
320        self.stats
321            .total_sent_tokens
322            .fetch_add(original_tokens as u64, Ordering::Relaxed);
323        StoreResult {
324            line_count,
325            original_tokens,
326            read_count: 1,
327            was_hit: false,
328            full_content_delivered: false,
329        }
330    }
331
332    /// Returns the sum of original token counts across all cached entries.
333    pub fn total_cached_tokens(&self) -> usize {
334        self.entries.values().map(|e| e.original_tokens).sum()
335    }
336
337    /// Evict until cache fits within token budget using RRF (Reciprocal Rank Fusion).
338    /// Combines recency, frequency, and size signals to evict least-valuable entries first.
339    pub fn evict_if_needed(&mut self, incoming_tokens: usize) {
340        let max_tokens = max_cache_tokens();
341        let current = self.total_cached_tokens();
342        if current + incoming_tokens <= max_tokens {
343            return;
344        }
345
346        let now = Instant::now();
347        let all: Vec<(&String, &CacheEntry)> = self.entries.iter().collect();
348        let mut scores = eviction_scores_rrf(&all, now);
349        apply_hebbian_bonus(&mut scores, &self.hebbian_eviction_bonus());
350        // Sort ascending: lowest RRF score = least valuable = evict first
351        scores.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
352
353        let mut freed = 0usize;
354        let mut redelivered = 0u64;
355        let target = (current + incoming_tokens).saturating_sub(max_tokens);
356
357        for (path, _score) in &scores {
358            if freed >= target {
359                break;
360            }
361            if let Some(entry) = self.entries.remove(path) {
362                freed += entry.original_tokens;
363                if entry.full_content_delivered {
364                    redelivered += 1;
365                }
366                self.file_refs.remove(path);
367            }
368        }
369        crate::core::cache_telemetry::record_eviction(redelivered);
370    }
371
372    /// Returns all cached entries as (path, entry) pairs.
373    pub fn get_all_entries(&self) -> Vec<(&String, &CacheEntry)> {
374        self.entries.iter().collect()
375    }
376
377    /// Returns a reference to the aggregated cache statistics.
378    pub fn get_stats(&self) -> &CacheStats {
379        &self.stats
380    }
381
382    /// Returns the path-to-file-ref mapping (e.g. "/src/main.rs" → "F1").
383    pub fn file_ref_map(&self) -> &HashMap<String, String> {
384        &self.file_refs
385    }
386
387    /// Replaces the cross-file shared blocks used for deduplication.
388    pub fn set_shared_blocks(&mut self, blocks: Vec<SharedBlock>) {
389        self.shared_blocks = blocks;
390    }
391
392    /// Returns the current set of cross-file shared blocks.
393    pub fn get_shared_blocks(&self) -> &[SharedBlock] {
394        &self.shared_blocks
395    }
396
397    /// Replace shared blocks in content with cross-file references.
398    pub fn apply_dedup(&self, path: &str, content: &str) -> Option<String> {
399        if self.shared_blocks.is_empty() {
400            return None;
401        }
402        let refs: Vec<&SharedBlock> = self
403            .shared_blocks
404            .iter()
405            .filter(|b| b.canonical_path != path && content.contains(&b.content))
406            .collect();
407        if refs.is_empty() {
408            return None;
409        }
410        let mut result = content.to_string();
411        for block in refs {
412            result = result.replacen(
413                &block.content,
414                &format!(
415                    "[= {}:{}-{}]",
416                    block.canonical_ref, block.start_line, block.end_line
417                ),
418                1,
419            );
420        }
421        Some(result)
422    }
423
424    /// Removes a file from the cache, forcing a fresh read on next access.
425    pub fn invalidate(&mut self, path: &str) -> bool {
426        self.entries.remove(&normalize_key(path)).is_some()
427    }
428
429    /// #1287: which conversation first received the given compressed variant,
430    /// WITHOUT recording hit statistics — the caller decides between stub and
431    /// payload delivery and records accordingly.
432    pub fn compressed_delivered_conversation(&self, path: &str, mode_key: &str) -> VariantDelivery {
433        match self
434            .entries
435            .get(&normalize_key(path))
436            .and_then(|entry| entry.compressed_delivered_conversation(mode_key))
437        {
438            None => VariantDelivery::Absent,
439            Some(None) => VariantDelivery::UnknownConversation,
440            Some(Some(conversation)) => VariantDelivery::Conversation(conversation.to_string()),
441        }
442    }
443
444    /// Returns a cached compressed output for a given file and mode key.
445    /// Counts as a cache hit — the caller avoids a full disk read + recompression.
446    pub fn get_compressed(&self, path: &str, mode_key: &str) -> Option<&String> {
447        let key = normalize_key(path);
448        let entry = self.entries.get(&key)?;
449        let result = entry.get_compressed(mode_key)?;
450        entry.bump_read_count();
451        entry.touch();
452        self.stats.total_reads.fetch_add(1, Ordering::Relaxed);
453        self.stats.cache_hits.fetch_add(1, Ordering::Relaxed);
454        self.stats
455            .total_original_tokens
456            .fetch_add(entry.original_tokens as u64, Ordering::Relaxed);
457        let sent = count_tokens(result);
458        self.stats
459            .total_sent_tokens
460            .fetch_add(sent as u64, Ordering::Relaxed);
461        crate::core::events::emit_cache_hit(
462            path,
463            (entry.original_tokens as u64).saturating_sub(sent as u64),
464        );
465        crate::core::stats::record_reread(entry.original_tokens.saturating_sub(sent));
466        Some(result)
467    }
468
469    pub fn was_compressed_variant_evicted(&self, path: &str, mode_key: &str) -> bool {
470        self.entries
471            .get(&normalize_key(path))
472            .is_some_and(|entry| entry.was_compressed_variant_evicted(mode_key))
473    }
474
475    /// Marks that full (uncompressed) content was delivered for this file,
476    /// tagging it with the current conversation so a later re-read only serves
477    /// the `[unchanged]` stub to the same conversation (see
478    /// `crate::core::conversation`).
479    pub fn mark_full_delivered(&mut self, path: &str) {
480        let conversation = crate::core::conversation::current_conversation_id();
481        let key = normalize_key(path);
482        let file_ref = self.file_refs.get(&key).cloned();
483        if let Some(entry) = self.entries.get_mut(&key) {
484            entry.mark_full_delivered(conversation.clone());
485            // Write-through to the persistent stub index so an unchanged re-read
486            // in the same conversation survives a daemon restart / idle clear
487            // (#955). `record` ignores None-conversation deliveries.
488            crate::core::read_stub_index::record(crate::core::read_stub_index::StubRecord::new(
489                key.clone(),
490                entry.hash.clone(),
491                entry.stored_mtime,
492                entry.line_count,
493                file_ref.unwrap_or_default(),
494                conversation,
495            ));
496        }
497    }
498
499    /// Stores a compressed output for a given file and mode key.
500    pub fn set_compressed(&mut self, path: &str, mode_key: &str, output: String) {
501        if let Some(entry) = self.entries.get_mut(&normalize_key(path)) {
502            entry.set_compressed(mode_key, output);
503        }
504    }
505
506    /// Resets `full_content_delivered` for all entries without removing them.
507    /// Used after host context compaction — forces re-delivery on next read
508    /// while preserving compressed content and file refs.
509    pub fn reset_delivery_flags(&mut self) -> usize {
510        let mut count = 0;
511        for entry in self.entries.values_mut() {
512            if entry.full_content_delivered {
513                entry.full_content_delivered = false;
514                count += 1;
515            }
516        }
517        count
518    }
519
520    /// Returns whether full content was previously delivered for this path.
521    pub fn is_full_delivered(&self, path: &str) -> bool {
522        self.entries
523            .get(&normalize_key(path))
524            .is_some_and(|e| e.full_content_delivered)
525    }
526
527    /// Returns the last successful read mode for an entry, if one was recorded.
528    pub fn last_mode(&self, path: &str) -> Option<String> {
529        self.entries
530            .get(&normalize_key(path))
531            .map(|entry| entry.last_mode.clone())
532            .filter(|mode| !mode.is_empty())
533    }
534
535    /// Counts entries that have full content delivered — i.e. those that would
536    /// serve a cheap `[unchanged]` stub and therefore force a full re-delivery
537    /// if dropped. Used by re-delivery telemetry at clear/eviction sites.
538    pub fn count_full_delivered(&self) -> usize {
539        self.entries
540            .values()
541            .filter(|e| e.full_content_delivered)
542            .count()
543    }
544
545    /// Removes all compressed output variants (map, signatures, etc.) from every entry,
546    /// keeping the full zstd-compressed content intact. Returns the number of entries trimmed.
547    pub fn trim_compressed_outputs(&mut self) -> usize {
548        let mut trimmed = 0;
549        for entry in self.entries.values_mut() {
550            if entry.evict_compressed_outputs() {
551                trimmed += 1;
552            }
553        }
554        trimmed
555    }
556
557    /// Evicts all entries that have been read at most once (probationary).
558    /// Returns the number of entries removed.
559    pub fn evict_probationary(&mut self) -> usize {
560        let to_remove: Vec<String> = self
561            .entries
562            .iter()
563            .filter(|(_, e)| e.read_count() <= 1)
564            .map(|(k, _)| k.clone())
565            .collect();
566        let count = to_remove.len();
567        let mut redelivered = 0u64;
568        for key in &to_remove {
569            if self
570                .entries
571                .remove(key)
572                .is_some_and(|e| e.full_content_delivered)
573            {
574                redelivered += 1;
575            }
576            self.file_refs.remove(key);
577        }
578        crate::core::cache_telemetry::record_eviction(redelivered);
579        count
580    }
581
582    /// Evicts entries via RRF scoring until total tokens are at or below `target_tokens`.
583    pub fn evict_to_budget(&mut self, target_tokens: usize) {
584        let current = self.total_cached_tokens();
585        if current <= target_tokens {
586            return;
587        }
588        let now = Instant::now();
589        let all: Vec<(&String, &CacheEntry)> = self.entries.iter().collect();
590        let mut scores = eviction_scores_rrf(&all, now);
591        apply_hebbian_bonus(&mut scores, &self.hebbian_eviction_bonus());
592        scores.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
593
594        let mut freed = 0usize;
595        let mut redelivered = 0u64;
596        let target_free = current.saturating_sub(target_tokens);
597        for (path, _score) in &scores {
598            if freed >= target_free {
599                break;
600            }
601            if let Some(entry) = self.entries.remove(path) {
602                freed += entry.original_tokens;
603                if entry.full_content_delivered {
604                    redelivered += 1;
605                }
606                self.file_refs.remove(path);
607            }
608        }
609        crate::core::cache_telemetry::record_eviction(redelivered);
610    }
611
612    /// Estimates the approximate heap memory usage in bytes.
613    pub fn approximate_bytes(&self) -> usize {
614        let entries_bytes: usize = self
615            .entries
616            .values()
617            .map(|e| {
618                e.compressed_content.len()
619                    + e.hash.len()
620                    + e.path.len()
621                    + e.compressed_outputs
622                        .iter()
623                        .map(|(k, v)| k.len() + v.len())
624                        .sum::<usize>()
625                    + 128 // fixed overhead per entry
626            })
627            .sum();
628        let refs_bytes: usize = self.file_refs.iter().map(|(k, v)| k.len() + v.len()).sum();
629        let blocks_bytes: usize = self
630            .shared_blocks
631            .iter()
632            .map(|b| b.canonical_path.len() + b.canonical_ref.len() + b.content.len() + 32)
633            .sum();
634        entries_bytes + refs_bytes + blocks_bytes
635    }
636
637    const MAX_SHARED_BLOCKS: usize = 100;
638
639    /// Trims shared blocks to a maximum count, keeping the most recent.
640    pub fn trim_shared_blocks(&mut self) {
641        if self.shared_blocks.len() > Self::MAX_SHARED_BLOCKS {
642            let excess = self.shared_blocks.len() - Self::MAX_SHARED_BLOCKS;
643            self.shared_blocks.drain(..excess);
644        }
645    }
646
647    /// Clears all cached entries, file refs, and resets stats. Returns the number of entries removed.
648    pub fn clear(&mut self) -> usize {
649        let count = self.entries.len();
650        self.entries.clear();
651        self.file_refs.clear();
652        self.shared_blocks.clear();
653        self.next_ref = 1;
654        self.stats = CacheStats::default();
655        count
656    }
657}