fallow-engine 3.30.0

Typed analysis engine facade for fallow consumers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//! Parsed modules that a long-lived process keeps across analysis sessions.
//!
//! A typed MCP tool call builds a new [`AnalysisSession`] for each call. Each
//! session loads the persisted parse cache, checks each file against it, and
//! writes the cache back. A process that installs a [`WarmParseStore`] keeps
//! the parsed modules of recent sessions in memory. A later session with the
//! same file list and the same file fingerprints takes its modules from the
//! store and does no parse work.
//!
//! The store is safe to share between sessions with different configs,
//! because a parse depends only on the file path, the file content, and the
//! config hash of the persisted parse cache. The key holds all three: the
//! project root and the cache config hash, the ordered file list (the file ids
//! follow from it), and one fingerprint per file. The store keeps a module
//! only when each fingerprint can stand in for the file content without a
//! content check, which needs a known ctime. On a platform with no ctime, such
//! as Windows, each session parses through the persisted cache as before.
//!
//! The limit of the store is on the memory of the kept modules. The store
//! cannot measure that memory, so it makes an estimate from the source size
//! and the file count. Each kept file list holds its own modules: two lists
//! that share files, such as a full list and a production list, each count in
//! full.
//!
//! [`AnalysisSession`]: crate::session::AnalysisSession

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, PoisonError, RwLock};

use fallow_types::discover::{DiscoveredFile, FileId};
use fallow_types::extract::{ModuleInfo, SourceParseDegradation, SourceReadFailure};
use fallow_types::source_fingerprint::SourceFingerprint;

/// The default number of parsed file lists that a store keeps.
pub const DEFAULT_MAX_ENTRIES: usize = 4;

/// The default limit on the estimated memory of the kept modules.
pub const DEFAULT_MAX_RETAINED_BYTES: u64 = 512 * 1024 * 1024;

/// The estimated heap memory of the parsed modules for one byte of source.
///
/// The heap of the parsed modules of ten public projects was 4.4 to 10.5
/// times the source size. The estimate uses a value above the largest ratio,
/// so the real memory stays below the limit.
const RETAINED_BYTES_PER_SOURCE_BYTE: u64 = 12;

/// Memory limits of a [`WarmParseStore`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WarmParseLimits {
    /// The most parsed file lists that the store keeps. The store removes the
    /// least recently used list first.
    pub max_entries: usize,
    /// The limit on the estimated memory, in bytes, of the kept modules of
    /// all file lists. The estimate is 12 bytes for each source byte, plus
    /// the size of one module struct for each file. A file list with an
    /// estimate over this limit is not kept.
    pub max_retained_bytes: u64,
}

impl Default for WarmParseLimits {
    fn default() -> Self {
        Self {
            max_entries: DEFAULT_MAX_ENTRIES,
            max_retained_bytes: DEFAULT_MAX_RETAINED_BYTES,
        }
    }
}

/// The parse work of the sessions that used a store.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct WarmParseCounts {
    /// Parse passes over a full file list.
    pub parse_runs: usize,
    /// Files parsed from source.
    pub modules_parsed: usize,
    /// Files served from the persisted parse cache.
    pub disk_cache_hits: usize,
    /// Files served from the modules in the store.
    pub modules_reused: usize,
}

/// Parsed modules kept across analysis sessions in one process.
#[derive(Debug)]
pub struct WarmParseStore {
    limits: WarmParseLimits,
    entries: Mutex<Vec<WarmEntry>>,
    parse_runs: AtomicUsize,
    modules_parsed: AtomicUsize,
    disk_cache_hits: AtomicUsize,
    modules_reused: AtomicUsize,
}

#[derive(Debug)]
struct WarmEntry {
    root: PathBuf,
    cache_config_hash: u64,
    paths: Vec<PathBuf>,
    file_ids: Vec<FileId>,
    fingerprints: Vec<SourceFingerprint>,
    has_complexity: bool,
    retained_bytes: u64,
    parse: WarmParse,
}

/// The identity of one parse: the project, the file list, and the file
/// fingerprints.
#[derive(Debug, Clone, Copy)]
pub(crate) struct WarmParseKey<'a> {
    pub(crate) root: &'a Path,
    pub(crate) cache_config_hash: u64,
    pub(crate) files: &'a [DiscoveredFile],
    pub(crate) fingerprints: &'a [SourceFingerprint],
}

