Skip to main content

fallow_extract/cache/
store.rs

1//! Cache store: load, save, and query cached module data.
2
3use std::path::Path;
4use std::sync::atomic::{AtomicBool, Ordering};
5
6#[cfg(test)]
7use std::cell::Cell;
8
9use fallow_types::cache_rejection::CacheRejection;
10use fallow_types::path_guard::CacheTarget;
11use rustc_hash::FxHashMap;
12
13use bitcode::{Decode, Encode};
14
15use super::conversion::module_to_cached;
16use super::types::{
17    CACHE_VERSION, CachedModule, DEFAULT_CACHE_MAX_SIZE, EVICTION_SIGNIFICANT_BPS,
18    EVICTION_TARGET_BPS, EVICTION_TRIGGER_BPS,
19};
20
21#[cfg(test)]
22thread_local! {
23    static FULL_STORE_ENCODE_COUNT: Cell<usize> = const { Cell::new(0) };
24    static LAST_WORKING_SET_EVICTED_COUNT: Cell<usize> = const { Cell::new(0) };
25}
26
27/// What one eviction did to the working set of the latest run.
28///
29/// The working set is the entries that the latest run saw. An evicted
30/// working-set entry is a file that the next run of the same scope parses
31/// again, also on an unchanged tree.
32#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
33pub(super) struct WorkingSetEviction {
34    /// Entries that the latest run saw.
35    pub(super) entries: usize,
36    /// Working-set entries that eviction removed to stay under the cap.
37    pub(super) evicted: usize,
38    /// Encoded size of the working set before eviction, estimated as its
39    /// share of the encoded store.
40    pub(super) encoded_bytes: usize,
41}
42
43static WORKING_SET_EVICTION_WARNED: AtomicBool = AtomicBool::new(false);
44
45const BYTES_PER_MIB: usize = 1024 * 1024;
46
47/// Headroom, in basis points of the working set, in the suggested cap. A save
48/// above 80 percent of the cap evicts the entries of earlier runs, and a save
49/// above the cap also evicts the working set. With a cap of 125 percent of the
50/// working set, the working set alone stays under the 80 percent trigger.
51const SUGGESTED_CAP_BPS: usize = 12_500;
52
53/// Warn once for each process when the cap forced out working-set entries.
54///
55/// The warning uses the analysis diagnostic target, so a quiet run does not
56/// print it. A long-lived process, such as the language server, saves after
57/// each analysis, and one line is enough for it.
58fn warn_working_set_evicted(eviction: &WorkingSetEviction, max_size_bytes: usize) {
59    let Some(message) = working_set_eviction_message(eviction, max_size_bytes) else {
60        return;
61    };
62    if WORKING_SET_EVICTION_WARNED.swap(true, Ordering::Relaxed) {
63        return;
64    }
65    tracing::warn!(target: fallow_types::ANALYSIS_DIAGNOSTIC_LOG_TARGET, "{message}");
66}
67
68/// The warning text for an eviction that removed working-set entries, or
69/// `None` when the whole working set stayed in the cache.
70pub(super) fn working_set_eviction_message(
71    eviction: &WorkingSetEviction,
72    max_size_bytes: usize,
73) -> Option<String> {
74    if eviction.evicted == 0 || eviction.entries == 0 {
75        return None;
76    }
77    let percent = (eviction.evicted.saturating_mul(100) / eviction.entries).max(1);
78    let cap_mib = max_size_bytes.div_ceil(BYTES_PER_MIB);
79    let suggested_mib = (eviction.encoded_bytes / 10_000)
80        .saturating_mul(SUGGESTED_CAP_BPS)
81        .div_ceil(BYTES_PER_MIB)
82        .max(cap_mib.saturating_add(1));
83    Some(format!(
84        "Parse cache is full: {evicted} of {total} files of this run ({percent}%) do not fit in \
85         the {cap_mib} MiB cap, so the next run parses them again. Set `cache.maxSizeMb` in the \
86         config or FALLOW_CACHE_MAX_SIZE to {suggested_mib} or more.",
87        evicted = eviction.evicted,
88        total = eviction.entries,
89    ))
90}
91
92/// Cached module information stored on disk.
93///
94/// Entries are keyed on the ROOT-RELATIVE, forward-slash-normalised path, and
95/// the root is recorded once in the header. Absolute keys made the blob
96/// unusable anywhere but the directory that wrote it: a container job, a
97/// matrix over roots, a GitLab shell executor, or a plain `cp -Rp` to a
98/// sibling path paid the full decode of a multi-megabyte file and then missed
99/// every single lookup, with nothing on stderr to say so.
100#[derive(Debug, Encode, Decode)]
101pub struct CacheStore {
102    version: u32,
103    /// Stable hash of extraction-affecting config fields.
104    config_hash: u64,
105    /// Project root the entries are relative to, forward-slash normalised and
106    /// without a trailing separator. Informational after load: the loader
107    /// re-anchors to the CURRENT root, because a blob restored under another
108    /// path is exactly the case root-relative keys exist to serve.
109    root: String,
110    /// Map from root-relative file path to cached module data.
111    entries: FxHashMap<String, CachedModule>,
112}
113
114impl CacheStore {
115    /// Create a new empty cache anchored at `root`.
116    #[must_use]
117    pub fn new(root: &Path) -> Self {
118        Self {
119            version: CACHE_VERSION,
120            config_hash: 0,
121            root: normalise_root(root),
122            entries: FxHashMap::default(),
123        }
124    }
125
126    /// Load cache from disk.
127    ///
128    /// # Errors
129    ///
130    /// Returns the [`CacheRejection`] that decided against reuse. Every branch
131    /// names itself instead of collapsing into a bare miss: a run that read a
132    /// multi-megabyte blob and then refused it costs the same as a cold run,
133    /// and without a named reason it is indistinguishable from having no cache
134    /// at all. Callers carry
135    /// the reason into the perf table and `fallow doctor`.
136    ///
137    /// The version is read from the file header BEFORE the payload is
138    /// decoded, because the two are decided by different things. A format bump
139    /// changes the encoded shape, so decoding a blob from the previous release
140    /// fails outright and never reaches a version comparison made afterwards:
141    /// the most ordinary event there is (upgrading fallow) then reported
142    /// "cache file could not be decoded", which reads as corruption and sent
143    /// people looking for a damaged disk. With the version in front, an upgrade
144    /// says the format changed. The framing is checked separately from the
145    /// version it carries, so an unframed or unreadable payload reports `Undecodable`
146    /// rather than borrowing the upgrade message.
147    ///
148    /// Every branch that refuses a file that DID exist logs at warn, because
149    /// the user paid the read and got nothing back. Only the missing-file case
150    /// stays quiet.
151    pub fn load(
152        cache_dir: &Path,
153        root: &Path,
154        expected_config_hash: u64,
155        max_size_bytes: usize,
156    ) -> Result<Self, CacheRejection> {
157        Self::load_counting_bytes(cache_dir, root, expected_config_hash, max_size_bytes).0
158    }
159
160    /// [`Self::load`], plus the number of cache bytes read from disk.
161    ///
162    /// The count is returned also when the cache is refused, because the run
163    /// paid for the read either way. It is zero when no file was read.
164    pub fn load_counting_bytes(
165        cache_dir: &Path,
166        root: &Path,
167        expected_config_hash: u64,
168        max_size_bytes: usize,
169    ) -> (Result<Self, CacheRejection>, u64) {
170        let cache_file = cache_dir.join("cache.bin");
171        let data = match std::fs::read(&cache_file) {
172            Ok(data) => data,
173            Err(error) => {
174                if error.kind() != std::io::ErrorKind::NotFound {
175                    tracing::warn!("Cache file could not be read; check the path and permissions");
176                    return (Err(CacheRejection::Unreadable), 0);
177                }
178                return (Err(CacheRejection::Absent), 0);
179            }
180        };
181        let bytes_read = data.len() as u64;
182        (
183            Self::decode_loaded(&data, root, expected_config_hash, max_size_bytes),
184            bytes_read,
185        )
186    }
187
188    fn decode_loaded(
189        data: &[u8],
190        root: &Path,
191        expected_config_hash: u64,
192        max_size_bytes: usize,
193    ) -> Result<Self, CacheRejection> {
194        let safety_ceiling = max_size_bytes.max(DEFAULT_CACHE_MAX_SIZE);
195        if data.len() > safety_ceiling {
196            tracing::warn!(
197                size_mb = data.len() / (1024 * 1024),
198                ceiling_mb = safety_ceiling / (1024 * 1024),
199                "Cache file exceeds safety ceiling, ignoring"
200            );
201            return Err(CacheRejection::Oversize {
202                size_bytes: data.len() as u64,
203                ceiling_bytes: safety_ceiling as u64,
204            });
205        }
206        let payload = read_header(data)?;
207        let mut store: Self = match bitcode::decode(payload) {
208            Ok(s) => s,
209            Err(_) => {
210                tracing::warn!(
211                    "Cache file carries the current format version but its payload could not be \
212                     decoded, rebuilding"
213                );
214                return Err(CacheRejection::Undecodable);
215            }
216        };
217        // The header already agreed with `CACHE_VERSION`, so this catches only a
218        // file whose header and payload disagree: a spliced or hand-edited blob.
219        if store.version != CACHE_VERSION {
220            tracing::warn!(
221                cached_version = store.version,
222                expected_version = CACHE_VERSION,
223                "Cache header and payload declare different format versions, rebuilding"
224            );
225            return Err(CacheRejection::VersionMismatch);
226        }
227        if store.config_hash != expected_config_hash {
228            tracing::warn!(
229                target: fallow_types::ANALYSIS_DIAGNOSTIC_LOG_TARGET,
230                "Cache was built under different extraction config, rebuilding from cold"
231            );
232            return Err(CacheRejection::ConfigHashMismatch);
233        }
234        let current_root = normalise_root(root);
235        if store.root != current_root {
236            tracing::debug!(
237                cached_root = %store.root,
238                "Reusing a cache written under a different project root"
239            );
240            store.root = current_root;
241        }
242        Ok(store)
243    }
244
245    /// Save cache to disk with write-time size enforcement and atomic rename.
246    /// A symlink that leaves the base of `target` stops the save before any
247    /// write.
248    pub fn save(
249        &mut self,
250        target: CacheTarget<'_>,
251        config_hash: u64,
252        max_size_bytes: usize,
253    ) -> Result<(), String> {
254        target
255            .write_gitignore()
256            .map_err(|e| format!("Failed to write cache .gitignore: {e}"))?;
257
258        self.config_hash = config_hash;
259        let initial_entries = self.entries.len();
260        let mut encoded = self.encode();
261
262        #[cfg(test)]
263        LAST_WORKING_SET_EVICTED_COUNT.with(|count| count.set(0));
264
265        let trigger = (max_size_bytes / 10_000).saturating_mul(EVICTION_TRIGGER_BPS);
266        if encoded.len().saturating_add(CACHE_HEADER_LEN) > trigger {
267            // The cap is a promise about the file, and the file carries the
268            // header as well as the payload, so eviction aims below both.
269            let target = (max_size_bytes / 10_000)
270                .saturating_mul(EVICTION_TARGET_BPS)
271                .saturating_sub(CACHE_HEADER_LEN);
272            // The working set of the latest run may fill the whole cap.
273            let working_set = max_size_bytes.saturating_sub(CACHE_HEADER_LEN);
274            let (new_encoded, eviction) = self.evict_lru_to_target(target, working_set, encoded);
275            encoded = new_encoded;
276
277            #[cfg(test)]
278            LAST_WORKING_SET_EVICTED_COUNT.with(|count| count.set(eviction.evicted));
279
280            let evicted = initial_entries.saturating_sub(self.entries.len());
281            let final_size = encoded.len();
282            warn_working_set_evicted(&eviction, max_size_bytes);
283            let significant_evicted =
284                initial_entries.saturating_mul(EVICTION_SIGNIFICANT_BPS) / 10_000;
285            if evicted >= significant_evicted && initial_entries > 0 {
286                tracing::info!(
287                    evicted_entries = evicted,
288                    remaining_entries = self.entries.len(),
289                    final_size_kb = final_size / 1024,
290                    max_size_kb = max_size_bytes / 1024,
291                    "Cache eviction: removed oldest entries to stay under cap"
292                );
293            } else {
294                tracing::debug!(
295                    evicted_entries = evicted,
296                    remaining_entries = self.entries.len(),
297                    final_size_kb = final_size / 1024,
298                    max_size_kb = max_size_bytes / 1024,
299                    "Cache eviction"
300                );
301            }
302        }
303
304        target
305            .write_file("cache.bin", &framed(self.version, &encoded))
306            .map_err(|e| format!("Failed to write cache file: {e}"))
307    }
308
309    /// Evict the entries that runs saw least recently until the re-encoded
310    /// size is under `target_bytes` or only one entry remains.
311    ///
312    /// The entries with the newest seen stamp are the working set of the
313    /// latest run, and they all share that one stamp. Eviction removes older
314    /// entries down to `target_bytes` first. It removes working-set entries
315    /// only down to `working_set_bytes`, which is the cap itself. The low
316    /// target gives headroom for entries that other scopes add. The working
317    /// set must not go down to the low target: a working set a little over
318    /// the trigger then loses about 40 percent of its entries on every save,
319    /// and the next run parses those files again. The tie order of the keys
320    /// is stable, so the same entries go on each save and the rest stay hits.
321    fn evict_lru_to_target(
322        &mut self,
323        target_bytes: usize,
324        working_set_bytes: usize,
325        encoded: Vec<u8>,
326    ) -> (Vec<u8>, WorkingSetEviction) {
327        let mut order: Vec<(u64, String, usize)> = self
328            .entries
329            .iter()
330            .map(|(key, entry)| {
331                (
332                    entry.last_seen_secs,
333                    key.clone(),
334                    bitcode::encode(entry)
335                        .len()
336                        .saturating_add(key.len())
337                        .max(1),
338                )
339            })
340            .collect();
341        order.sort();
342        let newest = order.last().map_or(0, |(seen, _, _)| *seen);
343        let working_set_from = order.partition_point(|(seen, _, _)| *seen < newest);
344
345        let estimated_total: usize = order
346            .iter()
347            .map(|(_, _, estimated_bytes)| estimated_bytes)
348            .sum();
349        let estimated_working_set: usize = order[working_set_from..]
350            .iter()
351            .map(|(_, _, estimated_bytes)| estimated_bytes)
352            .sum();
353        // The per-entry estimates overshoot the real encoding, so the share of
354        // the real size gives the working-set size that a cap must hold.
355        let working_set_encoded_bytes = (encoded.len() as u128)
356            .saturating_mul(estimated_working_set as u128)
357            .checked_div(estimated_total as u128)
358            .map_or(encoded.len(), |bytes| {
359                usize::try_from(bytes).unwrap_or(usize::MAX)
360            });
361        let mut cursor = EvictionCursor {
362            idx: 0,
363            estimated_remaining: estimated_total,
364        };
365        let mut encoded = encoded;
366        if working_set_from > 0 {
367            encoded = self.evict_order_range(
368                &order,
369                &mut cursor,
370                working_set_from,
371                target_bytes,
372                encoded,
373            );
374        }
375        let working_set_target = target_bytes.max(working_set_bytes);
376        let working_set_evicted = if encoded.len() > working_set_target {
377            let keep_newest_from = order.len().saturating_sub(1);
378            let before_ws_idx = cursor.idx;
379            encoded = self.evict_order_range(
380                &order,
381                &mut cursor,
382                keep_newest_from,
383                working_set_target,
384                encoded,
385            );
386            cursor.idx.saturating_sub(before_ws_idx)
387        } else {
388            0
389        };
390
391        if encoded.len() > working_set_target && self.entries.len() == 1 {
392            tracing::warn!(
393                encoded_kb = encoded.len() / 1024,
394                target_kb = working_set_target / 1024,
395                "Single cache entry exceeds configured max; cache will overshoot the cap"
396            );
397        }
398        let eviction = WorkingSetEviction {
399            entries: order.len() - working_set_from,
400            evicted: working_set_evicted,
401            encoded_bytes: working_set_encoded_bytes,
402        };
403        (encoded, eviction)
404    }
405
406    /// Remove entries in `order` from `cursor.idx` up to (not including)
407    /// `end` until the re-encoded size is under `target_bytes`.
408    fn evict_order_range(
409        &mut self,
410        order: &[(u64, String, usize)],
411        cursor: &mut EvictionCursor,
412        end: usize,
413        target_bytes: usize,
414        mut encoded: Vec<u8>,
415    ) -> Vec<u8> {
416        const MAX_REFINEMENT_PASSES: usize = 2;
417        const ESTIMATE_SAFETY_BPS: usize = 9_800;
418        for _ in 0..MAX_REFINEMENT_PASSES {
419            if encoded.len() <= target_bytes || cursor.idx >= end {
420                return encoded;
421            }
422
423            let estimated_budget = estimated_eviction_budget(
424                cursor.estimated_remaining,
425                target_bytes,
426                encoded.len(),
427                ESTIMATE_SAFETY_BPS,
428            );
429            let start_idx = cursor.idx;
430            while cursor.idx < end && cursor.estimated_remaining > estimated_budget {
431                self.evict_at(order, cursor);
432            }
433            if cursor.idx == start_idx {
434                self.evict_at(order, cursor);
435            }
436            encoded = self.encode();
437        }
438
439        if encoded.len() > target_bytes && cursor.idx < end {
440            let conservative_budget = target_bytes / 2;
441            while cursor.idx < end && cursor.estimated_remaining > conservative_budget {
442                self.evict_at(order, cursor);
443            }
444            encoded = self.encode();
445        }
446
447        // Per-entry encodings are deliberately conservative, but keep the
448        // configured cap exact if a future bitcode layout violates that
449        // estimate. This safety path runs only after byte-aware retention had
450        // three opportunities to preserve a recent suffix.
451        if encoded.len() > target_bytes && cursor.idx < end {
452            while cursor.idx < end {
453                self.evict_at(order, cursor);
454            }
455            encoded = self.encode();
456        }
457        encoded
458    }
459
460    fn evict_at(&mut self, order: &[(u64, String, usize)], cursor: &mut EvictionCursor) {
461        let (_, key, estimated_bytes) = &order[cursor.idx];
462        self.entries.remove(key);
463        cursor.estimated_remaining = cursor.estimated_remaining.saturating_sub(*estimated_bytes);
464        cursor.idx += 1;
465    }
466
467    fn encode(&self) -> Vec<u8> {
468        #[cfg(test)]
469        FULL_STORE_ENCODE_COUNT.with(|count| count.set(count.get() + 1));
470        bitcode::encode(self)
471    }
472
473    #[cfg(test)]
474    pub(super) fn reset_full_store_encode_count() {
475        FULL_STORE_ENCODE_COUNT.with(|count| count.set(0));
476    }
477
478    #[cfg(test)]
479    pub(super) fn full_store_encode_count() -> usize {
480        FULL_STORE_ENCODE_COUNT.with(Cell::get)
481    }
482
483    #[cfg(test)]
484    pub(super) fn reset_last_working_set_evicted_count() {
485        LAST_WORKING_SET_EVICTED_COUNT.with(|count| count.set(0));
486    }
487
488    #[cfg(test)]
489    pub(super) fn last_working_set_evicted_count() -> usize {
490        LAST_WORKING_SET_EVICTED_COUNT.with(Cell::get)
491    }
492
493    /// Key `path` the way entries are stored: root-relative where possible,
494    /// forward-slash normalised.
495    ///
496    /// A path outside the root keeps its own normalised spelling. It is still
497    /// stable within one root, which is all a lookup needs, and no root-
498    /// relative spelling of it exists to prefer.
499    fn key_for(&self, path: &Path) -> String {
500        let text = path.to_string_lossy().replace('\\', "/");
501        if self.root.is_empty() {
502            return text;
503        }
504        match text
505            .strip_prefix(&self.root)
506            .and_then(|rest| rest.strip_prefix('/'))
507        {
508            Some(relative) => relative.to_owned(),
509            None => text,
510        }
511    }
512
513    /// Rebuild the absolute path an entry key refers to under the current root.
514    fn path_for_key(&self, key: &str) -> std::path::PathBuf {
515        if self.root.is_empty() {
516            return std::path::PathBuf::from(key);
517        }
518        let candidate = Path::new(key);
519        if candidate.is_absolute() {
520            return candidate.to_path_buf();
521        }
522        Path::new(&self.root).join(key)
523    }
524
525    /// Look up a cached module by path and content hash.
526    /// Returns None if not cached or hash mismatch.
527    #[must_use]
528    pub fn get(&self, path: &Path, content_hash: u64) -> Option<&CachedModule> {
529        let entry = self.entries.get(&self.key_for(path))?;
530        if entry.content_hash == content_hash {
531            Some(entry)
532        } else {
533            None
534        }
535    }
536
537    /// Insert or update a cached module.
538    pub fn insert(&mut self, path: &Path, module: CachedModule) {
539        let key = self.key_for(path);
540        self.entries.insert(key, module);
541    }
542
543    /// Replace the source fingerprint of the entry for `path`, and keep the
544    /// rest of the entry.
545    ///
546    /// A fresh checkout or a restored cache moves the file timestamps but not
547    /// the content. Rebuilding such an entry from the module copies every
548    /// extracted fact again, so a caller whose content hash still matches
549    /// refreshes only the metadata. Returns `false` when no entry exists.
550    pub fn refresh_fingerprint(
551        &mut self,
552        path: &Path,
553        fingerprint: fallow_types::source_fingerprint::SourceFingerprint,
554    ) -> bool {
555        let key = self.key_for(path);
556        let Some(entry) = self.entries.get_mut(&key) else {
557            return false;
558        };
559        entry.mtime_ns = fingerprint.mtime_ns;
560        entry.ctime_ns = fingerprint.ctime_ns;
561        entry.file_size = fingerprint.file_size;
562        true
563    }
564
565    /// Store the module of this run for `path`. Returns `true` when the store
566    /// changed.
567    ///
568    /// An entry whose content hash still matches is rewritten only when its
569    /// metadata fingerprint moved or when this run adds complexity or call
570    /// facts that the entry lacks. A rewrite keeps the complexity and the call
571    /// facts that an earlier run stored and this run did not extract: a
572    /// module of such a run has none of them by design, so a copy would strip
573    /// the entry and make each later run that reads them parse the file again.
574    pub fn record_module(
575        &mut self,
576        path: &Path,
577        module: &crate::ModuleInfo,
578        fingerprint: fallow_types::source_fingerprint::SourceFingerprint,
579        need_complexity: bool,
580        need_call_facts: bool,
581    ) -> bool {
582        let Some(cached) = self
583            .get_by_path_only(path)
584            .filter(|cached| cached.content_hash == module.content_hash)
585        else {
586            self.insert(
587                path,
588                module_to_cached(module, fingerprint, need_complexity, need_call_facts),
589            );
590            return true;
591        };
592        let adds_complexity = need_complexity && !cached.complexity_extracted;
593        let adds_call_facts = need_call_facts && cached.call_facts.is_none();
594        if !adds_complexity && !adds_call_facts {
595            return cached.source_fingerprint() != fingerprint
596                && self.refresh_fingerprint(path, fingerprint);
597        }
598        let mut refreshed = module_to_cached(module, fingerprint, need_complexity, need_call_facts);
599        if !need_complexity && cached.complexity_extracted {
600            refreshed.complexity.clone_from(&cached.complexity);
601            refreshed.complexity_extracted = true;
602        }
603        if !need_call_facts {
604            refreshed.call_facts.clone_from(&cached.call_facts);
605        }
606        self.insert(path, refreshed);
607        true
608    }
609
610    /// Look up a cached module by path only (ignoring hash).
611    #[must_use]
612    pub fn get_by_path_only(&self, path: &Path) -> Option<&CachedModule> {
613        self.entries.get(&self.key_for(path))
614    }
615
616    /// Remove cache entries for files that no longer exist on disk, and mark
617    /// the entries for every discovered file as seen by this run.
618    ///
619    /// Returns `true` when any entry was removed. The seen stamp alone does
620    /// not make the store dirty: a run that saves nothing else does not
621    /// rewrite the whole blob to persist it, and the next run that saves
622    /// stamps the same files again.
623    ///
624    /// The seen stamp orders eviction. A file that every run discovers keeps a
625    /// current stamp even when it never changes, so `evict_lru_to_target`
626    /// removes the entries that only another scope reads before it removes
627    /// the files that this scope reads on every run.
628    ///
629    /// The predicate is deliberately "still exists", not "was discovered by
630    /// this run". Discovery is scoped: `--production` drops test and story
631    /// files, `--root` narrows to a subtree, and `ignorePatterns` differs per
632    /// command. Evicting whatever the current scope did not walk meant one
633    /// `--production` run threw away the entries for every test file, and the
634    /// next full run reparsed them from cold. Entries are keyed by absolute
635    /// path, so the check is one `symlink_metadata` per undiscovered entry
636    /// (`symlink_metadata`, not `metadata`, so a broken symlink still counts as
637    /// present rather than being evicted as missing). Size is not this
638    /// method's concern: `evict_lru_to_target` remains the only guard on how
639    /// large the blob may grow.
640    pub fn retain_paths(&mut self, files: &[fallow_types::discover::DiscoveredFile]) -> bool {
641        use rustc_hash::FxHashSet;
642        let current_keys: FxHashSet<String> = files.iter().map(|f| self.key_for(&f.path)).collect();
643        let before = self.entries.len();
644        let retained: FxHashSet<String> = self
645            .entries
646            .keys()
647            .filter(|key| {
648                current_keys.contains(*key)
649                    || std::fs::symlink_metadata(self.path_for_key(key)).is_ok()
650            })
651            .cloned()
652            .collect();
653        self.entries.retain(|key, _| retained.contains(key));
654        let now = super::conversion::current_unix_seconds();
655        for key in &current_keys {
656            if let Some(entry) = self.entries.get_mut(key) {
657                entry.last_seen_secs = now;
658            }
659        }
660        self.entries.len() != before
661    }
662
663    /// Number of cached entries.
664    #[must_use]
665    pub fn len(&self) -> usize {
666        self.entries.len()
667    }
668
669    /// Whether the cache is empty.
670    #[must_use]
671    pub fn is_empty(&self) -> bool {
672        self.entries.is_empty()
673    }
674}
675
676/// Position in the sorted eviction order, and the estimated size of the
677/// entries that remain.
678struct EvictionCursor {
679    idx: usize,
680    estimated_remaining: usize,
681}
682
683/// Marker written ahead of every cache payload so the format version can be
684/// read without decoding the payload it describes.
685///
686/// Constant across format bumps: only the version field beside it moves. That
687/// lets future upgrades report an explicit version mismatch; older unframed
688/// caches still report an ambiguous decode failure.
689const CACHE_MAGIC: [u8; 4] = *b"FLWX";
690
691/// Bytes the framing adds ahead of the payload: the magic plus a little-endian
692/// `u32` format version.
693pub(super) const CACHE_HEADER_LEN: usize = CACHE_MAGIC.len() + 4;
694
695/// Prepend the format header to an encoded payload.
696///
697/// The version comes from the store being written rather than from the
698/// constant, so the header always describes the payload behind it.
699pub(super) fn framed(version: u32, payload: &[u8]) -> Vec<u8> {
700    let mut framed = Vec::with_capacity(CACHE_HEADER_LEN + payload.len());
701    framed.extend_from_slice(&CACHE_MAGIC);
702    framed.extend_from_slice(&version.to_le_bytes());
703    framed.extend_from_slice(payload);
704    framed
705}
706
707/// Split a cache file into its declared version and its payload, refusing
708/// anything this binary cannot read WITHOUT decoding it first.
709///
710/// The version check has to come first: a format bump changes the encoded
711/// shape, so a blob from the previous release fails to decode and a version
712/// comparison made after the decode is unreachable on the one event that
713/// triggers it most, an upgrade.
714///
715/// A recognized header exposes a version mismatch without decoding. Releases
716/// before framing wrote raw payloads, so a missing header cannot distinguish
717/// an older cache from foreign or damaged data. `Undecodable` keeps that
718/// uncertainty explicit and the next successful run replaces the blob.
719fn read_header(data: &[u8]) -> Result<&[u8], CacheRejection> {
720    let Some((header, payload)) = data.split_at_checked(CACHE_HEADER_LEN) else {
721        tracing::warn!("Cache file is too short to carry a format header, rebuilding");
722        return Err(CacheRejection::Undecodable);
723    };
724    let (declared_magic, declared_version) = header.split_at(CACHE_MAGIC.len());
725    if declared_magic != CACHE_MAGIC {
726        tracing::warn!("Cache file does not carry fallow's cache framing, rebuilding");
727        return Err(CacheRejection::Undecodable);
728    }
729    // The slice is exactly four bytes; the fallback only has to be a version
730    // this binary never writes, so an impossible header is refused rather than
731    // trusted.
732    let declared = declared_version.try_into().map_or(0, u32::from_le_bytes);
733    if declared != CACHE_VERSION {
734        tracing::warn!(
735            cached_version = declared,
736            expected_version = CACHE_VERSION,
737            "Cache format upgraded, rebuilding (one-time cost after version bump)"
738        );
739        return Err(CacheRejection::VersionMismatch);
740    }
741    Ok(payload)
742}
743
744pub(super) fn estimated_eviction_budget(
745    estimated_remaining: usize,
746    target_bytes: usize,
747    encoded_bytes: usize,
748    safety_bps: usize,
749) -> usize {
750    if encoded_bytes == 0 {
751        return 0;
752    }
753
754    const BASIS_POINTS: u128 = 10_000;
755    let scaled = estimated_remaining as u128 * target_bytes as u128 / encoded_bytes as u128;
756    let safety = (safety_bps as u128).min(BASIS_POINTS);
757    let budget = scaled / BASIS_POINTS * safety + scaled % BASIS_POINTS * safety / BASIS_POINTS;
758    budget.min(usize::MAX as u128) as usize
759}
760
761/// Normalise a project root for storage and prefix stripping: forward slashes,
762/// no trailing separator. An empty root disables stripping, which is what a
763/// default-constructed store gets.
764fn normalise_root(root: &Path) -> String {
765    let text = root.to_string_lossy().replace('\\', "/");
766    match text.strip_suffix('/') {
767        Some(trimmed) => trimmed.to_owned(),
768        None => text,
769    }
770}
771
772impl Default for CacheStore {
773    fn default() -> Self {
774        Self::new(Path::new(""))
775    }
776}