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 None,
182 |path, state| {
183 sig_sum = sig_sum.wrapping_add(file_sig(path, state));
184 file_count += 1;
185
186 let content: std::sync::Arc<str> = if let Some(cached) =
193 state.and_then(|s| crate::core::content_cache::get(path, s))
194 {
195 cached
196 } else {
197 let Ok(text) = std::fs::read_to_string(path) else {
198 return true;
199 };
200 let arc: std::sync::Arc<str> = std::sync::Arc::from(text);
201 if let Some(s) = state {
202 crate::core::content_cache::insert(path, s, std::sync::Arc::clone(&arc));
203 }
204 arc
205 };
206
207 if files.len() >= MAX_FILES {
208 aborted = true; return false;
210 }
211
212 scratch.clear();
213 let bytes = content.as_bytes();
214 if bytes.len() >= 3 {
215 for w in bytes.windows(3) {
216 if is_word_byte(w[0]) && is_word_byte(w[1]) && is_word_byte(w[2]) {
217 scratch.insert(pack(w[0], w[1], w[2]));
218 }
219 }
220 }
221 total_entries += scratch.len();
222 if total_entries > MAX_TOTAL_ENTRIES {
223 aborted = true; return false;
225 }
226 let mut tris: Vec<u32> = scratch.iter().copied().collect();
227 tris.sort_unstable();
228 files.push(path.to_path_buf());
229 per_file_trigrams.push(tris);
230 true
231 },
232 )?;
233
234 if aborted {
235 return None;
236 }
237
238 let narrowing = build_narrowing(&per_file_trigrams, total_entries);
239
240 Some(Self {
241 files,
242 narrowing,
243 respect_gitignore,
244 allow_secret_paths,
245 signature: finalize_sig(sig_sum, file_count),
246 })
247 }
248
249 fn config_matches(&self, respect_gitignore: bool, allow_secret_paths: bool) -> bool {
250 self.respect_gitignore == respect_gitignore && self.allow_secret_paths == allow_secret_paths
251 }
252
253 pub fn candidate_paths(
263 &self,
264 pattern: &str,
265 includes: &[Pattern],
266 root: &Path,
267 ) -> CandidateSet {
268 if let Some(ids) = self.literal_candidates(pattern) {
269 let paths = ids
270 .into_iter()
271 .map(|id| self.files[id as usize].clone())
272 .filter(|p| glob_matches(p, includes, root))
273 .collect();
274 CandidateSet::Narrowed(paths)
275 } else {
276 let paths = self
277 .files
278 .iter()
279 .filter(|p| glob_matches(p, includes, root))
280 .cloned()
281 .collect();
282 CandidateSet::FullList(paths)
283 }
284 }
285
286 fn literal_candidates(&self, pattern: &str) -> Option<Vec<u32>> {
290 let bytes = pattern.as_bytes();
291 if bytes.len() < 3 || !bytes.iter().all(|&b| is_word_byte(b)) {
292 return None;
293 }
294 let mut tris: Vec<u32> = bytes.windows(3).map(|w| pack(w[0], w[1], w[2])).collect();
296 tris.sort_unstable();
297 tris.dedup();
298
299 match &self.narrowing {
300 Narrowing::Postings(trigrams) => Some(Self::postings_intersect(trigrams, &tris)),
301 Narrowing::Blooms(blooms) => Some(Self::bloom_scan(blooms, &tris)),
302 }
303 }
304
305 fn postings_intersect(trigrams: &HashMap<u32, Vec<u32>>, tris: &[u32]) -> Vec<u32> {
308 let mut lists: Vec<&Vec<u32>> = Vec::with_capacity(tris.len());
309 for &tri in tris {
310 match trigrams.get(&tri) {
311 None => return Vec::new(),
313 Some(list) => lists.push(list),
314 }
315 }
316 lists.sort_by_key(|l| l.len());
317
318 let mut acc: Vec<u32> = lists[0].clone();
319 for list in &lists[1..] {
320 acc = intersect_sorted(&acc, list);
321 if acc.is_empty() {
322 break;
323 }
324 }
325 acc
326 }
327
328 fn bloom_scan(blooms: &[FileBloom], tris: &[u32]) -> Vec<u32> {
332 let mut out = Vec::new();
333 for (fid, bloom) in blooms.iter().enumerate() {
334 if tris.iter().all(|&t| bloom.maybe_contains(t)) {
335 out.push(fid as u32);
336 }
337 }
338 out
339 }
340}
341
342fn build_narrowing(per_file: &[Vec<u32>], total_entries: usize) -> Narrowing {
344 if total_entries <= MAX_POSTING_ENTRIES {
345 let mut trigrams: HashMap<u32, Vec<u32>> = HashMap::new();
346 for (fid, tris) in per_file.iter().enumerate() {
347 for &t in tris {
348 trigrams.entry(t).or_default().push(fid as u32);
350 }
351 }
352 Narrowing::Postings(trigrams)
353 } else {
354 let blooms = per_file
355 .iter()
356 .map(|tris| {
357 let mut b = FileBloom::with_capacity(tris.len());
358 for &t in tris {
359 b.insert(t);
360 }
361 b
362 })
363 .collect();
364 Narrowing::Blooms(blooms)
365 }
366}
367
368pub enum CandidateSet {
370 Narrowed(Vec<PathBuf>),
372 FullList(Vec<PathBuf>),
374}
375
376impl CandidateSet {
377 pub fn into_paths(self) -> Vec<PathBuf> {
378 match self {
379 CandidateSet::Narrowed(p) | CandidateSet::FullList(p) => p,
380 }
381 }
382}
383
384fn glob_matches(path: &Path, includes: &[Pattern], root: &Path) -> bool {
387 if includes.is_empty() {
388 return true;
389 }
390 let rel = path.strip_prefix(root).unwrap_or(path);
391 let rel_str = rel.to_string_lossy();
392 includes.iter().any(|p| p.matches(&rel_str))
393}
394
395pub fn boundary_skipped_files(
400 root: &str,
401 respect_gitignore: bool,
402 includes: &[Pattern],
403) -> Vec<(String, &'static str)> {
404 let root_path = Path::new(root);
405 if !root_path.exists() {
406 return Vec::new();
407 }
408 if !crate::core::graph_index::is_safe_scan_root_public(root) {
409 return Vec::new();
410 }
411
412 let walker = WalkBuilder::new(root_path)
413 .hidden(false)
414 .max_depth(Some(crate::tools::ctx_search::MAX_WALK_DEPTH))
415 .git_ignore(respect_gitignore)
416 .git_global(respect_gitignore)
417 .git_exclude(respect_gitignore)
418 .require_git(false)
419 .filter_entry(move |e| {
420 if respect_gitignore {
421 crate::core::walk_filter::keep_entry(e)
422 } else {
423 crate::core::cloud_files::keep_entry(e)
424 }
425 })
426 .build();
427
428 let mut skipped = Vec::new();
429 for entry in walker.filter_map(std::result::Result::ok) {
430 if entry.file_type().is_none_or(|ft| ft.is_dir()) {
431 continue;
432 }
433 if entry.file_type().is_some_and(|ft| ft.is_symlink()) {
434 continue;
435 }
436 let path = entry.path();
437 if is_binary_ext(path) || is_generated_file(path) {
438 continue;
439 }
440 if !includes.is_empty() && !glob_matches(path, includes, root_path) {
441 continue;
442 }
443 if let Some(reason) = crate::core::io_boundary::is_secret_like(path) {
444 let rel = path.strip_prefix(root_path).unwrap_or(path);
445 skipped.push((rel.to_string_lossy().into_owned(), reason));
446 }
447 }
448 skipped.sort_unstable();
449 skipped
450}
451
452fn intersect_sorted(a: &[u32], b: &[u32]) -> Vec<u32> {
454 let mut out = Vec::new();
455 let (mut i, mut j) = (0, 0);
456 while i < a.len() && j < b.len() {
457 match a[i].cmp(&b[j]) {
458 std::cmp::Ordering::Less => i += 1,
459 std::cmp::Ordering::Greater => j += 1,
460 std::cmp::Ordering::Equal => {
461 out.push(a[i]);
462 i += 1;
463 j += 1;
464 }
465 }
466 }
467 out
468}
469
470fn walk_index_corpus<F>(
485 root: &str,
486 respect_gitignore: bool,
487 allow_secret_paths: bool,
488 includes: Option<&[Pattern]>,
489 mut visit: F,
490) -> Option<()>
491where
492 F: FnMut(&Path, Option<crate::core::content_cache::FileState>) -> bool,
493{
494 let root_path = Path::new(root);
495 if !root_path.exists() {
496 return None;
497 }
498 if !crate::core::graph_index::is_safe_scan_root_public(root) {
503 return None;
504 }
505
506 let walker = WalkBuilder::new(root_path)
507 .hidden(true)
508 .max_depth(Some(MAX_WALK_DEPTH))
509 .git_ignore(respect_gitignore)
510 .git_global(respect_gitignore)
511 .git_exclude(respect_gitignore)
512 .require_git(false)
513 .filter_entry(crate::core::walk_filter::keep_entry)
514 .build();
515
516 for entry in walker.filter_map(std::result::Result::ok) {
517 if entry.file_type().is_none_or(|ft| ft.is_dir()) {
518 continue;
519 }
520 if entry.file_type().is_some_and(|ft| ft.is_symlink()) {
521 continue;
522 }
523 let path = entry.path();
524 if is_binary_ext(path) || is_generated_file(path) {
525 continue;
526 }
527 if let Some(includes) = includes {
528 if !includes.is_empty() && !glob_matches(path, includes, root_path) {
529 continue;
530 }
531 }
532 if !allow_secret_paths && crate::core::io_boundary::is_secret_like(path).is_some() {
533 continue;
534 }
535 let state = match std::fs::metadata(path) {
538 Ok(meta) if !meta.file_type().is_file() => continue,
539 Ok(meta) if meta.len() > MAX_FILE_SIZE => continue,
540 Ok(meta) => crate::core::content_cache::FileState::from_metadata(&meta),
541 Err(_) => continue,
542 };
543 if !visit(path, state) {
544 break;
545 }
546 }
547 Some(())
548}
549
550fn file_sig(path: &Path, state: Option<crate::core::content_cache::FileState>) -> u64 {
557 let mut h: u64 = 0xcbf2_9ce4_8422_2325; for &b in path.as_os_str().as_encoded_bytes() {
559 h ^= u64::from(b);
560 h = h.wrapping_mul(0x0000_0100_0000_01b3); }
562 if let Some(st) = state {
563 h ^= mix64(st.mtime_ms).rotate_left(1);
564 h ^= mix64(st.size_bytes).rotate_left(33);
565 }
566 mix64(h)
567}
568
569fn finalize_sig(sum: u64, count: usize) -> u64 {
573 sum ^ mix64(count as u64).rotate_left(32)
574}
575
576fn corpus_signature(root: &str, respect_gitignore: bool, allow_secret_paths: bool) -> Option<u64> {
583 let mut sum: u64 = 0;
584 let mut count: usize = 0;
585 walk_index_corpus(
586 root,
587 respect_gitignore,
588 allow_secret_paths,
589 None,
590 |path, state| {
591 sum = sum.wrapping_add(file_sig(path, state));
592 count += 1;
593 true
594 },
595 )?;
596 Some(finalize_sig(sum, count))
597}
598
599struct CacheEntry {
604 index: Option<Arc<SearchIndex>>,
605 building: bool,
606 last_verified: Option<Instant>,
610}
611
612impl CacheEntry {
613 fn empty() -> Self {
614 Self {
615 index: None,
616 building: false,
617 last_verified: None,
618 }
619 }
620}
621
622static CACHE: OnceLock<Mutex<HashMap<String, CacheEntry>>> = OnceLock::new();
623
624fn cache() -> &'static Mutex<HashMap<String, CacheEntry>> {
625 CACHE.get_or_init(|| Mutex::new(HashMap::new()))
626}
627
628fn index_disabled() -> bool {
631 std::env::var("LEAN_CTX_DISABLE_SEARCH_INDEX")
632 .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"))
633}
634
635fn coalesce_window() -> Option<Duration> {
641 let ms = std::env::var("LEAN_CTX_SEARCH_INDEX_COALESCE_MS")
642 .ok()
643 .and_then(|v| v.trim().parse::<u64>().ok())
644 .unwrap_or(0);
645 (ms > 0).then(|| Duration::from_millis(ms))
646}
647
648pub fn get_fresh(
652 root: &str,
653 respect_gitignore: bool,
654 allow_secret_paths: bool,
655) -> Option<Arc<SearchIndex>> {
656 if !respect_gitignore || index_disabled() {
658 return None;
659 }
660
661 let (candidate, last_verified) = {
664 let map = cache()
665 .lock()
666 .unwrap_or_else(std::sync::PoisonError::into_inner);
667 match map.get(root) {
668 Some(entry) => match &entry.index {
669 Some(idx) if idx.config_matches(respect_gitignore, allow_secret_paths) => {
670 (Some(Arc::clone(idx)), entry.last_verified)
671 }
672 _ => (None, None),
673 },
674 None => (None, None),
675 }
676 };
677
678 let Some(idx) = candidate else {
679 request_build(root, respect_gitignore, allow_secret_paths);
681 return None;
682 };
683
684 if let Some(window) = coalesce_window()
687 && last_verified.is_some_and(|t| t.elapsed() < window)
688 {
689 return Some(idx);
690 }
691
692 match corpus_signature(root, respect_gitignore, allow_secret_paths) {
696 Some(sig) if sig == idx.signature => {
697 mark_verified(root);
698 Some(idx)
699 }
700 _ => {
701 request_build(root, respect_gitignore, allow_secret_paths);
704 None
705 }
706 }
707}
708
709pub fn clear_resident() {
715 let mut map = cache()
716 .lock()
717 .unwrap_or_else(std::sync::PoisonError::into_inner);
718 for entry in map.values_mut() {
719 entry.index = None;
720 entry.last_verified = None;
721 }
722}
723
724fn mark_verified(root: &str) {
727 let mut map = cache()
728 .lock()
729 .unwrap_or_else(std::sync::PoisonError::into_inner);
730 if let Some(entry) = map.get_mut(root) {
731 entry.last_verified = Some(Instant::now());
732 }
733}
734
735fn request_build(root: &str, respect_gitignore: bool, allow_secret_paths: bool) {
737 let needs_build = {
738 let mut map = cache()
739 .lock()
740 .unwrap_or_else(std::sync::PoisonError::into_inner);
741 let entry = map
742 .entry(root.to_string())
743 .or_insert_with(CacheEntry::empty);
744 if entry.building {
745 false
746 } else {
747 entry.building = true;
748 true
749 }
750 };
751 if needs_build {
752 spawn_build(root.to_string(), respect_gitignore, allow_secret_paths);
753 }
754}
755
756pub fn ensure_background(root: &str, respect_gitignore: bool, allow_secret_paths: bool) {
759 if !respect_gitignore || index_disabled() {
760 return;
761 }
762 let has_index = {
766 let map = cache()
767 .lock()
768 .unwrap_or_else(std::sync::PoisonError::into_inner);
769 map.get(root).is_some_and(|entry| {
770 entry
771 .index
772 .as_ref()
773 .is_some_and(|idx| idx.config_matches(respect_gitignore, allow_secret_paths))
774 })
775 };
776 if !has_index {
777 request_build(root, respect_gitignore, allow_secret_paths);
778 }
779}
780
781pub fn warm_blocking(root: &str, respect_gitignore: bool, allow_secret_paths: bool) -> bool {
785 if !respect_gitignore || index_disabled() {
786 return false;
787 }
788 let Some(idx) = SearchIndex::build(root, respect_gitignore, allow_secret_paths) else {
789 return false;
790 };
791 let mut map = cache()
792 .lock()
793 .unwrap_or_else(std::sync::PoisonError::into_inner);
794 map.insert(
795 root.to_string(),
796 CacheEntry {
797 index: Some(Arc::new(idx)),
798 building: false,
799 last_verified: Some(Instant::now()),
800 },
801 );
802 true
803}
804
805fn search_index_lock_name(root: &str) -> String {
810 format!(
811 "search-idx-{}",
812 &crate::core::index_namespace::namespace_hash(Path::new(root))[..8]
813 )
814}
815
816#[derive(Debug, Clone, Copy, PartialEq, Eq)]
819enum BuildOutcome {
820 Built,
821 Deferred,
822}
823
824fn build_guarded(root: &str, respect_gitignore: bool, allow_secret_paths: bool) -> BuildOutcome {
834 let lock = crate::core::startup_guard::try_acquire_lock(
835 &search_index_lock_name(root),
836 Duration::from_millis(200),
837 Duration::from_mins(3),
838 );
839 if lock.is_none() {
840 let mut map = cache()
843 .lock()
844 .unwrap_or_else(std::sync::PoisonError::into_inner);
845 if let Some(entry) = map.get_mut(root) {
846 entry.building = false;
847 }
848 return BuildOutcome::Deferred;
849 }
850
851 let built = std::panic::catch_unwind(|| {
852 SearchIndex::build(root, respect_gitignore, allow_secret_paths)
853 })
854 .ok()
855 .flatten();
856
857 let mut map = cache()
858 .lock()
859 .unwrap_or_else(std::sync::PoisonError::into_inner);
860 if let Some(entry) = map.get_mut(root) {
861 entry.building = false;
862 if let Some(idx) = built {
863 entry.index = Some(Arc::new(idx));
864 entry.last_verified = Some(Instant::now());
866 }
867 }
868 drop(lock);
870 BuildOutcome::Built
871}
872
873fn spawn_build(root: String, respect_gitignore: bool, allow_secret_paths: bool) {
874 std::thread::spawn(move || {
875 let _ = build_guarded(&root, respect_gitignore, allow_secret_paths);
876 });
877}
878
879#[cfg(test)]
880mod tests {
881 use super::*;
882
883 fn corpus() -> tempfile::TempDir {
884 let dir = tempfile::tempdir().unwrap();
885 std::fs::write(dir.path().join("a.rs"), "fn handler() {}\nlet x = 1;\n").unwrap();
886 std::fs::write(dir.path().join("b.rs"), "fn other() {}\n// nothing here\n").unwrap();
887 std::fs::write(dir.path().join("c.txt"), "handler appears in text too\n").unwrap();
888 dir
889 }
890
891 #[test]
892 fn build_refuses_to_index_home_directory() {
893 if let Some(home) = dirs::home_dir() {
896 assert!(
897 SearchIndex::build(&home.to_string_lossy(), true, false).is_none(),
898 "search index must never auto-build over the home directory"
899 );
900 }
901 }
902
903 #[test]
904 fn narrows_to_files_containing_literal() {
905 let dir = corpus();
906 let idx = SearchIndex::build(dir.path().to_str().unwrap(), true, false).unwrap();
907 let cands = idx.candidate_paths("handler", &[], dir.path());
908 let paths = cands.into_paths();
909 assert!(paths.iter().any(|p| p.ends_with("a.rs")));
911 assert!(paths.iter().any(|p| p.ends_with("c.txt")));
912 assert!(!paths.iter().any(|p| p.ends_with("b.rs")));
913 }
914
915 #[test]
916 fn absent_trigram_yields_empty_candidates() {
917 let dir = corpus();
918 let idx = SearchIndex::build(dir.path().to_str().unwrap(), true, false).unwrap();
919 match idx.candidate_paths("zzzqqq", &[], dir.path()) {
920 CandidateSet::Narrowed(p) => assert!(p.is_empty()),
921 CandidateSet::FullList(_) => panic!("pure literal should narrow"),
922 }
923 }
924
925 #[test]
926 fn ext_filter_restricts_candidates() {
927 let dir = corpus();
928 let idx = SearchIndex::build(dir.path().to_str().unwrap(), true, false).unwrap();
929 let paths = idx
930 .candidate_paths(
931 "handler",
932 &[glob::Pattern::new("*.rs").unwrap()],
933 dir.path(),
934 )
935 .into_paths();
936 assert!(paths.iter().all(|p| p.extension().unwrap() == "rs"));
937 assert!(paths.iter().any(|p| p.ends_with("a.rs")));
938 }
939
940 #[test]
941 #[cfg(unix)]
942 fn build_skips_named_pipe_without_hanging() {
943 use std::sync::mpsc;
944 use std::time::Duration;
945 let dir = corpus();
949 let fifo = dir.path().join("pipe.fifo");
950 let c = std::ffi::CString::new(fifo.to_string_lossy().as_bytes()).unwrap();
951 assert_eq!(
952 unsafe { libc::mkfifo(c.as_ptr(), 0o644) },
955 0,
956 "mkfifo failed"
957 );
958
959 let root = dir.path().to_str().unwrap().to_string();
960 let (tx, rx) = mpsc::channel();
961 std::thread::spawn(move || {
962 let built = SearchIndex::build(&root, true, false);
963 let _ = tx.send(built.map(|idx| {
964 idx.candidate_paths("handler", &[], std::path::Path::new(&root))
965 .into_paths()
966 }));
967 });
968 let paths = rx
969 .recv_timeout(Duration::from_secs(5))
970 .expect("SearchIndex::build hung on a FIFO (#336 regression)")
971 .expect("index should build");
972 assert!(paths.iter().any(|p| p.ends_with("a.rs")));
973 assert!(!paths.iter().any(|p| p.ends_with("pipe.fifo")));
974 }
975
976 #[test]
977 fn regex_query_falls_back_to_full_list() {
978 let dir = corpus();
979 let idx = SearchIndex::build(dir.path().to_str().unwrap(), true, false).unwrap();
980 match idx.candidate_paths("fn .*\\(\\)", &[], dir.path()) {
981 CandidateSet::FullList(p) => assert!(!p.is_empty()),
982 CandidateSet::Narrowed(_) => panic!("metachar query must not narrow"),
983 }
984 }
985
986 #[test]
987 fn short_query_falls_back_to_full_list() {
988 let dir = corpus();
989 let idx = SearchIndex::build(dir.path().to_str().unwrap(), true, false).unwrap();
990 assert!(matches!(
991 idx.candidate_paths("fn", &[], dir.path()),
992 CandidateSet::FullList(_)
993 ));
994 }
995
996 #[test]
1000 fn narrowing_has_identical_recall_to_full_scan() {
1001 use regex::Regex;
1002 use std::collections::BTreeSet;
1003
1004 let dir = tempfile::tempdir().unwrap();
1005 let samples = [
1007 (
1008 "auth/login.rs",
1009 "fn authenticate(user) {}\nlet token = mint();\n",
1010 ),
1011 (
1012 "auth/session.rs",
1013 "struct Session;\n// authenticate again here\n",
1014 ),
1015 ("db/pool.rs", "fn connect() {}\nlet retries = 3;\n"),
1016 (
1017 "ui/button.tsx",
1018 "export const Button = () => authenticate;\n",
1019 ),
1020 ("readme.md", "This project uses authenticate flows.\n"),
1021 ("unrelated.rs", "fn helper() { let v = 1; }\n"),
1022 ];
1023 for (rel, content) in samples {
1024 let p = dir.path().join(rel);
1025 std::fs::create_dir_all(p.parent().unwrap()).unwrap();
1026 std::fs::write(p, content).unwrap();
1027 }
1028 let idx = SearchIndex::build(dir.path().to_str().unwrap(), true, false).unwrap();
1029
1030 let full_scan = |pat: &str| -> BTreeSet<String> {
1031 let re = Regex::new(pat).unwrap();
1032 let mut hits = BTreeSet::new();
1033 for (rel, content) in samples {
1034 for (i, line) in content.lines().enumerate() {
1035 if re.is_match(line) {
1036 hits.insert(format!("{rel}:{}", i + 1));
1037 }
1038 }
1039 }
1040 hits
1041 };
1042
1043 for query in ["authenticate", "Session", "retries", "token"] {
1044 let re = Regex::new(query).unwrap();
1045 let candidates = idx.candidate_paths(query, &[], dir.path()).into_paths();
1046 let mut narrowed = BTreeSet::new();
1047 for path in &candidates {
1048 let content = std::fs::read_to_string(path).unwrap();
1049 let rel = path.strip_prefix(dir.path()).unwrap().to_string_lossy();
1050 for (i, line) in content.lines().enumerate() {
1051 if re.is_match(line) {
1052 narrowed.insert(format!("{}:{}", rel.replace('\\', "/"), i + 1));
1053 }
1054 }
1055 }
1056 assert_eq!(
1057 narrowed,
1058 full_scan(query),
1059 "recall mismatch for query {query:?}"
1060 );
1061 }
1062 }
1063
1064 #[test]
1065 fn intersect_sorted_basic() {
1066 assert_eq!(
1067 intersect_sorted(&[1, 2, 3, 5], &[2, 3, 4, 5]),
1068 vec![2, 3, 5]
1069 );
1070 assert_eq!(intersect_sorted(&[1, 2], &[3, 4]), Vec::<u32>::new());
1071 }
1072
1073 fn trigrams_of(s: &str) -> Vec<u32> {
1076 let mut set = HashSet::new();
1077 let b = s.as_bytes();
1078 if b.len() >= 3 {
1079 for w in b.windows(3) {
1080 if is_word_byte(w[0]) && is_word_byte(w[1]) && is_word_byte(w[2]) {
1081 set.insert(pack(w[0], w[1], w[2]));
1082 }
1083 }
1084 }
1085 let mut v: Vec<u32> = set.into_iter().collect();
1086 v.sort_unstable();
1087 v
1088 }
1089
1090 #[test]
1091 fn file_bloom_has_no_false_negatives() {
1092 let tris = trigrams_of("fn authenticate(user) { let token = mint(); }");
1093 let mut bloom = FileBloom::with_capacity(tris.len());
1094 for &t in &tris {
1095 bloom.insert(t);
1096 }
1097 assert!(tris.iter().all(|&t| bloom.maybe_contains(t)));
1099 }
1100
1101 #[test]
1105 fn bloom_tier_is_superset_of_postings_tier() {
1106 let mut seed = 0x1234_5678_9abc_def0u64;
1108 let mut rng = || {
1109 seed = seed
1110 .wrapping_mul(6364136223846793005)
1111 .wrapping_add(1442695040888963407);
1112 (seed >> 33) as u32
1113 };
1114 let mut per_file: Vec<Vec<u32>> = Vec::new();
1115 for _ in 0..80 {
1116 let n = 50 + (rng() % 250) as usize;
1117 let mut s = HashSet::new();
1118 for _ in 0..n {
1119 s.insert(rng() & 0x00FF_FFFF);
1120 }
1121 let mut v: Vec<u32> = s.into_iter().collect();
1122 v.sort_unstable();
1123 per_file.push(v);
1124 }
1125 let total: usize = per_file.iter().map(Vec::len).sum();
1126
1127 let postings = build_narrowing(&per_file, total); let blooms = build_narrowing(&per_file, MAX_POSTING_ENTRIES + 1); let (Narrowing::Postings(pt), Narrowing::Blooms(bl)) = (&postings, &blooms) else {
1130 panic!("unexpected narrowing tiers");
1131 };
1132
1133 for f in &per_file {
1136 if f.len() < 3 {
1137 continue;
1138 }
1139 let q = vec![f[0], f[f.len() / 2], f[f.len() - 1]];
1140 let exact = SearchIndex::postings_intersect(pt, &q);
1141 let bloom: HashSet<u32> = SearchIndex::bloom_scan(bl, &q).into_iter().collect();
1142 for id in exact {
1143 assert!(
1144 bloom.contains(&id),
1145 "Bloom tier dropped a true match (false negative) for {q:?}"
1146 );
1147 }
1148 }
1149 }
1150
1151 #[test]
1154 fn bloom_tier_end_to_end_recall() {
1155 let samples = [
1156 (
1157 "auth_login.rs",
1158 "fn authenticate(user) {}\nlet token = mint();\n",
1159 ),
1160 (
1161 "auth_session.rs",
1162 "struct Session;\n// authenticate again here\n",
1163 ),
1164 ("db_pool.rs", "fn connect() {}\nlet retries = 3;\n"),
1165 (
1166 "ui_button.tsx",
1167 "export const Button = () => authenticate;\n",
1168 ),
1169 ("readme.md", "This project uses authenticate flows.\n"),
1170 ("unrelated.rs", "fn helper() { let v = 1; }\n"),
1171 ];
1172 let files: Vec<PathBuf> = samples.iter().map(|(rel, _)| PathBuf::from(rel)).collect();
1173 let per_file: Vec<Vec<u32>> = samples.iter().map(|(_, c)| trigrams_of(c)).collect();
1174
1175 let idx = SearchIndex {
1176 files,
1177 narrowing: build_narrowing(&per_file, MAX_POSTING_ENTRIES + 1),
1178 respect_gitignore: true,
1179 allow_secret_paths: false,
1180 signature: 0, };
1182 assert!(
1183 matches!(idx.narrowing, Narrowing::Blooms(_)),
1184 "test must exercise the Bloom tier"
1185 );
1186
1187 for query in ["authenticate", "Session", "retries", "token"] {
1188 let cands: HashSet<String> = idx
1189 .candidate_paths(query, &[], std::path::Path::new(""))
1190 .into_paths()
1191 .iter()
1192 .map(|p| p.to_string_lossy().to_string())
1193 .collect();
1194 for (rel, content) in samples {
1195 if content.contains(query) {
1196 assert!(
1197 cands.contains(rel),
1198 "Bloom tier dropped real match {rel} for query {query:?}"
1199 );
1200 }
1201 }
1202 }
1203 }
1204
1205 struct DataDirGuard {
1208 prev: Option<String>,
1209 }
1210 impl DataDirGuard {
1211 fn set(path: &std::path::Path) -> Self {
1212 let prev = std::env::var("LEAN_CTX_DATA_DIR").ok();
1213 crate::test_env::set_var("LEAN_CTX_DATA_DIR", path);
1214 Self { prev }
1215 }
1216 }
1217 impl Drop for DataDirGuard {
1218 fn drop(&mut self) {
1219 match self.prev.as_deref() {
1220 Some(v) => crate::test_env::set_var("LEAN_CTX_DATA_DIR", v),
1221 None => crate::test_env::remove_var("LEAN_CTX_DATA_DIR"),
1222 }
1223 }
1224 }
1225
1226 #[test]
1227 fn search_index_lock_name_is_per_repo_and_distinct() {
1228 let a = search_index_lock_name("/tmp/repo-a");
1229 let b = search_index_lock_name("/tmp/repo-b");
1230 assert!(a.starts_with("search-idx-"), "unexpected lock name: {a}");
1231 assert_ne!(a, b, "lock name must be per-repo");
1232 assert_eq!(a, search_index_lock_name("/tmp/repo-a"), "stable per repo");
1233 let h = &crate::core::index_namespace::namespace_hash(Path::new("/tmp/repo-a"))[..8];
1236 assert_ne!(
1237 a,
1238 format!("graph-idx-{h}"),
1239 "must not collide with graph lock"
1240 );
1241 assert_ne!(
1242 a,
1243 format!("bm25-idx-{h}"),
1244 "must not collide with bm25 lock"
1245 );
1246 }
1247
1248 #[test]
1249 fn build_guarded_builds_when_uncontended() {
1250 let _env = crate::core::data_dir::test_env_lock();
1251 let data = tempfile::tempdir().unwrap();
1252 let _guard = DataDirGuard::set(data.path());
1253
1254 let dir = corpus();
1255 let root = dir.path().to_string_lossy().to_string();
1256 {
1258 let mut map = cache()
1259 .lock()
1260 .unwrap_or_else(std::sync::PoisonError::into_inner);
1261 map.insert(
1262 root.clone(),
1263 CacheEntry {
1264 index: None,
1265 building: true,
1266 last_verified: None,
1267 },
1268 );
1269 }
1270 assert_eq!(
1271 build_guarded(&root, true, false),
1272 BuildOutcome::Built,
1273 "an uncontended root must build"
1274 );
1275 let map = cache()
1276 .lock()
1277 .unwrap_or_else(std::sync::PoisonError::into_inner);
1278 let entry = map.get(&root).expect("entry present");
1279 assert!(!entry.building, "building flag must clear after build");
1280 assert!(entry.index.is_some(), "index must be installed after build");
1281 }
1282
1283 #[test]
1284 fn build_guarded_defers_when_another_process_holds_the_lock() {
1285 let _env = crate::core::data_dir::test_env_lock();
1286 let data = tempfile::tempdir().unwrap();
1287 let _guard = DataDirGuard::set(data.path());
1288
1289 let dir = corpus();
1290 let root = dir.path().to_string_lossy().to_string();
1291 let lock_path = data
1295 .path()
1296 .join(format!(".{}.lock", search_index_lock_name(&root)));
1297 std::fs::write(&lock_path, format!("{}\n", std::process::id())).unwrap();
1298
1299 {
1300 let mut map = cache()
1301 .lock()
1302 .unwrap_or_else(std::sync::PoisonError::into_inner);
1303 map.insert(
1304 root.clone(),
1305 CacheEntry {
1306 index: None,
1307 building: true,
1308 last_verified: None,
1309 },
1310 );
1311 }
1312 assert_eq!(
1313 build_guarded(&root, true, false),
1314 BuildOutcome::Deferred,
1315 "a contended root must defer the proactive pre-warm"
1316 );
1317 let map = cache()
1318 .lock()
1319 .unwrap_or_else(std::sync::PoisonError::into_inner);
1320 let entry = map.get(&root).expect("entry present");
1321 assert!(
1322 !entry.building,
1323 "deferred build must clear the in-flight flag so a later nudge retries"
1324 );
1325 assert!(
1326 entry.index.is_none(),
1327 "deferred build must not run a second walk / install an index"
1328 );
1329 }
1330
1331 #[test]
1332 fn corpus_signature_matches_a_freshly_built_index() {
1333 let dir = corpus();
1334 let root = dir.path().to_string_lossy().to_string();
1335 let idx = SearchIndex::build(&root, true, false).expect("index builds");
1336 let sig = corpus_signature(&root, true, false).expect("signature computes");
1337 assert_eq!(
1338 idx.signature, sig,
1339 "a freshly built index must match the live corpus signature, or it \
1340 would be treated as permanently stale and never served"
1341 );
1342 assert_eq!(sig, corpus_signature(&root, true, false).unwrap());
1344 }
1345
1346 #[test]
1347 fn corpus_signature_changes_on_edit_add_and_delete() {
1348 let dir = corpus();
1349 let root = dir.path().to_string_lossy().to_string();
1350 let base = corpus_signature(&root, true, false).unwrap();
1351
1352 std::fs::write(
1353 dir.path().join("a.rs"),
1354 "fn handler() {}\nlet x = 1;\nlet y = 2;\n",
1355 )
1356 .unwrap();
1357 let after_edit = corpus_signature(&root, true, false).unwrap();
1358 assert_ne!(
1359 base, after_edit,
1360 "an in-place edit must change the signature"
1361 );
1362
1363 std::fs::write(dir.path().join("d.rs"), "fn fresh() {}\n").unwrap();
1364 let after_add = corpus_signature(&root, true, false).unwrap();
1365 assert_ne!(
1366 after_edit, after_add,
1367 "adding a file must change the signature"
1368 );
1369
1370 std::fs::remove_file(dir.path().join("b.rs")).unwrap();
1371 let after_delete = corpus_signature(&root, true, false).unwrap();
1372 assert_ne!(
1373 after_add, after_delete,
1374 "deleting a file must change the signature"
1375 );
1376 }
1377
1378 #[test]
1379 fn get_fresh_serves_unchanged_then_refuses_after_edit() {
1380 let _env = crate::core::data_dir::test_env_lock();
1381 let data = tempfile::tempdir().unwrap();
1382 let _guard = DataDirGuard::set(data.path());
1383 crate::test_env::remove_var("LEAN_CTX_DISABLE_SEARCH_INDEX");
1384 crate::test_env::remove_var("LEAN_CTX_SEARCH_INDEX_COALESCE_MS");
1385
1386 let dir = corpus();
1387 let root = dir.path().to_string_lossy().to_string();
1388 assert!(warm_blocking(&root, true, false), "index warms");
1389
1390 assert!(
1392 get_fresh(&root, true, false).is_some(),
1393 "an unchanged corpus must serve the resident index"
1394 );
1395
1396 std::fs::write(
1399 dir.path().join("a.rs"),
1400 "fn handler() {}\nlet x = 1;\nlet z = 9;\n",
1401 )
1402 .unwrap();
1403 assert!(
1404 get_fresh(&root, true, false).is_none(),
1405 "an edited corpus must refuse the stale resident index (#624)"
1406 );
1407 }
1408}