impl WarmParseKey<'_> {
    /// Whether the store may keep the modules of this parse. Each fingerprint
    /// must stand in for the file content without a content check.
    pub(crate) fn is_reusable(&self) -> bool {
        self.files.len() == self.fingerprints.len()
            && self
                .fingerprints
                .iter()
                .all(|fingerprint| fingerprint.is_trustworthy_without_content())
    }

    /// The estimated heap memory of the parsed modules of this file list.
    fn retained_bytes(&self) -> u64 {
        estimated_retained_bytes(self.fingerprints)
    }
}

/// The estimated heap memory of the parsed modules of the files with these
/// fingerprints: 12 bytes for each source byte, plus the size of one module
/// struct for each file. [`WarmParseLimits::max_retained_bytes`] applies to
/// this estimate.
#[must_use]
pub fn estimated_retained_bytes(fingerprints: &[SourceFingerprint]) -> u64 {
    let source_bytes: u64 = fingerprints
        .iter()
        .map(|fingerprint| fingerprint.file_size)
        .sum();
    let module_bytes = u64::try_from(size_of::<ModuleInfo>()).unwrap_or(u64::MAX);
    let file_count = u64::try_from(fingerprints.len()).unwrap_or(u64::MAX);
    source_bytes
        .saturating_mul(RETAINED_BYTES_PER_SOURCE_BYTE)
        .saturating_add(file_count.saturating_mul(module_bytes))
}

/// The output of one parse that a later session can use again.
#[derive(Debug, Clone)]
pub(crate) struct WarmParse {
    pub(crate) modules: Arc<[ModuleInfo]>,
    pub(crate) read_failures: Arc<[SourceReadFailure]>,
    pub(crate) parse_degradations: Arc<[SourceParseDegradation]>,
}

impl WarmEntry {
    fn matches(&self, key: &WarmParseKey<'_>) -> bool {
        self.matches_files(key) && self.fingerprints == key.fingerprints
    }

    /// Whether the entry is a parse of the same file list. The kept modules
    /// carry their file ids, so the ids must also be the same.
    fn matches_files(&self, key: &WarmParseKey<'_>) -> bool {
        self.cache_config_hash == key.cache_config_hash
            && self.root == key.root
            && self
                .paths
                .iter()
                .eq(key.files.iter().map(|file| &file.path))
            && self
                .file_ids
                .iter()
                .copied()
                .eq(key.files.iter().map(|file| file.id))
    }
}

impl WarmParseStore {
    /// Create an empty store with the given memory limits.
    #[must_use]
    pub fn new(limits: WarmParseLimits) -> Self {
        Self {
            limits,
            entries: Mutex::new(Vec::new()),
            parse_runs: AtomicUsize::new(0),
            modules_parsed: AtomicUsize::new(0),
            disk_cache_hits: AtomicUsize::new(0),
            modules_reused: AtomicUsize::new(0),
        }
    }

    /// The parse work of the sessions that used this store.
    #[must_use]
    pub fn counts(&self) -> WarmParseCounts {
        WarmParseCounts {
            parse_runs: self.parse_runs.load(Ordering::Relaxed),
            modules_parsed: self.modules_parsed.load(Ordering::Relaxed),
            disk_cache_hits: self.disk_cache_hits.load(Ordering::Relaxed),
            modules_reused: self.modules_reused.load(Ordering::Relaxed),
        }
    }

    /// The number of parsed file lists in the store.
    #[must_use]
    pub fn len(&self) -> usize {
        self.lock().len()
    }

