Skip to main content

lean_ctx/core/bm25_index/
mod.rs

1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
3use std::time::UNIX_EPOCH;
4
5use serde::{Deserialize, Serialize};
6mod build;
7mod chunking;
8pub use chunking::*;
9mod coordinator;
10pub use coordinator::{SearchIndexBuildProgress, get_or_start_build};
11#[cfg(test)]
12mod tests;
13
14pub(crate) const MAX_BM25_FILES: usize = 5000;
15const CHUNK_COUNT_WARNING: usize = 50_000;
16const ZSTD_LEVEL: i32 = 9;
17
18const DEFAULT_BM25_IGNORES: &[&str] = &[
19    "vendor/**",
20    "dist/**",
21    "build/**",
22    "public/vendor/**",
23    "public/js/**",
24    "public/css/**",
25    "public/build/**",
26    ".next/**",
27    ".nuxt/**",
28    "__pycache__/**",
29    "*.min.js",
30    "*.min.css",
31    "*.bundle.js",
32    "*.chunk.js",
33];
34
35fn max_bm25_cache_bytes() -> u64 {
36    // Single source of truth: `Config::bm25_max_cache_mb_effective` (env override
37    // › explicit config › disk-budget › generous default). Decoupled from the RAM
38    // profile so large repos persist instead of rebuilding forever (issue #249).
39    let mb = std::env::var("LEAN_CTX_BM25_MAX_CACHE_MB")
40        .ok()
41        .and_then(|v| v.parse::<u64>().ok())
42        .unwrap_or_else(|| crate::core::config::Config::load().bm25_max_cache_mb_effective());
43    mb * 1024 * 1024
44}
45
46/// Effective on-disk ceiling (bytes) for the persisted BM25 index. Single source
47/// of truth shared with `doctor` so its "oversized index" warning matches what
48/// `save`/`load` actually enforce.
49pub fn persist_ceiling_bytes() -> u64 {
50    max_bm25_cache_bytes()
51}
52
53/// Outcome of persisting a BM25 index to disk. Distinguishes a real write from a
54/// size-capped refusal so callers never mistake "refused to persist" for
55/// success (the bug behind the perpetual "index warming" report, issue #249).
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum SaveOutcome {
58    /// Written to disk. Carries the compressed (zstd) size in bytes.
59    Persisted { compressed_bytes: u64 },
60    /// Built fine but NOT written — the compressed size exceeds the disk
61    /// ceiling. The in-memory index is still usable for this process; callers
62    /// should surface the remedy (raise the cap / add ignore patterns) instead
63    /// of silently rebuilding on every call.
64    SkippedTooLarge {
65        compressed_bytes: u64,
66        limit_bytes: u64,
67    },
68}
69
70#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
71pub struct CodeChunk {
72    pub file_path: String,
73    pub symbol_name: String,
74    pub kind: ChunkKind,
75    pub start_line: usize,
76    pub end_line: usize,
77    pub content: String,
78    #[serde(default)]
79    pub tokens: Vec<String>,
80    pub token_count: usize,
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
84pub enum ChunkKind {
85    Function,
86    Struct,
87    Impl,
88    Module,
89    Class,
90    Method,
91    Other,
92    // -- External source kinds (Context Engine) --
93    Issue,
94    PullRequest,
95    WikiPage,
96    DbSchema,
97    ApiEndpoint,
98    Ticket,
99    ExternalOther,
100}
101
102#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
103pub struct IndexedFileState {
104    pub mtime_ms: u64,
105    pub size_bytes: u64,
106}
107
108impl IndexedFileState {
109    fn from_path(path: &Path) -> Option<Self> {
110        let meta = path.metadata().ok()?;
111        let size_bytes = meta.len();
112        let mtime_ms = meta
113            .modified()
114            .ok()
115            .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
116            .map(|d| d.as_millis() as u64)?;
117        Some(Self {
118            mtime_ms,
119            size_bytes,
120        })
121    }
122}
123
124#[derive(Debug, Clone, Serialize, Deserialize)]
125pub struct BM25Index {
126    pub chunks: Vec<CodeChunk>,
127    pub inverted: HashMap<String, Vec<(usize, f64)>>,
128    pub avg_doc_len: f64,
129    pub doc_count: usize,
130    pub doc_freqs: HashMap<String, usize>,
131    #[serde(default)]
132    pub files: HashMap<String, IndexedFileState>,
133    /// Content fingerprint of every directory that contained an indexed file
134    /// when this index was built, keyed by root-relative path (`""` = the root
135    /// itself). Sampling tracked *files* can never reveal a file that was never
136    /// indexed, so the fast staleness check would keep serving a partial index
137    /// forever after new files appear (#1724). Creating or removing an entry
138    /// bumps its parent directory's mtime on every filesystem we support, so
139    /// comparing this snapshot detects added/deleted files in one stat per
140    /// directory instead of a full ingest walk.
141    #[serde(default)]
142    pub dirs: HashMap<String, u64>,
143    /// True once `shrink_resident_content_to_snippet` has trimmed each chunk's
144    /// `content` down to the snippet lines. Resident-only RAM-saving state: never
145    /// persisted (`skip`) so the on-disk index keeps full content, and a reload
146    /// always starts as `false`. Guards the embedding pass against re-embedding
147    /// truncated bodies (see `ensure_embeddings`).
148    #[serde(default, skip)]
149    pub content_truncated: bool,
150}
151
152#[derive(Debug, Clone, Serialize, Deserialize)]
153pub struct SearchResult {
154    pub chunk_idx: usize,
155    pub score: f64,
156    pub file_path: String,
157    pub symbol_name: String,
158    pub kind: ChunkKind,
159    pub start_line: usize,
160    pub end_line: usize,
161    pub snippet: String,
162}
163
164const BM25_K1: f64 = 1.2;
165const BM25_B: f64 = 0.75;
166
167fn structural_query_boost(query: &str, chunk: &CodeChunk) -> f64 {
168    let raw_terms: std::collections::HashSet<String> = query
169        .split(|c: char| !(c.is_alphanumeric() || c == '_'))
170        .filter(|term| term.len() >= 3)
171        .map(str::to_ascii_lowercase)
172        .collect();
173    let path_terms: std::collections::HashSet<String> = tokenize(&chunk.file_path)
174        .into_iter()
175        .map(|term| term.to_ascii_lowercase())
176        .collect();
177
178    let mut boost = 0.0;
179    if raw_terms.contains(&chunk.symbol_name.to_ascii_lowercase()) {
180        boost += 32.0;
181    }
182    boost += raw_terms.intersection(&path_terms).count() as f64 * 8.0;
183
184    let has_identifier = query.split_whitespace().any(|term| {
185        let has_lower = term.chars().any(char::is_lowercase);
186        let has_upper = term.chars().any(char::is_uppercase);
187        (has_lower && has_upper) || term.contains('_') || term.contains('.')
188    });
189    if has_identifier {
190        let extension = std::path::Path::new(&chunk.file_path)
191            .extension()
192            .and_then(std::ffi::OsStr::to_str)
193            .unwrap_or_default()
194            .to_ascii_lowercase();
195        if matches!(extension.as_str(), "md" | "mdx" | "rst" | "txt" | "adoc") {
196            boost -= 8.0;
197        } else if !extension.is_empty() {
198            boost += 4.0;
199        }
200    }
201    boost
202}
203
204impl Default for BM25Index {
205    fn default() -> Self {
206        Self::new()
207    }
208}
209
210impl BM25Index {
211    pub fn new() -> Self {
212        Self {
213            chunks: Vec::new(),
214            inverted: HashMap::new(),
215            avg_doc_len: 0.0,
216            doc_count: 0,
217            doc_freqs: HashMap::new(),
218            files: HashMap::new(),
219            dirs: HashMap::new(),
220            content_truncated: false,
221        }
222    }
223
224    /// Approximate heap memory used by this index in bytes.
225    pub fn memory_usage_bytes(&self) -> usize {
226        let chunks_size: usize = self
227            .chunks
228            .iter()
229            .map(|c| {
230                c.content.len()
231                    + c.file_path.len()
232                    + c.symbol_name.len()
233                    + c.tokens.iter().map(String::len).sum::<usize>()
234                    + 64
235            })
236            .sum();
237        let inverted_size: usize = self
238            .inverted
239            .iter()
240            .map(|(k, v)| k.len() + v.len() * 16 + 32)
241            .sum();
242        let files_size: usize = self.files.keys().map(|k| k.len() + 24).sum();
243        let dirs_size: usize = self.dirs.keys().map(|k| k.len() + 16).sum();
244        let freqs_size: usize = self.doc_freqs.keys().map(|k| k.len() + 16).sum();
245        chunks_size + inverted_size + files_size + dirs_size + freqs_size
246    }
247
248    /// Drops all in-memory data, effectively freeing heap. Index can be re-loaded from disk.
249    pub fn unload(&mut self) {
250        let usage = self.memory_usage_bytes();
251        self.chunks = Vec::new();
252        self.inverted = HashMap::new();
253        self.doc_freqs = HashMap::new();
254        self.files = HashMap::new();
255        self.dirs = HashMap::new();
256        self.avg_doc_len = 0.0;
257        self.doc_count = 0;
258        tracing::info!(
259            "[bm25] unloaded index, freed ~{:.1}MB",
260            usage as f64 / 1_048_576.0
261        );
262    }
263
264    /// Shrinks each resident chunk's `content` to its first `keep_lines` lines,
265    /// reclaiming the RAM held by the full source bodies once the embedding pass
266    /// has already consumed them. The search path only ever reads
267    /// `content.lines().take(5)` for snippets, so the trimmed copy is functionally
268    /// complete for BM25/dense/hybrid result rendering.
269    ///
270    /// Further shrinks resident content (chunks are already truncated to 10 lines
271    /// during `add_chunk`; this method can tighten that further). Sets
272    /// `content_truncated` so a later `ensure_embeddings` against this same
273    /// resident index skips re-embedding (which would otherwise feed truncated
274    /// bodies to the embedder).
275    ///
276    /// Idempotent and only ever shrinks: chunks shorter than `keep_lines` are
277    /// left untouched.
278    pub fn shrink_resident_content_to_snippet(&mut self, keep_lines: usize) {
279        let before = self.memory_usage_bytes();
280        for chunk in &mut self.chunks {
281            // Cheap line-count gate: only allocate a new string when the body is
282            // actually longer than the snippet window.
283            if chunk.content.lines().nth(keep_lines).is_some() {
284                let trimmed: String = chunk
285                    .content
286                    .lines()
287                    .take(keep_lines)
288                    .collect::<Vec<_>>()
289                    .join("\n");
290                chunk.content = trimmed;
291                // Reclaim the spare capacity left by the larger original body.
292                chunk.content.shrink_to_fit();
293            }
294        }
295        self.content_truncated = true;
296        let after = self.memory_usage_bytes();
297        tracing::debug!(
298            "[bm25] shrank resident content to {keep_lines} lines/chunk, freed ~{:.1}MB",
299            before.saturating_sub(after) as f64 / 1_048_576.0
300        );
301    }
302
303    /// Builds an index from explicit chunks (unit tests; avoids filesystem walking).
304    #[cfg(test)]
305    pub(crate) fn from_chunks_for_test(chunks: Vec<CodeChunk>) -> Self {
306        let mut index = Self::new();
307        for mut chunk in chunks {
308            if chunk.token_count == 0 {
309                chunk.token_count = tokenize(&chunk.content).len();
310            }
311            index.add_chunk(chunk);
312        }
313        index.finalize();
314        index
315    }
316
317    pub fn build_from_directory(root: &Path) -> Self {
318        Self::build_from_directory_inner(root, &HashMap::new())
319    }
320
321    /// Like `build_from_directory` but reuses file content from a prior scan
322    /// (e.g. the graph index walk) to avoid redundant disk reads.
323    pub fn build_with_content_hint(root: &Path, content_hint: &HashMap<String, String>) -> Self {
324        Self::build_from_directory_inner(root, content_hint)
325    }
326
327    fn build_from_directory_inner(root: &Path, content_hint: &HashMap<String, String>) -> Self {
328        let root_str = root.to_string_lossy();
329        if !super::graph_index::is_safe_scan_root_public(&root_str) {
330            tracing::warn!("[bm25: scan aborted for unsafe root {root_str}]");
331            return Self::new();
332        }
333        let files = list_code_files(root);
334        // Snapshot directory mtimes *before* the (slow) chunking pass: a file
335        // that lands while we build then leaves its directory newer than the
336        // snapshot, so the next staleness check sees it instead of silently
337        // pinning the partial tree (#1724).
338        let dirs = dir_states(root, &files);
339
340        // #933: parallel fast path for the common case. The per-file parse +
341        // tokenize work is pure and thread-safe, so we fan it across a rayon pool
342        // and merge sequentially in file order — measured 2.85 s → 0.69 s (~4x) on
343        // the lean-ctx repo. Under memory pressure (or for tiny corpora, where pool
344        // setup is not worth it) we fall back to the sequential build, which carries
345        // the incremental early-break. #685 adds admission control: a corpus whose
346        // estimated peak would blow past the guardian's hard threshold degrades to
347        // the sequential build up front instead of OOMing mid-fan-out. Both paths
348        // produce an identical index (see `build` module + determinism tests).
349        if files.len() >= build::PARALLEL_MIN_FILES
350            && !crate::core::memory_guard::is_under_pressure()
351            && !crate::core::memory_guard::abort_requested()
352            && crate::core::index_admission::admit_files(
353                crate::core::index_admission::BuildKind::Bm25,
354                root,
355                &files,
356            )
357            .parallel_ok
358        {
359            let mut index = Self::build_parallel(root, content_hint, &files);
360            index.dirs = dirs;
361            return index;
362        }
363        let mut index = Self::build_sequential(root, content_hint, &files);
364        index.dirs = dirs;
365        index
366    }
367
368    /// Group a previous index's chunks by file, each file's list sorted by
369    /// (start_line, end_line, symbol_name) — the deterministic reuse order shared
370    /// by both incremental rebuild paths (and the equivalence test, so it feeds
371    /// them identical inputs).
372    fn group_prev_chunks_by_file(prev: &BM25Index) -> HashMap<String, Vec<CodeChunk>> {
373        let mut old_by_file: HashMap<String, Vec<CodeChunk>> = HashMap::new();
374        for c in &prev.chunks {
375            old_by_file
376                .entry(c.file_path.clone())
377                .or_default()
378                .push(c.clone());
379        }
380        for v in old_by_file.values_mut() {
381            v.sort_by(|a, b| {
382                a.start_line
383                    .cmp(&b.start_line)
384                    .then_with(|| a.end_line.cmp(&b.end_line))
385                    .then_with(|| a.symbol_name.cmp(&b.symbol_name))
386            });
387        }
388        old_by_file
389    }
390
391    pub fn rebuild_incremental(root: &Path, prev: &BM25Index) -> Self {
392        let old_by_file = Self::group_prev_chunks_by_file(prev);
393        let files = list_code_files(root);
394        let dirs = dir_states(root, &files);
395
396        // #581: mirror `build()`'s dispatch. The edit loop is the hottest path in
397        // daily use, and its serial cost is dominated by re-tokenizing the *many
398        // unchanged* files' reused chunks — not the few changed ones. So the
399        // parallel path fans the entire tokenization (changed files via
400        // `prepare_file`, unchanged via re-`prepare_chunk`) across the rayon pool
401        // and merges sequentially in file order. The sequential path keeps the
402        // per-file memory-pressure early-break and serves small corpora / pressure.
403        // #685: oversized corpora degrade to sequential via admission control.
404        // Both produce an identical index (see determinism tests).
405        if files.len() >= build::PARALLEL_MIN_FILES
406            && !crate::core::memory_guard::is_under_pressure()
407            && !crate::core::memory_guard::abort_requested()
408            && crate::core::index_admission::admit_files(
409                crate::core::index_admission::BuildKind::Bm25,
410                root,
411                &files,
412            )
413            .parallel_ok
414        {
415            let mut index = Self::rebuild_incremental_parallel(root, prev, &old_by_file, &files);
416            index.dirs = dirs;
417            return index;
418        }
419        let mut index = Self::rebuild_incremental_sequential(root, prev, &old_by_file, &files);
420        index.dirs = dirs;
421        index
422    }
423
424    /// Sequential incremental rebuild with per-file memory-pressure guards. Reuses
425    /// unchanged files' chunks and re-extracts changed ones. Used for small
426    /// corpora and as the safe fallback under memory pressure.
427    pub(crate) fn rebuild_incremental_sequential(
428        root: &Path,
429        prev: &BM25Index,
430        old_by_file: &HashMap<String, Vec<CodeChunk>>,
431        files: &[String],
432    ) -> Self {
433        let mut index = Self::new();
434        const MAX_FILE_SIZE_BYTES: u64 = 2 * 1024 * 1024;
435        let root_key = root.to_string_lossy().to_string();
436        let total = files.len() as u64;
437        crate::core::index_progress::report_bm25(&root_key, 0, total);
438
439        for (i, rel) in files.iter().enumerate() {
440            if i.is_multiple_of(16) || i + 1 == files.len() {
441                crate::core::index_progress::report_bm25(&root_key, (i + 1) as u64, total);
442            }
443            if i.is_multiple_of(500) && crate::core::memory_guard::is_under_pressure() {
444                tracing::warn!(
445                    "[bm25: stopping incremental rebuild at file {i}/{} due to memory pressure]",
446                    files.len()
447                );
448                break;
449            }
450
451            let abs = root.join(rel);
452            let Some(state) = IndexedFileState::from_path(&abs) else {
453                continue;
454            };
455
456            let unchanged = prev.files.get(rel).is_some_and(|old| *old == state);
457            if unchanged
458                && let Some(chunks) = old_by_file.get(rel)
459                && chunks.first().is_some_and(|c| !c.content.is_empty())
460            {
461                for chunk in chunks {
462                    index.add_chunk(chunk.clone());
463                }
464                index.files.insert(rel.clone(), state);
465                continue;
466            }
467
468            if state.size_bytes > MAX_FILE_SIZE_BYTES {
469                continue;
470            }
471            let content = if crate::core::extractors::is_binary_document(&abs) {
472                match std::fs::read(&abs) {
473                    Ok(bytes) => crate::core::extractors::extract(&abs, &bytes).text,
474                    Err(_) => continue,
475                }
476            } else {
477                match std::fs::read_to_string(&abs) {
478                    Ok(c) => c,
479                    Err(_) => continue,
480                }
481            };
482            if content.is_empty() {
483                continue;
484            }
485            // #1739: see `build::prepare_file` — same predicate, same position.
486            if looks_minified(&content) {
487                tracing::debug!("[bm25: skipping minified payload {rel}]");
488                continue;
489            }
490            let mut chunks = extract_chunks(rel, &content);
491            chunks.sort_by(|a, b| {
492                a.start_line
493                    .cmp(&b.start_line)
494                    .then_with(|| a.end_line.cmp(&b.end_line))
495                    .then_with(|| a.symbol_name.cmp(&b.symbol_name))
496            });
497            for chunk in chunks {
498                index.add_chunk(chunk);
499            }
500            index.files.insert(rel.clone(), state);
501        }
502
503        index.finalize();
504        index
505    }
506
507    fn add_chunk(&mut self, mut chunk: CodeChunk) {
508        let idx = self.chunks.len();
509
510        let enriched = enrich_for_bm25(&chunk);
511        let tokens = tokenize(&enriched);
512        for token in &tokens {
513            let lower = token.to_lowercase();
514            let postings = self.inverted.entry(lower.clone()).or_default();
515            if postings.last().map(|(last_idx, _)| *last_idx) != Some(idx) {
516                *self.doc_freqs.entry(lower).or_insert(0) += 1;
517            }
518            postings.push((idx, 1.0));
519        }
520
521        // #790: truncate content to snippet AFTER tokenization — full text was
522        // used for BM25 scoring above; stored content is only for result display.
523        const SNIPPET_LINES: usize = 10;
524        if chunk.content.lines().nth(SNIPPET_LINES).is_some() {
525            chunk.content = chunk
526                .content
527                .lines()
528                .take(SNIPPET_LINES)
529                .collect::<Vec<_>>()
530                .join("\n");
531            chunk.content.shrink_to_fit();
532        }
533
534        self.chunks.push(CodeChunk {
535            token_count: tokens.len(),
536            tokens: Vec::new(),
537            ..chunk
538        });
539    }
540
541    fn finalize(&mut self) {
542        self.doc_count = self.chunks.len();
543        if self.doc_count == 0 {
544            return;
545        }
546
547        let total_len: usize = self.chunks.iter().map(|c| c.token_count).sum();
548        self.avg_doc_len = total_len as f64 / self.doc_count as f64;
549    }
550
551    pub fn search(&self, query: &str, top_k: usize) -> Vec<SearchResult> {
552        let query_tokens = tokenize(query);
553        if query_tokens.is_empty() || self.doc_count == 0 {
554            return Vec::new();
555        }
556
557        // Pre-allocated score array: O(1) per-access vs HashMap overhead.
558        // Kolmogorov-optimal: minimal allocation for the scoring operation.
559        let n = self.chunks.len();
560        let mut scores = vec![0.0f64; n];
561        let mut touched = Vec::with_capacity(n.min(256));
562
563        for token in &query_tokens {
564            let lower = token.to_lowercase();
565            let df = *self.doc_freqs.get(&lower).unwrap_or(&0) as f64;
566            if df == 0.0 {
567                continue;
568            }
569
570            let idf = ((self.doc_count as f64 - df + 0.5) / (df + 0.5) + 1.0).ln();
571
572            if let Some(postings) = self.inverted.get(&lower) {
573                for &(idx, weight) in postings {
574                    let doc_len = self.chunks[idx].token_count as f64;
575                    let norm_len = doc_len / self.avg_doc_len.max(1.0);
576                    let bm25 = idf * (weight * (BM25_K1 + 1.0))
577                        / (weight + BM25_K1 * (1.0 - BM25_B + BM25_B * norm_len));
578
579                    if scores[idx] == 0.0 {
580                        touched.push(idx);
581                    }
582                    scores[idx] += bm25;
583                }
584            }
585        }
586
587        for &idx in &touched {
588            scores[idx] += structural_query_boost(query, &self.chunks[idx]);
589        }
590
591        let mut results: Vec<SearchResult> = touched
592            .iter()
593            .filter(|&&idx| scores[idx] > 0.0)
594            .map(|&idx| {
595                let chunk = &self.chunks[idx];
596                let snippet = chunk.content.lines().take(5).collect::<Vec<_>>().join("\n");
597                SearchResult {
598                    chunk_idx: idx,
599                    score: scores[idx],
600                    file_path: chunk.file_path.clone(),
601                    symbol_name: chunk.symbol_name.clone(),
602                    kind: chunk.kind.clone(),
603                    start_line: chunk.start_line,
604                    end_line: chunk.end_line,
605                    snippet,
606                }
607            })
608            .collect();
609
610        results.sort_by(|a, b| {
611            b.score
612                .partial_cmp(&a.score)
613                .unwrap_or(std::cmp::Ordering::Equal)
614                .then_with(|| a.file_path.cmp(&b.file_path))
615                .then_with(|| a.symbol_name.cmp(&b.symbol_name))
616                .then_with(|| a.start_line.cmp(&b.start_line))
617                .then_with(|| a.end_line.cmp(&b.end_line))
618        });
619        results.truncate(top_k);
620        results
621    }
622
623    pub fn save(&self, root: &Path) -> std::io::Result<SaveOutcome> {
624        if self.chunks.len() > CHUNK_COUNT_WARNING {
625            tracing::warn!(
626                "[bm25] index has {} chunks (threshold {}), consider adding extra_ignore_patterns",
627                self.chunks.len(),
628                CHUNK_COUNT_WARNING
629            );
630        }
631
632        let dir = index_dir(root);
633        std::fs::create_dir_all(&dir)?;
634
635        // #790: stream postcard → zstd → file to avoid holding the full
636        // serialized buffer in memory. Temp-file + rename for atomicity.
637        let target = dir.join("bm25_index.bin.zst");
638        let tmp = dir.join("bm25_index.bin.zst.tmp");
639        {
640            let file = std::fs::File::create(&tmp)?;
641            let buf_writer = std::io::BufWriter::new(file);
642            let mut encoder = zstd::Encoder::new(buf_writer, ZSTD_LEVEL)
643                .map_err(|e| std::io::Error::other(format!("zstd encoder init: {e}")))?;
644            postcard::to_io(self, &mut encoder)
645                .map_err(|e| std::io::Error::other(e.to_string()))?;
646            encoder.finish()?;
647        }
648
649        let compressed_bytes = std::fs::metadata(&tmp)?.len();
650        let max_bytes = max_bm25_cache_bytes();
651        if compressed_bytes > max_bytes {
652            let _ = std::fs::remove_file(&tmp);
653            tracing::warn!(
654                "[bm25] compressed index too large ({:.1} MB, limit {:.0} MB), refusing to persist: {}",
655                compressed_bytes as f64 / 1_048_576.0,
656                max_bytes / (1024 * 1024),
657                dir.display()
658            );
659            return Ok(SaveOutcome::SkippedTooLarge {
660                compressed_bytes,
661                limit_bytes: max_bytes,
662            });
663        }
664
665        tracing::info!(
666            "[bm25] index: {:.1} MB zstd compressed",
667            compressed_bytes as f64 / 1_048_576.0,
668        );
669
670        std::fs::rename(&tmp, &target)?;
671
672        let _ = std::fs::remove_file(dir.join("bm25_index.bin"));
673        let _ = std::fs::remove_file(dir.join("bm25_index.json"));
674
675        let _ = std::fs::write(
676            dir.join("project_root.txt"),
677            root.to_string_lossy().as_bytes(),
678        );
679
680        Ok(SaveOutcome::Persisted { compressed_bytes })
681    }
682
683    pub fn load(root: &Path) -> Option<Self> {
684        let dir = index_dir(root);
685        let max_bytes = max_bm25_cache_bytes();
686
687        let zst_path = dir.join("bm25_index.bin.zst");
688        if zst_path.exists() {
689            let meta = std::fs::metadata(&zst_path).ok()?;
690            if meta.len() > max_bytes {
691                tracing::warn!(
692                    "[bm25] compressed index too large ({:.1} GB, limit {:.0} MB), quarantining: {}",
693                    meta.len() as f64 / 1_073_741_824.0,
694                    max_bytes / (1024 * 1024),
695                    zst_path.display()
696                );
697                let quarantined = zst_path.with_extension("zst.quarantined");
698                let _ = std::fs::rename(&zst_path, &quarantined);
699                return None;
700            }
701            let compressed = std::fs::read(&zst_path).ok()?;
702            let max_decompressed = max_decompressed_bytes(meta.len());
703            let data = bounded_zstd_decode(&compressed, max_decompressed)?;
704            let idx: Self = postcard::from_bytes(&data).ok()?;
705            return Some(idx);
706        }
707
708        let bin_path = dir.join("bm25_index.bin");
709        if bin_path.exists() {
710            let meta = std::fs::metadata(&bin_path).ok()?;
711            if meta.len() > max_bytes {
712                tracing::warn!(
713                    "[bm25] index too large ({:.1} GB, limit {:.0} MB), quarantining: {}",
714                    meta.len() as f64 / 1_073_741_824.0,
715                    max_bytes / (1024 * 1024),
716                    bin_path.display()
717                );
718                let quarantined = bin_path.with_extension("bin.quarantined");
719                let _ = std::fs::rename(&bin_path, &quarantined);
720                return None;
721            }
722            let data = std::fs::read(&bin_path).ok()?;
723            let idx: Self = postcard::from_bytes(&data).ok()?;
724            // Auto-migrate: compress legacy .bin to .bin.zst
725            if let Ok(compressed) = zstd::encode_all(data.as_slice(), ZSTD_LEVEL) {
726                let zst_tmp = zst_path.with_extension("zst.tmp");
727                if std::fs::write(&zst_tmp, &compressed).is_ok()
728                    && std::fs::rename(&zst_tmp, &zst_path).is_ok()
729                {
730                    tracing::info!(
731                        "[bm25] migrated {:.1} MB → {:.1} MB zstd",
732                        data.len() as f64 / 1_048_576.0,
733                        compressed.len() as f64 / 1_048_576.0
734                    );
735                    let _ = std::fs::remove_file(&bin_path);
736                }
737            }
738            return Some(idx);
739        }
740
741        let json_path = dir.join("bm25_index.json");
742        if json_path.exists() {
743            let meta = std::fs::metadata(&json_path).ok()?;
744            if meta.len() > max_bytes {
745                tracing::warn!(
746                    "[bm25] index too large ({:.1} GB, limit {:.0} MB), quarantining: {}",
747                    meta.len() as f64 / 1_073_741_824.0,
748                    max_bytes / (1024 * 1024),
749                    json_path.display()
750                );
751                let quarantined = json_path.with_extension("json.quarantined");
752                let _ = std::fs::rename(&json_path, &quarantined);
753                return None;
754            }
755            let data = std::fs::read_to_string(&json_path).ok()?;
756            return serde_json::from_str(&data).ok();
757        }
758
759        None
760    }
761
762    pub fn load_or_build(root: &Path) -> Self {
763        Self::load_or_build_inner(root, false)
764    }
765
766    /// Like `load_or_build` but uses a fast sentinel-sampling staleness check
767    /// that skips the expensive full directory walk for new-file detection.
768    pub fn load_or_build_fast(root: &Path) -> Self {
769        Self::load_or_build_inner(root, true)
770    }
771
772    fn load_or_build_inner(root: &Path, fast_stale: bool) -> Self {
773        if !is_safe_bm25_root(root) {
774            return Self::default();
775        }
776        if let Some(idx) = Self::load(root) {
777            let stale = if fast_stale {
778                bm25_index_looks_stale_fast(&idx, root)
779            } else {
780                bm25_index_looks_stale(&idx, root)
781            };
782            if !stale {
783                return idx;
784            }
785            tracing::debug!(
786                "[bm25_index: stale index detected for {}; rebuilding]",
787                root.display()
788            );
789            let rebuilt = if idx.files.is_empty() {
790                Self::build_from_directory(root)
791            } else {
792                Self::rebuild_incremental(root, &idx)
793            };
794            let _ = rebuilt.save(root);
795            return rebuilt;
796        }
797
798        let built = Self::build_from_directory(root);
799        let _ = built.save(root);
800        built
801    }
802
803    pub fn index_file_path(root: &Path) -> PathBuf {
804        let dir = index_dir(root);
805        let zst = dir.join("bm25_index.bin.zst");
806        if zst.exists() {
807            return zst;
808        }
809        let bin = dir.join("bm25_index.bin");
810        if bin.exists() {
811            return bin;
812        }
813        dir.join("bm25_index.json")
814    }
815
816    /// Ingest external `ContentChunk`s into the BM25 index.
817    /// Converts each chunk to a `CodeChunk` (backward-compatible) and
818    /// rebuilds the inverted index. Returns the number of chunks ingested.
819    pub fn ingest_content_chunks(
820        &mut self,
821        chunks: impl IntoIterator<Item = super::content_chunk::ContentChunk>,
822    ) -> usize {
823        let mut count = 0usize;
824        for cc in chunks {
825            self.add_chunk(cc.into());
826            count += 1;
827        }
828        if count > 0 {
829            self.finalize();
830        }
831        count
832    }
833
834    /// Number of chunks originating from external providers.
835    pub fn external_chunk_count(&self) -> usize {
836        self.chunks
837            .iter()
838            .filter(|c| c.file_path.contains("://"))
839            .count()
840    }
841
842    /// Remove every chunk whose `file_path` starts with `prefix` (e.g.
843    /// `health://`) and rebuild the inverted index. Lets a recomputed source
844    /// (like the code-health fabric) evict its prior pass so stale entries never
845    /// linger in search. Returns the number of chunks removed.
846    pub fn remove_chunks_with_prefix(&mut self, prefix: &str) -> usize {
847        let before = self.chunks.len();
848        self.chunks.retain(|c| !c.file_path.starts_with(prefix));
849        let removed = before - self.chunks.len();
850        if removed > 0 {
851            self.finalize();
852        }
853        removed
854    }
855}
856
857fn is_safe_bm25_root(root: &Path) -> bool {
858    super::graph_index::is_safe_scan_root_public(&root.to_string_lossy())
859}
860
861fn bm25_index_looks_stale(index: &BM25Index, root: &Path) -> bool {
862    bm25_index_looks_stale_inner(index, root, false)
863}
864
865/// Fast staleness check: samples a subset of tracked files and skips the
866/// expensive `list_code_files()` walk for new-file detection.
867pub fn bm25_index_looks_stale_fast(index: &BM25Index, root: &Path) -> bool {
868    bm25_index_looks_stale_inner(index, root, true)
869}
870
871fn bm25_index_looks_stale_inner(index: &BM25Index, root: &Path, fast: bool) -> bool {
872    if index.chunks.is_empty() {
873        return false;
874    }
875
876    if index.files.is_empty() {
877        let mut seen = std::collections::HashSet::<&str>::new();
878        for chunk in &index.chunks {
879            let rel = chunk.file_path.trim_start_matches(['/', '\\']);
880            if rel.is_empty() {
881                continue;
882            }
883            if !seen.insert(rel) {
884                continue;
885            }
886            if !root.join(rel).exists() {
887                return true;
888            }
889        }
890        return false;
891    }
892
893    if fast {
894        let sample_size = index.files.len().min(SENTINEL_SAMPLE_SIZE);
895        let step = if index.files.len() > sample_size {
896            index.files.len() / sample_size
897        } else {
898            1
899        };
900        for (i, (rel, old_state)) in index.files.iter().enumerate() {
901            if i % step != 0 {
902                continue;
903            }
904            let abs = root.join(rel);
905            if !abs.exists() {
906                return true;
907            }
908            let Some(cur) = IndexedFileState::from_path(&abs) else {
909                return true;
910            };
911            if &cur != old_state {
912                return true;
913            }
914        }
915        // Sampling tracked files says nothing about files that were never
916        // indexed, so without this the fast path serves a partial tree forever
917        // (#1724). The directory snapshot closes that hole for one stat per
918        // indexed directory.
919        return dirs_look_stale(index, root);
920    }
921
922    for (rel, old_state) in &index.files {
923        let abs = root.join(rel);
924        if !abs.exists() {
925            return true;
926        }
927        let Some(cur) = IndexedFileState::from_path(&abs) else {
928            return true;
929        };
930        if &cur != old_state {
931            return true;
932        }
933    }
934
935    for rel in list_code_files(root) {
936        if !index.files.contains_key(&rel) {
937            return true;
938        }
939    }
940
941    false
942}
943
944const SENTINEL_SAMPLE_SIZE: usize = 10;
945
946/// True when recorded directory fingerprints no longer match the filesystem —
947/// i.e. a file was added to (or removed from) the indexed tree.
948///
949/// An index persisted before directory snapshots existed carries no `dirs`, so
950/// its freshness cannot be proven cheaply: it is reported stale exactly once,
951/// and the resulting rebuild records the snapshot for every later call.
952fn dirs_look_stale(index: &BM25Index, root: &Path) -> bool {
953    if index.dirs.is_empty() {
954        return true;
955    }
956    for (rel, recorded) in &index.dirs {
957        let abs = if rel.is_empty() {
958            root.to_path_buf()
959        } else {
960            root.join(rel)
961        };
962        if dir_fingerprint(&abs) != Some(*recorded) {
963            return true;
964        }
965    }
966    false
967}
968
969fn dir_fingerprint(path: &Path) -> Option<u64> {
970    use std::hash::{Hash, Hasher};
971
972    let meta = std::fs::metadata(path).ok()?;
973    let modified = meta.modified().ok()?.duration_since(UNIX_EPOCH).ok()?;
974    let mut entries = std::fs::read_dir(path)
975        .ok()?
976        .filter_map(Result::ok)
977        .map(|entry| entry.file_name().to_string_lossy().into_owned())
978        .collect::<Vec<_>>();
979    entries.sort_unstable();
980    let mut hasher = std::collections::hash_map::DefaultHasher::new();
981    modified.as_nanos().hash(&mut hasher);
982    entries.hash(&mut hasher);
983    Some(hasher.finish())
984}
985
986/// Content snapshot of the root plus every ancestor directory of an indexed file.
987/// Ancestors are included so a brand-new top-level directory (whose own mtime
988/// was never recorded) is still caught through its recorded parent.
989fn dir_states(root: &Path, files: &[String]) -> HashMap<String, u64> {
990    let mut rels: std::collections::HashSet<String> = std::collections::HashSet::new();
991    rels.insert(String::new());
992    for rel in files {
993        let mut cur = Path::new(rel);
994        while let Some(parent) = cur.parent() {
995            let key = parent.to_string_lossy().to_string();
996            // Once a directory is known, so are all of its ancestors.
997            if !rels.insert(key) {
998                break;
999            }
1000            cur = parent;
1001        }
1002    }
1003    rels.into_iter()
1004        .filter_map(|rel| {
1005            let abs = if rel.is_empty() {
1006                root.to_path_buf()
1007            } else {
1008                root.join(&rel)
1009            };
1010            dir_fingerprint(&abs).map(|fingerprint| (rel, fingerprint))
1011        })
1012        .collect()
1013}
1014
1015/// Streams the persisted index out, refusing anything past `max_bytes`.
1016///
1017/// The buffer never grows beyond `max_bytes`, so the ceiling passed in *is* the
1018/// worst-case allocation — which is why #1739 hinged on that ceiling being a
1019/// sane number rather than on this loop. Our own writer streams postcard into
1020/// the encoder (#790) and so never records a frame content size, which rules
1021/// out a cheap header pre-check.
1022fn bounded_zstd_decode(compressed: &[u8], max_bytes: u64) -> Option<Vec<u8>> {
1023    use std::io::Read;
1024    let mut decoder = zstd::Decoder::new(compressed).ok()?;
1025    let mut buf = Vec::new();
1026    let mut chunk = vec![0u8; 65536];
1027    let mut total = 0u64;
1028    loop {
1029        let n = decoder.read(&mut chunk).ok()?;
1030        if n == 0 {
1031            break;
1032        }
1033        total += n as u64;
1034        if total > max_bytes {
1035            tracing::warn!(
1036                "[bm25] decompressed index exceeds limit ({:.0} MB > {:.0} MB), aborting load",
1037                total as f64 / (1024.0 * 1024.0),
1038                max_bytes as f64 / (1024.0 * 1024.0)
1039            );
1040            return None;
1041        }
1042        buf.extend_from_slice(&chunk[..n]);
1043    }
1044    Some(buf)
1045}
1046
1047/// Worst-case RAM this process will spend decompressing a persisted index.
1048///
1049/// #1739: this was `max_bm25_cache_bytes() * 20` — twenty times a **disk**
1050/// budget, with no reference to the file at hand or to the machine's memory. On
1051/// the default 512 MB disk budget that authorised a 10 GB allocation for any
1052/// index, however small the file; because `ctx_search` reloads on demand,
1053/// repeated calls stacked to 20 GB RSS and froze the host.
1054///
1055/// The index is decompressed into RAM, so RAM is what has to bound it, and a
1056/// given file cannot plausibly expand past a fixed ratio of its own size.
1057fn max_decompressed_bytes(compressed_bytes: u64) -> u64 {
1058    /// postcard + zstd on an index this shape expands well under this.
1059    const MAX_EXPANSION_RATIO: u64 = 20;
1060    /// Keeps small indices loadable on hosts that report little or no RAM.
1061    const FLOOR: u64 = 64 * 1024 * 1024;
1062
1063    let file_derived = compressed_bytes
1064        .saturating_mul(MAX_EXPANSION_RATIO)
1065        .max(FLOOR);
1066    match crate::core::memory_guard::rss_limit_bytes() {
1067        Some(limit) => file_derived.min(limit.max(FLOOR)),
1068        None => file_derived,
1069    }
1070}
1071
1072fn index_dir(root: &Path) -> PathBuf {
1073    crate::core::index_namespace::vectors_dir(root)
1074}
1075
1076fn list_code_files(root: &Path) -> Vec<String> {
1077    let cfg = crate::core::config::Config::load();
1078    // #735: the declared corpus filter ([index] config + CLI overlay) decides
1079    // membership before anything is chunked; the semantic index chunks this
1080    // corpus, so it inherits the same universe.
1081    let filter = crate::core::index_filter::IndexFileFilter::resolve(&cfg);
1082
1083    let walker = ignore::WalkBuilder::new(root)
1084        // #1792: the BM25 corpus is authoritative for `ctx_compose`/`ctx_overview`,
1085        // so omitting tracked dotfiles made "no match" indistinguishable from
1086        // "not indexed".
1087        .hidden(crate::core::walk_filter::SKIP_HIDDEN_IN_CONTENT_WALK)
1088        .git_ignore(filter.respect_gitignore)
1089        .git_global(filter.respect_gitignore)
1090        .git_exclude(filter.respect_gitignore)
1091        .require_git(false)
1092        .max_depth(Some(20))
1093        .filter_entry(crate::core::walk_filter::keep_entry)
1094        .build();
1095
1096    let mut ignore_patterns: Vec<glob::Pattern> = DEFAULT_BM25_IGNORES
1097        .iter()
1098        .filter_map(|p| glob::Pattern::new(p).ok())
1099        .collect();
1100    ignore_patterns.extend(
1101        cfg.extra_ignore_patterns
1102            .iter()
1103            .filter_map(|p| glob::Pattern::new(p).ok()),
1104    );
1105
1106    let mut files: Vec<String> = Vec::new();
1107    let mut filtered_out = 0usize;
1108    // Mirrors graph_index_max_files: 0 = unlimited, default 5000 (MAX_BM25_FILES).
1109    let max_files = if cfg.bm25_max_files == 0 {
1110        usize::MAX
1111    } else {
1112        cfg.bm25_max_files as usize
1113    };
1114    for entry in walker.flatten() {
1115        let path = entry.path();
1116        if !path.is_file() {
1117            continue;
1118        }
1119        if !crate::core::ingestion::is_ingestible(path) {
1120            continue;
1121        }
1122        let rel = path
1123            .strip_prefix(root)
1124            .unwrap_or(path)
1125            .to_string_lossy()
1126            .to_string();
1127        if rel.is_empty() {
1128            continue;
1129        }
1130        if ignore_patterns.iter().any(|p| p.matches(&rel)) {
1131            continue;
1132        }
1133        // Match on forward slashes so globs behave identically on Windows;
1134        // the index key keeps the platform separator (existing indexes stay
1135        // valid).
1136        if filter.is_excluded(&rel.replace('\\', "/")) {
1137            filtered_out += 1;
1138            continue;
1139        }
1140        if files.len() >= max_files {
1141            tracing::warn!(
1142                "[bm25] file cap reached ({max_files}), skipping remaining files in {}. \
1143                 Set bm25_max_files in config (0 = unlimited) to index more.",
1144                root.display()
1145            );
1146            break;
1147        }
1148        files.push(rel);
1149    }
1150
1151    if filtered_out > 0 {
1152        tracing::info!(
1153            "[bm25] index filter excluded {filtered_out} files ({})",
1154            filter.summary().unwrap_or_default()
1155        );
1156    }
1157
1158    files.sort();
1159    files.dedup();
1160    files
1161}
1162
1163pub fn is_code_file(path: &Path) -> bool {
1164    let ext = path
1165        .extension()
1166        .and_then(|e| e.to_str())
1167        .unwrap_or("")
1168        .to_lowercase();
1169    matches!(
1170        ext.as_str(),
1171        "rs" | "ts"
1172            | "tsx"
1173            | "js"
1174            | "jsx"
1175            | "py"
1176            | "go"
1177            | "java"
1178            | "c"
1179            | "cc"
1180            | "cpp"
1181            | "h"
1182            | "hpp"
1183            | "rb"
1184            | "cs"
1185            | "kt"
1186            | "swift"
1187            | "php"
1188            | "scala"
1189            | "sql"
1190            | "ex"
1191            | "exs"
1192            | "zig"
1193            | "lua"
1194            | "dart"
1195            | "vue"
1196            | "svelte"
1197    )
1198}