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    /// The optional facts that the kept modules hold.
108    has: fallow_extract::ParseNeeds,
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 every optional fact that the
250    /// caller needs. A hit becomes the most recently used
251    /// entry.
252    pub(crate) fn get(
253        &self,
254        key: &WarmParseKey<'_>,
255        needs: fallow_extract::ParseNeeds,
256    ) -> Option<WarmParse> {
257        if !key.is_reusable() {
258            return None;
259        }
260        let entries = self.lock();
261        let entry = entries
262            .iter()
263            .find(|entry| entry.matches(key) && entry.has.covers(needs))?;
264        let kept_read_started_ns = entry.read_started_ns;
265        let parse = entry.parse.clone();
266        drop(entries);
267        // Read the files outside the store lock, so another session does not
268        // wait on this disk work.
269        if !unsettled_files_match(key, kept_read_started_ns, &parse.modules) {
270            return None;
271        }
272        let mut entries = self.lock();
273        if let Some(position) = entries
274            .iter()
275            .position(|entry| Arc::ptr_eq(&entry.parse.modules, &parse.modules))
276        {
277            let mut entry = entries.remove(position);
278            // The content of each unsettled file was read after the read
279            // start of `key`, so the fingerprints prove the kept modules from
280            // that time on. A later hit then needs no read for these files.
281            entry.read_started_ns = entry.read_started_ns.max(key.read_started_ns);
282            entries.push(entry);
283        }
284        drop(entries);
285        self.modules_reused
286            .fetch_add(parse.modules.len(), Ordering::Relaxed);
287        Some(parse)
288    }
289
290    /// Keep the parse for `key`. It replaces an older parse of the same file
291    /// list, and the least recently used entries leave the store until it is
292    /// within its limits.
293    pub(crate) fn put(
294        &self,
295        key: &WarmParseKey<'_>,
296        has: fallow_extract::ParseNeeds,
297        parse: WarmParse,
298    ) {
299        let retained_bytes = key.retained_bytes();
300        let keep = key.is_reusable()
301            && self.limits.max_entries > 0
302            && retained_bytes <= self.limits.max_retained_bytes;
303        let entry = keep.then(|| WarmEntry {
304            root: key.root.to_path_buf(),
305            cache_config_hash: key.cache_config_hash,
306            paths: key.files.iter().map(|file| file.path.clone()).collect(),
307            file_ids: key.files.iter().map(|file| file.id).collect(),
308            fingerprints: key.fingerprints.to_vec(),
309            read_started_ns: key.read_started_ns,
310            has,
311            retained_bytes,
312            parse,
313        });
314
315        let mut entries = self.lock();
316        entries.retain(|entry| !entry.matches_files(key));
317        entries.extend(entry);
318        let mut total_bytes: u64 = entries.iter().map(|entry| entry.retained_bytes).sum();
319        while entries.len() > self.limits.max_entries
320            || total_bytes > self.limits.max_retained_bytes
321        {
322            let removed = entries.remove(0);
323            total_bytes -= removed.retained_bytes;
324        }
325        drop(entries);
326    }
327
328    /// Count one parse pass over a full file list.
329    pub(crate) fn record_parse(&self, cache_misses: usize, cache_hits: usize) {
330        self.parse_runs.fetch_add(1, Ordering::Relaxed);
331        self.modules_parsed
332            .fetch_add(cache_misses, Ordering::Relaxed);
333        self.disk_cache_hits
334            .fetch_add(cache_hits, Ordering::Relaxed);
335    }
336
337    fn lock(&self) -> std::sync::MutexGuard<'_, Vec<WarmEntry>> {
338        self.entries.lock().unwrap_or_else(PoisonError::into_inner)
339    }
340}
341
342static INSTALLED: RwLock<Option<Arc<WarmParseStore>>> = RwLock::new(None);
343
344/// Make `store` the store of each session that this process creates from now
345/// on. `None` removes the store, so new sessions parse as before.
346///
347/// Only a long-lived process that runs many analyses of the same project
348/// installs a store, such as the MCP server. A session keeps the store that
349/// was installed when the session was created.
350pub fn install(store: Option<Arc<WarmParseStore>>) {
351    *INSTALLED.write().unwrap_or_else(PoisonError::into_inner) = store;
352}
353
354/// The store that new sessions use, if a process installed one.
355#[must_use]
356pub fn installed() -> Option<Arc<WarmParseStore>> {
357    INSTALLED
358        .read()
359        .unwrap_or_else(PoisonError::into_inner)
360        .clone()
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366
367    const fn needs(complexity: bool, call_facts: bool) -> fallow_extract::ParseNeeds {
368        fallow_extract::ParseNeeds {
369            complexity,
370            call_facts,
371            flags: false,
372            component_contracts: false,
373        }
374    }
375    use fallow_types::source_fingerprint::TIMESTAMP_SETTLE_WINDOW_NS;
376
377    fn files(paths: &[&str]) -> Vec<DiscoveredFile> {
378        paths
379            .iter()
380            .enumerate()
381            .map(|(index, path)| DiscoveredFile {
382                id: FileId(u32::try_from(index).expect("small index")),
383                path: PathBuf::from(path),
384                size_bytes: 1,
385            })
386            .collect()
387    }
388
389    fn fingerprints(count: usize, size: u64) -> Vec<SourceFingerprint> {
390        (0..count)
391            .map(|index| SourceFingerprint::with_ctime(10 + index as u64, 20, size))
392            .collect()
393    }
394
395    fn parse() -> WarmParse {
396        WarmParse {
397            modules: Arc::from(Vec::new()),
398            read_failures: Arc::from(Vec::new()),
399            parse_degradations: Arc::from(Vec::new()),
400        }
401    }
402
403    fn key<'a>(
404        root: &'a Path,
405        files: &'a [DiscoveredFile],
406        fingerprints: &'a [SourceFingerprint],
407    ) -> WarmParseKey<'a> {
408        WarmParseKey {
409            root,
410            cache_config_hash: 7,
411            files,
412            fingerprints,
413            read_started_ns: u64::MAX,
414        }
415    }
416
417    #[test]
418    fn a_hit_needs_the_same_files_and_fingerprints() {
419        let store = WarmParseStore::new(WarmParseLimits::default());
420        let root = Path::new("/project");
421        let listed = files(&["/project/a.ts", "/project/b.ts"]);
422        let marks = fingerprints(2, 5);
423        store.put(&key(root, &listed, &marks), needs(true, true), parse());
424
425        assert!(
426            store
427                .get(&key(root, &listed, &marks), needs(true, false))
428                .is_some()
429        );
430
431        let mut edited = marks.clone();
432        edited[1].mtime_ns += 1;
433        assert!(
434            store
435                .get(&key(root, &listed, &edited), needs(false, false))
436                .is_none()
437        );
438
439        let added = files(&["/project/a.ts", "/project/b.ts", "/project/c.ts"]);
440        assert!(
441            store
442                .get(&key(root, &added, &fingerprints(3, 5)), needs(false, false))
443                .is_none()
444        );
445
446        let mut other_config = key(root, &listed, &marks);
447        other_config.cache_config_hash = 8;
448        assert!(store.get(&other_config, needs(false, false)).is_none());
449    }
450
451    #[test]
452    fn a_parse_without_complexity_does_not_serve_a_request_for_it() {
453        let store = WarmParseStore::new(WarmParseLimits::default());
454        let root = Path::new("/project");
455        let listed = files(&["/project/a.ts"]);
456        let marks = fingerprints(1, 5);
457        store.put(&key(root, &listed, &marks), needs(false, true), parse());
458
459        assert!(
460            store
461                .get(&key(root, &listed, &marks), needs(true, false))
462                .is_none()
463        );
464        assert!(
465            store
466                .get(&key(root, &listed, &marks), needs(false, false))
467                .is_some()
468        );
469    }
470
471    #[test]
472    fn a_parse_without_call_facts_does_not_serve_a_request_for_them() {
473        let store = WarmParseStore::new(WarmParseLimits::default());
474        let root = Path::new("/project");
475        let listed = files(&["/project/a.ts"]);
476        let marks = fingerprints(1, 5);
477        store.put(&key(root, &listed, &marks), needs(true, false), parse());
478
479        assert!(
480            store
481                .get(&key(root, &listed, &marks), needs(true, true))
482                .is_none()
483        );
484        assert!(
485            store
486                .get(&key(root, &listed, &marks), needs(true, false))
487                .is_some()
488        );
489    }
490
491    #[test]
492    fn fingerprints_without_ctime_are_not_kept() {
493        let store = WarmParseStore::new(WarmParseLimits::default());
494        let root = Path::new("/project");
495        let listed = files(&["/project/a.ts"]);
496        let marks = [SourceFingerprint::new(10, 5)];
497        store.put(&key(root, &listed, &marks), needs(true, true), parse());
498
499        assert!(store.is_empty());
500        assert!(
501            store
502                .get(&key(root, &listed, &marks), needs(false, false))
503                .is_none()
504        );
505    }
506
507    #[test]
508    fn a_fingerprint_inside_the_settle_window_needs_the_kept_content() {
509        let project = tempfile::tempdir().expect("project");
510        let source = project.path().join("a.ts");
511        std::fs::write(&source, "export const a = 1;\n").expect("write source");
512        let store = WarmParseStore::new(WarmParseLimits::default());
513        let listed = files(&[source.to_str().expect("utf-8 path")]);
514        let marks = [SourceFingerprint::with_ctime(10, 20, 5)];
515        let recent = WarmParseKey {
516            read_started_ns: 20,
517            ..key(project.path(), &listed, &marks)
518        };
519        store.put(&recent, needs(true, true), parse());
520
521        assert_eq!(store.len(), 1);
522        assert!(
523            store.get(&recent, needs(false, false)).is_none(),
524            "a readable file without a matching kept module is not reused"
525        );
526        let settled = WarmParseKey {
527            read_started_ns: u64::MAX,
528            ..recent
529        };
530        store.put(&settled, needs(true, true), parse());
531        assert!(
532            store.get(&settled, needs(false, false)).is_some(),
533            "a settled fingerprint needs no content check"
534        );
535    }
536
537    /// A real file and a parse of it, so the kept module has the content hash
538    /// of the file.
539    fn parsed_file(dir: &Path, source: &str) -> (Vec<DiscoveredFile>, WarmParse) {
540        let path = dir.join("a.ts");
541        std::fs::write(&path, source).expect("write source");
542        let listed = files(&[path.to_str().expect("utf-8 path")]);
543        let module = fallow_extract::parse_single_file(&listed[0]).expect("parse source");
544        let parse = WarmParse {
545            modules: Arc::from(vec![module]),
546            ..parse()
547        };
548        (listed, parse)
549    }
550
551    #[test]
552    fn an_unsettled_fingerprint_with_the_kept_content_is_reused() {
553        let project = tempfile::tempdir().expect("project");
554        let (listed, kept) = parsed_file(project.path(), "export const a = 1;\n");
555        let marks = [SourceFingerprint::with_ctime(10, 20, 5)];
556        let recent = WarmParseKey {
557            read_started_ns: 20,
558            ..key(project.path(), &listed, &marks)
559        };
560        let store = WarmParseStore::new(WarmParseLimits::default());
561        store.put(&recent, needs(true, true), kept);
562
563        assert!(store.get(&recent, needs(false, false)).is_some());
564    }
565
566    /// A hit that checked the content of an unsettled file proves the
567    /// fingerprint from the read start of that hit on. The entry takes that
568    /// read start, so a later hit needs no content read.
569    #[test]
570    fn a_verified_hit_settles_the_entry() {
571        let project = tempfile::tempdir().expect("project");
572        let (listed, kept) = parsed_file(project.path(), "export const a = 1;\n");
573        let marks = [SourceFingerprint::with_ctime(10, 20, 5)];
574        let recent = WarmParseKey {
575            read_started_ns: 20,
576            ..key(project.path(), &listed, &marks)
577        };
578        let store = WarmParseStore::new(WarmParseLimits::default());
579        store.put(&recent, needs(true, true), kept);
580
581        let later = WarmParseKey {
582            read_started_ns: 20 + TIMESTAMP_SETTLE_WINDOW_NS,
583            ..recent
584        };
585        assert!(
586            store.get(&later, needs(false, false)).is_some(),
587            "the kept content matches"
588        );
589        assert_eq!(
590            store.lock()[0].read_started_ns,
591            later.read_started_ns,
592            "the entry takes the read start of the verified hit"
593        );
594
595        // A different source with the same size and fingerprints. A settled
596        // entry does not read the file, so only the stored read start can
597        // explain a hit here.
598        std::fs::write(&listed[0].path, "export const b = 1;\n").expect("rewrite source");
599        assert!(
600            store.get(&later, needs(false, false)).is_some(),
601            "a settled entry needs no content read"
602        );
603    }
604
605    #[test]
606    fn a_new_parse_of_the_same_files_replaces_the_old_one() {
607        let store = WarmParseStore::new(WarmParseLimits::default());
608        let root = Path::new("/project");
609        let listed = files(&["/project/a.ts"]);
610        let before = fingerprints(1, 5);
611        let after = fingerprints(1, 6);
612        store.put(&key(root, &listed, &before), needs(true, true), parse());
613        store.put(&key(root, &listed, &after), needs(true, true), parse());
614
615        assert_eq!(store.len(), 1);
616        assert!(
617            store
618                .get(&key(root, &listed, &after), needs(true, false))
619                .is_some()
620        );
621    }
622
623    #[test]
624    fn the_least_recently_used_entry_leaves_first() {
625        let store = WarmParseStore::new(WarmParseLimits {
626            max_entries: 2,
627            max_retained_bytes: u64::MAX,
628        });
629        let marks = fingerprints(1, 5);
630        let first = files(&["/first/a.ts"]);
631        let second = files(&["/second/a.ts"]);
632        let third = files(&["/third/a.ts"]);
633        store.put(
634            &key(Path::new("/first"), &first, &marks),
635            needs(true, true),
636            parse(),
637        );
638        store.put(
639            &key(Path::new("/second"), &second, &marks),
640            needs(true, true),
641            parse(),
642        );
643        assert!(
644            store
645                .get(
646                    &key(Path::new("/first"), &first, &marks),
647                    needs(true, false)
648                )
649                .is_some()
650        );
651        store.put(
652            &key(Path::new("/third"), &third, &marks),
653            needs(true, true),
654            parse(),
655        );
656
657        assert_eq!(store.len(), 2);
658        assert!(
659            store
660                .get(
661                    &key(Path::new("/second"), &second, &marks),
662                    needs(true, false)
663                )
664                .is_none()
665        );
666        assert!(
667            store
668                .get(
669                    &key(Path::new("/first"), &first, &marks),
670                    needs(true, false)
671                )
672                .is_some()
673        );
674    }
675
676    #[test]
677    fn the_default_limit_counts_the_memory_of_the_kept_modules() {
678        let store = WarmParseStore::new(WarmParseLimits::default());
679        let large = files(&["/large/a.ts"]);
680        store.put(
681            &key(
682                Path::new("/large"),
683                &large,
684                &fingerprints(1, 64 * 1024 * 1024),
685            ),
686            needs(true, true),
687            parse(),
688        );
689        assert!(
690            store.is_empty(),
691            "the modules of 64 MiB of source take more memory than the default limit"
692        );
693
694        let medium = files(&["/medium/a.ts"]);
695        store.put(
696            &key(
697                Path::new("/medium"),
698                &medium,
699                &fingerprints(1, 16 * 1024 * 1024),
700            ),
701            needs(true, true),
702            parse(),
703        );
704        assert_eq!(store.len(), 1);
705    }
706
707    #[test]
708    fn a_list_with_other_file_ids_is_not_served() {
709        let store = WarmParseStore::new(WarmParseLimits::default());
710        let root = Path::new("/project");
711        let listed = files(&["/project/a.ts", "/project/b.ts"]);
712        let marks = fingerprints(2, 5);
713        store.put(&key(root, &listed, &marks), needs(true, true), parse());
714
715        let mut renumbered = listed.clone();
716        renumbered[0].id = FileId(7);
717        assert!(
718            store
719                .get(&key(root, &renumbered, &marks), needs(false, false))
720                .is_none()
721        );
722        assert!(
723            store
724                .get(&key(root, &listed, &marks), needs(false, false))
725                .is_some()
726        );
727    }
728
729    #[test]
730    fn the_memory_limit_bounds_the_store() {
731        let small = files(&["/small/a.ts"]);
732        let small_marks = fingerprints(1, 6);
733        let small_key = key(Path::new("/small"), &small, &small_marks);
734        let store = WarmParseStore::new(WarmParseLimits {
735            max_entries: 8,
736            max_retained_bytes: small_key.retained_bytes(),
737        });
738        let large = files(&["/large/a.ts", "/large/b.ts"]);
739        store.put(&small_key, needs(true, true), parse());
740        store.put(
741            &key(Path::new("/large"), &large, &fingerprints(2, 6)),
742            needs(true, true),
743            parse(),
744        );
745        assert_eq!(store.len(), 1, "a list over the limit is not kept");
746
747        let other = files(&["/other/a.ts"]);
748        store.put(
749            &key(Path::new("/other"), &other, &fingerprints(1, 6)),
750            needs(true, true),
751            parse(),
752        );
753        assert_eq!(
754            store.len(),
755            1,
756            "the older list leaves to keep the sum within the limit"
757        );
758        assert!(
759            store
760                .get(
761                    &key(Path::new("/other"), &other, &fingerprints(1, 6)),
762                    needs(true, false)
763                )
764                .is_some()
765        );
766    }
767}