    /// Whether the store keeps no parsed file list.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.lock().is_empty()
    }

    /// The kept parse for `key`, when it has complexity or the caller needs
    /// none. A hit becomes the most recently used entry.
    pub(crate) fn get(&self, key: &WarmParseKey<'_>, need_complexity: bool) -> Option<WarmParse> {
        if !key.is_reusable() {
            return None;
        }
        let mut entries = self.lock();
        let position = entries
            .iter()
            .position(|entry| entry.matches(key) && (entry.has_complexity || !need_complexity))?;
        let entry = entries.remove(position);
        let parse = entry.parse.clone();
        entries.push(entry);
        drop(entries);
        self.modules_reused
            .fetch_add(parse.modules.len(), Ordering::Relaxed);
        Some(parse)
    }

    /// Keep the parse for `key`. It replaces an older parse of the same file
    /// list, and the least recently used entries leave the store until it is
    /// within its limits.
    pub(crate) fn put(&self, key: &WarmParseKey<'_>, has_complexity: bool, parse: WarmParse) {
        let retained_bytes = key.retained_bytes();
        let keep = key.is_reusable()
            && self.limits.max_entries > 0
            && retained_bytes <= self.limits.max_retained_bytes;
        let entry = keep.then(|| WarmEntry {
            root: key.root.to_path_buf(),
            cache_config_hash: key.cache_config_hash,
            paths: key.files.iter().map(|file| file.path.clone()).collect(),
            file_ids: key.files.iter().map(|file| file.id).collect(),
            fingerprints: key.fingerprints.to_vec(),
            has_complexity,
            retained_bytes,
            parse,
        });

        let mut entries = self.lock();
        entries.retain(|entry| !entry.matches_files(key));
        entries.extend(entry);
        let mut total_bytes: u64 = entries.iter().map(|entry| entry.retained_bytes).sum();
        while entries.len() > self.limits.max_entries
            || total_bytes > self.limits.max_retained_bytes
        {
            let removed = entries.remove(0);
            total_bytes -= removed.retained_bytes;
        }
        drop(entries);
    }

    /// Count one parse pass over a full file list.
    pub(crate) fn record_parse(&self, cache_misses: usize, cache_hits: usize) {
        self.parse_runs.fetch_add(1, Ordering::Relaxed);
        self.modules_parsed
            .fetch_add(cache_misses, Ordering::Relaxed);
        self.disk_cache_hits
            .fetch_add(cache_hits, Ordering::Relaxed);
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, Vec<WarmEntry>> {
        self.entries.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

static INSTALLED: RwLock<Option<Arc<WarmParseStore>>> = RwLock::new(None);

/// Make `store` the store of each session that this process creates from now
/// on. `None` removes the store, so new sessions parse as before.
///
/// Only a long-lived process that runs many analyses of the same project
/// installs a store, such as the MCP server. A session keeps the store that
/// was installed when the session was created.
pub fn install(store: Option<Arc<WarmParseStore>>) {
    *INSTALLED.write().unwrap_or_else(PoisonError::into_inner) = store;
}

/// The store that new sessions use, if a process installed one.
#[must_use]
pub fn installed() -> Option<Arc<WarmParseStore>> {
    INSTALLED
        .read()
        .unwrap_or_else(PoisonError::into_inner)
        .clone()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn files(paths: &[&str]) -> Vec<DiscoveredFile> {
        paths
            .iter()
            .enumerate()
            .map(|(index, path)| DiscoveredFile {
                id: FileId(u32::try_from(index).expect("small index")),
                path: PathBuf::from(path),
                size_bytes: 1,
            })
            .collect()
    }

    fn fingerprints(count: usize, size: u64) -> Vec<SourceFingerprint> {
        (0..count)
            .map(|index| SourceFingerprint::with_ctime(10 + index as u64, 20, size))
            .collect()
    }

    fn parse() -> WarmParse {
        WarmParse {
            modules: Arc::from(Vec::new()),
            read_failures: Arc::from(Vec::new()),
            parse_degradations: Arc::from(Vec::new()),
        }
    }

    fn key<'a>(
        root: &'a Path,
        files: &'a [DiscoveredFile],
        fingerprints: &'a [SourceFingerprint],
    ) -> WarmParseKey<'a> {
        WarmParseKey {
            root,
            cache_config_hash: 7,
            files,
            fingerprints,
        }
    }

    #[test]
    fn a_hit_needs_the_same_files_and_fingerprints() {
        let store = WarmParseStore::new(WarmParseLimits::default());
        let root = Path::new("/project");
        let listed = files(&["/project/a.ts", "/project/b.ts"]);
        let marks = fingerprints(2, 5);
        store.put(&key(root, &listed, &marks), true, parse());

        assert!(store.get(&key(root, &listed, &marks), true).is_some());

        let mut edited = marks.clone();
        edited[1].mtime_ns += 1;
        assert!(store.get(&key(root, &listed, &edited), false).is_none());

        let added = files(&["/project/a.ts", "/project/b.ts", "/project/c.ts"]);
        assert!(
            store
                .get(&key(root, &added, &fingerprints(3, 5)), false)
                .is_none()
        );

        let mut other_config = key(root, &listed, &marks);
        other_config.cache_config_hash = 8;
        assert!(store.get(&other_config, false).is_none());
    }

    #[test]
    fn a_parse_without_complexity_does_not_serve_a_request_for_it() {
        let store = WarmParseStore::new(WarmParseLimits::default());
        let root = Path::new("/project");
        let listed = files(&["/project/a.ts"]);
        let marks = fingerprints(1, 5);
        store.put(&key(root, &listed, &marks), false, parse());

        assert!(store.get(&key(root, &listed, &marks), true).is_none());
        assert!(store.get(&key(root, &listed, &marks), false).is_some());
    }

    #[test]
    fn fingerprints_without_ctime_are_not_kept() {
        let store = WarmParseStore::new(WarmParseLimits::default());
        let root = Path::new("/project");
        let listed = files(&["/project/a.ts"]);
        let marks = [SourceFingerprint::new(10, 5)];
        store.put(&key(root, &listed, &marks), true, parse());

        assert!(store.is_empty());
        assert!(store.get(&key(root, &listed, &marks), false).is_none());
    }

    #[test]
    fn a_new_parse_of_the_same_files_replaces_the_old_one() {
        let store = WarmParseStore::new(WarmParseLimits::default());
        let root = Path::new("/project");
        let listed = files(&["/project/a.ts"]);
        let before = fingerprints(1, 5);
        let after = fingerprints(1, 6);
        store.put(&key(root, &listed, &before), true, parse());
        store.put(&key(root, &listed, &after), true, parse());

        assert_eq!(store.len(), 1);
        assert!(store.get(&key(root, &listed, &after), true).is_some());
    }

    #[test]
    fn the_least_recently_used_entry_leaves_first() {
        let store = WarmParseStore::new(WarmParseLimits {
            max_entries: 2,
            max_retained_bytes: u64::MAX,
        });
        let marks = fingerprints(1, 5);
        let first = files(&["/first/a.ts"]);
        let second = files(&["/second/a.ts"]);
        let third = files(&["/third/a.ts"]);
        store.put(&key(Path::new("/first"), &first, &marks), true, parse());
        store.put(&key(Path::new("/second"), &second, &marks), true, parse());
        assert!(
            store
                .get(&key(Path::new("/first"), &first, &marks), true)
                .is_some()
        );
        store.put(&key(Path::new("/third"), &third, &marks), true, parse());

        assert_eq!(store.len(), 2);
        assert!(
            store
                .get(&key(Path::new("/second"), &second, &marks), true)
                .is_none()
        );
        assert!(
            store
                .get(&key(Path::new("/first"), &first, &marks), true)
                .is_some()
        );
    }

    #[test]
    fn the_default_limit_counts_the_memory_of_the_kept_modules() {
        let store = WarmParseStore::new(WarmParseLimits::default());
        let large = files(&["/large/a.ts"]);
        store.put(
            &key(
                Path::new("/large"),
                &large,
                &fingerprints(1, 64 * 1024 * 1024),
            ),
            true,
            parse(),
        );
        assert!(
            store.is_empty(),
            "the modules of 64 MiB of source take more memory than the default limit"
        );

        let medium = files(&["/medium/a.ts"]);
        store.put(
            &key(
                Path::new("/medium"),
                &medium,
                &fingerprints(1, 16 * 1024 * 1024),
            ),
            true,
            parse(),
        );
        assert_eq!(store.len(), 1);
    }

    #[test]
    fn a_list_with_other_file_ids_is_not_served() {
        let store = WarmParseStore::new(WarmParseLimits::default());
        let root = Path::new("/project");
        let listed = files(&["/project/a.ts", "/project/b.ts"]);
        let marks = fingerprints(2, 5);
        store.put(&key(root, &listed, &marks), true, parse());

        let mut renumbered = listed.clone();
        renumbered[0].id = FileId(7);
        assert!(store.get(&key(root, &renumbered, &marks), false).is_none());
        assert!(store.get(&key(root, &listed, &marks), false).is_some());
    }

    #[test]
    fn the_memory_limit_bounds_the_store() {
        let small = files(&["/small/a.ts"]);
        let small_marks = fingerprints(1, 6);
        let small_key = key(Path::new("/small"), &small, &small_marks);
        let store = WarmParseStore::new(WarmParseLimits {
            max_entries: 8,
            max_retained_bytes: small_key.retained_bytes(),
        });
        let large = files(&["/large/a.ts", "/large/b.ts"]);
        store.put(&small_key, true, parse());
        store.put(
            &key(Path::new("/large"), &large, &fingerprints(2, 6)),
            true,
            parse(),
        );
        assert_eq!(store.len(), 1, "a list over the limit is not kept");

        let other = files(&["/other/a.ts"]);
        store.put(
            &key(Path::new("/other"), &other, &fingerprints(1, 6)),
            true,
            parse(),
        );
        assert_eq!(
            store.len(),
            1,
            "the older list leaves to keep the sum within the limit"
        );
        assert!(
            store
                .get(&key(Path::new("/other"), &other, &fingerprints(1, 6)), true)
                .is_some()
        );
    }
}