Skip to main content

lean_ctx/core/
search_index.rs

1//! Resident line-search index for `ctx_search` (Phase 1 of the efficiency epic).
2//!
3//! Historically `ctx_search` walked the filesystem, read every file, and ran a
4//! regex on every line on *every* call — `O(files × lines)`. That is the
5//! 40–200 ms latency floor this module eliminates.
6//!
7//! This module keeps a RAM-resident trigram index (`trigram → file ids`) so the
8//! common case (an identifier / literal query) collapses to: intersect a few
9//! posting lists in memory → read & regex-verify only the handful of candidate
10//! files. The index never decides matches itself; it only *narrows the file
11//! set*, then `ctx_search` verifies candidates with the exact same regex loop,
12//! so the returned `file:line` hits are byte-identical to the walk path.
13//!
14//! Design notes:
15//! - The index is built with the *same* walk config and file filters as
16//!   `ctx_search` (see [`crate::tools::ctx_search`]) so the searchable universe
17//!   is identical — that is what guarantees recall parity.
18//! - Only `[A-Za-z0-9_]` trigrams are indexed. Lookups only ever use trigrams
19//!   from pure-identifier queries, so this is both sufficient and memory-bounded.
20//! - Narrowing is applied *only* for pure `[A-Za-z0-9_]` literal queries (the
21//!   dominant agent case). Any query containing a regex metacharacter falls
22//!   back to scanning the cached file list (still skips the directory walk).
23//! - Freshness is a function of *corpus state*, not the clock: the build records
24//!   a cheap, order-independent signature over the eligible files' `(path,
25//!   mtime, size)`, and every [`get_fresh`] re-derives it via a stat-only walk
26//!   that shares the build's exact filter path. The resident index is served
27//!   only when the signature matches live disk — so an edit, *even through a
28//!   tool lean-ctx never observes* (native editors, `git checkout`), is
29//!   reflected on the very next search instead of lingering for a TTL window.
30//!   A push-based fs-watcher (zero per-lookup cost) is a possible future
31//!   optimization on top of this correctness gate.
32
33use std::collections::{HashMap, HashSet};
34use std::path::{Path, PathBuf};
35use std::sync::{Arc, Mutex, OnceLock};
36use std::time::{Duration, Instant};
37
38use glob::Pattern;
39use ignore::WalkBuilder;
40
41use crate::tools::ctx_search::{MAX_FILE_SIZE, MAX_WALK_DEPTH, is_binary_ext, is_generated_file};
42
43/// Upper bound on indexed files; larger trees fall back to the walk path.
44const MAX_FILES: usize = 200_000;
45
46/// Posting-entry budget (`file_id` occurrences across all trigrams). Up to this
47/// many entries we keep exact inverted posting lists (fastest, sparse lookups).
48/// Beyond it we switch to the per-file Bloom tier instead of giving up — see
49/// [`Narrowing`]. ~4 bytes each → ~48 MB before the switch.
50const MAX_POSTING_ENTRIES: usize = 12_000_000;
51
52/// Hard ceiling on total trigram entries collected during a build. Past this we
53/// abandon indexing (walk fallback) to avoid pathological memory use even with
54/// the compact Bloom tier.
55const MAX_TOTAL_ENTRIES: usize = 48_000_000;
56
57/// Bloom tuning: bits per distinct trigram and number of hash probes. ~12 bits
58/// with k=7 keeps the false-positive rate well under 1% — and a false positive
59/// only costs one extra regex-verified file read (never a missed match).
60const BLOOM_BITS_PER_ITEM: usize = 12;
61const BLOOM_K: usize = 7;
62/// Per-file Bloom size clamp (in bits): 64 bits min, 1 Mi bits (128 KiB) max.
63const BLOOM_MIN_BITS: usize = 64;
64const BLOOM_MAX_BITS: usize = 1 << 20;
65
66/// A trigram is indexable only if all three bytes are `[A-Za-z0-9_]`.
67fn is_word_byte(b: u8) -> bool {
68    b.is_ascii_alphanumeric() || b == b'_'
69}
70
71fn pack(b0: u8, b1: u8, b2: u8) -> u32 {
72    (u32::from(b0) << 16) | (u32::from(b1) << 8) | u32::from(b2)
73}
74
75/// How candidate files are narrowed for a literal query. Two tiers, chosen by
76/// corpus size, both providing a *superset* of true matches (zero false
77/// negatives) which `ctx_search` then regex-verifies:
78/// - `Postings`: exact inverted lists `trigram → sorted file ids`. Fast, sparse
79///   lookups; used while total entries fit [`MAX_POSTING_ENTRIES`].
80/// - `Blooms`: one compact per-file Bloom filter of the file's trigrams. ~3×
81///   smaller than postings, so monorepos that would otherwise blow the posting
82///   budget still get index-narrowing instead of a full directory walk.
83enum Narrowing {
84    Postings(HashMap<u32, Vec<u32>>),
85    Blooms(Vec<FileBloom>),
86}
87
88/// A per-file Bloom filter over the file's word-trigrams. No false negatives:
89/// if any probed bit for a trigram is unset, the file provably lacks it.
90struct FileBloom {
91    /// Bit storage; the filter width `m = bits.len() * 64` is a power of two.
92    bits: Vec<u64>,
93}
94
95/// 64-bit avalanche mix (splitmix64 finalizer) — spreads a packed trigram into
96/// a well-distributed hash for double-probing.
97#[inline]
98fn mix64(mut x: u64) -> u64 {
99    x = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
100    x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
101    x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
102    x ^ (x >> 31)
103}
104
105impl FileBloom {
106    fn with_capacity(distinct_trigrams: usize) -> Self {
107        let target = distinct_trigrams
108            .saturating_mul(BLOOM_BITS_PER_ITEM)
109            .next_power_of_two()
110            .clamp(BLOOM_MIN_BITS, BLOOM_MAX_BITS);
111        FileBloom {
112            bits: vec![0u64; target / 64],
113        }
114    }
115
116    #[inline]
117    fn m_bits(&self) -> usize {
118        self.bits.len() * 64
119    }
120
121    /// Double hashing: `p_i = h1 + i·h2 (mod m)` with `m` a power of two.
122    #[inline]
123    fn probes(&self, trigram: u32) -> impl Iterator<Item = usize> + '_ {
124        let m = self.m_bits();
125        let mask = m - 1; // m is a power of two
126        let h = mix64(u64::from(trigram));
127        let h1 = (h & 0xFFFF_FFFF) as usize;
128        let h2 = ((h >> 32) as usize) | 1; // odd step → full-period probing
129        (0..BLOOM_K).map(move |i| h1.wrapping_add(i.wrapping_mul(h2)) & mask)
130    }
131
132    fn insert(&mut self, trigram: u32) {
133        for p in self.probes(trigram).collect::<Vec<_>>() {
134            self.bits[p / 64] |= 1u64 << (p % 64);
135        }
136    }
137
138    fn maybe_contains(&self, trigram: u32) -> bool {
139        self.probes(trigram)
140            .all(|p| self.bits[p / 64] & (1u64 << (p % 64)) != 0)
141    }
142}
143
144/// RAM-resident trigram index over one project root.
145pub struct SearchIndex {
146    files: Vec<PathBuf>,
147    /// Candidate-narrowing structure (exact postings or compact per-file Bloom).
148    narrowing: Narrowing,
149    respect_gitignore: bool,
150    allow_secret_paths: bool,
151    /// Signature of the on-disk corpus this index was built from — the freshness
152    /// truth checked on every [`get_fresh`] (see [`corpus_signature`]).
153    signature: u64,
154}
155
156impl SearchIndex {
157    /// Build the index by walking `root` with the exact same config and filters
158    /// as `ctx_search`, so the searchable file universe is identical.
159    pub fn build(root: &str, respect_gitignore: bool, allow_secret_paths: bool) -> Option<Self> {
160        let mut files: Vec<PathBuf> = Vec::new();
161        // Per-file sorted, deduped trigrams. Same memory as the posting lists
162        // would be, but grouped by file so we can materialise *either* tier
163        // afterwards without a second pass over the corpus.
164        let mut per_file_trigrams: Vec<Vec<u32>> = Vec::new();
165        let mut total_entries: usize = 0;
166        let mut scratch: HashSet<u32> = HashSet::new();
167        // Corpus-signature accumulators. The running sum is order-independent
168        // (commutative `wrapping_add`) and the file count is folded in at the end
169        // so a change that happens to cancel under addition is still detected.
170        // Folded over the *eligible-by-stat* universe — before the read below —
171        // so the stat-only re-walk in [`corpus_signature`] reproduces it exactly,
172        // including files that turn out to be non-UTF-8 (counted, never indexed).
173        let mut sig_sum: u64 = 0;
174        let mut file_count: usize = 0;
175        let mut aborted = false;
176
177        walk_index_corpus(
178            root,
179            respect_gitignore,
180            allow_secret_paths,
181            None,
182            |path, state| {
183                sig_sum = sig_sum.wrapping_add(file_sig(path, state));
184                file_count += 1;
185
186                // Read the corpus exactly once (issue #148): reuse a fresh cached
187                // copy if a prior `ctx_search`/build already read this file, else
188                // read it now and publish it so the upcoming `ctx_search` verify
189                // pass is an in-memory hit instead of a second disk read. Mirrors
190                // ctx_search: a non-UTF-8 file is never searchable, so it is skipped
191                // for trigrams (but already folded into the signature above).
192                let content: std::sync::Arc<str> = if let Some(cached) =
193                    state.and_then(|s| crate::core::content_cache::get(path, s))
194                {
195                    cached
196                } else {
197                    let Ok(text) = std::fs::read_to_string(path) else {
198                        return true;
199                    };
200                    let arc: std::sync::Arc<str> = std::sync::Arc::from(text);
201                    if let Some(s) = state {
202                        crate::core::content_cache::insert(path, s, std::sync::Arc::clone(&arc));
203                    }
204                    arc
205                };
206
207                if files.len() >= MAX_FILES {
208                    aborted = true; // too large even for the Bloom tier — use the walk
209                    return false;
210                }
211
212                scratch.clear();
213                let bytes = content.as_bytes();
214                if bytes.len() >= 3 {
215                    for w in bytes.windows(3) {
216                        if is_word_byte(w[0]) && is_word_byte(w[1]) && is_word_byte(w[2]) {
217                            scratch.insert(pack(w[0], w[1], w[2]));
218                        }
219                    }
220                }
221                total_entries += scratch.len();
222                if total_entries > MAX_TOTAL_ENTRIES {
223                    aborted = true; // memory guard — fall back to walk
224                    return false;
225                }
226                let mut tris: Vec<u32> = scratch.iter().copied().collect();
227                tris.sort_unstable();
228                files.push(path.to_path_buf());
229                per_file_trigrams.push(tris);
230                true
231            },
232        )?;
233
234        if aborted {
235            return None;
236        }
237
238        let narrowing = build_narrowing(&per_file_trigrams, total_entries);
239
240        Some(Self {
241            files,
242            narrowing,
243            respect_gitignore,
244            allow_secret_paths,
245            signature: finalize_sig(sig_sum, file_count),
246        })
247    }
248
249    fn config_matches(&self, respect_gitignore: bool, allow_secret_paths: bool) -> bool {
250        self.respect_gitignore == respect_gitignore && self.allow_secret_paths == allow_secret_paths
251    }
252
253    /// Candidate files for `pattern`, filtered by the `include` glob (matched
254    /// against each file's path relative to `root`). `None` means "no safe
255    /// narrowing possible" — the caller should scan the full file list.
256    ///
257    /// Narrowing is applied only for pure `[A-Za-z0-9_]` literals of length ≥ 3.
258    /// For such a literal every match contains it on a single line, hence the
259    /// file contains all of its consecutive trigrams: intersecting their
260    /// posting lists yields a *superset* of matching files (zero false
261    /// negatives), which the caller then regex-verifies.
262    pub fn candidate_paths(
263        &self,
264        pattern: &str,
265        includes: &[Pattern],
266        root: &Path,
267    ) -> CandidateSet {
268        if let Some(ids) = self.literal_candidates(pattern) {
269            let paths = ids
270                .into_iter()
271                .map(|id| self.files[id as usize].clone())
272                .filter(|p| glob_matches(p, includes, root))
273                .collect();
274            CandidateSet::Narrowed(paths)
275        } else {
276            let paths = self
277                .files
278                .iter()
279                .filter(|p| glob_matches(p, includes, root))
280                .cloned()
281                .collect();
282            CandidateSet::FullList(paths)
283        }
284    }
285
286    /// Returns candidate file ids for a pure-literal query, or `None` if the
287    /// query is not a trigram-narrowable pure `[A-Za-z0-9_]` literal. Both tiers
288    /// return a *superset* of true matches (zero false negatives).
289    fn literal_candidates(&self, pattern: &str) -> Option<Vec<u32>> {
290        let bytes = pattern.as_bytes();
291        if bytes.len() < 3 || !bytes.iter().all(|&b| is_word_byte(b)) {
292            return None;
293        }
294        // Distinct trigrams of the literal.
295        let mut tris: Vec<u32> = bytes.windows(3).map(|w| pack(w[0], w[1], w[2])).collect();
296        tris.sort_unstable();
297        tris.dedup();
298
299        match &self.narrowing {
300            Narrowing::Postings(trigrams) => Some(Self::postings_intersect(trigrams, &tris)),
301            Narrowing::Blooms(blooms) => Some(Self::bloom_scan(blooms, &tris)),
302        }
303    }
304
305    /// Exact-tier: intersect the posting lists of every required trigram
306    /// (smallest first for a cheap intersection).
307    fn postings_intersect(trigrams: &HashMap<u32, Vec<u32>>, tris: &[u32]) -> Vec<u32> {
308        let mut lists: Vec<&Vec<u32>> = Vec::with_capacity(tris.len());
309        for &tri in tris {
310            match trigrams.get(&tri) {
311                // A required trigram is absent → provably no match anywhere.
312                None => return Vec::new(),
313                Some(list) => lists.push(list),
314            }
315        }
316        lists.sort_by_key(|l| l.len());
317
318        let mut acc: Vec<u32> = lists[0].clone();
319        for list in &lists[1..] {
320            acc = intersect_sorted(&acc, list);
321            if acc.is_empty() {
322                break;
323            }
324        }
325        acc
326    }
327
328    /// Bloom-tier: a file is a candidate iff its Bloom filter may contain every
329    /// required trigram. No false negatives (an unset probe bit ⇒ the trigram is
330    /// provably absent), so the result is still a superset of true matches.
331    fn bloom_scan(blooms: &[FileBloom], tris: &[u32]) -> Vec<u32> {
332        let mut out = Vec::new();
333        for (fid, bloom) in blooms.iter().enumerate() {
334            if tris.iter().all(|&t| bloom.maybe_contains(t)) {
335                out.push(fid as u32);
336            }
337        }
338        out
339    }
340}
341
342/// Materialise the appropriate narrowing tier for a freshly walked corpus.
343fn build_narrowing(per_file: &[Vec<u32>], total_entries: usize) -> Narrowing {
344    if total_entries <= MAX_POSTING_ENTRIES {
345        let mut trigrams: HashMap<u32, Vec<u32>> = HashMap::new();
346        for (fid, tris) in per_file.iter().enumerate() {
347            for &t in tris {
348                // file ids are appended in ascending order ⇒ lists stay sorted.
349                trigrams.entry(t).or_default().push(fid as u32);
350            }
351        }
352        Narrowing::Postings(trigrams)
353    } else {
354        let blooms = per_file
355            .iter()
356            .map(|tris| {
357                let mut b = FileBloom::with_capacity(tris.len());
358                for &t in tris {
359                    b.insert(t);
360                }
361                b
362            })
363            .collect();
364        Narrowing::Blooms(blooms)
365    }
366}
367
368/// Result of [`SearchIndex::candidate_paths`].
369pub enum CandidateSet {
370    /// Trigram-narrowed candidate files (a superset of real matches).
371    Narrowed(Vec<PathBuf>),
372    /// No safe narrowing — the full cached file list (still skips the walk).
373    FullList(Vec<PathBuf>),
374}
375
376impl CandidateSet {
377    pub fn into_paths(self) -> Vec<PathBuf> {
378        match self {
379            CandidateSet::Narrowed(p) | CandidateSet::FullList(p) => p,
380        }
381    }
382}
383
384/// True when `path` matches *any* of the `includes` globs (relative to `root`),
385/// or when there is no filter (`includes` empty).
386fn glob_matches(path: &Path, includes: &[Pattern], root: &Path) -> bool {
387    if includes.is_empty() {
388        return true;
389    }
390    let rel = path.strip_prefix(root).unwrap_or(path);
391    let rel_str = rel.to_string_lossy();
392    includes.iter().any(|p| p.matches(&rel_str))
393}
394
395/// Secret-like files under `root` that match `includes`, for boundary-skip
396/// reporting on the trigram-index fast path (#1481). The include filter runs
397/// before the secret-like check so the note reflects only files the query
398/// would have searched.
399pub fn boundary_skipped_files(
400    root: &str,
401    respect_gitignore: bool,
402    includes: &[Pattern],
403) -> Vec<(String, &'static str)> {
404    let root_path = Path::new(root);
405    if !root_path.exists() {
406        return Vec::new();
407    }
408    if !crate::core::graph_index::is_safe_scan_root_public(root) {
409        return Vec::new();
410    }
411
412    let walker = WalkBuilder::new(root_path)
413        .hidden(false)
414        .max_depth(Some(crate::tools::ctx_search::MAX_WALK_DEPTH))
415        .git_ignore(respect_gitignore)
416        .git_global(respect_gitignore)
417        .git_exclude(respect_gitignore)
418        .require_git(false)
419        .filter_entry(move |e| {
420            if respect_gitignore {
421                crate::core::walk_filter::keep_entry(e)
422            } else {
423                crate::core::cloud_files::keep_entry(e)
424            }
425        })
426        .build();
427
428    let mut skipped = Vec::new();
429    for entry in walker.filter_map(std::result::Result::ok) {
430        if entry.file_type().is_none_or(|ft| ft.is_dir()) {
431            continue;
432        }
433        if entry.file_type().is_some_and(|ft| ft.is_symlink()) {
434            continue;
435        }
436        let path = entry.path();
437        if is_binary_ext(path) || is_generated_file(path) {
438            continue;
439        }
440        if !includes.is_empty() && !glob_matches(path, includes, root_path) {
441            continue;
442        }
443        if let Some(reason) = crate::core::io_boundary::is_secret_like(path) {
444            let rel = path.strip_prefix(root_path).unwrap_or(path);
445            skipped.push((rel.to_string_lossy().into_owned(), reason));
446        }
447    }
448    skipped.sort_unstable();
449    skipped
450}
451
452/// Intersection of two ascending, deduped `u32` slices.
453fn intersect_sorted(a: &[u32], b: &[u32]) -> Vec<u32> {
454    let mut out = Vec::new();
455    let (mut i, mut j) = (0, 0);
456    while i < a.len() && j < b.len() {
457        match a[i].cmp(&b[j]) {
458            std::cmp::Ordering::Less => i += 1,
459            std::cmp::Ordering::Greater => j += 1,
460            std::cmp::Ordering::Equal => {
461                out.push(a[i]);
462                i += 1;
463                j += 1;
464            }
465        }
466    }
467    out
468}
469
470// ---------------------------------------------------------------------------
471// Corpus freshness: the build and its freshness check share one traversal so
472// the signature is computed over an identical file universe (parity is what
473// makes the equality check trustworthy).
474// ---------------------------------------------------------------------------
475
476/// Walk `root` with the *exact* `ctx_search` file universe — same gitignore
477/// semantics, depth limit, and binary/generated/secret/size/regular-file guards
478/// — invoking `visit(path, state)` for every eligible regular file with its
479/// `(mtime, size)` identity (`None` only when the platform cannot report mtime).
480/// `visit` returns `false` to stop early. Returns `None` for a missing or unsafe
481/// scan root (HOME, fs root, …), the same guard that makes the caller fall back
482/// to a direct walk. This traversal reads nothing: it is the shared spine of
483/// both [`SearchIndex::build`] and [`corpus_signature`].
484fn walk_index_corpus<F>(
485    root: &str,
486    respect_gitignore: bool,
487    allow_secret_paths: bool,
488    includes: Option<&[Pattern]>,
489    mut visit: F,
490) -> Option<()>
491where
492    F: FnMut(&Path, Option<crate::core::content_cache::FileState>) -> bool,
493{
494    let root_path = Path::new(root);
495    if !root_path.exists() {
496        return None;
497    }
498    // Never auto-index a broad/unsafe root (HOME, filesystem root, a dir with
499    // dozens of unrelated subtrees). Mirrors the graph/BM25 guard and stops a
500    // walk of the whole home directory — which on Windows would hydrate OneDrive
501    // placeholders (#363).
502    if !crate::core::graph_index::is_safe_scan_root_public(root) {
503        return None;
504    }
505
506    let walker = WalkBuilder::new(root_path)
507        .hidden(true)
508        .max_depth(Some(MAX_WALK_DEPTH))
509        .git_ignore(respect_gitignore)
510        .git_global(respect_gitignore)
511        .git_exclude(respect_gitignore)
512        .require_git(false)
513        .filter_entry(crate::core::walk_filter::keep_entry)
514        .build();
515
516    for entry in walker.filter_map(std::result::Result::ok) {
517        if entry.file_type().is_none_or(|ft| ft.is_dir()) {
518            continue;
519        }
520        if entry.file_type().is_some_and(|ft| ft.is_symlink()) {
521            continue;
522        }
523        let path = entry.path();
524        if is_binary_ext(path) || is_generated_file(path) {
525            continue;
526        }
527        if let Some(includes) = includes {
528            if !includes.is_empty() && !glob_matches(path, includes, root_path) {
529                continue;
530            }
531        }
532        if !allow_secret_paths && crate::core::io_boundary::is_secret_like(path).is_some() {
533            continue;
534        }
535        // `metadata` (stat) never opens the file, so it cannot block on a
536        // FIFO/socket/device node (#336); those are filtered out here.
537        let state = match std::fs::metadata(path) {
538            Ok(meta) if !meta.file_type().is_file() => continue,
539            Ok(meta) if meta.len() > MAX_FILE_SIZE => continue,
540            Ok(meta) => crate::core::content_cache::FileState::from_metadata(&meta),
541            Err(_) => continue,
542        };
543        if !visit(path, state) {
544            break;
545        }
546    }
547    Some(())
548}
549
550/// Stable per-file contribution to the corpus signature: folds the path with its
551/// `(mtime, size)` identity. Order-independent (callers combine with
552/// `wrapping_add`), so traversal order never affects the result. A file with no
553/// resolvable mtime contributes its path only — add/rename/delete are still
554/// detected, while an in-place edit on such an exotic filesystem is the same
555/// blind spot the `(mtime, size)` content cache already documents.
556fn file_sig(path: &Path, state: Option<crate::core::content_cache::FileState>) -> u64 {
557    let mut h: u64 = 0xcbf2_9ce4_8422_2325; // FNV-1a offset basis
558    for &b in path.as_os_str().as_encoded_bytes() {
559        h ^= u64::from(b);
560        h = h.wrapping_mul(0x0000_0100_0000_01b3); // FNV-1a prime
561    }
562    if let Some(st) = state {
563        h ^= mix64(st.mtime_ms).rotate_left(1);
564        h ^= mix64(st.size_bytes).rotate_left(33);
565    }
566    mix64(h)
567}
568
569/// Fold the order-independent per-file sum together with the file count into the
570/// final signature, so adding and removing files whose hashes cancel under
571/// addition still changes the result.
572fn finalize_sig(sum: u64, count: usize) -> u64 {
573    sum ^ mix64(count as u64).rotate_left(32)
574}
575
576/// Cheap, stat-only signature of the *current* on-disk corpus for `root`.
577/// Compared against [`SearchIndex::signature`] in [`get_fresh`] to detect any
578/// change — content edits (including via tools lean-ctx never observes),
579/// additions, renames and deletions — so a stale candidate set can never
580/// silently drop a real match. `None` mirrors a non-indexable root (the caller
581/// then walks directly).
582fn corpus_signature(root: &str, respect_gitignore: bool, allow_secret_paths: bool) -> Option<u64> {
583    let mut sum: u64 = 0;
584    let mut count: usize = 0;
585    walk_index_corpus(
586        root,
587        respect_gitignore,
588        allow_secret_paths,
589        None,
590        |path, state| {
591            sum = sum.wrapping_add(file_sig(path, state));
592            count += 1;
593            true
594        },
595    )?;
596    Some(finalize_sig(sum, count))
597}
598
599// ---------------------------------------------------------------------------
600// Resident cache (one index per project root) with background (re)build.
601// ---------------------------------------------------------------------------
602
603struct CacheEntry {
604    index: Option<Arc<SearchIndex>>,
605    building: bool,
606    /// When this root's resident index was last confirmed current against disk.
607    /// Gates the optional coalesce window in [`get_fresh`]; `None` forces a fresh
608    /// verification on the next lookup.
609    last_verified: Option<Instant>,
610}
611
612impl CacheEntry {
613    fn empty() -> Self {
614        Self {
615            index: None,
616            building: false,
617            last_verified: None,
618        }
619    }
620}
621
622static CACHE: OnceLock<Mutex<HashMap<String, CacheEntry>>> = OnceLock::new();
623
624fn cache() -> &'static Mutex<HashMap<String, CacheEntry>> {
625    CACHE.get_or_init(|| Mutex::new(HashMap::new()))
626}
627
628/// Escape hatch: `LEAN_CTX_DISABLE_SEARCH_INDEX=1` forces the walk path
629/// everywhere (debugging / A-B measurement / opt-out).
630fn index_disabled() -> bool {
631    std::env::var("LEAN_CTX_DISABLE_SEARCH_INDEX")
632        .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"))
633}
634
635/// Optional coalescing window for the freshness check. Default `0` (disabled):
636/// every [`get_fresh`] re-verifies the corpus signature against disk, so a fresh
637/// edit is never missed. On very large indexed trees, set
638/// `LEAN_CTX_SEARCH_INDEX_COALESCE_MS` to trade a bounded staleness window for
639/// fewer stat-walks under bursty search load.
640fn coalesce_window() -> Option<Duration> {
641    let ms = std::env::var("LEAN_CTX_SEARCH_INDEX_COALESCE_MS")
642        .ok()
643        .and_then(|v| v.trim().parse::<u64>().ok())
644        .unwrap_or(0);
645    (ms > 0).then(|| Duration::from_millis(ms))
646}
647
648/// Returns a fresh resident index for `root` if one is available for the given
649/// config, otherwise spawns a background (re)build and returns `None` so the
650/// caller uses the walk fallback for this call.
651pub fn get_fresh(
652    root: &str,
653    respect_gitignore: bool,
654    allow_secret_paths: bool,
655) -> Option<Arc<SearchIndex>> {
656    // Privileged "ignore gitignore" scans are rare and bypass the index.
657    if !respect_gitignore || index_disabled() {
658        return None;
659    }
660
661    // Phase 1 (locked, O(1)): grab the resident index for this config, if any,
662    // together with when it was last verified against disk.
663    let (candidate, last_verified) = {
664        let map = cache()
665            .lock()
666            .unwrap_or_else(std::sync::PoisonError::into_inner);
667        match map.get(root) {
668            Some(entry) => match &entry.index {
669                Some(idx) if idx.config_matches(respect_gitignore, allow_secret_paths) => {
670                    (Some(Arc::clone(idx)), entry.last_verified)
671                }
672                _ => (None, None),
673            },
674            None => (None, None),
675        }
676    };
677
678    let Some(idx) = candidate else {
679        // No usable index yet → build in the background, walk this call.
680        request_build(root, respect_gitignore, allow_secret_paths);
681        return None;
682    };
683
684    // Coalesce (opt-in, default off): inside the window trust the recent
685    // verification and skip the stat-walk — keeps bursty search load O(1).
686    if let Some(window) = coalesce_window()
687        && last_verified.is_some_and(|t| t.elapsed() < window)
688    {
689        return Some(idx);
690    }
691
692    // Phase 2 (unlocked): verify the live corpus signature. Deliberately held
693    // *outside* the cache mutex so a multi-millisecond stat-walk never serializes
694    // other roots or concurrent searches.
695    match corpus_signature(root, respect_gitignore, allow_secret_paths) {
696        Some(sig) if sig == idx.signature => {
697            mark_verified(root);
698            Some(idx)
699        }
700        _ => {
701            // Corpus changed (or root no longer indexable): walk accurately now
702            // and rebuild the index in the background for the next call.
703            request_build(root, respect_gitignore, allow_secret_paths);
704            None
705        }
706    }
707}
708
709/// Drop every resident trigram index (#685 eviction hook). In-flight builds
710/// keep their `building` flag (the entry is reset, not the build thread), so
711/// a running build still installs its result; subsequent searches fall back
712/// to the walk path until the next `ensure_background` rebuilds. Correctness
713/// is unaffected — the resident index is purely an accelerator.
714pub fn clear_resident() {
715    let mut map = cache()
716        .lock()
717        .unwrap_or_else(std::sync::PoisonError::into_inner);
718    for entry in map.values_mut() {
719        entry.index = None;
720        entry.last_verified = None;
721    }
722}
723
724/// Record that `root`'s resident index was just confirmed current, extending its
725/// coalesce window.
726fn mark_verified(root: &str) {
727    let mut map = cache()
728        .lock()
729        .unwrap_or_else(std::sync::PoisonError::into_inner);
730    if let Some(entry) = map.get_mut(root) {
731        entry.last_verified = Some(Instant::now());
732    }
733}
734
735/// Spawn a background (re)build for `root` unless one is already in flight.
736fn request_build(root: &str, respect_gitignore: bool, allow_secret_paths: bool) {
737    let needs_build = {
738        let mut map = cache()
739            .lock()
740            .unwrap_or_else(std::sync::PoisonError::into_inner);
741        let entry = map
742            .entry(root.to_string())
743            .or_insert_with(CacheEntry::empty);
744        if entry.building {
745            false
746        } else {
747            entry.building = true;
748            true
749        }
750    };
751    if needs_build {
752        spawn_build(root.to_string(), respect_gitignore, allow_secret_paths);
753    }
754}
755
756/// Ensure a resident index for `root` is built (or building) in the background.
757/// Safe to call repeatedly; deduped via the per-root `building` flag.
758pub fn ensure_background(root: &str, respect_gitignore: bool, allow_secret_paths: bool) {
759    if !respect_gitignore || index_disabled() {
760        return;
761    }
762    // Prewarm only when there is no usable index yet — staleness of an existing
763    // index is corrected on demand by `get_fresh`'s signature gate, so there is
764    // nothing to proactively refresh here.
765    let has_index = {
766        let map = cache()
767            .lock()
768            .unwrap_or_else(std::sync::PoisonError::into_inner);
769        map.get(root).is_some_and(|entry| {
770            entry
771                .index
772                .as_ref()
773                .is_some_and(|idx| idx.config_matches(respect_gitignore, allow_secret_paths))
774        })
775    };
776    if !has_index {
777        request_build(root, respect_gitignore, allow_secret_paths);
778    }
779}
780
781/// Build the index synchronously and install it in the resident cache.
782/// Returns `true` on success. Useful for CLI prewarm and benchmarks that need a
783/// guaranteed-warm index. Respects the disable env var.
784pub fn warm_blocking(root: &str, respect_gitignore: bool, allow_secret_paths: bool) -> bool {
785    if !respect_gitignore || index_disabled() {
786        return false;
787    }
788    let Some(idx) = SearchIndex::build(root, respect_gitignore, allow_secret_paths) else {
789        return false;
790    };
791    let mut map = cache()
792        .lock()
793        .unwrap_or_else(std::sync::PoisonError::into_inner);
794    map.insert(
795        root.to_string(),
796        CacheEntry {
797            index: Some(Arc::new(idx)),
798            building: false,
799            last_verified: Some(Instant::now()),
800        },
801    );
802    true
803}
804
805/// Per-repo lock name serializing the resident search-index build across
806/// processes, mirroring the `graph-idx` / `bm25-idx` locks in
807/// [`crate::core::index_orchestrator`]. Distinct `search-` prefix so the three
808/// indexers never serialize against one another.
809fn search_index_lock_name(root: &str) -> String {
810    format!(
811        "search-idx-{}",
812        &crate::core::index_namespace::namespace_hash(Path::new(root))[..8]
813    )
814}
815
816/// Outcome of a guarded background build: did this process do the walk, or did
817/// it yield to another process already building the same root?
818#[derive(Debug, Clone, Copy, PartialEq, Eq)]
819enum BuildOutcome {
820    Built,
821    Deferred,
822}
823
824/// Build the resident index under a cross-process herd guard (#460).
825///
826/// The trigram index is RAM-resident (not shareable on disk), so on lock
827/// contention we *defer* the proactive pre-warm instead of running a second
828/// simultaneous file walk: a boot wave of N sessions on one repo then triggers
829/// ~1 walk at a time, not N. Deferring is safe — `ctx_search` still works via
830/// its walk fallback, and the per-process `building` flag is cleared so the next
831/// `get_fresh` / `ensure_background` nudge retries once the holder releases. The
832/// short 200 ms wait keeps the common single-session path latency-free.
833fn build_guarded(root: &str, respect_gitignore: bool, allow_secret_paths: bool) -> BuildOutcome {
834    let lock = crate::core::startup_guard::try_acquire_lock(
835        &search_index_lock_name(root),
836        Duration::from_millis(200),
837        Duration::from_mins(3),
838    );
839    if lock.is_none() {
840        // Another process owns the build. Clear the in-flight flag so a later
841        // nudge retries rather than leaving `building` stuck true forever.
842        let mut map = cache()
843            .lock()
844            .unwrap_or_else(std::sync::PoisonError::into_inner);
845        if let Some(entry) = map.get_mut(root) {
846            entry.building = false;
847        }
848        return BuildOutcome::Deferred;
849    }
850
851    let built = std::panic::catch_unwind(|| {
852        SearchIndex::build(root, respect_gitignore, allow_secret_paths)
853    })
854    .ok()
855    .flatten();
856
857    let mut map = cache()
858        .lock()
859        .unwrap_or_else(std::sync::PoisonError::into_inner);
860    if let Some(entry) = map.get_mut(root) {
861        entry.building = false;
862        if let Some(idx) = built {
863            entry.index = Some(Arc::new(idx));
864            // A just-built index is current with the disk it walked.
865            entry.last_verified = Some(Instant::now());
866        }
867    }
868    // `lock` is held until here so the cross-process guard spans the whole walk.
869    drop(lock);
870    BuildOutcome::Built
871}
872
873fn spawn_build(root: String, respect_gitignore: bool, allow_secret_paths: bool) {
874    std::thread::spawn(move || {
875        let _ = build_guarded(&root, respect_gitignore, allow_secret_paths);
876    });
877}
878
879#[cfg(test)]
880mod tests {
881    use super::*;
882
883    fn corpus() -> tempfile::TempDir {
884        let dir = tempfile::tempdir().unwrap();
885        std::fs::write(dir.path().join("a.rs"), "fn handler() {}\nlet x = 1;\n").unwrap();
886        std::fs::write(dir.path().join("b.rs"), "fn other() {}\n// nothing here\n").unwrap();
887        std::fs::write(dir.path().join("c.txt"), "handler appears in text too\n").unwrap();
888        dir
889    }
890
891    #[test]
892    fn build_refuses_to_index_home_directory() {
893        // Auto-indexing HOME would walk the entire home tree and, on Windows,
894        // hydrate every OneDrive placeholder (#363). The build must bail out.
895        if let Some(home) = dirs::home_dir() {
896            assert!(
897                SearchIndex::build(&home.to_string_lossy(), true, false).is_none(),
898                "search index must never auto-build over the home directory"
899            );
900        }
901    }
902
903    #[test]
904    fn narrows_to_files_containing_literal() {
905        let dir = corpus();
906        let idx = SearchIndex::build(dir.path().to_str().unwrap(), true, false).unwrap();
907        let cands = idx.candidate_paths("handler", &[], dir.path());
908        let paths = cands.into_paths();
909        // a.rs and c.txt contain "handler"; b.rs must be excluded.
910        assert!(paths.iter().any(|p| p.ends_with("a.rs")));
911        assert!(paths.iter().any(|p| p.ends_with("c.txt")));
912        assert!(!paths.iter().any(|p| p.ends_with("b.rs")));
913    }
914
915    #[test]
916    fn absent_trigram_yields_empty_candidates() {
917        let dir = corpus();
918        let idx = SearchIndex::build(dir.path().to_str().unwrap(), true, false).unwrap();
919        match idx.candidate_paths("zzzqqq", &[], dir.path()) {
920            CandidateSet::Narrowed(p) => assert!(p.is_empty()),
921            CandidateSet::FullList(_) => panic!("pure literal should narrow"),
922        }
923    }
924
925    #[test]
926    fn ext_filter_restricts_candidates() {
927        let dir = corpus();
928        let idx = SearchIndex::build(dir.path().to_str().unwrap(), true, false).unwrap();
929        let paths = idx
930            .candidate_paths(
931                "handler",
932                &[glob::Pattern::new("*.rs").unwrap()],
933                dir.path(),
934            )
935            .into_paths();
936        assert!(paths.iter().all(|p| p.extension().unwrap() == "rs"));
937        assert!(paths.iter().any(|p| p.ends_with("a.rs")));
938    }
939
940    #[test]
941    #[cfg(unix)]
942    fn build_skips_named_pipe_without_hanging() {
943        use std::sync::mpsc;
944        use std::time::Duration;
945        // #336: the background index build read every file, so a FIFO in the
946        // corpus blocked the build thread forever. It must be skipped while the
947        // regular files are still indexed, and the build must return.
948        let dir = corpus();
949        let fifo = dir.path().join("pipe.fifo");
950        let c = std::ffi::CString::new(fifo.to_string_lossy().as_bytes()).unwrap();
951        assert_eq!(
952            // SAFETY: `c` is a live CString providing a valid NUL-terminated
953            // path pointer for the duration of the call.
954            unsafe { libc::mkfifo(c.as_ptr(), 0o644) },
955            0,
956            "mkfifo failed"
957        );
958
959        let root = dir.path().to_str().unwrap().to_string();
960        let (tx, rx) = mpsc::channel();
961        std::thread::spawn(move || {
962            let built = SearchIndex::build(&root, true, false);
963            let _ = tx.send(built.map(|idx| {
964                idx.candidate_paths("handler", &[], std::path::Path::new(&root))
965                    .into_paths()
966            }));
967        });
968        let paths = rx
969            .recv_timeout(Duration::from_secs(5))
970            .expect("SearchIndex::build hung on a FIFO (#336 regression)")
971            .expect("index should build");
972        assert!(paths.iter().any(|p| p.ends_with("a.rs")));
973        assert!(!paths.iter().any(|p| p.ends_with("pipe.fifo")));
974    }
975
976    #[test]
977    fn regex_query_falls_back_to_full_list() {
978        let dir = corpus();
979        let idx = SearchIndex::build(dir.path().to_str().unwrap(), true, false).unwrap();
980        match idx.candidate_paths("fn .*\\(\\)", &[], dir.path()) {
981            CandidateSet::FullList(p) => assert!(!p.is_empty()),
982            CandidateSet::Narrowed(_) => panic!("metachar query must not narrow"),
983        }
984    }
985
986    #[test]
987    fn short_query_falls_back_to_full_list() {
988        let dir = corpus();
989        let idx = SearchIndex::build(dir.path().to_str().unwrap(), true, false).unwrap();
990        assert!(matches!(
991            idx.candidate_paths("fn", &[], dir.path()),
992            CandidateSet::FullList(_)
993        ));
994    }
995
996    /// The core correctness claim: trigram narrowing never drops a real match.
997    /// For each literal query, the set of `file:line` hits found by scanning only
998    /// the narrowed candidates must equal the set found by scanning every file.
999    #[test]
1000    fn narrowing_has_identical_recall_to_full_scan() {
1001        use regex::Regex;
1002        use std::collections::BTreeSet;
1003
1004        let dir = tempfile::tempdir().unwrap();
1005        // A spread of files; some contain the query tokens, most do not.
1006        let samples = [
1007            (
1008                "auth/login.rs",
1009                "fn authenticate(user) {}\nlet token = mint();\n",
1010            ),
1011            (
1012                "auth/session.rs",
1013                "struct Session;\n// authenticate again here\n",
1014            ),
1015            ("db/pool.rs", "fn connect() {}\nlet retries = 3;\n"),
1016            (
1017                "ui/button.tsx",
1018                "export const Button = () => authenticate;\n",
1019            ),
1020            ("readme.md", "This project uses authenticate flows.\n"),
1021            ("unrelated.rs", "fn helper() { let v = 1; }\n"),
1022        ];
1023        for (rel, content) in samples {
1024            let p = dir.path().join(rel);
1025            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
1026            std::fs::write(p, content).unwrap();
1027        }
1028        let idx = SearchIndex::build(dir.path().to_str().unwrap(), true, false).unwrap();
1029
1030        let full_scan = |pat: &str| -> BTreeSet<String> {
1031            let re = Regex::new(pat).unwrap();
1032            let mut hits = BTreeSet::new();
1033            for (rel, content) in samples {
1034                for (i, line) in content.lines().enumerate() {
1035                    if re.is_match(line) {
1036                        hits.insert(format!("{rel}:{}", i + 1));
1037                    }
1038                }
1039            }
1040            hits
1041        };
1042
1043        for query in ["authenticate", "Session", "retries", "token"] {
1044            let re = Regex::new(query).unwrap();
1045            let candidates = idx.candidate_paths(query, &[], dir.path()).into_paths();
1046            let mut narrowed = BTreeSet::new();
1047            for path in &candidates {
1048                let content = std::fs::read_to_string(path).unwrap();
1049                let rel = path.strip_prefix(dir.path()).unwrap().to_string_lossy();
1050                for (i, line) in content.lines().enumerate() {
1051                    if re.is_match(line) {
1052                        narrowed.insert(format!("{}:{}", rel.replace('\\', "/"), i + 1));
1053                    }
1054                }
1055            }
1056            assert_eq!(
1057                narrowed,
1058                full_scan(query),
1059                "recall mismatch for query {query:?}"
1060            );
1061        }
1062    }
1063
1064    #[test]
1065    fn intersect_sorted_basic() {
1066        assert_eq!(
1067            intersect_sorted(&[1, 2, 3, 5], &[2, 3, 4, 5]),
1068            vec![2, 3, 5]
1069        );
1070        assert_eq!(intersect_sorted(&[1, 2], &[3, 4]), Vec::<u32>::new());
1071    }
1072
1073    // ── Bloom tier ────────────────────────────────────────────────────────
1074
1075    fn trigrams_of(s: &str) -> Vec<u32> {
1076        let mut set = HashSet::new();
1077        let b = s.as_bytes();
1078        if b.len() >= 3 {
1079            for w in b.windows(3) {
1080                if is_word_byte(w[0]) && is_word_byte(w[1]) && is_word_byte(w[2]) {
1081                    set.insert(pack(w[0], w[1], w[2]));
1082                }
1083            }
1084        }
1085        let mut v: Vec<u32> = set.into_iter().collect();
1086        v.sort_unstable();
1087        v
1088    }
1089
1090    #[test]
1091    fn file_bloom_has_no_false_negatives() {
1092        let tris = trigrams_of("fn authenticate(user) { let token = mint(); }");
1093        let mut bloom = FileBloom::with_capacity(tris.len());
1094        for &t in &tris {
1095            bloom.insert(t);
1096        }
1097        // Every inserted trigram must be reported present (Bloom guarantee).
1098        assert!(tris.iter().all(|&t| bloom.maybe_contains(t)));
1099    }
1100
1101    /// Parity fuzz: the Bloom tier must return a *superset* of the exact posting
1102    /// tier for every query (zero false negatives). False positives are allowed
1103    /// (and verified away downstream), so we assert containment, not equality.
1104    #[test]
1105    fn bloom_tier_is_superset_of_postings_tier() {
1106        // Deterministic synthetic corpus (LCG → reproducible).
1107        let mut seed = 0x1234_5678_9abc_def0u64;
1108        let mut rng = || {
1109            seed = seed
1110                .wrapping_mul(6364136223846793005)
1111                .wrapping_add(1442695040888963407);
1112            (seed >> 33) as u32
1113        };
1114        let mut per_file: Vec<Vec<u32>> = Vec::new();
1115        for _ in 0..80 {
1116            let n = 50 + (rng() % 250) as usize;
1117            let mut s = HashSet::new();
1118            for _ in 0..n {
1119                s.insert(rng() & 0x00FF_FFFF);
1120            }
1121            let mut v: Vec<u32> = s.into_iter().collect();
1122            v.sort_unstable();
1123            per_file.push(v);
1124        }
1125        let total: usize = per_file.iter().map(Vec::len).sum();
1126
1127        let postings = build_narrowing(&per_file, total); // ≤ cap → postings
1128        let blooms = build_narrowing(&per_file, MAX_POSTING_ENTRIES + 1); // forced bloom
1129        let (Narrowing::Postings(pt), Narrowing::Blooms(bl)) = (&postings, &blooms) else {
1130            panic!("unexpected narrowing tiers");
1131        };
1132
1133        // Queries drawn from real file trigrams (these MUST be found by both),
1134        // plus a few that are unlikely to exist anywhere.
1135        for f in &per_file {
1136            if f.len() < 3 {
1137                continue;
1138            }
1139            let q = vec![f[0], f[f.len() / 2], f[f.len() - 1]];
1140            let exact = SearchIndex::postings_intersect(pt, &q);
1141            let bloom: HashSet<u32> = SearchIndex::bloom_scan(bl, &q).into_iter().collect();
1142            for id in exact {
1143                assert!(
1144                    bloom.contains(&id),
1145                    "Bloom tier dropped a true match (false negative) for {q:?}"
1146                );
1147            }
1148        }
1149    }
1150
1151    /// End-to-end: an index forced onto the Bloom tier must still surface every
1152    /// file that actually contains the literal (recall parity with a full scan).
1153    #[test]
1154    fn bloom_tier_end_to_end_recall() {
1155        let samples = [
1156            (
1157                "auth_login.rs",
1158                "fn authenticate(user) {}\nlet token = mint();\n",
1159            ),
1160            (
1161                "auth_session.rs",
1162                "struct Session;\n// authenticate again here\n",
1163            ),
1164            ("db_pool.rs", "fn connect() {}\nlet retries = 3;\n"),
1165            (
1166                "ui_button.tsx",
1167                "export const Button = () => authenticate;\n",
1168            ),
1169            ("readme.md", "This project uses authenticate flows.\n"),
1170            ("unrelated.rs", "fn helper() { let v = 1; }\n"),
1171        ];
1172        let files: Vec<PathBuf> = samples.iter().map(|(rel, _)| PathBuf::from(rel)).collect();
1173        let per_file: Vec<Vec<u32>> = samples.iter().map(|(_, c)| trigrams_of(c)).collect();
1174
1175        let idx = SearchIndex {
1176            files,
1177            narrowing: build_narrowing(&per_file, MAX_POSTING_ENTRIES + 1),
1178            respect_gitignore: true,
1179            allow_secret_paths: false,
1180            signature: 0, // freshness is not exercised by candidate_paths
1181        };
1182        assert!(
1183            matches!(idx.narrowing, Narrowing::Blooms(_)),
1184            "test must exercise the Bloom tier"
1185        );
1186
1187        for query in ["authenticate", "Session", "retries", "token"] {
1188            let cands: HashSet<String> = idx
1189                .candidate_paths(query, &[], std::path::Path::new(""))
1190                .into_paths()
1191                .iter()
1192                .map(|p| p.to_string_lossy().to_string())
1193                .collect();
1194            for (rel, content) in samples {
1195                if content.contains(query) {
1196                    assert!(
1197                        cands.contains(rel),
1198                        "Bloom tier dropped real match {rel} for query {query:?}"
1199                    );
1200                }
1201            }
1202        }
1203    }
1204
1205    /// A scoped override of `LEAN_CTX_DATA_DIR`, restored on drop, so the
1206    /// cross-process lock files land in an isolated temp dir during tests.
1207    struct DataDirGuard {
1208        prev: Option<String>,
1209    }
1210    impl DataDirGuard {
1211        fn set(path: &std::path::Path) -> Self {
1212            let prev = std::env::var("LEAN_CTX_DATA_DIR").ok();
1213            crate::test_env::set_var("LEAN_CTX_DATA_DIR", path);
1214            Self { prev }
1215        }
1216    }
1217    impl Drop for DataDirGuard {
1218        fn drop(&mut self) {
1219            match self.prev.as_deref() {
1220                Some(v) => crate::test_env::set_var("LEAN_CTX_DATA_DIR", v),
1221                None => crate::test_env::remove_var("LEAN_CTX_DATA_DIR"),
1222            }
1223        }
1224    }
1225
1226    #[test]
1227    fn search_index_lock_name_is_per_repo_and_distinct() {
1228        let a = search_index_lock_name("/tmp/repo-a");
1229        let b = search_index_lock_name("/tmp/repo-b");
1230        assert!(a.starts_with("search-idx-"), "unexpected lock name: {a}");
1231        assert_ne!(a, b, "lock name must be per-repo");
1232        assert_eq!(a, search_index_lock_name("/tmp/repo-a"), "stable per repo");
1233        // Must not collide with the graph/bm25 locks for the same repo, or the
1234        // three indexers would needlessly serialize against one another.
1235        let h = &crate::core::index_namespace::namespace_hash(Path::new("/tmp/repo-a"))[..8];
1236        assert_ne!(
1237            a,
1238            format!("graph-idx-{h}"),
1239            "must not collide with graph lock"
1240        );
1241        assert_ne!(
1242            a,
1243            format!("bm25-idx-{h}"),
1244            "must not collide with bm25 lock"
1245        );
1246    }
1247
1248    #[test]
1249    fn build_guarded_builds_when_uncontended() {
1250        let _env = crate::core::data_dir::test_env_lock();
1251        let data = tempfile::tempdir().unwrap();
1252        let _guard = DataDirGuard::set(data.path());
1253
1254        let dir = corpus();
1255        let root = dir.path().to_string_lossy().to_string();
1256        // Seed the in-flight flag the way `ensure_background` does before spawn.
1257        {
1258            let mut map = cache()
1259                .lock()
1260                .unwrap_or_else(std::sync::PoisonError::into_inner);
1261            map.insert(
1262                root.clone(),
1263                CacheEntry {
1264                    index: None,
1265                    building: true,
1266                    last_verified: None,
1267                },
1268            );
1269        }
1270        assert_eq!(
1271            build_guarded(&root, true, false),
1272            BuildOutcome::Built,
1273            "an uncontended root must build"
1274        );
1275        let map = cache()
1276            .lock()
1277            .unwrap_or_else(std::sync::PoisonError::into_inner);
1278        let entry = map.get(&root).expect("entry present");
1279        assert!(!entry.building, "building flag must clear after build");
1280        assert!(entry.index.is_some(), "index must be installed after build");
1281    }
1282
1283    #[test]
1284    fn build_guarded_defers_when_another_process_holds_the_lock() {
1285        let _env = crate::core::data_dir::test_env_lock();
1286        let data = tempfile::tempdir().unwrap();
1287        let _guard = DataDirGuard::set(data.path());
1288
1289        let dir = corpus();
1290        let root = dir.path().to_string_lossy().to_string();
1291        // Pre-hold the cross-process lock with *this* (alive) PID and a fresh
1292        // mtime, so neither the dead-owner nor the staleness reclaim can take it
1293        // — exactly the "another session is already building" state from #460.
1294        let lock_path = data
1295            .path()
1296            .join(format!(".{}.lock", search_index_lock_name(&root)));
1297        std::fs::write(&lock_path, format!("{}\n", std::process::id())).unwrap();
1298
1299        {
1300            let mut map = cache()
1301                .lock()
1302                .unwrap_or_else(std::sync::PoisonError::into_inner);
1303            map.insert(
1304                root.clone(),
1305                CacheEntry {
1306                    index: None,
1307                    building: true,
1308                    last_verified: None,
1309                },
1310            );
1311        }
1312        assert_eq!(
1313            build_guarded(&root, true, false),
1314            BuildOutcome::Deferred,
1315            "a contended root must defer the proactive pre-warm"
1316        );
1317        let map = cache()
1318            .lock()
1319            .unwrap_or_else(std::sync::PoisonError::into_inner);
1320        let entry = map.get(&root).expect("entry present");
1321        assert!(
1322            !entry.building,
1323            "deferred build must clear the in-flight flag so a later nudge retries"
1324        );
1325        assert!(
1326            entry.index.is_none(),
1327            "deferred build must not run a second walk / install an index"
1328        );
1329    }
1330
1331    #[test]
1332    fn corpus_signature_matches_a_freshly_built_index() {
1333        let dir = corpus();
1334        let root = dir.path().to_string_lossy().to_string();
1335        let idx = SearchIndex::build(&root, true, false).expect("index builds");
1336        let sig = corpus_signature(&root, true, false).expect("signature computes");
1337        assert_eq!(
1338            idx.signature, sig,
1339            "a freshly built index must match the live corpus signature, or it \
1340             would be treated as permanently stale and never served"
1341        );
1342        // Re-derivation is deterministic for an unchanged corpus.
1343        assert_eq!(sig, corpus_signature(&root, true, false).unwrap());
1344    }
1345
1346    #[test]
1347    fn corpus_signature_changes_on_edit_add_and_delete() {
1348        let dir = corpus();
1349        let root = dir.path().to_string_lossy().to_string();
1350        let base = corpus_signature(&root, true, false).unwrap();
1351
1352        std::fs::write(
1353            dir.path().join("a.rs"),
1354            "fn handler() {}\nlet x = 1;\nlet y = 2;\n",
1355        )
1356        .unwrap();
1357        let after_edit = corpus_signature(&root, true, false).unwrap();
1358        assert_ne!(
1359            base, after_edit,
1360            "an in-place edit must change the signature"
1361        );
1362
1363        std::fs::write(dir.path().join("d.rs"), "fn fresh() {}\n").unwrap();
1364        let after_add = corpus_signature(&root, true, false).unwrap();
1365        assert_ne!(
1366            after_edit, after_add,
1367            "adding a file must change the signature"
1368        );
1369
1370        std::fs::remove_file(dir.path().join("b.rs")).unwrap();
1371        let after_delete = corpus_signature(&root, true, false).unwrap();
1372        assert_ne!(
1373            after_add, after_delete,
1374            "deleting a file must change the signature"
1375        );
1376    }
1377
1378    #[test]
1379    fn get_fresh_serves_unchanged_then_refuses_after_edit() {
1380        let _env = crate::core::data_dir::test_env_lock();
1381        let data = tempfile::tempdir().unwrap();
1382        let _guard = DataDirGuard::set(data.path());
1383        crate::test_env::remove_var("LEAN_CTX_DISABLE_SEARCH_INDEX");
1384        crate::test_env::remove_var("LEAN_CTX_SEARCH_INDEX_COALESCE_MS");
1385
1386        let dir = corpus();
1387        let root = dir.path().to_string_lossy().to_string();
1388        assert!(warm_blocking(&root, true, false), "index warms");
1389
1390        // Unchanged corpus → the resident index is served.
1391        assert!(
1392            get_fresh(&root, true, false).is_some(),
1393            "an unchanged corpus must serve the resident index"
1394        );
1395
1396        // Native edit (size changes) → the now-stale index is refused so the
1397        // caller walks the live corpus instead of trusting outdated trigrams.
1398        std::fs::write(
1399            dir.path().join("a.rs"),
1400            "fn handler() {}\nlet x = 1;\nlet z = 9;\n",
1401        )
1402        .unwrap();
1403        assert!(
1404            get_fresh(&root, true, false).is_none(),
1405            "an edited corpus must refuse the stale resident index (#624)"
1406        );
1407    }
1408}