Skip to main content

aft/
readonly_artifacts.rs

1use std::path::{Path, PathBuf};
2use std::time::Duration;
3
4// These openers borrow cache artifacts that may be owned by a different AFT
5// session. They therefore only read and verify the opened snapshot; any repair,
6// migration, deletion, or rebuild must be left to the session that owns writes
7// for that project.
8use crate::cache_freshness::{artifact_generation, ArtifactGeneration};
9use crate::search_index::{
10    artifact_cache_key_with_memo, resolve_cache_dir, resolve_cache_dir_with_key, BorrowedIndexLoad,
11    BorrowedIndexLoadStop, SearchIndex,
12};
13use crate::semantic_index::SemanticIndex;
14
15#[derive(Clone, Debug)]
16pub(crate) enum ReadOnlyArtifact<T> {
17    Fresh(T),
18    Stale(ReadOnlyStale<T>),
19    Degraded(ReadOnlyDegradation),
20    Cancelled,
21    Absent,
22}
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub(crate) struct ReadOnlyDegradation {
26    pub reason: &'static str,
27}
28
29pub(crate) const BORROWED_SEARCH_LOAD_DEGRADATION: ReadOnlyDegradation = ReadOnlyDegradation {
30    reason: "borrowed_search_index_load_budget",
31};
32pub(crate) const BORROWED_SEMANTIC_LOAD_DEGRADATION: ReadOnlyDegradation = ReadOnlyDegradation {
33    reason: "borrowed_semantic_index_load_budget",
34};
35const BORROWED_SEMANTIC_MAX_BYTES: u64 = 64 * 1024 * 1024;
36
37#[cfg(test)]
38thread_local! {
39    static BORROWED_SEARCH_LOAD_LIMITS_FOR_TEST: std::cell::Cell<Option<(usize, Duration)>> = const { std::cell::Cell::new(None) };
40}
41
42fn borrowed_search_load_limits() -> (usize, Duration) {
43    #[cfg(test)]
44    if let Some(limits) = BORROWED_SEARCH_LOAD_LIMITS_FOR_TEST.with(std::cell::Cell::get) {
45        return limits;
46    }
47    (
48        crate::search_index::BORROWED_INDEX_LOAD_MAX_RECORDS,
49        crate::search_index::BORROWED_INDEX_LOAD_BUDGET,
50    )
51}
52
53#[cfg(test)]
54pub(crate) fn with_borrowed_search_load_limits_for_test<R>(
55    max_records: usize,
56    duration: Duration,
57    run: impl FnOnce() -> R,
58) -> R {
59    BORROWED_SEARCH_LOAD_LIMITS_FOR_TEST.with(|slot| {
60        let previous = slot.replace(Some((max_records, duration)));
61        let result = run();
62        slot.set(previous);
63        result
64    })
65}
66
67#[derive(Clone, Debug)]
68pub(crate) struct ReadOnlyStale<T> {
69    pub index: T,
70    pub drift_count: usize,
71    pub ignore_rules_differ: bool,
72}
73
74impl<T> ReadOnlyArtifact<T> {
75    pub(crate) fn map<U>(self, map: impl FnOnce(T) -> U) -> ReadOnlyArtifact<U> {
76        match self {
77            Self::Fresh(index) => ReadOnlyArtifact::Fresh(map(index)),
78            Self::Stale(stale) => ReadOnlyArtifact::Stale(ReadOnlyStale {
79                index: map(stale.index),
80                drift_count: stale.drift_count,
81                ignore_rules_differ: stale.ignore_rules_differ,
82            }),
83            Self::Degraded(degradation) => ReadOnlyArtifact::Degraded(degradation),
84            Self::Cancelled => ReadOnlyArtifact::Cancelled,
85            Self::Absent => ReadOnlyArtifact::Absent,
86        }
87    }
88}
89
90#[derive(Clone, Debug, PartialEq, Eq)]
91pub(crate) struct BorrowedArtifactGeneration {
92    pub path: PathBuf,
93    pub generation: ArtifactGeneration,
94}
95
96#[derive(Debug)]
97pub(crate) enum GitRootResolutionError {
98    PathNotFound(PathBuf),
99    NotAGitRoot,
100    Other(String),
101}
102
103pub(crate) fn resolve_git_root_from_user_path(
104    project_root: &Path,
105    raw_path: &str,
106) -> Result<PathBuf, GitRootResolutionError> {
107    let expanded = expand_tilde(raw_path);
108    let requested = if expanded.is_absolute() {
109        expanded
110    } else {
111        project_root.join(expanded)
112    };
113    if !requested.exists() {
114        return Err(GitRootResolutionError::PathNotFound(requested));
115    }
116
117    let existing = nearest_existing_parent(&requested)
118        .ok_or_else(|| GitRootResolutionError::PathNotFound(requested.clone()))?;
119
120    // `nearest_existing_parent` returns an `fs::canonicalize` result, which on
121    // Windows is a verbatim (`\\?\C:\...`) path. Normalize before comparing the
122    // requested directory with the configured root so aliases such as `.` and
123    // symlinks remain local without requiring the workspace itself to be Git.
124    let existing = crate::inspect::job::canonicalize_normalized(&existing);
125    if existing == crate::inspect::job::canonicalize_normalized(project_root) {
126        return Ok(project_root.to_path_buf());
127    }
128
129    let git_base = if existing.is_file() {
130        existing.parent().unwrap_or(&existing).to_path_buf()
131    } else {
132        existing
133    };
134    git_toplevel(&git_base).map_err(|error| match error.as_str() {
135        "not_a_git_root" => GitRootResolutionError::NotAGitRoot,
136        _ => GitRootResolutionError::Other(error),
137    })
138}
139
140#[cfg(test)]
141pub(crate) fn search_index_artifact_generation(
142    project_root: &Path,
143    storage_dir: Option<&Path>,
144) -> Option<BorrowedArtifactGeneration> {
145    let cache_dir = search_index_cache_dir(project_root, storage_dir)?;
146    search_artifact_generation_from_cache_dir(cache_dir)
147}
148
149pub(crate) fn search_index_artifact_generation_with_key(
150    project_key: &str,
151    storage_dir: Option<&Path>,
152) -> Option<BorrowedArtifactGeneration> {
153    search_artifact_generation_from_cache_dir(resolve_cache_dir_with_key(project_key, storage_dir))
154}
155
156fn search_artifact_generation_from_cache_dir(
157    cache_dir: PathBuf,
158) -> Option<BorrowedArtifactGeneration> {
159    let path = cache_dir.join("cache.bin");
160    let generation = artifact_generation(&path)?;
161    Some(BorrowedArtifactGeneration { path, generation })
162}
163
164pub(crate) fn open_search_index_read_only(
165    project_root: &Path,
166    storage_dir: Option<&Path>,
167) -> ReadOnlyArtifact<SearchIndex> {
168    let Some(cache_dir) = search_index_cache_dir(project_root, storage_dir) else {
169        return ReadOnlyArtifact::Absent;
170    };
171    open_search_index_from_cache_dir(project_root, cache_dir)
172}
173
174pub(crate) fn open_search_index_read_only_with_key(
175    project_root: &Path,
176    storage_dir: Option<&Path>,
177    project_key: &str,
178) -> ReadOnlyArtifact<SearchIndex> {
179    open_search_index_from_cache_dir(
180        project_root,
181        resolve_cache_dir_with_key(project_key, storage_dir),
182    )
183}
184
185fn open_search_index_from_cache_dir(
186    project_root: &Path,
187    cache_dir: PathBuf,
188) -> ReadOnlyArtifact<SearchIndex> {
189    let (max_records, duration) = borrowed_search_load_limits();
190    open_search_index_from_cache_dir_with_budget(project_root, cache_dir, max_records, duration)
191}
192
193fn open_search_index_from_cache_dir_with_budget(
194    project_root: &Path,
195    cache_dir: PathBuf,
196    max_records: usize,
197    duration: Duration,
198) -> ReadOnlyArtifact<SearchIndex> {
199    if !cache_dir.join("cache.bin").is_file() {
200        return ReadOnlyArtifact::Absent;
201    }
202
203    let (mut index, ignore_rules_differ) =
204        match SearchIndex::read_from_disk_borrow_tolerant_with_budget(
205            &cache_dir,
206            project_root,
207            max_records,
208            duration,
209        ) {
210            BorrowedIndexLoad::Loaded(index, ignore_rules_differ) => (index, ignore_rules_differ),
211            BorrowedIndexLoad::Stopped(BorrowedIndexLoadStop::BudgetExceeded) => {
212                return ReadOnlyArtifact::Degraded(BORROWED_SEARCH_LOAD_DEGRADATION);
213            }
214            BorrowedIndexLoad::Stopped(BorrowedIndexLoadStop::Cancelled) => {
215                return ReadOnlyArtifact::Cancelled;
216            }
217            BorrowedIndexLoad::Invalid => return ReadOnlyArtifact::Absent,
218        };
219
220    index.set_ready(true);
221    if ignore_rules_differ {
222        ReadOnlyArtifact::Stale(ReadOnlyStale {
223            index,
224            drift_count: 0,
225            ignore_rules_differ,
226        })
227    } else {
228        ReadOnlyArtifact::Fresh(index)
229    }
230}
231
232fn search_index_cache_dir(project_root: &Path, storage_dir: Option<&Path>) -> Option<PathBuf> {
233    match storage_dir {
234        Some(storage_dir) => {
235            match artifact_cache_key_with_memo(project_root, project_root, storage_dir, None) {
236                Ok(project_key) => {
237                    Some(resolve_cache_dir_with_key(&project_key, Some(storage_dir)))
238                }
239                Err(error) => {
240                    crate::slog_warn!("read-only search index unavailable: {}", error);
241                    None
242                }
243            }
244        }
245        None => Some(resolve_cache_dir(project_root, None)),
246    }
247}
248
249#[cfg(test)]
250pub(crate) fn semantic_index_artifact_generation(
251    project_root: &Path,
252    storage_dir: Option<&Path>,
253) -> Option<BorrowedArtifactGeneration> {
254    let (data_path, _) = semantic_index_location(project_root, storage_dir)?;
255    borrowed_artifact_generation(data_path)
256}
257
258pub(crate) fn semantic_index_artifact_generation_with_key(
259    project_key: &str,
260    storage_dir: Option<&Path>,
261) -> Option<BorrowedArtifactGeneration> {
262    let storage_dir = storage_dir?;
263    borrowed_artifact_generation(
264        storage_dir
265            .join("semantic")
266            .join(project_key)
267            .join("semantic.bin"),
268    )
269}
270
271fn borrowed_artifact_generation(path: PathBuf) -> Option<BorrowedArtifactGeneration> {
272    let generation = artifact_generation(&path)?;
273    Some(BorrowedArtifactGeneration { path, generation })
274}
275
276pub(crate) fn open_semantic_index_read_only(
277    project_root: &Path,
278    storage_dir: Option<&Path>,
279) -> ReadOnlyArtifact<SemanticIndex> {
280    let Some((data_path, project_key)) = semantic_index_location(project_root, storage_dir) else {
281        return ReadOnlyArtifact::Absent;
282    };
283    open_semantic_index_from_location(project_root, storage_dir, data_path, &project_key)
284}
285
286pub(crate) fn open_semantic_index_read_only_with_key(
287    project_root: &Path,
288    storage_dir: Option<&Path>,
289    project_key: &str,
290) -> ReadOnlyArtifact<SemanticIndex> {
291    let Some(storage_dir) = storage_dir else {
292        return ReadOnlyArtifact::Absent;
293    };
294    let data_path = storage_dir
295        .join("semantic")
296        .join(project_key)
297        .join("semantic.bin");
298    open_semantic_index_from_location(project_root, Some(storage_dir), data_path, project_key)
299}
300
301fn open_semantic_index_from_location(
302    project_root: &Path,
303    storage_dir: Option<&Path>,
304    data_path: PathBuf,
305    project_key: &str,
306) -> ReadOnlyArtifact<SemanticIndex> {
307    let Some(storage_dir) = storage_dir else {
308        return ReadOnlyArtifact::Absent;
309    };
310    let Ok(metadata) = data_path.metadata() else {
311        return ReadOnlyArtifact::Absent;
312    };
313    if metadata.len() > BORROWED_SEMANTIC_MAX_BYTES {
314        return ReadOnlyArtifact::Degraded(BORROWED_SEMANTIC_LOAD_DEGRADATION);
315    }
316    if search_cancelled() {
317        return ReadOnlyArtifact::Cancelled;
318    }
319
320    let opened =
321        SemanticIndex::read_from_disk_borrow_tolerant(storage_dir, project_key, project_root)
322            .map(ReadOnlyArtifact::Fresh)
323            .unwrap_or(ReadOnlyArtifact::Absent);
324    if search_cancelled() {
325        ReadOnlyArtifact::Cancelled
326    } else {
327        opened
328    }
329}
330
331fn search_cancelled() -> bool {
332    crate::executor::current_job_cancelled()
333}
334
335fn semantic_index_location(
336    project_root: &Path,
337    storage_dir: Option<&Path>,
338) -> Option<(PathBuf, String)> {
339    let storage_dir = storage_dir?;
340    let project_key =
341        match artifact_cache_key_with_memo(project_root, project_root, storage_dir, None) {
342            Ok(project_key) => project_key,
343            Err(error) => {
344                crate::slog_warn!("read-only semantic index unavailable: {}", error);
345                return None;
346            }
347        };
348    let data_path = storage_dir
349        .join("semantic")
350        .join(&project_key)
351        .join("semantic.bin");
352    Some((data_path, project_key))
353}
354
355fn expand_tilde(raw: &str) -> PathBuf {
356    if raw == "~" {
357        return home_dir().unwrap_or_else(|| PathBuf::from(raw));
358    }
359    if let Some(rest) = raw.strip_prefix("~/") {
360        if let Some(home) = home_dir() {
361            return home.join(rest);
362        }
363    }
364    PathBuf::from(raw)
365}
366
367fn home_dir() -> Option<PathBuf> {
368    std::env::var_os("HOME")
369        .or_else(|| std::env::var_os("USERPROFILE"))
370        .map(PathBuf::from)
371}
372
373fn nearest_existing_parent(path: &Path) -> Option<PathBuf> {
374    let mut current = path.to_path_buf();
375    loop {
376        if current.exists() {
377            return std::fs::canonicalize(&current).ok().or(Some(current));
378        }
379        if !current.pop() {
380            return None;
381        }
382    }
383}
384
385fn git_toplevel(base_dir: &Path) -> Result<PathBuf, String> {
386    let output = crate::effective_path::new_command("git")
387        .args(["rev-parse", "--show-toplevel"])
388        .current_dir(base_dir)
389        .output()
390        .map_err(|error| format!("failed to run git: {error}"))?;
391
392    if !output.status.success() {
393        let stderr = String::from_utf8_lossy(&output.stderr);
394        if stderr.contains("not a git repository") {
395            return Err("not_a_git_root".to_string());
396        }
397        return Err(format!("git rev-parse failed: {}", stderr.trim()));
398    }
399
400    let toplevel = String::from_utf8_lossy(&output.stdout).trim().to_string();
401    if toplevel.is_empty() {
402        return Err("git rev-parse returned an empty toplevel".to_string());
403    }
404    let toplevel = PathBuf::from(toplevel);
405    Ok(std::fs::canonicalize(&toplevel).unwrap_or(toplevel))
406}
407
408#[cfg(test)]
409mod tests {
410    use super::*;
411
412    use std::collections::BTreeMap;
413    use std::fs;
414    use std::process::Command;
415    use std::time::SystemTime;
416
417    use tempfile::TempDir;
418
419    use crate::context::BORROWED_INDEX_CACHE_CAPACITY;
420    use crate::search_index::artifact_cache_key;
421    use crate::semantic_index::{SemanticIndex, SemanticIndexFingerprint};
422
423    #[derive(Debug, PartialEq, Eq)]
424    struct FileSnapshot {
425        modified: SystemTime,
426        hash: blake3::Hash,
427    }
428
429    fn git_command(root: &Path) -> Command {
430        let mut command = Command::new("git");
431        crate::test_env::apply_hermetic_git_env(command.current_dir(root));
432        command
433    }
434
435    fn init_git(root: &Path) {
436        let status = git_command(root)
437            .args(["init"])
438            .status()
439            .expect("run git init");
440        assert!(status.success(), "git init failed");
441        let status = git_command(root)
442            .args(["config", "user.email", "test@example.com"])
443            .status()
444            .expect("configure git email");
445        assert!(status.success(), "git config email failed");
446        let status = git_command(root)
447            .args(["config", "user.name", "AFT Test"])
448            .status()
449            .expect("configure git name");
450        assert!(status.success(), "git config name failed");
451    }
452
453    fn commit_all(root: &Path) {
454        let status = git_command(root)
455            .args(["add", "."])
456            .status()
457            .expect("git add");
458        assert!(status.success(), "git add failed");
459        let status = git_command(root)
460            .args(["commit", "-m", "initial"])
461            .status()
462            .expect("git commit");
463        assert!(status.success(), "git commit failed");
464    }
465
466    fn fixture_project() -> (TempDir, PathBuf) {
467        let temp = tempfile::tempdir().expect("create project");
468        init_git(temp.path());
469        let source = temp.path().join("src/lib.rs");
470        fs::create_dir_all(source.parent().expect("source parent")).expect("create src");
471        fs::write(&source, "pub fn readonly_needle() -> bool { true }\n").expect("write source");
472        commit_all(temp.path());
473        let root = fs::canonicalize(temp.path()).expect("canonical project root");
474        (temp, root)
475    }
476
477    fn snapshot_dir(root: &Path) -> BTreeMap<PathBuf, FileSnapshot> {
478        fn visit(dir: &Path, out: &mut BTreeMap<PathBuf, FileSnapshot>, base: &Path) {
479            for entry in fs::read_dir(dir).expect("read dir") {
480                let entry = entry.expect("dir entry");
481                let path = entry.path();
482                let meta = entry.metadata().expect("entry metadata");
483                if meta.is_dir() {
484                    visit(&path, out, base);
485                } else if meta.is_file() {
486                    let bytes = fs::read(&path).expect("read snapshot file");
487                    out.insert(
488                        path.strip_prefix(base)
489                            .expect("relative snapshot path")
490                            .to_path_buf(),
491                        FileSnapshot {
492                            modified: meta.modified().expect("snapshot mtime"),
493                            hash: blake3::hash(&bytes),
494                        },
495                    );
496                }
497            }
498        }
499
500        let mut out = BTreeMap::new();
501        if root.exists() {
502            visit(root, &mut out, root);
503        }
504        out
505    }
506
507    fn build_search_artifact(root: &Path, storage: &Path) -> PathBuf {
508        let cache_dir = resolve_cache_dir(root, Some(storage));
509        let mut index = SearchIndex::build(root);
510        index.write_to_disk(
511            &cache_dir,
512            crate::search_index::current_git_head(root).as_deref(),
513        );
514        cache_dir
515    }
516
517    fn clone_checkout(root: &Path) -> (TempDir, PathBuf) {
518        let temp = tempfile::tempdir().expect("create clone dir");
519        let clone_root = temp.path().join("clone");
520        // fixture_project returns a canonicalized root, which on Windows is a
521        // verbatim `\\?\` path. git cannot take verbatim paths as the clone
522        // source, so strip the prefix for the git invocation only.
523        let clone_source = root
524            .to_string_lossy()
525            .trim_start_matches(r"\\?\")
526            .to_string();
527        let mut command = Command::new("git");
528        let status = crate::test_env::apply_hermetic_git_env(&mut command)
529            .arg("clone")
530            .arg("--quiet")
531            .arg(&clone_source)
532            .arg(&clone_root)
533            .status()
534            .expect("git clone");
535        assert!(status.success(), "git clone failed");
536        let clone_root = fs::canonicalize(clone_root).expect("canonical clone root");
537        (temp, clone_root)
538    }
539
540    fn build_semantic_artifact(root: &Path, storage: &Path) {
541        let source = root.join("src/lib.rs");
542        let fingerprint = SemanticIndexFingerprint {
543            backend: "openai_compatible".to_string(),
544            model: "readonly-test".to_string(),
545            base_url: "http://127.0.0.1".to_string(),
546            dimension: 3,
547            chunking_version: 1,
548        };
549        let mut embed =
550            |texts: Vec<String>| Ok::<_, String>(vec![vec![0.1, 0.2, 0.3]; texts.len()]);
551        let mut index =
552            SemanticIndex::build(root, &[source], &mut embed, 8).expect("build semantic index");
553        index.set_fingerprint(fingerprint);
554        index.write_to_disk(storage, &artifact_cache_key(root));
555    }
556
557    fn borrowed_context(root: &Path, storage: &Path) -> crate::context::AppContext {
558        crate::context::AppContext::new(
559            crate::context::default_language_provider_factory(),
560            crate::config::Config {
561                project_root: Some(root.to_path_buf()),
562                storage_dir: Some(storage.to_path_buf()),
563                ..crate::config::Config::default()
564            },
565        )
566    }
567
568    fn cached_search_index(
569        ctx: &crate::context::AppContext,
570        root: &Path,
571        storage: &Path,
572    ) -> std::sync::Arc<SearchIndex> {
573        match ctx.open_borrowed_search_index(root, Some(storage)) {
574            ReadOnlyArtifact::Fresh(index)
575            | ReadOnlyArtifact::Stale(ReadOnlyStale { index, .. }) => index,
576            other => panic!("expected borrowed search index, got {other:?}"),
577        }
578    }
579
580    #[cfg(debug_assertions)]
581    #[test]
582    fn repeated_borrowed_opens_cache_one_load_per_artifact_generation() {
583        let _git_env = crate::test_env::hermetic_git_env_guard();
584        let (_project, root) = fixture_project();
585        let storage = tempfile::tempdir().expect("storage");
586        build_search_artifact(&root, storage.path());
587        let ctx = borrowed_context(&root, storage.path());
588        search_index_artifact_generation(&root, Some(storage.path()))
589            .expect("seed borrowed artifact generation");
590        let artifact_before = snapshot_dir(storage.path());
591
592        crate::cache_freshness::reset_verify_file_strict_count_for_debug();
593        let first = cached_search_index(&ctx, &root, storage.path());
594        let second = cached_search_index(&ctx, &root, storage.path());
595        assert!(std::sync::Arc::ptr_eq(&first, &second));
596        assert_eq!(ctx.borrowed_index_cache_len_for_test(), 1);
597        assert_eq!(
598            ctx.artifact_cache_key_derivation_count_for_test(),
599            1,
600            "artifact identity should be derived only on the first external search"
601        );
602        assert_eq!(
603            crate::cache_freshness::verify_file_strict_count_under_for_debug(&root),
604            0,
605            "neither the first load nor a cache hit may run a corpus census"
606        );
607        assert_eq!(snapshot_dir(storage.path()), artifact_before);
608
609        let added = root.join("src/added.rs");
610        fs::write(&added, "pub fn generation_two() {}\n").expect("add generation file");
611        build_search_artifact(&root, storage.path());
612        let rebuilt_snapshot = snapshot_dir(storage.path());
613        let third = cached_search_index(&ctx, &root, storage.path());
614        assert!(
615            !std::sync::Arc::ptr_eq(&first, &third),
616            "an owner rebuild must invalidate the cached rerooted generation"
617        );
618        assert!(third.path_to_id.contains_key(&added));
619        assert_eq!(ctx.borrowed_index_cache_len_for_test(), 1);
620        assert_eq!(ctx.artifact_cache_key_derivation_count_for_test(), 1);
621        assert_eq!(snapshot_dir(storage.path()), rebuilt_snapshot);
622
623        assert!(ctx.evict_idle_artifacts());
624        assert_eq!(ctx.borrowed_index_cache_len_for_test(), 0);
625    }
626
627    #[test]
628    fn repeated_borrowed_semantic_opens_reuse_rerooted_generation() {
629        let _git_env = crate::test_env::hermetic_git_env_guard();
630        let (_project, root) = fixture_project();
631        let storage = tempfile::tempdir().expect("storage");
632        build_semantic_artifact(&root, storage.path());
633        let ctx = borrowed_context(&root, storage.path());
634        semantic_index_artifact_generation(&root, Some(storage.path()))
635            .expect("seed semantic artifact generation");
636        let artifact_before = snapshot_dir(storage.path());
637
638        let first = match ctx.open_borrowed_semantic_index(&root, Some(storage.path())) {
639            ReadOnlyArtifact::Fresh(index) => index,
640            other => panic!("expected borrowed semantic index, got {other:?}"),
641        };
642        let second = match ctx.open_borrowed_semantic_index(&root, Some(storage.path())) {
643            ReadOnlyArtifact::Fresh(index) => index,
644            other => panic!("expected cached semantic index, got {other:?}"),
645        };
646        assert!(std::sync::Arc::ptr_eq(&first, &second));
647        assert_eq!(ctx.borrowed_index_cache_len_for_test(), 1);
648        assert_eq!(snapshot_dir(storage.path()), artifact_before);
649    }
650
651    #[test]
652    fn borrowed_index_cache_is_bounded_and_idle_evictable() {
653        let _git_env = crate::test_env::hermetic_git_env_guard();
654        let storage = tempfile::tempdir().expect("storage");
655        let mut projects = Vec::new();
656        for _ in 0..=BORROWED_INDEX_CACHE_CAPACITY {
657            let (project, root) = fixture_project();
658            build_search_artifact(&root, storage.path());
659            projects.push((project, root));
660        }
661        let ctx = borrowed_context(&projects[0].1, storage.path());
662        let first = cached_search_index(&ctx, &projects[0].1, storage.path());
663        for (_, root) in projects.iter().skip(1) {
664            cached_search_index(&ctx, root, storage.path());
665        }
666        assert_eq!(
667            ctx.borrowed_index_cache_len_for_test(),
668            BORROWED_INDEX_CACHE_CAPACITY
669        );
670        let reloaded_first = cached_search_index(&ctx, &projects[0].1, storage.path());
671        assert!(!std::sync::Arc::ptr_eq(&first, &reloaded_first));
672
673        assert!(ctx.evict_idle_artifacts());
674        assert_eq!(ctx.borrowed_index_cache_len_for_test(), 0);
675    }
676
677    #[test]
678    fn stale_posting_verification_stops_at_injected_file_budget() {
679        let _git_env = crate::test_env::hermetic_git_env_guard();
680        let (_project, root) = fixture_project();
681        for file_index in 0..20 {
682            fs::write(
683                root.join(format!("src/stale_{file_index}.rs")),
684                "pub fn stale_budget_needle() {}\n",
685            )
686            .expect("write indexed stale candidate");
687        }
688        let storage = tempfile::tempdir().expect("storage");
689        build_search_artifact(&root, storage.path());
690        for file_index in 0..20 {
691            fs::write(
692                root.join(format!("src/stale_{file_index}.rs")),
693                "pub fn changed_after_index_build() {}\n",
694            )
695            .expect("replace indexed stale candidate");
696        }
697        let index = match open_search_index_read_only(&root, Some(storage.path())) {
698            ReadOnlyArtifact::Fresh(index) => index,
699            other => panic!("expected borrowed index, got {other:?}"),
700        };
701        let compiled = match crate::pattern_compile::compile(
702            "stale_budget_needle",
703            crate::pattern_compile::CompileOpts {
704                literal: true,
705                ..crate::pattern_compile::CompileOpts::default()
706            },
707        ) {
708            crate::pattern_compile::CompileResult::Ok(compiled) => compiled,
709            other => panic!("literal compile failed: {other:?}"),
710        };
711
712        let result = index.snapshot().search_grep_bounded(
713            &compiled,
714            &[],
715            &[],
716            &root,
717            10,
718            None,
719            1,
720            std::time::Duration::from_secs(1),
721        );
722        assert!(result.matches.is_empty());
723        assert!(result.files_searched <= 1);
724        assert!(result.truncated);
725        assert!(result.engine_capped);
726    }
727
728    #[test]
729    fn churned_borrowed_generation_stops_at_load_budget() {
730        let _git_env = crate::test_env::hermetic_git_env_guard();
731        let (_project, root) = fixture_project();
732        for file_index in 0..64 {
733            fs::write(
734                root.join(format!("src/module_{file_index}.rs")),
735                format!("pub fn borrowed_budget_{file_index}() {{}}\n"),
736            )
737            .expect("write borrowed corpus file");
738        }
739        let storage = tempfile::tempdir().expect("storage");
740        let cache_dir = build_search_artifact(&root, storage.path());
741        assert!(matches!(
742            open_search_index_from_cache_dir_with_budget(
743                &root,
744                cache_dir.clone(),
745                10_000,
746                Duration::from_secs(5),
747            ),
748            ReadOnlyArtifact::Fresh(_)
749        ));
750
751        for file_index in 0..40 {
752            fs::write(
753                root.join(format!("src/module_{file_index}.rs")),
754                format!("pub fn churned_borrowed_budget_{file_index}() {{}}\n"),
755            )
756            .expect("churn borrowed corpus file");
757        }
758        build_search_artifact(&root, storage.path());
759
760        let started = std::time::Instant::now();
761        let opened = open_search_index_from_cache_dir_with_budget(
762            &root,
763            cache_dir,
764            10,
765            Duration::from_secs(5),
766        );
767        assert_eq!(
768            started.elapsed() < Duration::from_secs(1),
769            true,
770            "record budget must stop before rerooting the churned corpus"
771        );
772        assert!(matches!(
773            opened,
774            ReadOnlyArtifact::Degraded(BORROWED_SEARCH_LOAD_DEGRADATION)
775        ));
776    }
777
778    #[test]
779    fn cancelled_borrowed_load_stops_at_checkpoint() {
780        let _git_env = crate::test_env::hermetic_git_env_guard();
781        let (_project, root) = fixture_project();
782        let storage = tempfile::tempdir().expect("storage");
783        let cache_dir = build_search_artifact(&root, storage.path());
784        let cancellation = crate::executor::JobCancellation::new();
785        cancellation.request_cancel();
786        let _installed = crate::executor::install_job_cancellation(cancellation);
787
788        assert!(matches!(
789            open_search_index_from_cache_dir_with_budget(
790                &root,
791                cache_dir,
792                10_000,
793                Duration::from_secs(5),
794            ),
795            ReadOnlyArtifact::Cancelled
796        ));
797    }
798
799    #[test]
800    fn oversized_borrowed_semantic_artifact_degrades_before_parse() {
801        let _git_env = crate::test_env::hermetic_git_env_guard();
802        let (_project, root) = fixture_project();
803        let storage = tempfile::tempdir().expect("storage");
804        let data_path = storage
805            .path()
806            .join("semantic")
807            .join(artifact_cache_key(&root))
808            .join("semantic.bin");
809        fs::create_dir_all(data_path.parent().expect("semantic parent"))
810            .expect("create semantic artifact directory");
811        let file = fs::File::create(&data_path).expect("create sparse semantic artifact");
812        file.set_len(BORROWED_SEMANTIC_MAX_BYTES + 1)
813            .expect("size sparse semantic artifact");
814
815        assert!(matches!(
816            open_semantic_index_read_only(&root, Some(storage.path())),
817            ReadOnlyArtifact::Degraded(BORROWED_SEMANTIC_LOAD_DEGRADATION)
818        ));
819    }
820
821    #[cfg(debug_assertions)]
822    #[test]
823    fn search_opener_skips_full_corpus_strict_census() {
824        let _git_env = crate::test_env::hermetic_git_env_guard();
825        let (_project, root) = fixture_project();
826        let storage = tempfile::tempdir().expect("storage");
827
828        assert!(matches!(
829            open_search_index_read_only(&root, Some(storage.path())),
830            ReadOnlyArtifact::Absent
831        ));
832
833        build_search_artifact(&root, storage.path());
834        crate::cache_freshness::reset_verify_file_strict_count_for_debug();
835        assert!(matches!(
836            open_search_index_read_only(&root, Some(storage.path())),
837            ReadOnlyArtifact::Fresh(_)
838        ));
839        assert_eq!(
840            crate::cache_freshness::verify_file_strict_count_under_for_debug(&root),
841            0,
842            "a borrowed open must not restore the full-corpus strict hash census"
843        );
844
845        fs::write(
846            root.join("src/lib.rs"),
847            "pub fn readonly_needle() -> bool { false }\n",
848        )
849        .expect("mutate fixture");
850        match open_search_index_read_only(&root, Some(storage.path())) {
851            ReadOnlyArtifact::Fresh(index) => {
852                assert!(index.stored_git_head().is_some());
853            }
854            other => panic!("expected silently served borrowed artifact, got {other:?}"),
855        }
856        assert_eq!(
857            crate::cache_freshness::verify_file_strict_count_under_for_debug(&root),
858            0
859        );
860    }
861
862    #[test]
863    fn search_opener_marks_cross_checkout_ignore_rule_mismatch_as_stale() {
864        let _git_env = crate::test_env::hermetic_git_env_guard();
865        let (_project, root) = fixture_project();
866        let storage = tempfile::tempdir().expect("storage");
867        let owner_only_ignore = root.join(".foo/.gitignore");
868        fs::create_dir_all(owner_only_ignore.parent().expect("ignore parent"))
869            .expect("create ignore dir");
870        fs::write(&owner_only_ignore, "# owner-only ignore file\n").expect("write ignore file");
871        build_search_artifact(&root, storage.path());
872
873        let (_clone, sibling_root) = clone_checkout(&root);
874        match open_search_index_read_only(&sibling_root, Some(storage.path())) {
875            ReadOnlyArtifact::Stale(stale) => {
876                assert!(stale.ignore_rules_differ);
877                assert!(stale.index.stored_git_head().is_some());
878            }
879            other => panic!("expected stale borrowed artifact, got {other:?}"),
880        }
881    }
882
883    #[test]
884    fn owner_search_loader_stays_strict_on_ignore_rule_mismatch() {
885        let _git_env = crate::test_env::hermetic_git_env_guard();
886        let (_project, root) = fixture_project();
887        let storage = tempfile::tempdir().expect("storage");
888        let cache_dir = build_search_artifact(&root, storage.path());
889        let owner_only_ignore = root.join(".foo/.gitignore");
890        fs::create_dir_all(owner_only_ignore.parent().expect("ignore parent"))
891            .expect("create ignore dir");
892        fs::write(&owner_only_ignore, "# owner-only ignore file\n").expect("write ignore file");
893
894        assert!(SearchIndex::read_from_disk(&cache_dir, &root).is_none());
895    }
896
897    #[test]
898    fn read_only_openers_never_modify_artifact_directory() {
899        let _git_env = crate::test_env::hermetic_git_env_guard();
900        let (_project, root) = fixture_project();
901        let storage = tempfile::tempdir().expect("storage");
902        let search_cache_dir = build_search_artifact(&root, storage.path());
903        build_semantic_artifact(&root, storage.path());
904        artifact_cache_key_with_memo(&root, &root, storage.path(), None)
905            .expect("seed cache-key memo before read-only snapshot");
906        let semantic_cache_dir = storage
907            .path()
908            .join("semantic")
909            .join(artifact_cache_key(&root));
910
911        let before = snapshot_dir(storage.path());
912        assert!(matches!(
913            open_search_index_read_only(&root, Some(storage.path())),
914            ReadOnlyArtifact::Fresh(_)
915        ));
916        assert!(matches!(
917            open_semantic_index_read_only(&root, Some(storage.path())),
918            ReadOnlyArtifact::Fresh(_)
919        ));
920        assert_eq!(snapshot_dir(storage.path()), before);
921
922        fs::write(
923            root.join("src/lib.rs"),
924            "pub fn readonly_needle() -> bool { false }\n",
925        )
926        .expect("mutate fixture");
927        let stale_before = snapshot_dir(storage.path());
928        assert!(matches!(
929            open_search_index_read_only(&root, Some(storage.path())),
930            ReadOnlyArtifact::Fresh(_)
931        ));
932        assert!(matches!(
933            open_semantic_index_read_only(&root, Some(storage.path())),
934            ReadOnlyArtifact::Fresh(_)
935        ));
936        assert_eq!(snapshot_dir(storage.path()), stale_before);
937        assert!(search_cache_dir.join("cache.bin").is_file());
938        assert!(semantic_cache_dir.join("semantic.bin").is_file());
939    }
940}