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