lean_ctx/core/
bm25_cache.rs1use std::path::{Path, PathBuf};
2use std::sync::Arc;
3use std::time::{Instant, SystemTime};
4
5use super::bm25_index::BM25Index;
6
7const DEFAULT_TTL_SECS: u64 = 60;
8
9#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
16pub struct IndexFingerprint {
17 mtime: Option<SystemTime>,
18 size: u64,
19}
20
21pub struct Bm25CacheEntry {
22 pub root: PathBuf,
23 pub index: Arc<BM25Index>,
24 pub loaded_at: Instant,
25 pub fingerprint: IndexFingerprint,
27}
28
29impl Bm25CacheEntry {
30 pub fn is_fresh(&self) -> bool {
31 if self.loaded_at.elapsed().as_secs() >= ttl_secs() {
32 return false;
33 }
34 index_fingerprint(&self.root) == self.fingerprint
37 }
38}
39
40pub fn index_fingerprint(root: &Path) -> IndexFingerprint {
42 match std::fs::metadata(BM25Index::index_file_path(root)) {
43 Ok(m) => IndexFingerprint {
44 mtime: m.modified().ok(),
45 size: m.len(),
46 },
47 Err(_) => IndexFingerprint::default(),
48 }
49}
50
51fn ttl_secs() -> u64 {
52 std::env::var("LEAN_CTX_BM25_CACHE_TTL")
53 .ok()
54 .and_then(|v| v.parse().ok())
55 .unwrap_or(DEFAULT_TTL_SECS)
56}
57
58pub type SharedBm25Cache = std::sync::Arc<std::sync::Mutex<Option<Bm25CacheEntry>>>;
59
60pub fn get_or_load(cache: &SharedBm25Cache, root: &Path) -> Arc<BM25Index> {
63 {
64 let guard = cache
65 .lock()
66 .unwrap_or_else(std::sync::PoisonError::into_inner);
67 if let Some(ref entry) = *guard
68 && entry.root == root
69 && entry.is_fresh()
70 {
71 return Arc::clone(&entry.index);
72 }
73 }
74
75 let index = Arc::new(BM25Index::load_or_build_fast(root));
76
77 let mut guard = cache
78 .lock()
79 .unwrap_or_else(std::sync::PoisonError::into_inner);
80 *guard = Some(Bm25CacheEntry {
81 root: root.to_path_buf(),
82 index: Arc::clone(&index),
83 loaded_at: Instant::now(),
84 fingerprint: index_fingerprint(root),
85 });
86
87 index
88}
89
90pub fn peek(cache: &SharedBm25Cache, root: &Path) -> Option<Arc<BM25Index>> {
92 let guard = cache
93 .lock()
94 .unwrap_or_else(std::sync::PoisonError::into_inner);
95 guard
96 .as_ref()
97 .filter(|entry| entry.root == root)
98 .map(|entry| Arc::clone(&entry.index))
99}
100
101pub fn get_or_background(cache: &SharedBm25Cache, root: &Path) -> Option<Arc<BM25Index>> {
104 let guard = cache
105 .lock()
106 .unwrap_or_else(std::sync::PoisonError::into_inner);
107 let entry = guard.as_ref()?;
108 if entry.root != root {
109 return None;
110 }
111
112 let idx = Arc::clone(&entry.index);
113
114 if !entry.is_fresh() {
115 let root_str = root.to_string_lossy().to_string();
116 let cache_clone = cache.clone();
117 let root_clone = root.to_path_buf();
118 std::thread::spawn(move || {
119 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
123 let rebuilt = BM25Index::load_or_build(&root_clone);
124 let rebuilt_fp = index_fingerprint(&root_clone);
125 let mut g = cache_clone
126 .lock()
127 .unwrap_or_else(std::sync::PoisonError::into_inner);
128 *g = Some(Bm25CacheEntry {
129 root: root_clone,
130 index: Arc::new(rebuilt),
131 loaded_at: Instant::now(),
132 fingerprint: rebuilt_fp,
133 });
134 }));
135 if result.is_ok() {
136 tracing::debug!("[bm25_cache: background refresh done for {root_str}]");
137 } else {
138 tracing::warn!(
139 "[bm25_cache: background refresh panicked for {root_str}; serving stale index]"
140 );
141 }
142 });
143 }
144
145 Some(idx)
146}
147
148pub fn unload(cache: &SharedBm25Cache) {
151 let mut guard = cache
152 .lock()
153 .unwrap_or_else(std::sync::PoisonError::into_inner);
154 if guard.is_some() {
155 *guard = None;
156 tracing::info!("[bm25_cache] unloaded index to free memory");
157 }
158}
159
160pub fn memory_usage(cache: &SharedBm25Cache) -> usize {
162 let guard = cache
163 .lock()
164 .unwrap_or_else(std::sync::PoisonError::into_inner);
165 guard.as_ref().map_or(0, |e| e.index.memory_usage_bytes())
166}
167
168pub fn shrink_resident_to_snippet(
183 cache: &SharedBm25Cache,
184 root: &Path,
185 keep_lines: usize,
186) -> usize {
187 let mut guard = cache
188 .lock()
189 .unwrap_or_else(std::sync::PoisonError::into_inner);
190 let Some(entry) = guard.as_mut() else {
191 return 0;
192 };
193 if entry.root != root || entry.index.content_truncated {
194 return 0;
195 }
196 let Some(index) = Arc::get_mut(&mut entry.index) else {
199 tracing::debug!(
200 "[bm25_cache] resident index still shared; skipping content shrink for now"
201 );
202 return 0;
203 };
204 let before = index.memory_usage_bytes();
205 index.shrink_resident_content_to_snippet(keep_lines);
206 before.saturating_sub(index.memory_usage_bytes())
207}
208
209#[cfg(test)]
210pub mod tests {
211 use super::*;
212 use std::sync::Arc;
213
214 #[test]
215 fn fresh_cache_returns_same_instance() {
216 let cache: SharedBm25Cache = Arc::new(std::sync::Mutex::new(None));
217 let tmp = tempfile::tempdir().unwrap();
218 let root = tmp.path();
219 std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
220
221 let idx1 = get_or_load(&cache, root);
222 assert!(idx1.doc_count > 0);
223
224 let idx2 = get_or_load(&cache, root);
225 assert_eq!(idx1.doc_count, idx2.doc_count);
226 }
227
228 #[test]
229 fn different_root_invalidates() {
230 let cache: SharedBm25Cache = Arc::new(std::sync::Mutex::new(None));
231 let tmp1 = tempfile::tempdir().unwrap();
232 let tmp2 = tempfile::tempdir().unwrap();
233 std::fs::write(tmp1.path().join("a.rs"), "fn a() {}\n").unwrap();
234 std::fs::write(tmp2.path().join("b.rs"), "fn b() {}\n").unwrap();
235
236 let _ = get_or_load(&cache, tmp1.path());
237 let idx2 = get_or_load(&cache, tmp2.path());
238
239 let guard = cache
240 .lock()
241 .unwrap_or_else(std::sync::PoisonError::into_inner);
242 let entry = guard.as_ref().unwrap();
243 assert_eq!(entry.root, tmp2.path());
244 assert_eq!(entry.index.doc_count, idx2.doc_count);
245 }
246
247 #[test]
248 fn get_or_background_returns_none_on_empty() {
249 let cache: SharedBm25Cache = Arc::new(std::sync::Mutex::new(None));
250 let tmp = tempfile::tempdir().unwrap();
251 assert!(get_or_background(&cache, tmp.path()).is_none());
252 }
253
254 #[test]
255 fn fingerprint_default_when_index_file_absent() {
256 let tmp = tempfile::tempdir().unwrap();
257 assert_eq!(index_fingerprint(tmp.path()), IndexFingerprint::default());
259 }
260
261 #[test]
262 fn fingerprint_detects_size_change_under_equal_mtime() {
263 let mtime = Some(SystemTime::UNIX_EPOCH);
266 let a = IndexFingerprint { mtime, size: 100 };
267 let b = IndexFingerprint { mtime, size: 200 };
268 assert_ne!(a, b);
269 assert_eq!(a, IndexFingerprint { mtime, size: 100 });
270 }
271}