Skip to main content

lean_ctx/core/cache/
warming.rs

1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
3use std::time::SystemTime;
4
5use crate::core::session::SessionState;
6use crate::core::tokens::count_tokens;
7
8use super::{SessionCache, max_cache_tokens};
9
10const MAX_WARM_FILE_BYTES: usize = 50 * 1024;
11const MAX_RECENT_FILES: usize = 50;
12
13/// A file accessed by one or more previous sessions.
14#[derive(Clone, Debug, Eq, PartialEq)]
15pub struct RecentFile {
16    pub path: String,
17    pub last_access: SystemTime,
18    pub read_count: u32,
19    /// Largest observed token count, used to estimate the benefit of a warm hit.
20    pub tokens: usize,
21}
22
23trait WarmCache {
24    fn contains(&self, path: &str) -> bool;
25    fn total_tokens(&self) -> usize;
26    fn insert(&mut self, path: &str, content: &str);
27}
28
29impl WarmCache for SessionCache {
30    fn contains(&self, path: &str) -> bool {
31        self.get(path).is_some()
32    }
33
34    fn total_tokens(&self) -> usize {
35        self.total_cached_tokens()
36    }
37
38    fn insert(&mut self, path: &str, content: &str) {
39        self.store(path, content);
40    }
41}
42
43/// Pre-populates a session cache with the highest-priority recent files.
44///
45/// Warming stops when the cache reaches 80% of its configured token budget.
46/// Missing, oversized, unreadable, and already-cached files are ignored.
47pub fn warm_cache(cache: &mut SessionCache, history: &[RecentFile]) {
48    warm_cache_with(cache, history, max_cache_tokens(), |path| {
49        let metadata = std::fs::metadata(path).ok()?;
50        if !metadata.is_file() || metadata.len() > MAX_WARM_FILE_BYTES as u64 {
51            return None;
52        }
53        crate::core::io_boundary::read_file_lossy(path).ok()
54    });
55}
56
57fn warm_cache_with<C, F>(cache: &mut C, history: &[RecentFile], token_budget: usize, mut load: F)
58where
59    C: WarmCache,
60    F: FnMut(&str) -> Option<String>,
61{
62    let warming_limit = token_budget.saturating_mul(4) / 5;
63
64    for recent in history {
65        if cache.total_tokens() >= warming_limit {
66            break;
67        }
68        if cache.contains(&recent.path) {
69            continue;
70        }
71
72        let Some(content) = load(&recent.path) else {
73            continue;
74        };
75        if content.len() > MAX_WARM_FILE_BYTES {
76            continue;
77        }
78
79        let incoming_tokens = count_tokens(&content);
80        if cache.total_tokens().saturating_add(incoming_tokens) > warming_limit {
81            continue;
82        }
83        cache.insert(&recent.path, &content);
84    }
85}
86
87/// Collects, deduplicates, and ranks files touched by previous sessions.
88///
89/// Read counts are summed across sessions. The largest observed token count
90/// estimates the avoided read cost. A session's update time is used as the
91/// recency of its file accesses because `FileTouched` has no own timestamp.
92pub fn collect_recent_files(sessions: &[SessionState]) -> Vec<RecentFile> {
93    collect_recent_files_with(sessions, |_, file| Some(file.path.clone()))
94}
95
96/// Collect warm candidates only from the requested project and pass every
97/// persisted path through PathJail again before it can reach disk I/O.
98pub fn collect_recent_files_in_project(
99    sessions: &[SessionState],
100    project_root: &str,
101) -> Vec<RecentFile> {
102    let Some(root) = normalized_safe_root(project_root) else {
103        return Vec::new();
104    };
105    collect_recent_files_with(sessions, |session, file| {
106        if file.stale
107            || session
108                .project_root
109                .as_deref()
110                .and_then(normalized_safe_root)
111                != Some(root.clone())
112        {
113            return None;
114        }
115        crate::core::pathjail::jail_path(Path::new(&file.path), &root)
116            .ok()
117            .map(|path| path.to_string_lossy().into_owned())
118    })
119}
120
121fn normalized_safe_root(project_root: &str) -> Option<PathBuf> {
122    let path = Path::new(project_root);
123    if project_root.trim().is_empty() || crate::core::pathutil::is_broad_or_unsafe_root(path) {
124        return None;
125    }
126    Some(crate::core::pathutil::safe_canonicalize_or_self(path))
127}
128
129fn collect_recent_files_with<F>(sessions: &[SessionState], resolve_path: F) -> Vec<RecentFile>
130where
131    F: Fn(&SessionState, &crate::core::session::FileTouched) -> Option<String>,
132{
133    let mut recent_by_path: HashMap<String, RecentFile> = HashMap::new();
134
135    for session in sessions {
136        let last_access = SystemTime::from(session.updated_at);
137        for file in &session.files_touched {
138            let Some(path) = resolve_path(session, file) else {
139                continue;
140            };
141            let recent = recent_by_path
142                .entry(path.clone())
143                .or_insert_with(|| RecentFile {
144                    path,
145                    last_access,
146                    read_count: 0,
147                    tokens: file.tokens,
148                });
149            recent.read_count = recent.read_count.saturating_add(file.read_count);
150            recent.tokens = recent.tokens.max(file.tokens);
151            recent.last_access = recent.last_access.max(last_access);
152        }
153    }
154
155    let mut recent: Vec<RecentFile> = recent_by_path.into_values().collect();
156    recent.sort_by(|a, b| {
157        (b.read_count as usize)
158            .saturating_mul(b.tokens)
159            .cmp(&(a.read_count as usize).saturating_mul(a.tokens))
160            .then_with(|| b.last_access.cmp(&a.last_access))
161            .then_with(|| a.path.cmp(&b.path))
162    });
163    recent.truncate(MAX_RECENT_FILES);
164    recent
165}
166
167#[cfg(test)]
168mod tests {
169    use std::collections::HashMap;
170    use std::time::{Duration, SystemTime};
171
172    use chrono::{TimeZone, Utc};
173
174    use super::*;
175
176    #[derive(Default)]
177    struct MemoryCache {
178        entries: HashMap<String, String>,
179    }
180
181    impl WarmCache for MemoryCache {
182        fn contains(&self, path: &str) -> bool {
183            self.entries.contains_key(path)
184        }
185
186        fn total_tokens(&self) -> usize {
187            self.entries
188                .values()
189                .map(|content| count_tokens(content))
190                .sum()
191        }
192
193        fn insert(&mut self, path: &str, content: &str) {
194            self.entries.insert(path.to_string(), content.to_string());
195        }
196    }
197
198    fn recent(path: &str) -> RecentFile {
199        RecentFile {
200            path: path.to_string(),
201            last_access: SystemTime::UNIX_EPOCH,
202            read_count: 1,
203            tokens: 1,
204        }
205    }
206
207    fn session_at(timestamp: i64) -> SessionState {
208        let time = Utc.timestamp_opt(timestamp, 0).unwrap();
209        SessionState {
210            id: format!("session-{timestamp}"),
211            version: 0,
212            started_at: time,
213            updated_at: time,
214            project_root: None,
215            shell_cwd: None,
216            task: None,
217            findings: Vec::new(),
218            decisions: Vec::new(),
219            files_touched: Vec::new(),
220            test_results: None,
221            progress: Vec::new(),
222            next_steps: Vec::new(),
223            evidence: Vec::new(),
224            intents: Vec::new(),
225            active_structured_intent: None,
226            stats: crate::core::session::SessionStats::default(),
227            terse_mode: false,
228            compression_level: String::new(),
229            last_consolidate_ts: None,
230            last_aaak_hash: None,
231            extra_roots: Vec::new(),
232            wakeup_manifest: Vec::new(),
233            playbook: crate::core::session::Playbook::default(),
234            last_semantic_query: None,
235            last_flush: None,
236            live_zone: Default::default(),
237            handoff_context: Default::default(),
238        }
239    }
240
241    #[test]
242    fn warming_skips_cached_missing_and_oversized_files() {
243        let mut cache = MemoryCache::default();
244        cache
245            .entries
246            .insert("cached.rs".to_string(), "cached".to_string());
247        let history = [
248            recent("cached.rs"),
249            recent("missing.rs"),
250            recent("large.rs"),
251            recent("good.rs"),
252        ];
253        let contents = HashMap::from([
254            ("large.rs", "x".repeat(MAX_WARM_FILE_BYTES + 1)),
255            ("good.rs", "fn good() {}".to_string()),
256        ]);
257        let mut loaded = Vec::new();
258
259        warm_cache_with(&mut cache, &history, 10_000, |path| {
260            loaded.push(path.to_string());
261            contents.get(path).cloned()
262        });
263
264        assert!(!loaded.contains(&"cached.rs".to_string()));
265        assert!(!cache.entries.contains_key("missing.rs"));
266        assert!(!cache.entries.contains_key("large.rs"));
267        assert_eq!(
268            cache.entries.get("good.rs").map(String::as_str),
269            Some("fn good() {}")
270        );
271    }
272
273    #[test]
274    fn warming_stops_at_eighty_percent_of_budget() {
275        let first_content = "first file content";
276        let first_tokens = count_tokens(first_content);
277        let budget = first_tokens.saturating_mul(5).div_ceil(4);
278        let history = [recent("first.rs"), recent("second.rs")];
279        let mut cache = MemoryCache::default();
280        let mut loaded = Vec::new();
281
282        warm_cache_with(&mut cache, &history, budget, |path| {
283            loaded.push(path.to_string());
284            Some(first_content.to_string())
285        });
286
287        assert!(cache.entries.contains_key("first.rs"));
288        assert!(!cache.entries.contains_key("second.rs"));
289        assert_eq!(loaded, vec!["first.rs"]);
290        assert!(cache.total_tokens() <= budget.saturating_mul(4) / 5);
291    }
292
293    #[test]
294    fn recent_files_are_deduplicated_and_ranked_by_expected_benefit() {
295        let mut older = session_at(10);
296        older.touch_file("frequent.rs", None, "full", 10);
297        older.touch_file("frequent.rs", None, "full", 10);
298        older.touch_file("recent.rs", None, "full", 10);
299        older.updated_at = Utc.timestamp_opt(10, 0).unwrap();
300
301        let mut newer = session_at(20);
302        newer.touch_file("frequent.rs", None, "full", 10);
303        newer.touch_file("recent.rs", None, "full", 10);
304        newer.touch_file("peer.rs", None, "full", 10);
305        newer.updated_at = Utc.timestamp_opt(20, 0).unwrap();
306
307        let result = collect_recent_files(&[older, newer]);
308
309        assert_eq!(
310            result
311                .iter()
312                .map(|file| file.path.as_str())
313                .collect::<Vec<_>>(),
314            vec!["frequent.rs", "recent.rs", "peer.rs"]
315        );
316        assert_eq!(result[0].read_count, 3);
317        assert_eq!(
318            result[0].last_access,
319            SystemTime::UNIX_EPOCH + Duration::from_secs(20)
320        );
321        assert_eq!(result[0].tokens, 10);
322    }
323
324    #[test]
325    fn recent_files_prioritize_read_count_times_tokens() {
326        let mut session = session_at(10);
327        session.touch_file("frequent.rs", None, "full", 10);
328        session.touch_file("frequent.rs", None, "full", 10);
329        session.touch_file("small.rs", None, "full", 1);
330        session.touch_file("large.rs", None, "full", 100);
331
332        let result = collect_recent_files(&[session]);
333
334        assert_eq!(
335            result
336                .iter()
337                .map(|file| file.path.as_str())
338                .collect::<Vec<_>>(),
339            vec!["large.rs", "frequent.rs", "small.rs"]
340        );
341    }
342
343    #[test]
344    fn recent_files_are_capped_at_fifty() {
345        let mut session = session_at(10);
346        for index in 0..60 {
347            session.touch_file(&format!("file-{index:02}.rs"), None, "full", 1);
348        }
349
350        let result = collect_recent_files(&[session]);
351
352        assert_eq!(result.len(), MAX_RECENT_FILES);
353    }
354
355    #[cfg(not(feature = "no-jail"))]
356    #[test]
357    fn project_warming_rejails_paths_and_skips_stale_records() {
358        let _data = crate::core::data_dir::isolated_data_dir();
359        let root = tempfile::tempdir().unwrap();
360        let outside = tempfile::tempdir().unwrap();
361        let good = root.path().join("good.rs");
362        let stale = root.path().join("stale.rs");
363        let secret = outside.path().join("secret.rs");
364        for path in [&good, &stale, &secret] {
365            std::fs::write(path, "fixture").unwrap();
366        }
367        let mut session = session_at(10);
368        session.project_root = Some(root.path().to_string_lossy().into_owned());
369        for path in [&good, &stale, &secret] {
370            session.touch_file(&path.to_string_lossy(), None, "full", 1);
371        }
372        session
373            .files_touched
374            .iter_mut()
375            .find(|file| file.path == stale.to_string_lossy().as_ref())
376            .expect("stale fixture")
377            .stale = true;
378
379        let warmed = collect_recent_files_in_project(
380            &[session],
381            root.path().to_str().expect("UTF-8 temporary root"),
382        );
383
384        assert_eq!(warmed.len(), 1);
385        assert_eq!(
386            warmed[0].path,
387            crate::core::pathutil::safe_canonicalize(&good)
388                .unwrap()
389                .to_string_lossy()
390                .into_owned()
391        );
392    }
393
394    #[cfg(feature = "no-jail")]
395    #[test]
396    fn project_warming_no_jail_skips_stale_and_accepts_outside_root() {
397        let root = tempfile::tempdir().unwrap();
398        let outside = tempfile::tempdir().unwrap();
399        let stale = root.path().join("stale.rs");
400        let outside_file = outside.path().join("outside.rs");
401        for path in [&stale, &outside_file] {
402            std::fs::write(path, "fixture").unwrap();
403        }
404
405        let mut session = session_at(10);
406        session.project_root = Some(root.path().to_string_lossy().into_owned());
407        for path in [&stale, &outside_file] {
408            session.touch_file(&path.to_string_lossy(), None, "full", 1);
409        }
410        session
411            .files_touched
412            .iter_mut()
413            .find(|file| file.path == stale.to_string_lossy().as_ref())
414            .expect("stale fixture")
415            .stale = true;
416
417        let warmed = collect_recent_files_in_project(
418            &[session],
419            root.path().to_str().expect("UTF-8 temporary root"),
420        );
421
422        assert_eq!(warmed.len(), 1);
423        assert_eq!(
424            warmed[0].path,
425            crate::core::pathutil::safe_canonicalize(&outside_file)
426                .unwrap()
427                .to_string_lossy()
428                .into_owned()
429        );
430    }
431}