Skip to main content

fallow_engine/
warm_parse.rs

1//! Parsed modules that a long-lived process keeps across analysis sessions.
2//!
3//! A typed MCP tool call builds a new [`AnalysisSession`] for each call. Each
4//! session loads the persisted parse cache, checks each file against it, and
5//! writes the cache back. A process that installs a [`WarmParseStore`] keeps
6//! the parsed modules of recent sessions in memory. A later session with the
7//! same file list and the same file fingerprints takes its modules from the
8//! store and does no parse work.
9//!
10//! The store is safe to share between sessions with different configs,
11//! because a parse depends only on the file path, the file content, and the
12//! config hash of the persisted parse cache. The key holds all three: the
13//! project root and the cache config hash, the ordered file list (the file ids
14//! follow from it), and one fingerprint per file. The store keeps a module
15//! only when each fingerprint can stand in for the file content without a
16//! content check, which needs a known ctime. On a platform with no ctime,
17//! such as Windows, each session parses through the persisted cache as
18//! before. A fingerprint that did not settle before the kept parse read the
19//! file can belong to a same-length write in the same timestamp tick, so a
20//! later session reads that file and compares its content hash with the kept
21//! module.
22//!
23//! The limit of the store is on the memory of the kept modules. The store
24//! cannot measure that memory, so it makes an estimate from the source size
25//! and the file count. Each kept file list holds its own modules: two lists
26//! that share files, such as a full list and a production list, each count in
27//! full.
28//!
29//! [`AnalysisSession`]: crate::session::AnalysisSession
30
31use std::path::{Path, PathBuf};
32use std::sync::atomic::{AtomicUsize, Ordering};
33use std::sync::{Arc, Mutex, PoisonError, RwLock};
34
35use fallow_types::discover::{DiscoveredFile, FileId};
36use fallow_types::extract::{ModuleInfo, SourceParseDegradation, SourceReadFailure};
37use fallow_types::source_fingerprint::SourceFingerprint;
38
39/// The default number of parsed file lists that a store keeps.
40const DEFAULT_MAX_ENTRIES: usize = 4;
41
42/// The default limit on the estimated memory of the kept modules.
43pub const DEFAULT_MAX_RETAINED_BYTES: u64 = 512 * 1024 * 1024;
44
45/// The estimated heap memory of the parsed modules for one byte of source.
46///
47/// The heap of the parsed modules of ten public projects was 4.4 to 10.5
48/// times the source size. The estimate uses a value above the largest ratio,
49/// so the real memory stays below the limit.
50const RETAINED_BYTES_PER_SOURCE_BYTE: u64 = 12;
51
52/// Memory limits of a [`WarmParseStore`].
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct WarmParseLimits {
55    /// The most parsed file lists that the store keeps. The store removes the
56    /// least recently used list first.
57    pub max_entries: usize,
58    /// The limit on the estimated memory, in bytes, of the kept modules of
59    /// all file lists. The estimate is 12 bytes for each source byte, plus
60    /// the size of one module struct for each file. A file list with an
61    /// estimate over this limit is not kept.
62    pub max_retained_bytes: u64,
63}
64
65impl Default for WarmParseLimits {
66    fn default() -> Self {
67        Self {
68            max_entries: DEFAULT_MAX_ENTRIES,
69            max_retained_bytes: DEFAULT_MAX_RETAINED_BYTES,
70        }
71    }
72}
73
74/// The parse work of the sessions that used a store.
75#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
76pub struct WarmParseCounts {
77    /// Parse passes over a full file list.
78    pub parse_runs: usize,
79    /// Files parsed from source.
80    pub modules_parsed: usize,
81    /// Files served from the persisted parse cache.
82    pub disk_cache_hits: usize,
83    /// Files served from the modules in the store.
84    pub modules_reused: usize,
85}
86
87/// Parsed modules kept across analysis sessions in one process.
88#[derive(Debug)]
89pub struct WarmParseStore {
90    limits: WarmParseLimits,
91    entries: Mutex<Vec<WarmEntry>>,
92    parse_runs: AtomicUsize,
93    modules_parsed: AtomicUsize,
94    disk_cache_hits: AtomicUsize,
95    modules_reused: AtomicUsize,
96}
97
98#[derive(Debug)]
99struct WarmEntry {
100    root: PathBuf,
101    cache_config_hash: u64,
102    paths: Vec<PathBuf>,
103    file_ids: Vec<FileId>,
104    fingerprints: Vec<SourceFingerprint>,
105    /// The wall-clock time before the parse read `fingerprints`.
106    read_started_ns: u64,
107    has_complexity: bool,
108    has_call_facts: bool,
109    retained_bytes: u64,
110    parse: WarmParse,
111}
112
113/// The identity of one parse: the project, the file list, and the file
114/// fingerprints.
115#[derive(Debug, Clone, Copy)]
116pub(crate) struct WarmParseKey<'a> {
117    pub(crate) root: &'a Path,
118    pub(crate) cache_config_hash: u64,
119    pub(crate) files: &'a [DiscoveredFile],
120    pub(crate) fingerprints: &'a [SourceFingerprint],
121    /// The wall-clock time before the session read `fingerprints`.
122    pub(crate) read_started_ns: u64,
123}
124
125impl WarmParseKey<'_> {
126    /// Whether the store may keep the modules of this parse. Each fingerprint
127    /// must be able to stand in for the file content, which needs a known
128    /// ctime.
129    pub(crate) fn is_reusable(&self) -> bool {
130        self.files.len() == self.fingerprints.len()
131            && self
132                .fingerprints
133                .iter()
134                .all(|fingerprint| fingerprint.is_trustworthy_without_content())
135    }
136
137    /// The estimated heap memory of the parsed modules of this file list.
138    fn retained_bytes(&self) -> u64 {
139        estimated_retained_bytes(self.fingerprints)
140    }
141}
142
143/// The estimated heap memory of the parsed modules of the files with these
144/// fingerprints: 12 bytes for each source byte, plus the size of one module
145/// struct for each file. [`WarmParseLimits::max_retained_bytes`] applies to
146/// this estimate.
147#[must_use]
148pub fn estimated_retained_bytes(fingerprints: &[SourceFingerprint]) -> u64 {
149    let source_bytes: u64 = fingerprints
150        .iter()
151        .map(|fingerprint| fingerprint.file_size)
152        .sum();
153    let module_bytes = u64::try_from(size_of::<ModuleInfo>()).unwrap_or(u64::MAX);
154    let file_count = u64::try_from(fingerprints.len()).unwrap_or(u64::MAX);
155    source_bytes
156        .saturating_mul(RETAINED_BYTES_PER_SOURCE_BYTE)
157        .saturating_add(file_count.saturating_mul(module_bytes))
158}
159
160/// Whether each file of `key` whose fingerprint did not settle before
161/// `kept_read_started_ns` still has the content hash of its kept module.
162///
163/// A same-length write in the same timestamp tick keeps the fingerprint, so
164/// only the content can tell for such a file.
165fn unsettled_files_match(
166    key: &WarmParseKey<'_>,
167    kept_read_started_ns: u64,
168    modules: &[ModuleInfo],
169) -> bool {
170    key.fingerprints
171        .iter()
172        .zip(key.files)
173        .all(|(fingerprint, file)| {
174            fingerprint.is_settled_before(kept_read_started_ns)
175                || crate::session_reuse::module_matches_source(modules, file.id, &file.path)
176        })
177}
178
179/// The output of one parse that a later session can use again.
180#[derive(Debug, Clone)]
181pub(crate) struct WarmParse {
182    pub(crate) modules: Arc<[ModuleInfo]>,
183    pub(crate) read_failures: Arc<[SourceReadFailure]>,
184    pub(crate) parse_degradations: Arc<[SourceParseDegradation]>,
185}
186
187impl WarmEntry {
188    /// Whether the entry is a parse of the same files with the same
189    /// fingerprints. The caller still checks the content of each file that
190    /// did not settle, see [`unsettled_files_match`].
191    fn matches(&self, key: &WarmParseKey<'_>) -> bool {
192        self.matches_files(key) && self.fingerprints == key.fingerprints
193    }
194
195    /// Whether the entry is a parse of the same file list. The kept modules
196    /// carry their file ids, so the ids must also be the same.
197    fn matches_files(&self, key: &WarmParseKey<'_>) -> bool {
198        self.cache_config_hash == key.cache_config_hash
199            && self.root == key.root
200            && self
201                .paths
202                .iter()
203                .eq(key.files.iter().map(|file| &file.path))
204            && self
205                .file_ids
206                .iter()
207                .copied()
208                .eq(key.files.iter().map(|file| file.id))
209    }
210}
211
212impl WarmParseStore {
213    /// Create an empty store with the given memory limits.
214    #[must_use]
215    pub fn new(limits: WarmParseLimits) -> Self {
216        Self {
217            limits,
218            entries: Mutex::new(Vec::new()),
219            parse_runs: AtomicUsize::new(0),
220            modules_parsed: AtomicUsize::new(0),
221            disk_cache_hits: AtomicUsize::new(0),
222            modules_reused: AtomicUsize::new(0),
223        }
224    }
225
226    /// The parse work of the sessions that used this store.
227    #[must_use]
228    pub fn counts(&self) -> WarmParseCounts {
229        WarmParseCounts {
230            parse_runs: self.parse_runs.load(Ordering::Relaxed),
231            modules_parsed: self.modules_parsed.load(Ordering::Relaxed),
232            disk_cache_hits: self.disk_cache_hits.load(Ordering::Relaxed),
233            modules_reused: self.modules_reused.load(Ordering::Relaxed),
234        }
235    }
236
237    /// The number of parsed file lists in the store.
238    #[must_use]
239    pub fn len(&self) -> usize {
240        self.lock().len()
241    }
242
243    /// Whether the store keeps no parsed file list.
244    #[must_use]
245    pub fn is_empty(&self) -> bool {
246        self.lock().is_empty()
247    }
248
249    /// The kept parse for `key`, when it has the complexity and the call
250    /// facts that the caller needs. A hit becomes the most recently used
251    /// entry.
252    pub(crate) fn get(
253        &self,
254        key: &WarmParseKey<'_>,
255        need_complexity: bool,
256        need_call_facts: bool,
257    ) -> Option<WarmParse> {
258        if !key.is_reusable() {
259            return None;
260        }
261        let entries = self.lock();
262        let entry = entries.iter().find(|entry| {
263            entry.matches(key)
264                && (entry.has_complexity || !need_complexity)
265                && (entry.has_call_facts || !need_call_facts)
266        })?;
267        let kept_read_started_ns = entry.read_started_ns;
268        let parse = entry.parse.clone();
269        drop(entries);
270        // Read the files outside the store lock, so another session does not
271        // wait on this disk work.
272        if !unsettled_files_match(key, kept_read_started_ns, &parse.modules) {
273            return None;
274        }
275        let mut entries = self.lock();
276        if let Some(position) = entries
277            .iter()
278            .position(|entry| Arc::ptr_eq(&entry.parse.modules, &parse.modules))
279        {
280            let mut entry = entries.remove(position);
281            // The content of each unsettled file was read after the read
282            // start of `key`, so the fingerprints prove the kept modules from
283            // that time on. A later hit then needs no read for these files.
284            entry.read_started_ns = entry.read_started_ns.max(key.read_started_ns);
285            entries.push(entry);
286        }
287        drop(entries);
288        self.modules_reused
289            .fetch_add(parse.modules.len(), Ordering::Relaxed);
290        Some(parse)
291    }
292
293    /// Keep the parse for `key`. It replaces an older parse of the same file
294    /// list, and the least recently used entries leave the store until it is
295    /// within its limits.
296    pub(crate) fn put(
297        &self,
298        key: &WarmParseKey<'_>,
299        has_complexity: bool,
300        has_call_facts: bool,
301        parse: WarmParse,
302    ) {
303        let retained_bytes = key.retained_bytes();
304        let keep = key.is_reusable()
305            && self.limits.max_entries > 0
306            && retained_bytes <= self.limits.max_retained_bytes;
307        let entry = keep.then(|| WarmEntry {
308            root: key.root.to_path_buf(),
309            cache_config_hash: key.cache_config_hash,
310            paths: key.files.iter().map(|file| file.path.clone()).collect(),
311            file_ids: key.files.iter().map(|file| file.id).collect(),
312            fingerprints: key.fingerprints.to_vec(),
313            read_started_ns: key.read_started_ns,
314            has_complexity,
315            has_call_facts,
316            retained_bytes,
317            parse,
318        });
319
320        let mut entries = self.lock();
321        entries.retain(|entry| !entry.matches_files(key));
322        entries.extend(entry);
323        let mut total_bytes: u64 = entries.iter().map(|entry| entry.retained_bytes).sum();
324        while entries.len() > self.limits.max_entries
325            || total_bytes > self.limits.max_retained_bytes
326        {
327            let removed = entries.remove(0);
328            total_bytes -= removed.retained_bytes;
329        }
330        drop(entries);
331    }
332
333    /// Count one parse pass over a full file list.
334    pub(crate) fn record_parse(&self, cache_misses: usize, cache_hits: usize) {
335        self.parse_runs.fetch_add(1, Ordering::Relaxed);
336        self.modules_parsed
337            .fetch_add(cache_misses, Ordering::Relaxed);
338        self.disk_cache_hits
339            .fetch_add(cache_hits, Ordering::Relaxed);
340    }
341
342    fn lock(&self) -> std::sync::MutexGuard<'_, Vec<WarmEntry>> {
343        self.entries.lock().unwrap_or_else(PoisonError::into_inner)
344    }
345}
346
347static INSTALLED: RwLock<Option<Arc<WarmParseStore>>> = RwLock::new(None);
348
349/// Make `store` the store of each session that this process creates from now
350/// on. `None` removes the store, so new sessions parse as before.
351///
352/// Only a long-lived process that runs many analyses of the same project
353/// installs a store, such as the MCP server. A session keeps the store that
354/// was installed when the session was created.
355pub fn install(store: Option<Arc<WarmParseStore>>) {
356    *INSTALLED.write().unwrap_or_else(PoisonError::into_inner) = store;
357}
358
359/// The store that new sessions use, if a process installed one.
360#[must_use]
361pub fn installed() -> Option<Arc<WarmParseStore>> {
362    INSTALLED
363        .read()
364        .unwrap_or_else(PoisonError::into_inner)
365        .clone()
366}
367
368#[cfg(test)]
369mod tests {
370    use super::*;
371    use fallow_types::source_fingerprint::TIMESTAMP_SETTLE_WINDOW_NS;
372
373    fn files(paths: &[&str]) -> Vec<DiscoveredFile> {
374        paths
375            .iter()
376            .enumerate()
377            .map(|(index, path)| DiscoveredFile {
378                id: FileId(u32::try_from(index).expect("small index")),
379                path: PathBuf::from(path),
380                size_bytes: 1,
381            })
382            .collect()
383    }
384
385    fn fingerprints(count: usize, size: u64) -> Vec<SourceFingerprint> {
386        (0..count)
387            .map(|index| SourceFingerprint::with_ctime(10 + index as u64, 20, size))
388            .collect()
389    }
390
391    fn parse() -> WarmParse {
392        WarmParse {
393            modules: Arc::from(Vec::new()),
394            read_failures: Arc::from(Vec::new()),
395            parse_degradations: Arc::from(Vec::new()),
396        }
397    }
398
399    fn key<'a>(
400        root: &'a Path,
401        files: &'a [DiscoveredFile],
402        fingerprints: &'a [SourceFingerprint],
403    ) -> WarmParseKey<'a> {
404        WarmParseKey {
405            root,
406            cache_config_hash: 7,
407            files,
408            fingerprints,
409            read_started_ns: u64::MAX,
410        }
411    }
412
413    #[test]
414    fn a_hit_needs_the_same_files_and_fingerprints() {
415        let store = WarmParseStore::new(WarmParseLimits::default());
416        let root = Path::new("/project");
417        let listed = files(&["/project/a.ts", "/project/b.ts"]);
418        let marks = fingerprints(2, 5);
419        store.put(&key(root, &listed, &marks), true, true, parse());
420
421        assert!(
422            store
423                .get(&key(root, &listed, &marks), true, false)
424                .is_some()
425        );
426
427        let mut edited = marks.clone();
428        edited[1].mtime_ns += 1;
429        assert!(
430            store
431                .get(&key(root, &listed, &edited), false, false)
432                .is_none()
433        );
434
435        let added = files(&["/project/a.ts", "/project/b.ts", "/project/c.ts"]);
436        assert!(
437            store
438                .get(&key(root, &added, &fingerprints(3, 5)), false, false)
439                .is_none()
440        );
441
442        let mut other_config = key(root, &listed, &marks);
443        other_config.cache_config_hash = 8;
444        assert!(store.get(&other_config, false, false).is_none());
445    }
446
447    #[test]
448    fn a_parse_without_complexity_does_not_serve_a_request_for_it() {
449        let store = WarmParseStore::new(WarmParseLimits::default());
450        let root = Path::new("/project");
451        let listed = files(&["/project/a.ts"]);
452        let marks = fingerprints(1, 5);
453        store.put(&key(root, &listed, &marks), false, true, parse());
454
455        assert!(
456            store
457                .get(&key(root, &listed, &marks), true, false)
458                .is_none()
459        );
460        assert!(
461            store
462                .get(&key(root, &listed, &marks), false, false)
463                .is_some()
464        );
465    }
466
467    #[test]
468    fn a_parse_without_call_facts_does_not_serve_a_request_for_them() {
469        let store = WarmParseStore::new(WarmParseLimits::default());
470        let root = Path::new("/project");
471        let listed = files(&["/project/a.ts"]);
472        let marks = fingerprints(1, 5);
473        store.put(&key(root, &listed, &marks), true, false, parse());
474
475        assert!(store.get(&key(root, &listed, &marks), true, true).is_none());
476        assert!(
477            store
478                .get(&key(root, &listed, &marks), true, false)
479                .is_some()
480        );
481    }
482
483    #[test]
484    fn fingerprints_without_ctime_are_not_kept() {
485        let store = WarmParseStore::new(WarmParseLimits::default());
486        let root = Path::new("/project");
487        let listed = files(&["/project/a.ts"]);
488        let marks = [SourceFingerprint::new(10, 5)];
489        store.put(&key(root, &listed, &marks), true, true, parse());
490
491        assert!(store.is_empty());
492        assert!(
493            store
494                .get(&key(root, &listed, &marks), false, false)
495                .is_none()
496        );
497    }
498
499    #[test]
500    fn a_fingerprint_inside_the_settle_window_needs_the_kept_content() {
501        let project = tempfile::tempdir().expect("project");
502        let source = project.path().join("a.ts");
503        std::fs::write(&source, "export const a = 1;\n").expect("write source");
504        let store = WarmParseStore::new(WarmParseLimits::default());
505        let listed = files(&[source.to_str().expect("utf-8 path")]);
506        let marks = [SourceFingerprint::with_ctime(10, 20, 5)];
507        let recent = WarmParseKey {
508            read_started_ns: 20,
509            ..key(project.path(), &listed, &marks)
510        };
511        store.put(&recent, true, true, parse());
512
513        assert_eq!(store.len(), 1);
514        assert!(
515            store.get(&recent, false, false).is_none(),
516            "a readable file without a matching kept module is not reused"
517        );
518        let settled = WarmParseKey {
519            read_started_ns: u64::MAX,
520            ..recent
521        };
522        store.put(&settled, true, true, parse());
523        assert!(
524            store.get(&settled, false, false).is_some(),
525            "a settled fingerprint needs no content check"
526        );
527    }
528
529    /// A real file and a parse of it, so the kept module has the content hash
530    /// of the file.
531    fn parsed_file(dir: &Path, source: &str) -> (Vec<DiscoveredFile>, WarmParse) {
532        let path = dir.join("a.ts");
533        std::fs::write(&path, source).expect("write source");
534        let listed = files(&[path.to_str().expect("utf-8 path")]);
535        let module = fallow_extract::parse_single_file(&listed[0]).expect("parse source");
536        let parse = WarmParse {
537            modules: Arc::from(vec![module]),
538            ..parse()
539        };
540        (listed, parse)
541    }
542
543    #[test]
544    fn an_unsettled_fingerprint_with_the_kept_content_is_reused() {
545        let project = tempfile::tempdir().expect("project");
546        let (listed, kept) = parsed_file(project.path(), "export const a = 1;\n");
547        let marks = [SourceFingerprint::with_ctime(10, 20, 5)];
548        let recent = WarmParseKey {
549            read_started_ns: 20,
550            ..key(project.path(), &listed, &marks)
551        };
552        let store = WarmParseStore::new(WarmParseLimits::default());
553        store.put(&recent, true, true, kept);
554
555        assert!(store.get(&recent, false, false).is_some());
556    }
557
558    /// A hit that checked the content of an unsettled file proves the
559    /// fingerprint from the read start of that hit on. The entry takes that
560    /// read start, so a later hit needs no content read.
561    #[test]
562    fn a_verified_hit_settles_the_entry() {
563        let project = tempfile::tempdir().expect("project");
564        let (listed, kept) = parsed_file(project.path(), "export const a = 1;\n");
565        let marks = [SourceFingerprint::with_ctime(10, 20, 5)];
566        let recent = WarmParseKey {
567            read_started_ns: 20,
568            ..key(project.path(), &listed, &marks)
569        };
570        let store = WarmParseStore::new(WarmParseLimits::default());
571        store.put(&recent, true, true, kept);
572
573        let later = WarmParseKey {
574            read_started_ns: 20 + TIMESTAMP_SETTLE_WINDOW_NS,
575            ..recent
576        };
577        assert!(
578            store.get(&later, false, false).is_some(),
579            "the kept content matches"
580        );
581        assert_eq!(
582            store.lock()[0].read_started_ns,
583            later.read_started_ns,
584            "the entry takes the read start of the verified hit"
585        );
586
587        // A different source with the same size and fingerprints. A settled
588        // entry does not read the file, so only the stored read start can
589        // explain a hit here.
590        std::fs::write(&listed[0].path, "export const b = 1;\n").expect("rewrite source");
591        assert!(
592            store.get(&later, false, false).is_some(),
593            "a settled entry needs no content read"
594        );
595    }
596
597    #[test]
598    fn a_new_parse_of_the_same_files_replaces_the_old_one() {
599        let store = WarmParseStore::new(WarmParseLimits::default());
600        let root = Path::new("/project");
601        let listed = files(&["/project/a.ts"]);
602        let before = fingerprints(1, 5);
603        let after = fingerprints(1, 6);
604        store.put(&key(root, &listed, &before), true, true, parse());
605        store.put(&key(root, &listed, &after), true, true, parse());
606
607        assert_eq!(store.len(), 1);
608        assert!(
609            store
610                .get(&key(root, &listed, &after), true, false)
611                .is_some()
612        );
613    }
614
615    #[test]
616    fn the_least_recently_used_entry_leaves_first() {
617        let store = WarmParseStore::new(WarmParseLimits {
618            max_entries: 2,
619            max_retained_bytes: u64::MAX,
620        });
621        let marks = fingerprints(1, 5);
622        let first = files(&["/first/a.ts"]);
623        let second = files(&["/second/a.ts"]);
624        let third = files(&["/third/a.ts"]);
625        store.put(
626            &key(Path::new("/first"), &first, &marks),
627            true,
628            true,
629            parse(),
630        );
631        store.put(
632            &key(Path::new("/second"), &second, &marks),
633            true,
634            true,
635            parse(),
636        );
637        assert!(
638            store
639                .get(&key(Path::new("/first"), &first, &marks), true, false)
640                .is_some()
641        );
642        store.put(
643            &key(Path::new("/third"), &third, &marks),
644            true,
645            true,
646            parse(),
647        );
648
649        assert_eq!(store.len(), 2);
650        assert!(
651            store
652                .get(&key(Path::new("/second"), &second, &marks), true, false)
653                .is_none()
654        );
655        assert!(
656            store
657                .get(&key(Path::new("/first"), &first, &marks), true, false)
658                .is_some()
659        );
660    }
661
662    #[test]
663    fn the_default_limit_counts_the_memory_of_the_kept_modules() {
664        let store = WarmParseStore::new(WarmParseLimits::default());
665        let large = files(&["/large/a.ts"]);
666        store.put(
667            &key(
668                Path::new("/large"),
669                &large,
670                &fingerprints(1, 64 * 1024 * 1024),
671            ),
672            true,
673            true,
674            parse(),
675        );
676        assert!(
677            store.is_empty(),
678            "the modules of 64 MiB of source take more memory than the default limit"
679        );
680
681        let medium = files(&["/medium/a.ts"]);
682        store.put(
683            &key(
684                Path::new("/medium"),
685                &medium,
686                &fingerprints(1, 16 * 1024 * 1024),
687            ),
688            true,
689            true,
690            parse(),
691        );
692        assert_eq!(store.len(), 1);
693    }
694
695    #[test]
696    fn a_list_with_other_file_ids_is_not_served() {
697        let store = WarmParseStore::new(WarmParseLimits::default());
698        let root = Path::new("/project");
699        let listed = files(&["/project/a.ts", "/project/b.ts"]);
700        let marks = fingerprints(2, 5);
701        store.put(&key(root, &listed, &marks), true, true, parse());
702
703        let mut renumbered = listed.clone();
704        renumbered[0].id = FileId(7);
705        assert!(
706            store
707                .get(&key(root, &renumbered, &marks), false, false)
708                .is_none()
709        );
710        assert!(
711            store
712                .get(&key(root, &listed, &marks), false, false)
713                .is_some()
714        );
715    }
716
717    #[test]
718    fn the_memory_limit_bounds_the_store() {
719        let small = files(&["/small/a.ts"]);
720        let small_marks = fingerprints(1, 6);
721        let small_key = key(Path::new("/small"), &small, &small_marks);
722        let store = WarmParseStore::new(WarmParseLimits {
723            max_entries: 8,
724            max_retained_bytes: small_key.retained_bytes(),
725        });
726        let large = files(&["/large/a.ts", "/large/b.ts"]);
727        store.put(&small_key, true, true, parse());
728        store.put(
729            &key(Path::new("/large"), &large, &fingerprints(2, 6)),
730            true,
731            true,
732            parse(),
733        );
734        assert_eq!(store.len(), 1, "a list over the limit is not kept");
735
736        let other = files(&["/other/a.ts"]);
737        store.put(
738            &key(Path::new("/other"), &other, &fingerprints(1, 6)),
739            true,
740            true,
741            parse(),
742        );
743        assert_eq!(
744            store.len(),
745            1,
746            "the older list leaves to keep the sum within the limit"
747        );
748        assert!(
749            store
750                .get(
751                    &key(Path::new("/other"), &other, &fingerprints(1, 6)),
752                    true,
753                    false
754                )
755                .is_some()
756        );
757    }
758}