1use rayon::prelude::*;
2#[cfg(debug_assertions)]
3use std::cell::Cell;
4use std::collections::BTreeMap;
5#[cfg(debug_assertions)]
6use std::collections::VecDeque;
7use std::fs;
8use std::path::{Path, PathBuf};
9#[cfg(any(debug_assertions, any(test, feature = "test-support")))]
10use std::sync::atomic::{AtomicUsize, Ordering};
11use std::sync::{Mutex, OnceLock};
12use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
13
14pub const CONTENT_HASH_SIZE_CAP: u64 = 4 * 1024 * 1024;
15#[cfg(debug_assertions)]
16const MAX_STRICT_VERIFY_DEBUG_PATHS: usize = 4096;
17
18#[cfg(any(test, feature = "test-support"))]
19pub static STRICT_VERIFY_POOL_BUILDS: AtomicUsize = AtomicUsize::new(0);
20
21#[cfg(debug_assertions)]
22static STRICT_VERIFY_FILE_CALLS: AtomicUsize = AtomicUsize::new(0);
23#[cfg(debug_assertions)]
24thread_local! {
25 static HASH_FILE_IF_SMALL_CALLS: Cell<usize> = const { Cell::new(0) };
26}
27#[cfg(any(debug_assertions, any(test, feature = "test-support")))]
28static WATCHED_HASH_FILE: OnceLock<Mutex<Option<(PathBuf, usize)>>> = OnceLock::new();
29
30const VERIFY_MEMO_TTL: Duration = Duration::from_secs(10 * 60);
31static VERIFY_MEMO: OnceLock<Mutex<VerifyMemo>> = OnceLock::new();
32
33#[rustfmt::skip]
34test_support_visibility! {
35#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
36pub(crate) enum VerifyArtifact {
37 Search,
38 #[cfg(any(test, feature = "test-support"))]
39 Semantic,
40}
41}
42
43#[rustfmt::skip]
44test_support_visibility! {
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub(crate) enum WarmVerifyPlan {
47 Skip,
48 StatFirst,
49 Strict,
50}
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum VerifyStrategy {
55 StatFirst,
56 Strict,
57}
58
59#[rustfmt::skip]
60test_support_visibility! {
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub(crate) struct ArtifactGeneration {
63 size: u64,
64 modified_nanos: Option<u128>,
65}
66}
67
68#[derive(Debug, Clone)]
69struct VerifyMemoEntry {
70 verify_completed_at: Instant,
71 generation: ArtifactGeneration,
72 invalidated: bool,
73}
74
75#[derive(Default)]
76struct VerifyMemo {
77 entries: BTreeMap<(PathBuf, VerifyArtifact), VerifyMemoEntry>,
78 invalidation_tickets: BTreeMap<PathBuf, u64>,
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub struct FileFreshness {
83 pub mtime: SystemTime,
84 pub size: u64,
85 pub content_hash: blake3::Hash,
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum FreshnessVerdict {
90 HotFresh,
91 ContentFresh {
92 new_mtime: SystemTime,
93 new_size: u64,
94 },
95 Stale,
96 Deleted,
97}
98
99pub fn hash_bytes(bytes: &[u8]) -> blake3::Hash {
100 crate::io_accounting::source_hash(bytes)
101}
102
103pub fn hash_file_if_small(path: &Path, size: u64) -> std::io::Result<Option<blake3::Hash>> {
104 if size > CONTENT_HASH_SIZE_CAP {
105 return Ok(None);
106 }
107 #[cfg(debug_assertions)]
108 HASH_FILE_IF_SMALL_CALLS.with(|calls| calls.set(calls.get() + 1));
109 #[cfg(any(debug_assertions, any(test, feature = "test-support")))]
110 {
111 let mut watched = WATCHED_HASH_FILE
112 .get_or_init(|| Mutex::new(None))
113 .lock()
114 .unwrap_or_else(std::sync::PoisonError::into_inner);
115 if let Some((watched_path, count)) = watched.as_mut() {
116 if watched_path == path {
117 *count += 1;
118 }
119 }
120 }
121 let (hash, bytes_read) = hash_small_reader(crate::project_content::open(path)?)?;
124 let work = &crate::io_accounting::WORK;
125 work.content_read_bytes
126 .fetch_add(bytes_read, std::sync::atomic::Ordering::Relaxed);
127 if hash.is_some() {
128 work.source_hashes
129 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
130 work.source_hash_bytes
131 .fetch_add(bytes_read, std::sync::atomic::Ordering::Relaxed);
132 }
133 Ok(hash)
134}
135
136fn hash_small_reader(reader: impl std::io::Read) -> std::io::Result<(Option<blake3::Hash>, u64)> {
141 use std::io::Read;
142 let mut reader = reader.take(CONTENT_HASH_SIZE_CAP + 1);
143 let mut hasher = blake3::Hasher::new();
144 let mut buffer = [0u8; 8192];
145 let mut total = 0u64;
146 loop {
147 let read = match reader.read(&mut buffer) {
148 Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
149 result => result?,
150 };
151 if read == 0 {
152 return Ok((Some(hasher.finalize()), total));
153 }
154 total += read as u64;
155 if total > CONTENT_HASH_SIZE_CAP {
156 return Ok((None, total));
157 }
158 hasher.update(&buffer[..read]);
159 }
160}
161
162pub fn metadata_matches(path: &Path, cached: &FileFreshness) -> std::io::Result<bool> {
163 let metadata = fs::metadata(path)?;
164 let new_size = metadata.len();
165 let new_mtime = metadata.modified().unwrap_or(UNIX_EPOCH);
166 Ok(new_size == cached.size && new_mtime == cached.mtime)
167}
168
169pub fn zero_hash() -> blake3::Hash {
170 blake3::Hash::from_bytes([0u8; 32])
171}
172
173#[rustfmt::skip]
174test_support_visibility! {
175
176pub(crate) fn artifact_generation(path: &Path) -> Option<ArtifactGeneration> {
177 let metadata = fs::metadata(path).ok()?;
178 let modified_nanos = metadata
179 .modified()
180 .ok()
181 .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())
182 .map(|duration| duration.as_nanos());
183 Some(ArtifactGeneration {
184 size: metadata.len(),
185 modified_nanos,
186 })
187}
188}
189
190fn verify_memo() -> &'static Mutex<VerifyMemo> {
191 VERIFY_MEMO.get_or_init(|| Mutex::new(VerifyMemo::default()))
192}
193
194#[rustfmt::skip]
195test_support_visibility! {
196
197pub(crate) fn warm_verify_plan(
198 root: &Path,
199 artifact: VerifyArtifact,
200 generation: Option<ArtifactGeneration>,
201) -> WarmVerifyPlan {
202 let Some(generation) = generation else {
203 return WarmVerifyPlan::Strict;
204 };
205 let memo = verify_memo()
206 .lock()
207 .unwrap_or_else(std::sync::PoisonError::into_inner);
208 let Some(entry) = memo.entries.get(&(root.to_path_buf(), artifact)) else {
209 return WarmVerifyPlan::Strict;
210 };
211 if entry.generation != generation {
212 return WarmVerifyPlan::Strict;
213 }
214 if entry.invalidated || entry.verify_completed_at.elapsed() >= VERIFY_MEMO_TTL {
215 WarmVerifyPlan::StatFirst
216 } else {
217 WarmVerifyPlan::Skip
218 }
219}
220}
221
222#[rustfmt::skip]
223test_support_visibility! {
224
225pub(crate) fn capture_verify_ticket(root: &Path) -> u64 {
226 verify_memo()
227 .lock()
228 .unwrap_or_else(std::sync::PoisonError::into_inner)
229 .invalidation_tickets
230 .get(root)
231 .copied()
232 .unwrap_or(0)
233}
234}
235
236#[rustfmt::skip]
237test_support_visibility! {
238
239pub(crate) fn record_verify_completed_if_unchanged(
240 root: &Path,
241 artifact: VerifyArtifact,
242 generation: Option<ArtifactGeneration>,
243 ticket: u64,
244) -> bool {
245 let Some(generation) = generation else {
246 return false;
247 };
248 let mut memo = verify_memo()
249 .lock()
250 .unwrap_or_else(std::sync::PoisonError::into_inner);
251 let current_ticket = memo.invalidation_tickets.get(root).copied().unwrap_or(0);
252 if current_ticket != ticket {
253 return false;
254 }
255 memo.entries.insert(
256 (root.to_path_buf(), artifact),
257 VerifyMemoEntry {
258 verify_completed_at: Instant::now(),
259 generation,
260 invalidated: false,
261 },
262 );
263 true
264}
265}
266
267#[doc(hidden)]
269pub fn seed_search_verify_memo_for_test(root: &Path, artifact_path: &Path) -> bool {
270 let ticket = capture_verify_ticket(root);
271 record_verify_completed_if_unchanged(
272 root,
273 VerifyArtifact::Search,
274 artifact_generation(artifact_path),
275 ticket,
276 )
277}
278
279#[doc(hidden)]
281pub fn search_warm_verify_plan_for_test(root: &Path, artifact_path: &Path) -> &'static str {
282 match warm_verify_plan(
283 root,
284 VerifyArtifact::Search,
285 artifact_generation(artifact_path),
286 ) {
287 WarmVerifyPlan::Skip => "skip",
288 WarmVerifyPlan::StatFirst => "stat_first",
289 WarmVerifyPlan::Strict => "strict",
290 }
291}
292
293#[cfg(any(test, feature = "test-support"))]
294pub fn record_verify_completed(
295 root: &Path,
296 artifact: VerifyArtifact,
297 generation: Option<ArtifactGeneration>,
298) {
299 let ticket = capture_verify_ticket(root);
300 let _ = record_verify_completed_if_unchanged(root, artifact, generation, ticket);
301}
302
303pub fn invalidate_verify_memo(root: &Path) {
304 let mut memo = verify_memo()
305 .lock()
306 .unwrap_or_else(std::sync::PoisonError::into_inner);
307 let ticket = memo
308 .invalidation_tickets
309 .entry(root.to_path_buf())
310 .or_insert(0);
311 *ticket = ticket.wrapping_add(1);
312 for ((memo_root, _), entry) in &mut memo.entries {
313 if memo_root == root {
314 entry.invalidated = true;
315 }
316 }
317}
318
319pub fn invalidate_verify_memo_strict(root: &Path) {
324 let mut memo = verify_memo()
325 .lock()
326 .unwrap_or_else(std::sync::PoisonError::into_inner);
327 let ticket = memo
328 .invalidation_tickets
329 .entry(root.to_path_buf())
330 .or_insert(0);
331 *ticket = ticket.wrapping_add(1);
332 memo.entries.retain(|(memo_root, _), _| memo_root != root);
333}
334
335pub fn collect(path: &Path) -> std::io::Result<FileFreshness> {
336 let metadata = fs::metadata(path)?;
337 let mtime = metadata.modified().unwrap_or(UNIX_EPOCH);
338 let size = metadata.len();
339 let content_hash = hash_file_if_small(path, size)?.unwrap_or_else(zero_hash);
340 Ok(FileFreshness {
341 mtime,
342 size,
343 content_hash,
344 })
345}
346
347pub fn verify_file(path: &Path, cached: &FileFreshness) -> FreshnessVerdict {
348 verify_file_inner(path, cached, false)
349}
350
351pub fn verify_file_strict(path: &Path, cached: &FileFreshness) -> FreshnessVerdict {
352 #[cfg(debug_assertions)]
353 {
354 STRICT_VERIFY_FILE_CALLS.fetch_add(1, Ordering::Relaxed);
355 let mut paths = strict_verify_paths_for_debug()
356 .lock()
357 .unwrap_or_else(std::sync::PoisonError::into_inner);
358 paths.push_back(path.to_path_buf());
359 while paths.len() > MAX_STRICT_VERIFY_DEBUG_PATHS {
360 paths.pop_front();
361 }
362 }
363 verify_file_inner(path, cached, true)
364}
365
366pub fn verify_files_strict_bounded<K: Send>(
373 files: Vec<(K, PathBuf, FileFreshness)>,
374) -> Vec<(K, PathBuf, FreshnessVerdict)> {
375 verify_files_bounded(files, VerifyStrategy::Strict)
376}
377
378pub fn verify_files_bounded<K: Send>(
379 files: Vec<(K, PathBuf, FileFreshness)>,
380 strategy: VerifyStrategy,
381) -> Vec<(K, PathBuf, FreshnessVerdict)> {
382 map_files_bounded(files, |(key, path, cached)| {
383 let verdict = match strategy {
384 VerifyStrategy::StatFirst => verify_file(&path, &cached),
385 VerifyStrategy::Strict => verify_file_strict(&path, &cached),
386 };
387 (key, path, verdict)
388 })
389}
390
391fn map_files_bounded<K: Send, V: Send>(
392 files: Vec<(K, PathBuf, FileFreshness)>,
393 map: impl Fn((K, PathBuf, FileFreshness)) -> V + Send + Sync,
394) -> Vec<V> {
395 if files.len() <= 1 {
396 return files.into_iter().map(map).collect();
397 }
398
399 let pool = strict_verify_pool();
400 match pool {
401 Some(pool) => pool.install(|| {
402 let files = files.into_par_iter();
403 files.map(map).collect()
404 }),
405 None => files.into_iter().map(map).collect(),
406 }
407}
408
409fn strict_verify_pool() -> Option<&'static rayon::ThreadPool> {
410 static POOL: OnceLock<Option<rayon::ThreadPool>> = OnceLock::new();
411 POOL.get_or_init(build_strict_verify_pool).as_ref()
412}
413
414fn build_strict_verify_pool() -> Option<rayon::ThreadPool> {
415 #[cfg(any(test, feature = "test-support"))]
416 STRICT_VERIFY_POOL_BUILDS.fetch_add(1, Ordering::Relaxed);
417 rayon::ThreadPoolBuilder::new()
418 .num_threads(strict_verify_pool_size())
419 .thread_name(|index| format!("aft-rayon-semantic-verify-{index}"))
420 .build()
421 .ok()
422}
423
424pub(crate) fn strict_verify_pool_size() -> usize {
425 std::thread::available_parallelism()
426 .map(|parallelism| parallelism.get())
427 .unwrap_or(1)
428 .div_ceil(2)
429 .clamp(1, 8)
430}
431
432#[cfg(debug_assertions)]
433fn strict_verify_paths_for_debug() -> &'static std::sync::Mutex<VecDeque<PathBuf>> {
434 static STRICT_VERIFY_FILE_PATHS: OnceLock<std::sync::Mutex<VecDeque<PathBuf>>> =
435 OnceLock::new();
436 STRICT_VERIFY_FILE_PATHS.get_or_init(|| std::sync::Mutex::new(VecDeque::new()))
437}
438
439#[cfg(debug_assertions)]
440#[doc(hidden)]
441pub fn reset_verify_file_strict_count_for_debug() {
442 STRICT_VERIFY_FILE_CALLS.store(0, Ordering::Relaxed);
443 strict_verify_paths_for_debug()
444 .lock()
445 .unwrap_or_else(std::sync::PoisonError::into_inner)
446 .clear();
447}
448
449#[cfg(debug_assertions)]
450#[doc(hidden)]
451pub fn verify_file_strict_count_for_debug() -> usize {
452 STRICT_VERIFY_FILE_CALLS.load(Ordering::Relaxed)
453}
454
455#[cfg(debug_assertions)]
460#[doc(hidden)]
461pub fn verify_file_strict_count_under_for_debug(root: &Path) -> usize {
462 strict_verify_paths_for_debug()
463 .lock()
464 .unwrap_or_else(std::sync::PoisonError::into_inner)
465 .iter()
466 .filter(|path| path.starts_with(root))
467 .count()
468}
469
470#[cfg(debug_assertions)]
471#[doc(hidden)]
472pub fn reset_hash_file_if_small_count_for_debug() {
473 HASH_FILE_IF_SMALL_CALLS.with(|calls| calls.set(0));
474}
475
476#[cfg(debug_assertions)]
477#[doc(hidden)]
478pub fn hash_file_if_small_count_for_debug() -> usize {
479 HASH_FILE_IF_SMALL_CALLS.with(Cell::get)
480}
481
482#[cfg(any(debug_assertions, any(test, feature = "test-support")))]
483#[doc(hidden)]
484pub fn watch_hash_file_for_debug(path: &Path) {
485 *WATCHED_HASH_FILE
486 .get_or_init(|| Mutex::new(None))
487 .lock()
488 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some((path.to_path_buf(), 0));
489}
490
491#[cfg(any(debug_assertions, any(test, feature = "test-support")))]
492#[doc(hidden)]
493pub fn watched_hash_file_count_for_debug() -> usize {
494 WATCHED_HASH_FILE
495 .get_or_init(|| Mutex::new(None))
496 .lock()
497 .unwrap_or_else(std::sync::PoisonError::into_inner)
498 .as_ref()
499 .map_or(0, |(_, count)| *count)
500}
501
502fn verify_file_inner(
503 path: &Path,
504 cached: &FileFreshness,
505 hash_matching_metadata: bool,
506) -> FreshnessVerdict {
507 let Ok(metadata) = fs::metadata(path) else {
508 return FreshnessVerdict::Deleted;
509 };
510 let new_size = metadata.len();
511 let new_mtime = metadata.modified().unwrap_or(UNIX_EPOCH);
512 if new_size == cached.size && new_mtime == cached.mtime {
513 if hash_matching_metadata {
514 if new_size > CONTENT_HASH_SIZE_CAP || cached.content_hash == zero_hash() {
515 return FreshnessVerdict::Stale;
516 }
517 return match hash_file_if_small(path, new_size) {
518 Ok(Some(hash)) if hash == cached.content_hash => FreshnessVerdict::HotFresh,
519 _ => FreshnessVerdict::Stale,
520 };
521 }
522 return FreshnessVerdict::HotFresh;
523 }
524 if new_size != cached.size || new_size > CONTENT_HASH_SIZE_CAP {
525 return FreshnessVerdict::Stale;
526 }
527 match hash_file_if_small(path, new_size) {
528 Ok(Some(hash)) if hash == cached.content_hash => FreshnessVerdict::ContentFresh {
529 new_mtime,
530 new_size,
531 },
532 _ => FreshnessVerdict::Stale,
533 }
534}
535
536#[cfg(any(test, feature = "test-support"))]
537#[cfg_attr(not(test), allow(dead_code, unused_imports))]
538pub mod tests {
539 use super::*;
540 use std::io::Write as _;
541
542 #[test]
543 fn audit10_freshness_hash_streams_bounded_buffers() {
544 struct MeasuredReader<'a> {
545 bytes: std::io::Cursor<Vec<u8>>,
546 largest: &'a mut usize,
547 consumed: &'a mut usize,
548 }
549 impl std::io::Read for MeasuredReader<'_> {
550 fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
551 *self.largest = (*self.largest).max(buffer.len());
552 let read = self.bytes.read(buffer)?;
553 *self.consumed += read;
554 Ok(read)
555 }
556 }
557 let data = vec![b'x'; 64 * 1024];
558 let mut largest = 0;
559 let mut consumed = 0;
560 let (hash, bytes_read) = hash_small_reader(MeasuredReader {
561 bytes: std::io::Cursor::new(data.clone()),
562 largest: &mut largest,
563 consumed: &mut consumed,
564 })
565 .unwrap();
566 assert_eq!(hash, Some(blake3::hash(&data)));
567 assert_eq!(bytes_read, data.len() as u64);
568 assert_eq!(consumed, data.len());
569 assert!(largest <= 8192, "read buffer grew to {largest}");
570 let data = vec![b'x'; CONTENT_HASH_SIZE_CAP as usize + 16384];
571 let mut largest = 0;
572 let mut consumed = 0;
573 let (hash, _) = hash_small_reader(MeasuredReader {
574 bytes: std::io::Cursor::new(data),
575 largest: &mut largest,
576 consumed: &mut consumed,
577 })
578 .unwrap();
579 assert!(hash.is_none());
580 assert_eq!(consumed as u64, CONTENT_HASH_SIZE_CAP + 1);
581 }
582
583 #[test]
584 fn audit10_file_growing_past_the_cap_has_no_hash() {
585 let dir = tempfile::tempdir().unwrap();
586 let path = dir.path().join("grown.rs");
587 fs::write(&path, vec![b'x'; CONTENT_HASH_SIZE_CAP as usize + 1]).unwrap();
588 assert!(hash_file_if_small(&path, 1).unwrap().is_none());
590 fs::write(&path, b"small").unwrap();
591 assert_eq!(
592 hash_file_if_small(&path, 5).unwrap(),
593 Some(blake3::hash(b"small"))
594 );
595 }
596
597 pub fn write(path: &Path, bytes: &[u8]) {
598 fs::write(path, bytes).unwrap();
599 }
600
601 #[test]
602 fn hot_fresh_when_mtime_size_match() {
603 let dir = tempfile::tempdir().unwrap();
604 let path = dir.path().join("a.txt");
605 write(&path, b"same");
606 let fresh = collect(&path).unwrap();
607 assert_eq!(verify_file(&path, &fresh), FreshnessVerdict::HotFresh);
608 }
609
610 #[test]
611 fn strict_hashes_small_file_when_metadata_matches() {
612 let dir = tempfile::tempdir().unwrap();
613 let path = dir.path().join("a.txt");
614 let original_mtime = filetime::FileTime::from_unix_time(1_700_000_000, 0);
615 write(&path, b"alpha");
616 filetime::set_file_mtime(&path, original_mtime).unwrap();
617 let fresh = collect(&path).unwrap();
618
619 assert_eq!(
620 verify_file_strict(&path, &fresh),
621 FreshnessVerdict::HotFresh
622 );
623
624 write(&path, b"bravo");
625 filetime::set_file_mtime(&path, original_mtime).unwrap();
626
627 assert_eq!(verify_file(&path, &fresh), FreshnessVerdict::HotFresh);
631 assert_eq!(verify_file_strict(&path, &fresh), FreshnessVerdict::Stale);
632 }
633
634 #[test]
635 fn strict_stale_when_large_file_hash_was_not_cached() {
636 let dir = tempfile::tempdir().unwrap();
637 let path = dir.path().join("big.bin");
638 let original_mtime = filetime::FileTime::from_unix_time(1_700_000_000, 0);
639 let file = fs::File::create(&path).unwrap();
640 file.set_len(CONTENT_HASH_SIZE_CAP + 1).unwrap();
641 filetime::set_file_mtime(&path, original_mtime).unwrap();
642 let fresh = collect(&path).unwrap();
643
644 assert_eq!(fresh.size, CONTENT_HASH_SIZE_CAP + 1);
645 assert_eq!(fresh.content_hash, zero_hash());
646 assert_eq!(verify_file(&path, &fresh), FreshnessVerdict::HotFresh);
649 assert_eq!(verify_file_strict(&path, &fresh), FreshnessVerdict::Stale);
650 }
651
652 #[test]
653 fn content_fresh_when_only_mtime_changes() {
654 let dir = tempfile::tempdir().unwrap();
655 let path = dir.path().join("a.txt");
656 write(&path, b"same");
657 let fresh = collect(&path).unwrap();
658 let mut file = fs::OpenOptions::new().append(true).open(&path).unwrap();
659 file.write_all(b"").unwrap();
660 aft_store::sync::sync_all(&file, &path).unwrap();
661 filetime::set_file_mtime(&path, filetime::FileTime::from_unix_time(1, 0)).unwrap();
662 assert!(matches!(
663 verify_file(&path, &fresh),
664 FreshnessVerdict::ContentFresh { .. }
665 ));
666 }
667
668 #[test]
669 fn stale_when_size_changes() {
670 let dir = tempfile::tempdir().unwrap();
671 let path = dir.path().join("a.txt");
672 write(&path, b"same");
673 let fresh = collect(&path).unwrap();
674 write(&path, b"different");
675 assert_eq!(verify_file(&path, &fresh), FreshnessVerdict::Stale);
676 }
677
678 #[test]
679 fn deleted_when_missing() {
680 let dir = tempfile::tempdir().unwrap();
681 let path = dir.path().join("a.txt");
682 write(&path, b"same");
683 let fresh = collect(&path).unwrap();
684 fs::remove_file(&path).unwrap();
685 assert_eq!(verify_file(&path, &fresh), FreshnessVerdict::Deleted);
686 }
687
688 #[test]
689 fn over_cap_hash_is_not_computed() {
690 let dir = tempfile::tempdir().unwrap();
691 let path = dir.path().join("big.bin");
692 fs::write(&path, vec![0u8; CONTENT_HASH_SIZE_CAP as usize + 1]).unwrap();
693 assert!(hash_file_if_small(&path, CONTENT_HASH_SIZE_CAP + 1)
694 .unwrap()
695 .is_none());
696 }
697
698 #[test]
699 fn audit_growth_repeated_bulk_verification_builds_only_one_pool() {
700 let dir = tempfile::tempdir().unwrap();
701 let mut files = Vec::new();
702 for index in 0..2 {
703 let path = dir.path().join(format!("pool-{index}.rs"));
704 write(&path, b"fn pool() {}\n");
705 files.push((index, path.clone(), collect(&path).unwrap()));
706 }
707 let before = STRICT_VERIFY_POOL_BUILDS.load(Ordering::Relaxed);
708 for _ in 0..2 {
709 let results = verify_files_bounded(files.clone(), VerifyStrategy::StatFirst);
710 assert_eq!(results.len(), 2);
711 }
712 let builds = STRICT_VERIFY_POOL_BUILDS.load(Ordering::Relaxed) - before;
713 assert_eq!(builds, 1, "two calls share one Rayon pool construction");
714 }
715
716 #[cfg(debug_assertions)]
717 #[test]
718 fn audit_growth_debug_strict_verify_path_history_is_bounded() {
719 const MAX_PATH_HISTORY: usize = 4096;
720 let dir = tempfile::tempdir().unwrap();
721 let path = dir.path().join("debug-history.rs");
722 write(&path, b"");
723 let freshness = collect(&path).unwrap();
724 for _ in 0..(MAX_PATH_HISTORY + 8) {
725 let _ = verify_file_strict(&path, &freshness);
726 }
727 assert!(
728 verify_file_strict_count_under_for_debug(dir.path()) <= MAX_PATH_HISTORY,
729 "debug path history exceeded {MAX_PATH_HISTORY} entries"
730 );
731 }
732}
733
734#[cfg(any(test, feature = "test-support"))]
735#[cfg_attr(not(test), allow(dead_code, unused_imports))]
736pub mod warm_reload_tests {
737 use super::*;
738
739 #[test]
740 fn stat_first_hashes_only_files_with_changed_metadata_while_cold_verify_is_strict() {
741 let dir = tempfile::tempdir().unwrap();
742 let path = dir.path().join("warm.rs");
743 fs::write(&path, b"fn warm() {}\n").unwrap();
744 let original_mtime = filetime::FileTime::from_unix_time(1_700_000_000, 0);
745 filetime::set_file_mtime(&path, original_mtime).unwrap();
746 let freshness = collect(&path).unwrap();
747
748 watch_hash_file_for_debug(&path);
749 let unchanged = verify_files_bounded(
750 vec![((), path.clone(), freshness)],
751 VerifyStrategy::StatFirst,
752 );
753 assert_eq!(unchanged[0].2, FreshnessVerdict::HotFresh);
754 assert_eq!(watched_hash_file_count_for_debug(), 0);
755
756 watch_hash_file_for_debug(&path);
757 let cold = verify_files_strict_bounded(vec![((), path.clone(), freshness)]);
758 assert_eq!(cold[0].2, FreshnessVerdict::HotFresh);
759 assert_eq!(watched_hash_file_count_for_debug(), 1);
760
761 filetime::set_file_mtime(&path, filetime::FileTime::from_unix_time(1, 0)).unwrap();
762 watch_hash_file_for_debug(&path);
763 let changed_stat = verify_files_bounded(
764 vec![((), path.clone(), freshness)],
765 VerifyStrategy::StatFirst,
766 );
767 assert!(matches!(
768 changed_stat[0].2,
769 FreshnessVerdict::ContentFresh { .. }
770 ));
771 assert_eq!(watched_hash_file_count_for_debug(), 1);
772 }
773
774 #[test]
775 fn verify_memo_skips_hits_and_invalidates_on_watcher_or_generation_change() {
776 let dir = tempfile::tempdir().unwrap();
777 let root = dir.path().join("root");
778 let artifact = dir.path().join("cache.bin");
779 fs::create_dir(&root).unwrap();
780 fs::write(&artifact, b"generation-one").unwrap();
781 let generation_one = artifact_generation(&artifact).unwrap();
782
783 assert_eq!(
784 warm_verify_plan(&root, VerifyArtifact::Search, Some(generation_one)),
785 WarmVerifyPlan::Strict
786 );
787 record_verify_completed(&root, VerifyArtifact::Search, Some(generation_one));
788 assert_eq!(
789 warm_verify_plan(&root, VerifyArtifact::Search, Some(generation_one)),
790 WarmVerifyPlan::Skip
791 );
792
793 invalidate_verify_memo(&root);
794 assert_eq!(
795 warm_verify_plan(&root, VerifyArtifact::Search, Some(generation_one)),
796 WarmVerifyPlan::StatFirst
797 );
798
799 fs::write(&artifact, b"generation-two-is-different").unwrap();
800 let generation_two = artifact_generation(&artifact).unwrap();
801 assert_ne!(generation_one, generation_two);
802 assert_eq!(
803 warm_verify_plan(&root, VerifyArtifact::Search, Some(generation_two)),
804 WarmVerifyPlan::Strict
805 );
806 }
807
808 #[test]
809 fn invalidation_between_verify_and_record_prevents_false_fresh_memo() {
810 let dir = tempfile::tempdir().unwrap();
811 let root = dir.path().join("root");
812 let artifact = dir.path().join("cache.bin");
813 fs::create_dir(&root).unwrap();
814 fs::write(&artifact, b"stable-generation").unwrap();
815 let generation = artifact_generation(&artifact).unwrap();
816
817 let stale_ticket = capture_verify_ticket(&root);
818 invalidate_verify_memo(&root);
819 assert!(!record_verify_completed_if_unchanged(
820 &root,
821 VerifyArtifact::Search,
822 Some(generation),
823 stale_ticket,
824 ));
825 assert_eq!(
826 warm_verify_plan(&root, VerifyArtifact::Search, Some(generation)),
827 WarmVerifyPlan::Strict
828 );
829
830 let current_ticket = capture_verify_ticket(&root);
831 assert!(record_verify_completed_if_unchanged(
832 &root,
833 VerifyArtifact::Search,
834 Some(generation),
835 current_ticket,
836 ));
837 assert_eq!(
838 warm_verify_plan(&root, VerifyArtifact::Search, Some(generation)),
839 WarmVerifyPlan::Skip
840 );
841 }
842
843 #[cfg(unix)]
844 pub fn process_cpu_time() -> Duration {
845 let mut usage = std::mem::MaybeUninit::<libc::rusage>::uninit();
846 let result = unsafe { libc::getrusage(libc::RUSAGE_SELF, usage.as_mut_ptr()) };
847 assert_eq!(result, 0, "getrusage should report process CPU time");
848 let usage = unsafe { usage.assume_init() };
849 let seconds = (usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) as u64;
850 let micros = (usage.ru_utime.tv_usec + usage.ru_stime.tv_usec) as u64;
851 Duration::from_secs(seconds) + Duration::from_micros(micros)
852 }
853}