1use 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
33pub(super) struct WorkingSetEviction {
34 pub(super) entries: usize,
36 pub(super) evicted: usize,
38 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
47const SUGGESTED_CAP_BPS: usize = 12_500;
52
53fn 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
68pub(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#[derive(Debug, Encode, Decode)]
101pub struct CacheStore {
102 version: u32,
103 config_hash: u64,
105 root: String,
110 entries: FxHashMap<String, CachedModule>,
112}
113
114impl CacheStore {
115 #[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 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 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 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 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 let target = (max_size_bytes / 10_000)
270 .saturating_mul(EVICTION_TARGET_BPS)
271 .saturating_sub(CACHE_HEADER_LEN);
272 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 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 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 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 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 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 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 #[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 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 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 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 #[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 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 ¤t_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 #[must_use]
665 pub fn len(&self) -> usize {
666 self.entries.len()
667 }
668
669 #[must_use]
671 pub fn is_empty(&self) -> bool {
672 self.entries.is_empty()
673 }
674}
675
676struct EvictionCursor {
679 idx: usize,
680 estimated_remaining: usize,
681}
682
683const CACHE_MAGIC: [u8; 4] = *b"FLWX";
690
691pub(super) const CACHE_HEADER_LEN: usize = CACHE_MAGIC.len() + 4;
694
695pub(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
707fn 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 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
761fn 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}