1use 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
43const MAX_FILES: usize = 200_000;
45
46const MAX_POSTING_ENTRIES: usize = 12_000_000;
51
52const MAX_TOTAL_ENTRIES: usize = 48_000_000;
56
57const BLOOM_BITS_PER_ITEM: usize = 12;
61const BLOOM_K: usize = 7;
62const BLOOM_MIN_BITS: usize = 64;
64const BLOOM_MAX_BITS: usize = 1 << 20;
65
66fn 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
75enum Narrowing {
84 Postings(HashMap<u32, Vec<u32>>),
85 Blooms(Vec<FileBloom>),
86}
87
88struct FileBloom {
91 bits: Vec<u64>,
93}
94
95#[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 #[inline]
123 fn probes(&self, trigram: u32) -> impl Iterator<Item = usize> + '_ {
124 let m = self.m_bits();
125 let mask = m - 1; let h = mix64(u64::from(trigram));
127 let h1 = (h & 0xFFFF_FFFF) as usize;
128 let h2 = ((h >> 32) as usize) | 1; (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
144pub struct SearchIndex {
146 files: Vec<PathBuf>,
147 narrowing: Narrowing,
149 respect_gitignore: bool,
150 allow_secret_paths: bool,
151 signature: u64,
154}
155
156impl SearchIndex {
157 pub fn build(root: &str, respect_gitignore: bool, allow_secret_paths: bool) -> Option<Self> {
160 let mut files: Vec<PathBuf> = Vec::new();
161 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 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 |path, state| {
182 sig_sum = sig_sum.wrapping_add(file_sig(path, state));
183 file_count += 1;
184
185 let content: std::sync::Arc<str> = if let Some(cached) =
192 state.and_then(|s| crate::core::content_cache::get(path, s))
193 {
194 cached
195 } else {
196 let Ok(text) = std::fs::read_to_string(path) else {
197 return true;
198 };
199 let arc: std::sync::Arc<str> = std::sync::Arc::from(text);
200 if let Some(s) = state {
201 crate::core::content_cache::insert(path, s, std::sync::Arc::clone(&arc));
202 }
203 arc
204 };
205
206 if files.len() >= MAX_FILES {
207 aborted = true; return false;
209 }
210
211 scratch.clear();
212 let bytes = content.as_bytes();
213 if bytes.len() >= 3 {
214 for w in bytes.windows(3) {
215 if is_word_byte(w[0]) && is_word_byte(w[1]) && is_word_byte(w[2]) {
216 scratch.insert(pack(w[0], w[1], w[2]));
217 }
218 }
219 }
220 total_entries += scratch.len();
221 if total_entries > MAX_TOTAL_ENTRIES {
222 aborted = true; return false;
224 }
225 let mut tris: Vec<u32> = scratch.iter().copied().collect();
226 tris.sort_unstable();
227 files.push(path.to_path_buf());
228 per_file_trigrams.push(tris);
229 true
230 },
231 )?;
232
233 if aborted {
234 return None;
235 }
236
237 let narrowing = build_narrowing(&per_file_trigrams, total_entries);
238
239 Some(Self {
240 files,
241 narrowing,
242 respect_gitignore,
243 allow_secret_paths,
244 signature: finalize_sig(sig_sum, file_count),
245 })
246 }
247
248 fn config_matches(&self, respect_gitignore: bool, allow_secret_paths: bool) -> bool {
249 self.respect_gitignore == respect_gitignore && self.allow_secret_paths == allow_secret_paths
250 }
251
252 pub fn candidate_paths(
262 &self,
263 pattern: &str,
264 includes: &[Pattern],
265 root: &Path,
266 ) -> CandidateSet {
267 if let Some(ids) = self.literal_candidates(pattern) {
268 let paths = ids
269 .into_iter()
270 .map(|id| self.files[id as usize].clone())
271 .filter(|p| glob_matches(p, includes, root))
272 .collect();
273 CandidateSet::Narrowed(paths)
274 } else {
275 let paths = self
276 .files
277 .iter()
278 .filter(|p| glob_matches(p, includes, root))
279 .cloned()
280 .collect();
281 CandidateSet::FullList(paths)
282 }
283 }
284
285 fn literal_candidates(&self, pattern: &str) -> Option<Vec<u32>> {
289 let bytes = pattern.as_bytes();
290 if bytes.len() < 3 || !bytes.iter().all(|&b| is_word_byte(b)) {
291 return None;
292 }
293 let mut tris: Vec<u32> = bytes.windows(3).map(|w| pack(w[0], w[1], w[2])).collect();
295 tris.sort_unstable();
296 tris.dedup();
297
298 match &self.narrowing {
299 Narrowing::Postings(trigrams) => Some(Self::postings_intersect(trigrams, &tris)),
300 Narrowing::Blooms(blooms) => Some(Self::bloom_scan(blooms, &tris)),
301 }
302 }
303
304 fn postings_intersect(trigrams: &HashMap<u32, Vec<u32>>, tris: &[u32]) -> Vec<u32> {
307 let mut lists: Vec<&Vec<u32>> = Vec::with_capacity(tris.len());
308 for &tri in tris {
309 match trigrams.get(&tri) {
310 None => return Vec::new(),
312 Some(list) => lists.push(list),
313 }
314 }
315 lists.sort_by_key(|l| l.len());
316
317 let mut acc: Vec<u32> = lists[0].clone();
318 for list in &lists[1..] {
319 acc = intersect_sorted(&acc, list);
320 if acc.is_empty() {
321 break;
322 }
323 }
324 acc
325 }
326
327 fn bloom_scan(blooms: &[FileBloom], tris: &[u32]) -> Vec<u32> {
331 let mut out = Vec::new();
332 for (fid, bloom) in blooms.iter().enumerate() {
333 if tris.iter().all(|&t| bloom.maybe_contains(t)) {
334 out.push(fid as u32);
335 }
336 }
337 out
338 }
339}
340
341fn build_narrowing(per_file: &[Vec<u32>], total_entries: usize) -> Narrowing {
343 if total_entries <= MAX_POSTING_ENTRIES {
344 let mut trigrams: HashMap<u32, Vec<u32>> = HashMap::new();
345 for (fid, tris) in per_file.iter().enumerate() {
346 for &t in tris {
347 trigrams.entry(t).or_default().push(fid as u32);
349 }
350 }
351 Narrowing::Postings(trigrams)
352 } else {
353 let blooms = per_file
354 .iter()
355 .map(|tris| {
356 let mut b = FileBloom::with_capacity(tris.len());
357 for &t in tris {
358 b.insert(t);
359 }
360 b
361 })
362 .collect();
363 Narrowing::Blooms(blooms)
364 }
365}
366
367pub enum CandidateSet {
369 Narrowed(Vec<PathBuf>),
371 FullList(Vec<PathBuf>),
373}
374
375impl CandidateSet {
376 pub fn into_paths(self) -> Vec<PathBuf> {
377 match self {
378 CandidateSet::Narrowed(p) | CandidateSet::FullList(p) => p,
379 }
380 }
381}
382
383fn glob_matches(path: &Path, includes: &[Pattern], root: &Path) -> bool {
386 if includes.is_empty() {
387 return true;
388 }
389 let rel = path.strip_prefix(root).unwrap_or(path);
390 let rel_str = rel.to_string_lossy();
391 includes.iter().any(|p| p.matches(&rel_str))
392}
393
394fn intersect_sorted(a: &[u32], b: &[u32]) -> Vec<u32> {
396 let mut out = Vec::new();
397 let (mut i, mut j) = (0, 0);
398 while i < a.len() && j < b.len() {
399 match a[i].cmp(&b[j]) {
400 std::cmp::Ordering::Less => i += 1,
401 std::cmp::Ordering::Greater => j += 1,
402 std::cmp::Ordering::Equal => {
403 out.push(a[i]);
404 i += 1;
405 j += 1;
406 }
407 }
408 }
409 out
410}
411
412fn walk_index_corpus<F>(
427 root: &str,
428 respect_gitignore: bool,
429 allow_secret_paths: bool,
430 mut visit: F,
431) -> Option<()>
432where
433 F: FnMut(&Path, Option<crate::core::content_cache::FileState>) -> bool,
434{
435 let root_path = Path::new(root);
436 if !root_path.exists() {
437 return None;
438 }
439 if !crate::core::graph_index::is_safe_scan_root_public(root) {
444 return None;
445 }
446
447 let walker = WalkBuilder::new(root_path)
448 .hidden(true)
449 .max_depth(Some(MAX_WALK_DEPTH))
450 .git_ignore(respect_gitignore)
451 .git_global(respect_gitignore)
452 .git_exclude(respect_gitignore)
453 .require_git(false)
454 .filter_entry(crate::core::walk_filter::keep_entry)
455 .build();
456
457 for entry in walker.filter_map(std::result::Result::ok) {
458 if entry.file_type().is_none_or(|ft| ft.is_dir()) {
459 continue;
460 }
461 if entry.file_type().is_some_and(|ft| ft.is_symlink()) {
462 continue;
463 }
464 let path = entry.path();
465 if is_binary_ext(path) || is_generated_file(path) {
466 continue;
467 }
468 if !allow_secret_paths && crate::core::io_boundary::is_secret_like(path).is_some() {
469 continue;
470 }
471 let state = match std::fs::metadata(path) {
474 Ok(meta) if !meta.file_type().is_file() => continue,
475 Ok(meta) if meta.len() > MAX_FILE_SIZE => continue,
476 Ok(meta) => crate::core::content_cache::FileState::from_metadata(&meta),
477 Err(_) => continue,
478 };
479 if !visit(path, state) {
480 break;
481 }
482 }
483 Some(())
484}
485
486fn file_sig(path: &Path, state: Option<crate::core::content_cache::FileState>) -> u64 {
493 let mut h: u64 = 0xcbf2_9ce4_8422_2325; for &b in path.as_os_str().as_encoded_bytes() {
495 h ^= u64::from(b);
496 h = h.wrapping_mul(0x0000_0100_0000_01b3); }
498 if let Some(st) = state {
499 h ^= mix64(st.mtime_ms).rotate_left(1);
500 h ^= mix64(st.size_bytes).rotate_left(33);
501 }
502 mix64(h)
503}
504
505fn finalize_sig(sum: u64, count: usize) -> u64 {
509 sum ^ mix64(count as u64).rotate_left(32)
510}
511
512fn corpus_signature(root: &str, respect_gitignore: bool, allow_secret_paths: bool) -> Option<u64> {
519 let mut sum: u64 = 0;
520 let mut count: usize = 0;
521 walk_index_corpus(
522 root,
523 respect_gitignore,
524 allow_secret_paths,
525 |path, state| {
526 sum = sum.wrapping_add(file_sig(path, state));
527 count += 1;
528 true
529 },
530 )?;
531 Some(finalize_sig(sum, count))
532}
533
534struct CacheEntry {
539 index: Option<Arc<SearchIndex>>,
540 building: bool,
541 last_verified: Option<Instant>,
545}
546
547impl CacheEntry {
548 fn empty() -> Self {
549 Self {
550 index: None,
551 building: false,
552 last_verified: None,
553 }
554 }
555}
556
557static CACHE: OnceLock<Mutex<HashMap<String, CacheEntry>>> = OnceLock::new();
558
559fn cache() -> &'static Mutex<HashMap<String, CacheEntry>> {
560 CACHE.get_or_init(|| Mutex::new(HashMap::new()))
561}
562
563fn index_disabled() -> bool {
566 std::env::var("LEAN_CTX_DISABLE_SEARCH_INDEX")
567 .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"))
568}
569
570fn coalesce_window() -> Option<Duration> {
576 let ms = std::env::var("LEAN_CTX_SEARCH_INDEX_COALESCE_MS")
577 .ok()
578 .and_then(|v| v.trim().parse::<u64>().ok())
579 .unwrap_or(0);
580 (ms > 0).then(|| Duration::from_millis(ms))
581}
582
583pub fn get_fresh(
587 root: &str,
588 respect_gitignore: bool,
589 allow_secret_paths: bool,
590) -> Option<Arc<SearchIndex>> {
591 if !respect_gitignore || index_disabled() {
593 return None;
594 }
595
596 let (candidate, last_verified) = {
599 let map = cache()
600 .lock()
601 .unwrap_or_else(std::sync::PoisonError::into_inner);
602 match map.get(root) {
603 Some(entry) => match &entry.index {
604 Some(idx) if idx.config_matches(respect_gitignore, allow_secret_paths) => {
605 (Some(Arc::clone(idx)), entry.last_verified)
606 }
607 _ => (None, None),
608 },
609 None => (None, None),
610 }
611 };
612
613 let Some(idx) = candidate else {
614 request_build(root, respect_gitignore, allow_secret_paths);
616 return None;
617 };
618
619 if let Some(window) = coalesce_window()
622 && last_verified.is_some_and(|t| t.elapsed() < window)
623 {
624 return Some(idx);
625 }
626
627 match corpus_signature(root, respect_gitignore, allow_secret_paths) {
631 Some(sig) if sig == idx.signature => {
632 mark_verified(root);
633 Some(idx)
634 }
635 _ => {
636 request_build(root, respect_gitignore, allow_secret_paths);
639 None
640 }
641 }
642}
643
644fn mark_verified(root: &str) {
647 let mut map = cache()
648 .lock()
649 .unwrap_or_else(std::sync::PoisonError::into_inner);
650 if let Some(entry) = map.get_mut(root) {
651 entry.last_verified = Some(Instant::now());
652 }
653}
654
655fn request_build(root: &str, respect_gitignore: bool, allow_secret_paths: bool) {
657 let needs_build = {
658 let mut map = cache()
659 .lock()
660 .unwrap_or_else(std::sync::PoisonError::into_inner);
661 let entry = map
662 .entry(root.to_string())
663 .or_insert_with(CacheEntry::empty);
664 if entry.building {
665 false
666 } else {
667 entry.building = true;
668 true
669 }
670 };
671 if needs_build {
672 spawn_build(root.to_string(), respect_gitignore, allow_secret_paths);
673 }
674}
675
676pub fn ensure_background(root: &str, respect_gitignore: bool, allow_secret_paths: bool) {
679 if !respect_gitignore || index_disabled() {
680 return;
681 }
682 let has_index = {
686 let map = cache()
687 .lock()
688 .unwrap_or_else(std::sync::PoisonError::into_inner);
689 map.get(root).is_some_and(|entry| {
690 entry
691 .index
692 .as_ref()
693 .is_some_and(|idx| idx.config_matches(respect_gitignore, allow_secret_paths))
694 })
695 };
696 if !has_index {
697 request_build(root, respect_gitignore, allow_secret_paths);
698 }
699}
700
701pub fn warm_blocking(root: &str, respect_gitignore: bool, allow_secret_paths: bool) -> bool {
705 if !respect_gitignore || index_disabled() {
706 return false;
707 }
708 let Some(idx) = SearchIndex::build(root, respect_gitignore, allow_secret_paths) else {
709 return false;
710 };
711 let mut map = cache()
712 .lock()
713 .unwrap_or_else(std::sync::PoisonError::into_inner);
714 map.insert(
715 root.to_string(),
716 CacheEntry {
717 index: Some(Arc::new(idx)),
718 building: false,
719 last_verified: Some(Instant::now()),
720 },
721 );
722 true
723}
724
725fn search_index_lock_name(root: &str) -> String {
730 format!(
731 "search-idx-{}",
732 &crate::core::index_namespace::namespace_hash(Path::new(root))[..8]
733 )
734}
735
736#[derive(Debug, Clone, Copy, PartialEq, Eq)]
739enum BuildOutcome {
740 Built,
741 Deferred,
742}
743
744fn build_guarded(root: &str, respect_gitignore: bool, allow_secret_paths: bool) -> BuildOutcome {
754 let lock = crate::core::startup_guard::try_acquire_lock(
755 &search_index_lock_name(root),
756 Duration::from_millis(200),
757 Duration::from_mins(3),
758 );
759 if lock.is_none() {
760 let mut map = cache()
763 .lock()
764 .unwrap_or_else(std::sync::PoisonError::into_inner);
765 if let Some(entry) = map.get_mut(root) {
766 entry.building = false;
767 }
768 return BuildOutcome::Deferred;
769 }
770
771 let built = std::panic::catch_unwind(|| {
772 SearchIndex::build(root, respect_gitignore, allow_secret_paths)
773 })
774 .ok()
775 .flatten();
776
777 let mut map = cache()
778 .lock()
779 .unwrap_or_else(std::sync::PoisonError::into_inner);
780 if let Some(entry) = map.get_mut(root) {
781 entry.building = false;
782 if let Some(idx) = built {
783 entry.index = Some(Arc::new(idx));
784 entry.last_verified = Some(Instant::now());
786 }
787 }
788 drop(lock);
790 BuildOutcome::Built
791}
792
793fn spawn_build(root: String, respect_gitignore: bool, allow_secret_paths: bool) {
794 std::thread::spawn(move || {
795 let _ = build_guarded(&root, respect_gitignore, allow_secret_paths);
796 });
797}
798
799#[cfg(test)]
800mod tests {
801 use super::*;
802
803 fn corpus() -> tempfile::TempDir {
804 let dir = tempfile::tempdir().unwrap();
805 std::fs::write(dir.path().join("a.rs"), "fn handler() {}\nlet x = 1;\n").unwrap();
806 std::fs::write(dir.path().join("b.rs"), "fn other() {}\n// nothing here\n").unwrap();
807 std::fs::write(dir.path().join("c.txt"), "handler appears in text too\n").unwrap();
808 dir
809 }
810
811 #[test]
812 fn build_refuses_to_index_home_directory() {
813 if let Some(home) = dirs::home_dir() {
816 assert!(
817 SearchIndex::build(&home.to_string_lossy(), true, false).is_none(),
818 "search index must never auto-build over the home directory"
819 );
820 }
821 }
822
823 #[test]
824 fn narrows_to_files_containing_literal() {
825 let dir = corpus();
826 let idx = SearchIndex::build(dir.path().to_str().unwrap(), true, false).unwrap();
827 let cands = idx.candidate_paths("handler", &[], dir.path());
828 let paths = cands.into_paths();
829 assert!(paths.iter().any(|p| p.ends_with("a.rs")));
831 assert!(paths.iter().any(|p| p.ends_with("c.txt")));
832 assert!(!paths.iter().any(|p| p.ends_with("b.rs")));
833 }
834
835 #[test]
836 fn absent_trigram_yields_empty_candidates() {
837 let dir = corpus();
838 let idx = SearchIndex::build(dir.path().to_str().unwrap(), true, false).unwrap();
839 match idx.candidate_paths("zzzqqq", &[], dir.path()) {
840 CandidateSet::Narrowed(p) => assert!(p.is_empty()),
841 CandidateSet::FullList(_) => panic!("pure literal should narrow"),
842 }
843 }
844
845 #[test]
846 fn ext_filter_restricts_candidates() {
847 let dir = corpus();
848 let idx = SearchIndex::build(dir.path().to_str().unwrap(), true, false).unwrap();
849 let paths = idx
850 .candidate_paths(
851 "handler",
852 &[glob::Pattern::new("*.rs").unwrap()],
853 dir.path(),
854 )
855 .into_paths();
856 assert!(paths.iter().all(|p| p.extension().unwrap() == "rs"));
857 assert!(paths.iter().any(|p| p.ends_with("a.rs")));
858 }
859
860 #[test]
861 #[cfg(unix)]
862 fn build_skips_named_pipe_without_hanging() {
863 use std::sync::mpsc;
864 use std::time::Duration;
865 let dir = corpus();
869 let fifo = dir.path().join("pipe.fifo");
870 let c = std::ffi::CString::new(fifo.to_string_lossy().as_bytes()).unwrap();
871 assert_eq!(
872 unsafe { libc::mkfifo(c.as_ptr(), 0o644) },
875 0,
876 "mkfifo failed"
877 );
878
879 let root = dir.path().to_str().unwrap().to_string();
880 let (tx, rx) = mpsc::channel();
881 std::thread::spawn(move || {
882 let built = SearchIndex::build(&root, true, false);
883 let _ = tx.send(built.map(|idx| {
884 idx.candidate_paths("handler", &[], std::path::Path::new(&root))
885 .into_paths()
886 }));
887 });
888 let paths = rx
889 .recv_timeout(Duration::from_secs(5))
890 .expect("SearchIndex::build hung on a FIFO (#336 regression)")
891 .expect("index should build");
892 assert!(paths.iter().any(|p| p.ends_with("a.rs")));
893 assert!(!paths.iter().any(|p| p.ends_with("pipe.fifo")));
894 }
895
896 #[test]
897 fn regex_query_falls_back_to_full_list() {
898 let dir = corpus();
899 let idx = SearchIndex::build(dir.path().to_str().unwrap(), true, false).unwrap();
900 match idx.candidate_paths("fn .*\\(\\)", &[], dir.path()) {
901 CandidateSet::FullList(p) => assert!(!p.is_empty()),
902 CandidateSet::Narrowed(_) => panic!("metachar query must not narrow"),
903 }
904 }
905
906 #[test]
907 fn short_query_falls_back_to_full_list() {
908 let dir = corpus();
909 let idx = SearchIndex::build(dir.path().to_str().unwrap(), true, false).unwrap();
910 assert!(matches!(
911 idx.candidate_paths("fn", &[], dir.path()),
912 CandidateSet::FullList(_)
913 ));
914 }
915
916 #[test]
920 fn narrowing_has_identical_recall_to_full_scan() {
921 use regex::Regex;
922 use std::collections::BTreeSet;
923
924 let dir = tempfile::tempdir().unwrap();
925 let samples = [
927 (
928 "auth/login.rs",
929 "fn authenticate(user) {}\nlet token = mint();\n",
930 ),
931 (
932 "auth/session.rs",
933 "struct Session;\n// authenticate again here\n",
934 ),
935 ("db/pool.rs", "fn connect() {}\nlet retries = 3;\n"),
936 (
937 "ui/button.tsx",
938 "export const Button = () => authenticate;\n",
939 ),
940 ("readme.md", "This project uses authenticate flows.\n"),
941 ("unrelated.rs", "fn helper() { let v = 1; }\n"),
942 ];
943 for (rel, content) in samples {
944 let p = dir.path().join(rel);
945 std::fs::create_dir_all(p.parent().unwrap()).unwrap();
946 std::fs::write(p, content).unwrap();
947 }
948 let idx = SearchIndex::build(dir.path().to_str().unwrap(), true, false).unwrap();
949
950 let full_scan = |pat: &str| -> BTreeSet<String> {
951 let re = Regex::new(pat).unwrap();
952 let mut hits = BTreeSet::new();
953 for (rel, content) in samples {
954 for (i, line) in content.lines().enumerate() {
955 if re.is_match(line) {
956 hits.insert(format!("{rel}:{}", i + 1));
957 }
958 }
959 }
960 hits
961 };
962
963 for query in ["authenticate", "Session", "retries", "token"] {
964 let re = Regex::new(query).unwrap();
965 let candidates = idx.candidate_paths(query, &[], dir.path()).into_paths();
966 let mut narrowed = BTreeSet::new();
967 for path in &candidates {
968 let content = std::fs::read_to_string(path).unwrap();
969 let rel = path.strip_prefix(dir.path()).unwrap().to_string_lossy();
970 for (i, line) in content.lines().enumerate() {
971 if re.is_match(line) {
972 narrowed.insert(format!("{}:{}", rel.replace('\\', "/"), i + 1));
973 }
974 }
975 }
976 assert_eq!(
977 narrowed,
978 full_scan(query),
979 "recall mismatch for query {query:?}"
980 );
981 }
982 }
983
984 #[test]
985 fn intersect_sorted_basic() {
986 assert_eq!(
987 intersect_sorted(&[1, 2, 3, 5], &[2, 3, 4, 5]),
988 vec![2, 3, 5]
989 );
990 assert_eq!(intersect_sorted(&[1, 2], &[3, 4]), Vec::<u32>::new());
991 }
992
993 fn trigrams_of(s: &str) -> Vec<u32> {
996 let mut set = HashSet::new();
997 let b = s.as_bytes();
998 if b.len() >= 3 {
999 for w in b.windows(3) {
1000 if is_word_byte(w[0]) && is_word_byte(w[1]) && is_word_byte(w[2]) {
1001 set.insert(pack(w[0], w[1], w[2]));
1002 }
1003 }
1004 }
1005 let mut v: Vec<u32> = set.into_iter().collect();
1006 v.sort_unstable();
1007 v
1008 }
1009
1010 #[test]
1011 fn file_bloom_has_no_false_negatives() {
1012 let tris = trigrams_of("fn authenticate(user) { let token = mint(); }");
1013 let mut bloom = FileBloom::with_capacity(tris.len());
1014 for &t in &tris {
1015 bloom.insert(t);
1016 }
1017 assert!(tris.iter().all(|&t| bloom.maybe_contains(t)));
1019 }
1020
1021 #[test]
1025 fn bloom_tier_is_superset_of_postings_tier() {
1026 let mut seed = 0x1234_5678_9abc_def0u64;
1028 let mut rng = || {
1029 seed = seed
1030 .wrapping_mul(6364136223846793005)
1031 .wrapping_add(1442695040888963407);
1032 (seed >> 33) as u32
1033 };
1034 let mut per_file: Vec<Vec<u32>> = Vec::new();
1035 for _ in 0..80 {
1036 let n = 50 + (rng() % 250) as usize;
1037 let mut s = HashSet::new();
1038 for _ in 0..n {
1039 s.insert(rng() & 0x00FF_FFFF);
1040 }
1041 let mut v: Vec<u32> = s.into_iter().collect();
1042 v.sort_unstable();
1043 per_file.push(v);
1044 }
1045 let total: usize = per_file.iter().map(Vec::len).sum();
1046
1047 let postings = build_narrowing(&per_file, total); let blooms = build_narrowing(&per_file, MAX_POSTING_ENTRIES + 1); let (Narrowing::Postings(pt), Narrowing::Blooms(bl)) = (&postings, &blooms) else {
1050 panic!("unexpected narrowing tiers");
1051 };
1052
1053 for f in &per_file {
1056 if f.len() < 3 {
1057 continue;
1058 }
1059 let q = vec![f[0], f[f.len() / 2], f[f.len() - 1]];
1060 let exact = SearchIndex::postings_intersect(pt, &q);
1061 let bloom: HashSet<u32> = SearchIndex::bloom_scan(bl, &q).into_iter().collect();
1062 for id in exact {
1063 assert!(
1064 bloom.contains(&id),
1065 "Bloom tier dropped a true match (false negative) for {q:?}"
1066 );
1067 }
1068 }
1069 }
1070
1071 #[test]
1074 fn bloom_tier_end_to_end_recall() {
1075 let samples = [
1076 (
1077 "auth_login.rs",
1078 "fn authenticate(user) {}\nlet token = mint();\n",
1079 ),
1080 (
1081 "auth_session.rs",
1082 "struct Session;\n// authenticate again here\n",
1083 ),
1084 ("db_pool.rs", "fn connect() {}\nlet retries = 3;\n"),
1085 (
1086 "ui_button.tsx",
1087 "export const Button = () => authenticate;\n",
1088 ),
1089 ("readme.md", "This project uses authenticate flows.\n"),
1090 ("unrelated.rs", "fn helper() { let v = 1; }\n"),
1091 ];
1092 let files: Vec<PathBuf> = samples.iter().map(|(rel, _)| PathBuf::from(rel)).collect();
1093 let per_file: Vec<Vec<u32>> = samples.iter().map(|(_, c)| trigrams_of(c)).collect();
1094
1095 let idx = SearchIndex {
1096 files,
1097 narrowing: build_narrowing(&per_file, MAX_POSTING_ENTRIES + 1),
1098 respect_gitignore: true,
1099 allow_secret_paths: false,
1100 signature: 0, };
1102 assert!(
1103 matches!(idx.narrowing, Narrowing::Blooms(_)),
1104 "test must exercise the Bloom tier"
1105 );
1106
1107 for query in ["authenticate", "Session", "retries", "token"] {
1108 let cands: HashSet<String> = idx
1109 .candidate_paths(query, &[], std::path::Path::new(""))
1110 .into_paths()
1111 .iter()
1112 .map(|p| p.to_string_lossy().to_string())
1113 .collect();
1114 for (rel, content) in samples {
1115 if content.contains(query) {
1116 assert!(
1117 cands.contains(rel),
1118 "Bloom tier dropped real match {rel} for query {query:?}"
1119 );
1120 }
1121 }
1122 }
1123 }
1124
1125 struct DataDirGuard {
1128 prev: Option<String>,
1129 }
1130 impl DataDirGuard {
1131 fn set(path: &std::path::Path) -> Self {
1132 let prev = std::env::var("LEAN_CTX_DATA_DIR").ok();
1133 crate::test_env::set_var("LEAN_CTX_DATA_DIR", path);
1134 Self { prev }
1135 }
1136 }
1137 impl Drop for DataDirGuard {
1138 fn drop(&mut self) {
1139 match self.prev.as_deref() {
1140 Some(v) => crate::test_env::set_var("LEAN_CTX_DATA_DIR", v),
1141 None => crate::test_env::remove_var("LEAN_CTX_DATA_DIR"),
1142 }
1143 }
1144 }
1145
1146 #[test]
1147 fn search_index_lock_name_is_per_repo_and_distinct() {
1148 let a = search_index_lock_name("/tmp/repo-a");
1149 let b = search_index_lock_name("/tmp/repo-b");
1150 assert!(a.starts_with("search-idx-"), "unexpected lock name: {a}");
1151 assert_ne!(a, b, "lock name must be per-repo");
1152 assert_eq!(a, search_index_lock_name("/tmp/repo-a"), "stable per repo");
1153 let h = &crate::core::index_namespace::namespace_hash(Path::new("/tmp/repo-a"))[..8];
1156 assert_ne!(
1157 a,
1158 format!("graph-idx-{h}"),
1159 "must not collide with graph lock"
1160 );
1161 assert_ne!(
1162 a,
1163 format!("bm25-idx-{h}"),
1164 "must not collide with bm25 lock"
1165 );
1166 }
1167
1168 #[test]
1169 fn build_guarded_builds_when_uncontended() {
1170 let _env = crate::core::data_dir::test_env_lock();
1171 let data = tempfile::tempdir().unwrap();
1172 let _guard = DataDirGuard::set(data.path());
1173
1174 let dir = corpus();
1175 let root = dir.path().to_string_lossy().to_string();
1176 {
1178 let mut map = cache()
1179 .lock()
1180 .unwrap_or_else(std::sync::PoisonError::into_inner);
1181 map.insert(
1182 root.clone(),
1183 CacheEntry {
1184 index: None,
1185 building: true,
1186 last_verified: None,
1187 },
1188 );
1189 }
1190 assert_eq!(
1191 build_guarded(&root, true, false),
1192 BuildOutcome::Built,
1193 "an uncontended root must build"
1194 );
1195 let map = cache()
1196 .lock()
1197 .unwrap_or_else(std::sync::PoisonError::into_inner);
1198 let entry = map.get(&root).expect("entry present");
1199 assert!(!entry.building, "building flag must clear after build");
1200 assert!(entry.index.is_some(), "index must be installed after build");
1201 }
1202
1203 #[test]
1204 fn build_guarded_defers_when_another_process_holds_the_lock() {
1205 let _env = crate::core::data_dir::test_env_lock();
1206 let data = tempfile::tempdir().unwrap();
1207 let _guard = DataDirGuard::set(data.path());
1208
1209 let dir = corpus();
1210 let root = dir.path().to_string_lossy().to_string();
1211 let lock_path = data
1215 .path()
1216 .join(format!(".{}.lock", search_index_lock_name(&root)));
1217 std::fs::write(&lock_path, format!("{}\n", std::process::id())).unwrap();
1218
1219 {
1220 let mut map = cache()
1221 .lock()
1222 .unwrap_or_else(std::sync::PoisonError::into_inner);
1223 map.insert(
1224 root.clone(),
1225 CacheEntry {
1226 index: None,
1227 building: true,
1228 last_verified: None,
1229 },
1230 );
1231 }
1232 assert_eq!(
1233 build_guarded(&root, true, false),
1234 BuildOutcome::Deferred,
1235 "a contended root must defer the proactive pre-warm"
1236 );
1237 let map = cache()
1238 .lock()
1239 .unwrap_or_else(std::sync::PoisonError::into_inner);
1240 let entry = map.get(&root).expect("entry present");
1241 assert!(
1242 !entry.building,
1243 "deferred build must clear the in-flight flag so a later nudge retries"
1244 );
1245 assert!(
1246 entry.index.is_none(),
1247 "deferred build must not run a second walk / install an index"
1248 );
1249 }
1250
1251 #[test]
1252 fn corpus_signature_matches_a_freshly_built_index() {
1253 let dir = corpus();
1254 let root = dir.path().to_string_lossy().to_string();
1255 let idx = SearchIndex::build(&root, true, false).expect("index builds");
1256 let sig = corpus_signature(&root, true, false).expect("signature computes");
1257 assert_eq!(
1258 idx.signature, sig,
1259 "a freshly built index must match the live corpus signature, or it \
1260 would be treated as permanently stale and never served"
1261 );
1262 assert_eq!(sig, corpus_signature(&root, true, false).unwrap());
1264 }
1265
1266 #[test]
1267 fn corpus_signature_changes_on_edit_add_and_delete() {
1268 let dir = corpus();
1269 let root = dir.path().to_string_lossy().to_string();
1270 let base = corpus_signature(&root, true, false).unwrap();
1271
1272 std::fs::write(
1273 dir.path().join("a.rs"),
1274 "fn handler() {}\nlet x = 1;\nlet y = 2;\n",
1275 )
1276 .unwrap();
1277 let after_edit = corpus_signature(&root, true, false).unwrap();
1278 assert_ne!(
1279 base, after_edit,
1280 "an in-place edit must change the signature"
1281 );
1282
1283 std::fs::write(dir.path().join("d.rs"), "fn fresh() {}\n").unwrap();
1284 let after_add = corpus_signature(&root, true, false).unwrap();
1285 assert_ne!(
1286 after_edit, after_add,
1287 "adding a file must change the signature"
1288 );
1289
1290 std::fs::remove_file(dir.path().join("b.rs")).unwrap();
1291 let after_delete = corpus_signature(&root, true, false).unwrap();
1292 assert_ne!(
1293 after_add, after_delete,
1294 "deleting a file must change the signature"
1295 );
1296 }
1297
1298 #[test]
1299 fn get_fresh_serves_unchanged_then_refuses_after_edit() {
1300 let _env = crate::core::data_dir::test_env_lock();
1301 let data = tempfile::tempdir().unwrap();
1302 let _guard = DataDirGuard::set(data.path());
1303 crate::test_env::remove_var("LEAN_CTX_DISABLE_SEARCH_INDEX");
1304 crate::test_env::remove_var("LEAN_CTX_SEARCH_INDEX_COALESCE_MS");
1305
1306 let dir = corpus();
1307 let root = dir.path().to_string_lossy().to_string();
1308 assert!(warm_blocking(&root, true, false), "index warms");
1309
1310 assert!(
1312 get_fresh(&root, true, false).is_some(),
1313 "an unchanged corpus must serve the resident index"
1314 );
1315
1316 std::fs::write(
1319 dir.path().join("a.rs"),
1320 "fn handler() {}\nlet x = 1;\nlet z = 9;\n",
1321 )
1322 .unwrap();
1323 assert!(
1324 get_fresh(&root, true, false).is_none(),
1325 "an edited corpus must refuse the stale resident index (#624)"
1326 );
1327 }
1328}