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#[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
34pub 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 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 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 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 pub fn flush_co_access(&mut self) {
79 self.co_access.end_burst();
80 }
81
82 #[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 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 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 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 pub fn get_file_ref_readonly(&self, path: &str) -> Option<String> {
143 self.file_refs.get(&normalize_key(path)).cloned()
144 }
145
146 pub fn get(&self, path: &str) -> Option<&CacheEntry> {
148 self.entries.get(&normalize_key(path))
149 }
150
151 pub fn get_mut(&mut self, path: &str) -> Option<&mut CacheEntry> {
153 self.entries.get_mut(&normalize_key(path))
154 }
155
156 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 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 (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 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 pub fn store(&mut self, path: &str, content: &str) -> StoreResult {
241 let key = normalize_key(path);
242 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 pub fn total_cached_tokens(&self) -> usize {
334 self.entries.values().map(|e| e.original_tokens).sum()
335 }
336
337 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 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 pub fn get_all_entries(&self) -> Vec<(&String, &CacheEntry)> {
374 self.entries.iter().collect()
375 }
376
377 pub fn get_stats(&self) -> &CacheStats {
379 &self.stats
380 }
381
382 pub fn file_ref_map(&self) -> &HashMap<String, String> {
384 &self.file_refs
385 }
386
387 pub fn set_shared_blocks(&mut self, blocks: Vec<SharedBlock>) {
389 self.shared_blocks = blocks;
390 }
391
392 pub fn get_shared_blocks(&self) -> &[SharedBlock] {
394 &self.shared_blocks
395 }
396
397 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 pub fn invalidate(&mut self, path: &str) -> bool {
426 self.entries.remove(&normalize_key(path)).is_some()
427 }
428
429 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 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 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 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 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 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 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 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 pub fn count_full_delivered(&self) -> usize {
539 self.entries
540 .values()
541 .filter(|e| e.full_content_delivered)
542 .count()
543 }
544
545 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 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 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 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 })
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 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 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}