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 policy_epoch: u64,
157}
158
159impl SearchIndex {
160 pub fn build(root: &str, respect_gitignore: bool, allow_secret_paths: bool) -> Option<Self> {
163 let mut files: Vec<PathBuf> = Vec::new();
164 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 let mut sig_sum: u64 = 0;
177 let mut file_count: usize = 0;
178 let mut aborted = false;
179 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 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 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; 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; 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 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 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 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 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 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 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 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
369fn 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 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
395pub enum CandidateSet {
397 Narrowed(Vec<PathBuf>),
399 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
411fn 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
422pub 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
479fn 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
497fn 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 if !crate::core::graph_index::is_safe_scan_root_public(root) {
530 return None;
531 }
532
533 let walker = WalkBuilder::new(root_path)
534 .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 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
579fn file_sig(path: &Path, state: Option<crate::core::content_cache::FileState>) -> u64 {
586 let mut h: u64 = 0xcbf2_9ce4_8422_2325; for &b in path.as_os_str().as_encoded_bytes() {
588 h ^= u64::from(b);
589 h = h.wrapping_mul(0x0000_0100_0000_01b3); }
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
598fn finalize_sig(sum: u64, count: usize) -> u64 {
602 sum ^ mix64(count as u64).rotate_left(32)
603}
604
605pub(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
632struct CacheEntry {
637 index: Option<Arc<SearchIndex>>,
638 building: bool,
639 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
661fn 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
668fn 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
681pub fn get_fresh(
685 root: &str,
686 respect_gitignore: bool,
687 allow_secret_paths: bool,
688) -> Option<Arc<SearchIndex>> {
689 if !respect_gitignore || index_disabled() {
691 return None;
692 }
693
694 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 request_build(root, respect_gitignore, allow_secret_paths);
714 return None;
715 };
716
717 if let Some(window) = coalesce_window()
720 && last_verified.is_some_and(|t| t.elapsed() < window)
721 {
722 return Some(idx);
723 }
724
725 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 request_build(root, respect_gitignore, allow_secret_paths);
737 None
738 }
739 }
740}
741
742pub 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
757fn 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
768fn 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
789pub fn ensure_background(root: &str, respect_gitignore: bool, allow_secret_paths: bool) {
792 if !respect_gitignore || index_disabled() {
793 return;
794 }
795 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
814pub 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
838fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
852enum BuildOutcome {
853 Built,
854 Deferred,
855}
856
857fn 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 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 entry.last_verified = Some(Instant::now());
899 }
900 }
901 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 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 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 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 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 #[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 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 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 assert!(tris.iter().all(|&t| bloom.maybe_contains(t)));
1132 }
1133
1134 #[test]
1138 fn bloom_tier_is_superset_of_postings_tier() {
1139 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); let blooms = build_narrowing(&per_file, MAX_POSTING_ENTRIES + 1); let (Narrowing::Postings(pt), Narrowing::Blooms(bl)) = (&postings, &blooms) else {
1163 panic!("unexpected narrowing tiers");
1164 };
1165
1166 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 #[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, 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 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 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 {
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 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 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 assert!(
1445 get_fresh(&root, true, false).is_some(),
1446 "an unchanged corpus must serve the resident index"
1447 );
1448
1449 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}