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 carry_over;
8mod chunking;
9pub use chunking::*;
10mod coordinator;
11pub mod coverage;
12mod evict;
13// pub only for lean-ctx-engine-ext; not public API
14#[doc(hidden)]
15pub mod external_origin;
16pub use coordinator::{SearchIndexBuildProgress, get_or_start_build};
17mod provider_origin;
18pub use provider_origin::ChunkOrigins;
19mod served_ranking;
20pub mod source_gate;
21#[cfg(test)]
22mod tests;
23mod walk;
24pub use walk::is_code_file;
25use walk::{admitted_scoped_source_paths, list_code_files};
26#[cfg(test)]
27use walk::{list_code_files_with, list_scoped_code_files};
28
29pub(crate) const MAX_BM25_FILES: usize = 5000;
30const CHUNK_COUNT_WARNING: usize = 50_000;
31const ZSTD_LEVEL: i32 = 9;
32
33const DEFAULT_BM25_IGNORES: &[&str] = &[
34    "vendor/**",
35    "dist/**",
36    "build/**",
37    "public/vendor/**",
38    "public/js/**",
39    "public/css/**",
40    "public/build/**",
41    ".next/**",
42    ".nuxt/**",
43    "__pycache__/**",
44    "*.min.js",
45    "*.min.css",
46    "*.bundle.js",
47    "*.chunk.js",
48];
49
50fn max_bm25_cache_bytes() -> u64 {
51    // Single source of truth: `Config::bm25_max_cache_mb_effective` (env override
52    // › explicit config › disk-budget › generous default). Decoupled from the RAM
53    // profile so large repos persist instead of rebuilding forever (issue #249).
54    let mb = std::env::var("LEAN_CTX_BM25_MAX_CACHE_MB")
55        .ok()
56        .and_then(|v| v.parse::<u64>().ok())
57        .unwrap_or_else(|| crate::core::config::Config::load().bm25_max_cache_mb_effective());
58    mb * 1024 * 1024
59}
60
61/// Effective on-disk ceiling (bytes) for the persisted BM25 index. Single source
62/// of truth shared with `doctor` so its "oversized index" warning matches what
63/// `save`/`load` actually enforce.
64pub fn persist_ceiling_bytes() -> u64 {
65    max_bm25_cache_bytes()
66}
67
68/// Outcome of persisting a BM25 index to disk. Distinguishes a real write from a
69/// size-capped refusal so callers never mistake "refused to persist" for
70/// success (the bug behind the perpetual "index warming" report, issue #249).
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub enum SaveOutcome {
73    /// Written to disk. Carries the compressed (zstd) size in bytes.
74    Persisted { compressed_bytes: u64 },
75    /// Built fine but NOT written — the compressed size exceeds the disk
76    /// ceiling. The in-memory index is still usable for this process; callers
77    /// should surface the remedy (raise the cap / add ignore patterns) instead
78    /// of silently rebuilding on every call.
79    SkippedTooLarge {
80        compressed_bytes: u64,
81        limit_bytes: u64,
82    },
83}
84
85#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
86pub struct CodeChunk {
87    pub file_path: String,
88    pub symbol_name: String,
89    pub kind: ChunkKind,
90    pub start_line: usize,
91    pub end_line: usize,
92    pub content: String,
93    #[serde(default)]
94    pub tokens: Vec<String>,
95    pub token_count: usize,
96    /// The untrusted origin of a provider chunk (pz21 §1.6). An index
97    /// written before it reads `None`: the chunk is then unknown.
98    #[serde(default)]
99    pub input_origin: Option<crate::core::context_admission::origin::InputOrigin>,
100}
101
102#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
103pub enum ChunkKind {
104    Function,
105    Struct,
106    Impl,
107    Module,
108    Class,
109    Method,
110    Other,
111    // -- External source kinds (Context Engine) --
112    Issue,
113    PullRequest,
114    WikiPage,
115    DbSchema,
116    ApiEndpoint,
117    Ticket,
118    ExternalOther,
119}
120
121#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
122pub struct IndexedFileState {
123    pub mtime_ms: u64,
124    pub size_bytes: u64,
125}
126
127impl IndexedFileState {
128    fn from_path(path: &Path) -> Option<Self> {
129        let meta = path.metadata().ok()?;
130        let size_bytes = meta.len();
131        let mtime_ms = meta
132            .modified()
133            .ok()
134            .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
135            .map(|d| d.as_millis() as u64)?;
136        Some(Self {
137            mtime_ms,
138            size_bytes,
139        })
140    }
141}
142
143#[derive(Debug, Clone, Serialize, Deserialize)]
144pub struct BM25Index {
145    pub chunks: Vec<CodeChunk>,
146    pub inverted: HashMap<String, Vec<(usize, f64)>>,
147    pub avg_doc_len: f64,
148    pub doc_count: usize,
149    pub doc_freqs: HashMap<String, usize>,
150    #[serde(default)]
151    pub files: HashMap<String, IndexedFileState>,
152    /// Content fingerprint of every directory that contained an indexed file
153    /// when this index was built, keyed by root-relative path (`""` = the root
154    /// itself). Sampling tracked *files* can never reveal a file that was never
155    /// indexed, so the fast staleness check would keep serving a partial index
156    /// forever after new files appear (#1724). Creating or removing an entry
157    /// bumps its parent directory's mtime on every filesystem we support, so
158    /// comparing this snapshot detects added/deleted files in one stat per
159    /// directory instead of a full ingest walk.
160    #[serde(default)]
161    pub dirs: HashMap<String, u64>,
162    /// Digest of the Context Gateway policy the chunk contents were admitted
163    /// under. An index built under another policy (or before admission
164    /// existed — its postcard layout lacks this field and no longer loads) is
165    /// rebuilt in full, never reused (G5, E3).
166    #[serde(default)]
167    pub admission_policy: Option<String>,
168    /// True once `shrink_resident_content_to_snippet` has trimmed each chunk's
169    /// `content` down to the snippet lines. Resident-only RAM-saving state: never
170    /// persisted (`skip`) so the on-disk index keeps full content, and a reload
171    /// always starts as `false`. Guards the embedding pass against re-embedding
172    /// truncated bodies (see `ensure_embeddings`).
173    #[serde(default, skip)]
174    pub content_truncated: bool,
175    /// Project root of an index its store loaded or handed out (`load`,
176    /// `load_or_build*`): `search` then serves a chunk only while the admitted
177    /// reader still returns its text (`source_gate`, G04). Resident only;
178    /// `None` for a view built in the running call.
179    #[serde(default, skip)]
180    pub source_root: Option<PathBuf>,
181    /// Where each chunk without a readable text file came from, by chunk
182    /// `file_path`. A reference, never a grant (`provider_origin`). Kept
183    /// beside the index file, not in it: the postcard layout is unchanged.
184    #[serde(default, skip)]
185    pub provider_origins: std::sync::Arc<ChunkOrigins>,
186}
187
188#[derive(Debug, Clone, Serialize, Deserialize)]
189pub struct SearchResult {
190    pub chunk_idx: usize,
191    pub score: f64,
192    pub file_path: String,
193    pub symbol_name: String,
194    pub kind: ChunkKind,
195    pub start_line: usize,
196    pub end_line: usize,
197    pub snippet: String,
198}
199
200const BM25_K1: f64 = 1.2;
201const BM25_B: f64 = 0.75;
202
203fn structural_query_boost(query: &str, chunk: &CodeChunk) -> f64 {
204    let raw_terms: std::collections::HashSet<String> = query
205        .split(|c: char| !(c.is_alphanumeric() || c == '_'))
206        .filter(|term| term.len() >= 3)
207        .map(str::to_ascii_lowercase)
208        .collect();
209    let path_terms: std::collections::HashSet<String> = tokenize(&chunk.file_path)
210        .into_iter()
211        .map(|term| term.to_ascii_lowercase())
212        .collect();
213
214    let mut boost = 0.0;
215    if raw_terms.contains(&chunk.symbol_name.to_ascii_lowercase()) {
216        boost += 32.0;
217    }
218    boost += raw_terms.intersection(&path_terms).count() as f64 * 8.0;
219
220    let has_identifier = query.split_whitespace().any(|term| {
221        let has_lower = term.chars().any(char::is_lowercase);
222        let has_upper = term.chars().any(char::is_uppercase);
223        (has_lower && has_upper) || term.contains('_') || term.contains('.')
224    });
225    if has_identifier {
226        let extension = std::path::Path::new(&chunk.file_path)
227            .extension()
228            .and_then(std::ffi::OsStr::to_str)
229            .unwrap_or_default()
230            .to_ascii_lowercase();
231        if matches!(extension.as_str(), "md" | "mdx" | "rst" | "txt" | "adoc") {
232            boost -= 8.0;
233        } else if !extension.is_empty() {
234            boost += 4.0;
235        }
236    }
237    boost
238}
239
240impl Default for BM25Index {
241    fn default() -> Self {
242        Self::new()
243    }
244}
245
246/// Sources admitted, then chunked in parallel, per batch of a fresh view.
247const ADMITTED_BATCH: usize = 256;
248/// Chunks one file may add to a fresh view.
249const FILE_CHUNK_COUNT: usize = 4096;
250
251type ChunkedFile = (Vec<CodeChunk>, usize, usize);
252
253/// The chunks of one admitted file in line order, charged against the given
254/// budgets, as a fresh view adds them.
255fn extract_sorted_chunks(
256    path: &str,
257    content: &str,
258    chunk_bytes: &mut usize,
259    chunk_count: &mut usize,
260) -> Result<Vec<CodeChunk>, String> {
261    let mut chunks = extract_admitted_chunks(path, content, chunk_bytes, chunk_count)?;
262    chunks.sort_by(|a, b| {
263        (a.start_line, a.end_line, &a.symbol_name).cmp(&(b.start_line, b.end_line, &b.symbol_name))
264    });
265    Ok(chunks)
266}
267
268/// Each admitted file's own byte allowance and its chunks under that
269/// allowance and the per-file chunk count, computed in parallel: chunking is
270/// a pure function of path and text. `None` for a file the memory guard
271/// stopped before it was chunked; the fold then chunks it itself.
272fn parallel_admitted_chunks(
273    admitted: &[(&str, String)],
274) -> Vec<(usize, Option<Result<ChunkedFile, String>>)> {
275    use rayon::prelude::*;
276    admitted
277        .par_iter()
278        .map(|(path, content)| {
279            let full_allowance =
280                (64 * 1024 * 1024usize).min(content.len().saturating_mul(5).max(64 * 1024));
281            if crate::core::memory_guard::abort_requested() {
282                return (full_allowance, None);
283            }
284            let mut bytes = full_allowance;
285            let mut count = FILE_CHUNK_COUNT;
286            let result = extract_sorted_chunks(path, content, &mut bytes, &mut count)
287                .map(|chunks| (chunks, full_allowance - bytes, FILE_CHUNK_COUNT - count));
288            (full_allowance, Some(result))
289        })
290        .collect()
291}
292
293/// One load–change–save of a persisted index at a time in this process. Two
294/// writers (two provider ingests a moment apart, an eviction after a search)
295/// otherwise each saved their own copy through the one temp file and could
296/// leave an index no reader loads, or drop the other's chunks.
297static PERSIST: std::sync::Mutex<()> = std::sync::Mutex::new(());
298
299pub(crate) fn persist_lock() -> std::sync::MutexGuard<'static, ()> {
300    PERSIST
301        .lock()
302        .unwrap_or_else(std::sync::PoisonError::into_inner)
303}
304
305impl BM25Index {
306    pub fn new() -> Self {
307        Self {
308            chunks: Vec::new(),
309            inverted: HashMap::new(),
310            avg_doc_len: 0.0,
311            doc_count: 0,
312            doc_freqs: HashMap::new(),
313            files: HashMap::new(),
314            dirs: HashMap::new(),
315            admission_policy: None,
316            content_truncated: false,
317            source_root: None,
318            provider_origins: std::sync::Arc::default(),
319        }
320    }
321
322    /// Approximate heap memory used by this index in bytes.
323    pub fn memory_usage_bytes(&self) -> usize {
324        let chunks_size: usize = self
325            .chunks
326            .iter()
327            .map(|c| {
328                c.content.len()
329                    + c.file_path.len()
330                    + c.symbol_name.len()
331                    + c.tokens.iter().map(String::len).sum::<usize>()
332                    + 64
333            })
334            .sum();
335        let inverted_size: usize = self
336            .inverted
337            .iter()
338            .map(|(k, v)| k.len() + v.len() * 16 + 32)
339            .sum();
340        let files_size: usize = self.files.keys().map(|k| k.len() + 24).sum();
341        let dirs_size: usize = self.dirs.keys().map(|k| k.len() + 16).sum();
342        let freqs_size: usize = self.doc_freqs.keys().map(|k| k.len() + 16).sum();
343        chunks_size + inverted_size + files_size + dirs_size + freqs_size
344    }
345
346    /// Drops all in-memory data, effectively freeing heap. Index can be re-loaded from disk.
347    pub fn unload(&mut self) {
348        let usage = self.memory_usage_bytes();
349        self.chunks = Vec::new();
350        self.inverted = HashMap::new();
351        self.doc_freqs = HashMap::new();
352        self.files = HashMap::new();
353        self.dirs = HashMap::new();
354        self.provider_origins = std::sync::Arc::default();
355        self.avg_doc_len = 0.0;
356        self.doc_count = 0;
357        tracing::info!(
358            "[bm25] unloaded index, freed ~{:.1}MB",
359            usage as f64 / 1_048_576.0
360        );
361    }
362
363    /// Shrinks each resident chunk's `content` to its first `keep_lines` lines,
364    /// reclaiming the RAM held by the full source bodies once the embedding pass
365    /// has already consumed them. Query previews can only select lines still
366    /// resident, so this trades preview coverage for memory in cached indexes.
367    /// Fresh admitted retrieval views retain their separately budgeted content.
368    ///
369    /// Further shrinks resident content (chunks are already truncated to 10 lines
370    /// during `add_chunk`; this method can tighten that further). Sets
371    /// `content_truncated` so a later `ensure_embeddings` against this same
372    /// resident index skips re-embedding (which would otherwise feed truncated
373    /// bodies to the embedder).
374    ///
375    /// Idempotent and only ever shrinks: chunks shorter than `keep_lines` are
376    /// left untouched.
377    pub fn shrink_resident_content_to_snippet(&mut self, keep_lines: usize) {
378        let before = self.memory_usage_bytes();
379        for chunk in &mut self.chunks {
380            // Cheap line-count gate: only allocate a new string when the body is
381            // actually longer than the snippet window.
382            if chunk.content.lines().nth(keep_lines).is_some() {
383                let trimmed: String = chunk
384                    .content
385                    .lines()
386                    .take(keep_lines)
387                    .collect::<Vec<_>>()
388                    .join("\n");
389                chunk.content = trimmed;
390                // Reclaim the spare capacity left by the larger original body.
391                chunk.content.shrink_to_fit();
392            }
393        }
394        self.content_truncated = true;
395        let after = self.memory_usage_bytes();
396        tracing::debug!(
397            "[bm25] shrank resident content to {keep_lines} lines/chunk, freed ~{:.1}MB",
398            before.saturating_sub(after) as f64 / 1_048_576.0
399        );
400    }
401
402    /// Builds an index from explicit chunks (unit tests; avoids filesystem walking).
403    #[cfg(any(test, feature = "test-support"))]
404    pub fn from_chunks_for_test(chunks: Vec<CodeChunk>) -> Self {
405        let mut index = Self::new();
406        for mut chunk in chunks {
407            if chunk.token_count == 0 {
408                chunk.token_count = tokenize(&chunk.content).len();
409            }
410            index.add_chunk(chunk);
411        }
412        index.finalize();
413        index
414    }
415
416    pub fn build_from_directory(root: &Path) -> Self {
417        Self::build_from_directory_inner(root, &HashMap::new())
418    }
419
420    /// Ephemeral retrieval view: admit each complete original source before
421    /// tokenization. Never consult metadata-only caches or persist this view.
422    ///
423    /// `subdir` / `in_scope` narrow the walk itself (see
424    /// `walk::list_scoped_code_files`), so the file budget counts only sources the
425    /// caller asked about.
426    pub fn build_from_admitted_sources(
427        root: &Path,
428        subdir: Option<&str>,
429        in_scope: &dyn Fn(&str) -> bool,
430        admit: impl FnMut(&str) -> Result<Option<String>, String>,
431    ) -> Result<Self, String> {
432        let rules = CorpusRules::load();
433        Self::build_scoped_from_admitted_sources(root, &rules, subdir, in_scope, admit)
434    }
435
436    fn build_scoped_from_admitted_sources(
437        root: &Path,
438        rules: &CorpusRules,
439        subdir: Option<&str>,
440        in_scope: &dyn Fn(&str) -> bool,
441        mut admit: impl FnMut(&str) -> Result<Option<String>, String>,
442    ) -> Result<Self, String> {
443        if !is_safe_bm25_root(root) {
444            return Err("source root is not safe to scan".into());
445        }
446        let mut index = Self::new();
447        let mut chunk_bytes = 64 * 1024 * 1024;
448        let mut chunk_count = 100_000;
449        // Memory a finished search dropped is not pressure: return it first.
450        if crate::core::memory_guard::is_under_pressure() {
451            crate::core::memory_guard::reclaim_now();
452        }
453        let paths = admitted_scoped_source_paths(root, rules, subdir, in_scope)?;
454        // Admission runs here, on the request's thread and in its scopes, one
455        // source after the other. Only the chunking of what was admitted — a
456        // pure function of path and text — runs in parallel, per batch; the
457        // fold below applies the budgets in path order exactly as a
458        // sequential build would, so the view is the same either way.
459        for batch in paths.chunks(ADMITTED_BATCH) {
460            let mut admitted = Vec::with_capacity(batch.len());
461            for path in batch {
462                // The working set of one search is freed when it ends: it is
463                // refused at the hard level, not at the soft target the
464                // guardian keeps idle memory under (the build reclaimed above).
465                if crate::core::memory_guard::abort_requested() {
466                    return Err("source search withheld under memory pressure".into());
467                }
468                let Some(content) = admit(path)? else {
469                    continue;
470                };
471                if looks_minified(&content) {
472                    continue;
473                }
474                admitted.push((path.as_str(), content));
475            }
476            let chunked = parallel_admitted_chunks(&admitted);
477            for ((path, content), (full_allowance, unbounded)) in admitted.iter().zip(chunked) {
478                let allowance = chunk_bytes.min(full_allowance);
479                if !crate::core::index_admission::admit(
480                    crate::core::index_admission::BuildKind::Bm25,
481                    allowance as u64,
482                )
483                .parallel_ok
484                {
485                    return Err("source search exceeds available memory headroom".into());
486                }
487                let count_allowance = chunk_count.min(FILE_CHUNK_COUNT);
488                // The parallel result holds only where this file's budgets
489                // were not capped by what earlier files used; otherwise it is
490                // recomputed here under the capped budgets.
491                let (chunks, used_bytes, used_count) = match unbounded {
492                    Some(Ok(result))
493                        if allowance == full_allowance && count_allowance == FILE_CHUNK_COUNT =>
494                    {
495                        result
496                    }
497                    Some(Err(error))
498                        if allowance == full_allowance && count_allowance == FILE_CHUNK_COUNT =>
499                    {
500                        return Err(error);
501                    }
502                    _ => {
503                        let mut file_chunk_bytes = allowance;
504                        let mut file_chunk_count = count_allowance;
505                        let chunks = extract_sorted_chunks(
506                            path,
507                            content,
508                            &mut file_chunk_bytes,
509                            &mut file_chunk_count,
510                        )?;
511                        (
512                            chunks,
513                            allowance - file_chunk_bytes,
514                            count_allowance - file_chunk_count,
515                        )
516                    }
517                };
518                chunk_bytes -= used_bytes;
519                chunk_count -= used_count;
520                for chunk in chunks {
521                    if crate::core::memory_guard::abort_requested() {
522                        return Err("source search withheld under memory pressure".into());
523                    }
524                    // This ephemeral view already charges the full admitted chunk
525                    // against its byte budget; retain it for query-centred previews.
526                    index.add_chunk_with_content_limit(chunk, None);
527                }
528            }
529        }
530        index.finalize();
531        Ok(index)
532    }
533
534    /// Like `build_from_directory` but reuses file content from a prior scan
535    /// (e.g. the graph index walk) to avoid redundant disk reads.
536    pub fn build_with_content_hint(root: &Path, content_hint: &HashMap<String, String>) -> Self {
537        Self::build_from_directory_inner(root, content_hint)
538    }
539
540    fn build_from_directory_inner(root: &Path, content_hint: &HashMap<String, String>) -> Self {
541        let root_str = root.to_string_lossy();
542        if !super::graph_index::is_safe_scan_root_public(&root_str) {
543            tracing::warn!("[bm25: scan aborted for unsafe root {root_str}]");
544            return Self::new();
545        }
546        let files = list_code_files(root);
547        // Snapshot directory mtimes *before* the (slow) chunking pass: a file
548        // that lands while we build then leaves its directory newer than the
549        // snapshot, so the next staleness check sees it instead of silently
550        // pinning the partial tree (#1724).
551        let dirs = dir_states(root, &files);
552        // One policy for the whole build, recorded with the index (G5).
553        let admission = crate::core::context_admission::stores::StoreAdmission::current();
554
555        // #933: parallel fast path for the common case. The per-file parse +
556        // tokenize work is pure and thread-safe, so we fan it across a rayon pool
557        // and merge sequentially in file order — measured 2.85 s → 0.69 s (~4x) on
558        // the lean-ctx repo. Under memory pressure (or for tiny corpora, where pool
559        // setup is not worth it) we fall back to the sequential build, which carries
560        // the incremental early-break. #685 adds admission control: a corpus whose
561        // estimated peak would blow past the guardian's hard threshold degrades to
562        // the sequential build up front instead of OOMing mid-fan-out. Both paths
563        // produce an identical index (see `build` module + determinism tests).
564        if files.len() >= build::PARALLEL_MIN_FILES
565            && !crate::core::memory_guard::is_under_pressure()
566            && !crate::core::memory_guard::abort_requested()
567            && crate::core::index_admission::admit_files(
568                crate::core::index_admission::BuildKind::Bm25,
569                root,
570                &files,
571            )
572            .parallel_ok
573        {
574            let mut index = Self::build_parallel(root, content_hint, &files, &admission);
575            index.dirs = dirs;
576            index.admission_policy = Some(admission.digest().to_owned());
577            return index;
578        }
579        let mut index = Self::build_sequential(root, content_hint, &files, &admission);
580        index.dirs = dirs;
581        index.admission_policy = Some(admission.digest().to_owned());
582        index
583    }
584
585    /// Group a previous index's chunks by file, each file's list sorted by
586    /// (start_line, end_line, symbol_name) — the deterministic reuse order shared
587    /// by both incremental rebuild paths (and the equivalence test, so it feeds
588    /// them identical inputs).
589    fn group_prev_chunks_by_file(prev: &BM25Index) -> HashMap<String, Vec<CodeChunk>> {
590        let mut old_by_file: HashMap<String, Vec<CodeChunk>> = HashMap::new();
591        for c in &prev.chunks {
592            old_by_file
593                .entry(c.file_path.clone())
594                .or_default()
595                .push(c.clone());
596        }
597        for v in old_by_file.values_mut() {
598            v.sort_by(|a, b| {
599                a.start_line
600                    .cmp(&b.start_line)
601                    .then_with(|| a.end_line.cmp(&b.end_line))
602                    .then_with(|| a.symbol_name.cmp(&b.symbol_name))
603            });
604        }
605        old_by_file
606    }
607
608    pub fn rebuild_incremental(root: &Path, prev: &BM25Index) -> Self {
609        // Reused chunks must have been admitted under the current policy.
610        let admission = crate::core::context_admission::stores::StoreAdmission::current();
611        if prev.admission_policy.as_deref() != Some(admission.digest()) {
612            return Self::build_from_directory(root);
613        }
614        let old_by_file = Self::group_prev_chunks_by_file(prev);
615        let files = list_code_files(root);
616        let dirs = dir_states(root, &files);
617
618        // #581: mirror `build()`'s dispatch. The edit loop is the hottest path in
619        // daily use, and its serial cost is dominated by re-tokenizing the *many
620        // unchanged* files' reused chunks — not the few changed ones. So the
621        // parallel path fans the entire tokenization (changed files via
622        // `prepare_file`, unchanged via re-`prepare_chunk`) across the rayon pool
623        // and merges sequentially in file order. The sequential path keeps the
624        // per-file memory-pressure early-break and serves small corpora / pressure.
625        // #685: oversized corpora degrade to sequential via admission control.
626        // Both produce an identical index (see determinism tests).
627        if files.len() >= build::PARALLEL_MIN_FILES
628            && !crate::core::memory_guard::is_under_pressure()
629            && !crate::core::memory_guard::abort_requested()
630            && crate::core::index_admission::admit_files(
631                crate::core::index_admission::BuildKind::Bm25,
632                root,
633                &files,
634            )
635            .parallel_ok
636        {
637            let mut index =
638                Self::rebuild_incremental_parallel(root, prev, &old_by_file, &files, &admission);
639            index.dirs = dirs;
640            index.admission_policy = Some(admission.digest().to_owned());
641            return index;
642        }
643        let mut index =
644            Self::rebuild_incremental_sequential(root, prev, &old_by_file, &files, &admission);
645        index.dirs = dirs;
646        index.admission_policy = Some(admission.digest().to_owned());
647        index
648    }
649
650    /// Sequential incremental rebuild with per-file memory-pressure guards. Reuses
651    /// unchanged files' chunks and re-extracts changed ones. Used for small
652    /// corpora and as the safe fallback under memory pressure.
653    pub(crate) fn rebuild_incremental_sequential(
654        root: &Path,
655        prev: &BM25Index,
656        old_by_file: &HashMap<String, Vec<CodeChunk>>,
657        files: &[String],
658        admission: &crate::core::context_admission::stores::StoreAdmission,
659    ) -> Self {
660        let mut index = Self::new();
661        const MAX_FILE_SIZE_BYTES: u64 = 2 * 1024 * 1024;
662        let root_key = root.to_string_lossy().to_string();
663        let total = files.len() as u64;
664        crate::core::index_progress::report_bm25(&root_key, 0, total);
665
666        for (i, rel) in files.iter().enumerate() {
667            if i.is_multiple_of(16) || i + 1 == files.len() {
668                crate::core::index_progress::report_bm25(&root_key, (i + 1) as u64, total);
669            }
670            if i.is_multiple_of(500) && crate::core::memory_guard::is_under_pressure() {
671                tracing::warn!(
672                    "[bm25: stopping incremental rebuild at file {i}/{} due to memory pressure]",
673                    files.len()
674                );
675                break;
676            }
677
678            let abs = root.join(rel);
679            let Some(state) = IndexedFileState::from_path(&abs) else {
680                continue;
681            };
682
683            let unchanged = prev.files.get(rel).is_some_and(|old| *old == state);
684            if unchanged
685                && let Some(chunks) = old_by_file.get(rel)
686                && chunks.first().is_some_and(|c| !c.content.is_empty())
687            {
688                for chunk in chunks {
689                    index.add_chunk(chunk.clone());
690                }
691                index.files.insert(rel.clone(), state);
692                continue;
693            }
694
695            if state.size_bytes > MAX_FILE_SIZE_BYTES {
696                continue;
697            }
698            let content = if crate::core::extractors::is_binary_document(&abs) {
699                match std::fs::read(&abs) {
700                    Ok(bytes) => crate::core::extractors::extract(&abs, &bytes).text,
701                    Err(_) => continue,
702                }
703            } else {
704                // An incompletely decoded source (replaced or dropped bytes)
705                // is never a complete source: it does not enter the index.
706                match crate::core::text_decode::read_text_checked(&abs) {
707                    Ok(decoded) if decoded.complete() => decoded.text,
708                    _ => continue,
709                }
710            };
711            if content.is_empty() {
712                continue;
713            }
714            // Derived store: only admitted text, never restricted (E3).
715            let Some(content) = admission.admit(&content, &abs, None) else {
716                continue;
717            };
718            // #1739: see `build::prepare_file` — same predicate, same position.
719            if looks_minified(&content) {
720                tracing::debug!("[bm25: skipping minified payload {rel}]");
721                continue;
722            }
723            let mut chunks = crate::core::derivation_cache::chunks(rel, &content);
724            chunks.sort_by(|a, b| {
725                a.start_line
726                    .cmp(&b.start_line)
727                    .then_with(|| a.end_line.cmp(&b.end_line))
728                    .then_with(|| a.symbol_name.cmp(&b.symbol_name))
729            });
730            for chunk in chunks {
731                index.add_chunk(chunk);
732            }
733            index.files.insert(rel.clone(), state);
734        }
735
736        index.finalize();
737        index
738    }
739
740    fn add_chunk(&mut self, chunk: CodeChunk) {
741        self.add_chunk_with_content_limit(chunk, Some(10));
742    }
743
744    fn add_chunk_with_content_limit(&mut self, mut chunk: CodeChunk, keep_lines: Option<usize>) {
745        let idx = self.chunks.len();
746
747        let enriched = enrich_for_bm25(&chunk);
748        let tokens = chunking::index_terms(&enriched);
749        for token in &tokens {
750            let lower = token.to_lowercase();
751            let postings = self.inverted.entry(lower.clone()).or_default();
752            if postings.last().map(|(last_idx, _)| *last_idx) != Some(idx) {
753                *self.doc_freqs.entry(lower).or_insert(0) += 1;
754            }
755            postings.push((idx, 1.0));
756        }
757
758        // #790: truncate content to snippet AFTER tokenization — full text was
759        // used for BM25 scoring above; stored content is only for result display.
760        if let Some(keep_lines) = keep_lines.filter(|&n| chunk.content.lines().nth(n).is_some()) {
761            chunk.content = chunk
762                .content
763                .lines()
764                .take(keep_lines)
765                .collect::<Vec<_>>()
766                .join("\n");
767            chunk.content.shrink_to_fit();
768        }
769
770        self.chunks.push(CodeChunk {
771            token_count: tokens.len(),
772            tokens: Vec::new(),
773            ..chunk
774        });
775    }
776
777    fn finalize(&mut self) {
778        self.doc_count = self.chunks.len();
779        if self.doc_count == 0 {
780            return;
781        }
782
783        let total_len: usize = self.chunks.iter().map(|c| c.token_count).sum();
784        self.avg_doc_len = total_len as f64 / self.doc_count as f64;
785    }
786
787    /// Every chunk matching `query`, best first. With `excluded` (one flag
788    /// per chunk) the flagged chunks do not enter the ranking at all: they
789    /// get no score and are left out of the corpus statistics (document
790    /// count, average length, document frequencies), so the result is the
791    /// ranking of an index that never held them (`served_ranking`).
792    fn rank(&self, query: &str, excluded: Option<&[bool]>) -> Vec<SearchResult> {
793        let query_tokens = tokenize(query);
794        if query_tokens.is_empty() || self.doc_count == 0 {
795            return Vec::new();
796        }
797        let (doc_count, avg_doc_len) = match excluded {
798            None => (self.doc_count, self.avg_doc_len),
799            Some(excluded) => self.served_corpus(excluded),
800        };
801        if doc_count == 0 {
802            return Vec::new();
803        }
804
805        // Pre-allocated score array: O(1) per-access vs HashMap overhead.
806        // Kolmogorov-optimal: minimal allocation for the scoring operation.
807        let n = self.chunks.len();
808        let mut scores = vec![0.0f64; n];
809        let mut touched = Vec::with_capacity(n.min(256));
810
811        for token in &query_tokens {
812            let lower = token.to_lowercase();
813            let Some(postings) = self.inverted.get(&lower) else {
814                continue;
815            };
816            let df = match excluded {
817                None => *self.doc_freqs.get(&lower).unwrap_or(&0),
818                Some(excluded) => served_ranking::doc_freq(postings, excluded),
819            };
820            let df = df as f64;
821            if df == 0.0 {
822                continue;
823            }
824
825            let idf = ((doc_count as f64 - df + 0.5) / (df + 0.5) + 1.0).ln();
826
827            for &(idx, weight) in postings {
828                if excluded.is_some_and(|excluded| served_ranking::is_excluded(excluded, idx)) {
829                    continue;
830                }
831                let doc_len = self.chunks[idx].token_count as f64;
832                let norm_len = doc_len / avg_doc_len.max(1.0);
833                let bm25 = idf * (weight * (BM25_K1 + 1.0))
834                    / (weight + BM25_K1 * (1.0 - BM25_B + BM25_B * norm_len));
835
836                if scores[idx] == 0.0 {
837                    touched.push(idx);
838                }
839                scores[idx] += bm25;
840            }
841        }
842
843        for &idx in &touched {
844            scores[idx] += structural_query_boost(query, &self.chunks[idx]);
845        }
846
847        let mut results: Vec<SearchResult> = touched
848            .iter()
849            .filter(|&&idx| scores[idx] > 0.0)
850            .map(|&idx| {
851                let chunk = &self.chunks[idx];
852                let snippet = query_snippet(&chunk.content, &query_tokens);
853                SearchResult {
854                    chunk_idx: idx,
855                    score: scores[idx],
856                    file_path: chunk.file_path.clone(),
857                    symbol_name: chunk.symbol_name.clone(),
858                    kind: chunk.kind.clone(),
859                    start_line: chunk.start_line,
860                    end_line: chunk.end_line,
861                    snippet,
862                }
863            })
864            .collect();
865
866        results.sort_by(|a, b| {
867            b.score
868                .partial_cmp(&a.score)
869                .unwrap_or(std::cmp::Ordering::Equal)
870                .then_with(|| a.file_path.cmp(&b.file_path))
871                .then_with(|| a.symbol_name.cmp(&b.symbol_name))
872                .then_with(|| a.start_line.cmp(&b.start_line))
873                .then_with(|| a.end_line.cmp(&b.end_line))
874        });
875        results
876    }
877
878    pub fn save(&self, root: &Path) -> std::io::Result<SaveOutcome> {
879        if self.chunks.len() > CHUNK_COUNT_WARNING {
880            tracing::warn!(
881                "[bm25] index has {} chunks (threshold {}), consider adding extra_ignore_patterns",
882                self.chunks.len(),
883                CHUNK_COUNT_WARNING
884            );
885        }
886
887        let dir = index_dir(root);
888        std::fs::create_dir_all(&dir)?;
889
890        // #790: stream postcard → zstd → file to avoid holding the full
891        // serialized buffer in memory. Temp-file + rename for atomicity.
892        let target = dir.join("bm25_index.bin.zst");
893        let tmp = dir.join("bm25_index.bin.zst.tmp");
894        {
895            let file = std::fs::File::create(&tmp)?;
896            let buf_writer = std::io::BufWriter::new(file);
897            let mut encoder = zstd::Encoder::new(buf_writer, ZSTD_LEVEL)
898                .map_err(|e| std::io::Error::other(format!("zstd encoder init: {e}")))?;
899            postcard::to_io(self, &mut encoder)
900                .map_err(|e| std::io::Error::other(e.to_string()))?;
901            encoder.finish()?;
902        }
903
904        let compressed_bytes = std::fs::metadata(&tmp)?.len();
905        let max_bytes = max_bm25_cache_bytes();
906        if compressed_bytes > max_bytes {
907            let _ = std::fs::remove_file(&tmp);
908            tracing::warn!(
909                "[bm25] compressed index too large ({:.1} MB, limit {:.0} MB), refusing to persist: {}",
910                compressed_bytes as f64 / 1_048_576.0,
911                max_bytes / (1024 * 1024),
912                dir.display()
913            );
914            return Ok(SaveOutcome::SkippedTooLarge {
915                compressed_bytes,
916                limit_bytes: max_bytes,
917            });
918        }
919
920        tracing::info!(
921            "[bm25] index: {:.1} MB zstd compressed",
922            compressed_bytes as f64 / 1_048_576.0,
923        );
924
925        std::fs::rename(&tmp, &target)?;
926
927        let _ = std::fs::remove_file(dir.join("bm25_index.bin"));
928        let _ = std::fs::remove_file(dir.join("bm25_index.json"));
929
930        let _ = std::fs::write(
931            dir.join("project_root.txt"),
932            root.to_string_lossy().as_bytes(),
933        );
934        self.save_provider_origins(&dir);
935
936        Ok(SaveOutcome::Persisted { compressed_bytes })
937    }
938
939    /// The persisted index, only when it was admitted under the current
940    /// admission policy: chunks admitted under another policy (or a legacy
941    /// index built from raw sources) are never served or reused (G5, E3).
942    pub fn load(root: &Path) -> Option<Self> {
943        let admission = crate::core::context_admission::stores::StoreAdmission::current();
944        // The directory name is a hash of this checkout; the root recorded at
945        // save is the authority. An index recorded for another root is
946        // rebuilt instead of served. (A restored hosted bundle carries no
947        // record; its directory is already this checkout's partition.)
948        let canonical = |path: &Path| crate::core::pathutil::safe_canonicalize_bounded(path, 2000);
949        if std::fs::read_to_string(index_dir(root).join("project_root.txt"))
950            .is_ok_and(|stored| canonical(Path::new(stored.trim())) != canonical(root))
951        {
952            return None;
953        }
954        Self::load_persisted(root)
955            .filter(|idx| idx.admission_policy.as_deref() == Some(admission.digest()))
956            .map(|idx| idx.rooted_at(root).with_provider_origins(&index_dir(root)))
957    }
958
959    fn load_persisted(root: &Path) -> Option<Self> {
960        let dir = index_dir(root);
961        let max_bytes = max_bm25_cache_bytes();
962
963        let zst_path = dir.join("bm25_index.bin.zst");
964        if zst_path.exists() {
965            let meta = std::fs::metadata(&zst_path).ok()?;
966            if meta.len() > max_bytes {
967                tracing::warn!(
968                    "[bm25] compressed index too large ({:.1} GB, limit {:.0} MB), quarantining: {}",
969                    meta.len() as f64 / 1_073_741_824.0,
970                    max_bytes / (1024 * 1024),
971                    zst_path.display()
972                );
973                let quarantined = zst_path.with_extension("zst.quarantined");
974                let _ = std::fs::rename(&zst_path, &quarantined);
975                return None;
976            }
977            let compressed = std::fs::read(&zst_path).ok()?;
978            let max_decompressed = max_decompressed_bytes(meta.len());
979            let data = bounded_zstd_decode(&compressed, max_decompressed)?;
980            let idx: Self = postcard::from_bytes(&data).ok()?;
981            return Some(idx);
982        }
983
984        let bin_path = dir.join("bm25_index.bin");
985        if bin_path.exists() {
986            let meta = std::fs::metadata(&bin_path).ok()?;
987            if meta.len() > max_bytes {
988                tracing::warn!(
989                    "[bm25] index too large ({:.1} GB, limit {:.0} MB), quarantining: {}",
990                    meta.len() as f64 / 1_073_741_824.0,
991                    max_bytes / (1024 * 1024),
992                    bin_path.display()
993                );
994                let quarantined = bin_path.with_extension("bin.quarantined");
995                let _ = std::fs::rename(&bin_path, &quarantined);
996                return None;
997            }
998            let data = std::fs::read(&bin_path).ok()?;
999            let idx: Self = postcard::from_bytes(&data).ok()?;
1000            // Auto-migrate: compress legacy .bin to .bin.zst
1001            if let Ok(compressed) = zstd::encode_all(data.as_slice(), ZSTD_LEVEL) {
1002                let zst_tmp = zst_path.with_extension("zst.tmp");
1003                if std::fs::write(&zst_tmp, &compressed).is_ok()
1004                    && std::fs::rename(&zst_tmp, &zst_path).is_ok()
1005                {
1006                    tracing::info!(
1007                        "[bm25] migrated {:.1} MB → {:.1} MB zstd",
1008                        data.len() as f64 / 1_048_576.0,
1009                        compressed.len() as f64 / 1_048_576.0
1010                    );
1011                    let _ = std::fs::remove_file(&bin_path);
1012                }
1013            }
1014            return Some(idx);
1015        }
1016
1017        let json_path = dir.join("bm25_index.json");
1018        if json_path.exists() {
1019            let meta = std::fs::metadata(&json_path).ok()?;
1020            if meta.len() > max_bytes {
1021                tracing::warn!(
1022                    "[bm25] index too large ({:.1} GB, limit {:.0} MB), quarantining: {}",
1023                    meta.len() as f64 / 1_073_741_824.0,
1024                    max_bytes / (1024 * 1024),
1025                    json_path.display()
1026                );
1027                let quarantined = json_path.with_extension("json.quarantined");
1028                let _ = std::fs::rename(&json_path, &quarantined);
1029                return None;
1030            }
1031            let data = std::fs::read_to_string(&json_path).ok()?;
1032            return serde_json::from_str(&data).ok();
1033        }
1034
1035        None
1036    }
1037
1038    pub fn load_or_build(root: &Path) -> Self {
1039        Self::load_or_build_inner(root, false)
1040    }
1041
1042    /// Like `load_or_build` but uses a fast sentinel-sampling staleness check
1043    /// that skips the expensive full directory walk for new-file detection.
1044    pub fn load_or_build_fast(root: &Path) -> Self {
1045        Self::load_or_build_inner(root, true)
1046    }
1047
1048    fn load_or_build_inner(root: &Path, fast_stale: bool) -> Self {
1049        if !is_safe_bm25_root(root) {
1050            return Self::default();
1051        }
1052        if let Some(idx) = Self::load(root) {
1053            let stale = if fast_stale {
1054                bm25_index_looks_stale_fast(&idx, root)
1055            } else {
1056                bm25_index_looks_stale(&idx, root)
1057            };
1058            if !stale {
1059                return idx;
1060            }
1061            tracing::debug!(
1062                "[bm25_index: stale index detected for {}; rebuilding]",
1063                root.display()
1064            );
1065            let rebuilt = if idx.files.is_empty() {
1066                Self::build_from_directory(root)
1067            } else {
1068                Self::rebuild_incremental(root, &idx)
1069            }
1070            .carrying_external_from(&idx);
1071            let _ = rebuilt.save(root);
1072            return rebuilt.rooted_at(root);
1073        }
1074
1075        let built = Self::build_from_directory(root);
1076        let _ = built.save(root);
1077        built.rooted_at(root)
1078    }
1079
1080    pub fn index_file_path(root: &Path) -> PathBuf {
1081        let dir = index_dir(root);
1082        let zst = dir.join("bm25_index.bin.zst");
1083        if zst.exists() {
1084            return zst;
1085        }
1086        let bin = dir.join("bm25_index.bin");
1087        if bin.exists() {
1088            return bin;
1089        }
1090        dir.join("bm25_index.json")
1091    }
1092
1093    /// Chunk count of the persisted index without loading it (#1914): postcard
1094    /// writes `chunks` — the first field — as a varint length prefix, so only
1095    /// the first few decompressed bytes are read. `None` for the legacy JSON
1096    /// format or an unreadable file; `Some(0)` for an index that holds nothing.
1097    pub fn persisted_chunk_count(root: &Path) -> Option<u64> {
1098        use std::io::Read;
1099        let path = Self::index_file_path(root);
1100        let file = std::fs::File::open(&path).ok()?;
1101        let mut head: Box<dyn Read> = match path.extension().and_then(|e| e.to_str()) {
1102            Some("zst") => Box::new(zstd::Decoder::new(file).ok()?),
1103            Some("bin") => Box::new(file),
1104            _ => return None,
1105        };
1106        let mut count = 0u64;
1107        for shift in (0..64).step_by(7) {
1108            let mut byte = [0u8; 1];
1109            head.read_exact(&mut byte).ok()?;
1110            count |= u64::from(byte[0] & 0x7f) << shift;
1111            if byte[0] & 0x80 == 0 {
1112                return Some(count);
1113            }
1114        }
1115        None
1116    }
1117}
1118
1119fn is_safe_bm25_root(root: &Path) -> bool {
1120    super::graph_index::is_safe_scan_root_public(&root.to_string_lossy())
1121}
1122
1123fn bm25_index_looks_stale(index: &BM25Index, root: &Path) -> bool {
1124    bm25_index_looks_stale_inner(index, root, false)
1125}
1126
1127/// Fast staleness check: samples a subset of tracked files and skips the
1128/// expensive `list_code_files()` walk for new-file detection.
1129pub fn bm25_index_looks_stale_fast(index: &BM25Index, root: &Path) -> bool {
1130    bm25_index_looks_stale_inner(index, root, true)
1131}
1132
1133fn bm25_index_looks_stale_inner(index: &BM25Index, root: &Path, fast: bool) -> bool {
1134    if index.chunks.is_empty() {
1135        return false;
1136    }
1137
1138    // An index persisted before secret-like paths were excluded from the walk
1139    // must be rebuilt, which drops them (GHSA-rxv5-4c3x-g4q6 A).
1140    if index
1141        .files
1142        .keys()
1143        .any(|rel| crate::core::io_boundary::is_secret_like(Path::new(rel)).is_some())
1144    {
1145        return true;
1146    }
1147
1148    if index.files.is_empty() {
1149        let mut seen = std::collections::HashSet::<&str>::new();
1150        for chunk in &index.chunks {
1151            let rel = chunk.file_path.trim_start_matches(['/', '\\']);
1152            if rel.is_empty() {
1153                continue;
1154            }
1155            if !seen.insert(rel) {
1156                continue;
1157            }
1158            if !root.join(rel).exists() {
1159                return true;
1160            }
1161        }
1162        return false;
1163    }
1164
1165    if fast {
1166        let sample_size = index.files.len().min(SENTINEL_SAMPLE_SIZE);
1167        let step = if index.files.len() > sample_size {
1168            index.files.len() / sample_size
1169        } else {
1170            1
1171        };
1172        for (i, (rel, old_state)) in index.files.iter().enumerate() {
1173            if i % step != 0 {
1174                continue;
1175            }
1176            let abs = root.join(rel);
1177            if !abs.exists() {
1178                return true;
1179            }
1180            let Some(cur) = IndexedFileState::from_path(&abs) else {
1181                return true;
1182            };
1183            if &cur != old_state {
1184                return true;
1185            }
1186        }
1187        // Sampling tracked files says nothing about files that were never
1188        // indexed, so without this the fast path serves a partial tree forever
1189        // (#1724). The directory snapshot closes that hole for one stat per
1190        // indexed directory.
1191        return dirs_look_stale(index, root);
1192    }
1193
1194    for (rel, old_state) in &index.files {
1195        let abs = root.join(rel);
1196        if !abs.exists() {
1197            return true;
1198        }
1199        let Some(cur) = IndexedFileState::from_path(&abs) else {
1200            return true;
1201        };
1202        if &cur != old_state {
1203            return true;
1204        }
1205    }
1206
1207    for rel in list_code_files(root) {
1208        if !index.files.contains_key(&rel) {
1209            return true;
1210        }
1211    }
1212
1213    false
1214}
1215
1216const SENTINEL_SAMPLE_SIZE: usize = 10;
1217
1218/// True when recorded directory fingerprints no longer match the filesystem —
1219/// i.e. a file was added to (or removed from) the indexed tree.
1220///
1221/// An index persisted before directory snapshots existed carries no `dirs`, so
1222/// its freshness cannot be proven cheaply: it is reported stale exactly once,
1223/// and the resulting rebuild records the snapshot for every later call.
1224fn dirs_look_stale(index: &BM25Index, root: &Path) -> bool {
1225    if index.dirs.is_empty() {
1226        return true;
1227    }
1228    for (rel, recorded) in &index.dirs {
1229        let abs = if rel.is_empty() {
1230            root.to_path_buf()
1231        } else {
1232            root.join(rel)
1233        };
1234        if dir_fingerprint(&abs) != Some(*recorded) {
1235            return true;
1236        }
1237    }
1238    false
1239}
1240
1241fn dir_fingerprint(path: &Path) -> Option<u64> {
1242    use std::hash::{Hash, Hasher};
1243
1244    let meta = std::fs::metadata(path).ok()?;
1245    let modified = meta.modified().ok()?.duration_since(UNIX_EPOCH).ok()?;
1246    let mut entries = std::fs::read_dir(path)
1247        .ok()?
1248        .filter_map(Result::ok)
1249        .map(|entry| entry.file_name().to_string_lossy().into_owned())
1250        .collect::<Vec<_>>();
1251    entries.sort_unstable();
1252    let mut hasher = std::collections::hash_map::DefaultHasher::new();
1253    modified.as_nanos().hash(&mut hasher);
1254    entries.hash(&mut hasher);
1255    Some(hasher.finish())
1256}
1257
1258/// Content snapshot of the root plus every ancestor directory of an indexed file.
1259/// Ancestors are included so a brand-new top-level directory (whose own mtime
1260/// was never recorded) is still caught through its recorded parent.
1261fn dir_states(root: &Path, files: &[String]) -> HashMap<String, u64> {
1262    let mut rels: std::collections::HashSet<String> = std::collections::HashSet::new();
1263    rels.insert(String::new());
1264    for rel in files {
1265        let mut cur = Path::new(rel);
1266        while let Some(parent) = cur.parent() {
1267            let key = parent.to_string_lossy().to_string();
1268            // Once a directory is known, so are all of its ancestors.
1269            if !rels.insert(key) {
1270                break;
1271            }
1272            cur = parent;
1273        }
1274    }
1275    rels.into_iter()
1276        .filter_map(|rel| {
1277            let abs = if rel.is_empty() {
1278                root.to_path_buf()
1279            } else {
1280                root.join(&rel)
1281            };
1282            dir_fingerprint(&abs).map(|fingerprint| (rel, fingerprint))
1283        })
1284        .collect()
1285}
1286
1287/// Streams the persisted index out, refusing anything past `max_bytes`.
1288///
1289/// The buffer never grows beyond `max_bytes`, so the ceiling passed in *is* the
1290/// worst-case allocation — which is why #1739 hinged on that ceiling being a
1291/// sane number rather than on this loop. Our own writer streams postcard into
1292/// the encoder (#790) and so never records a frame content size, which rules
1293/// out a cheap header pre-check.
1294fn bounded_zstd_decode(compressed: &[u8], max_bytes: u64) -> Option<Vec<u8>> {
1295    use std::io::Read;
1296    let mut decoder = zstd::Decoder::new(compressed).ok()?;
1297    let mut buf = Vec::new();
1298    let mut chunk = vec![0u8; 65536];
1299    let mut total = 0u64;
1300    loop {
1301        let n = decoder.read(&mut chunk).ok()?;
1302        if n == 0 {
1303            break;
1304        }
1305        total += n as u64;
1306        if total > max_bytes {
1307            tracing::warn!(
1308                "[bm25] decompressed index exceeds limit ({:.0} MB > {:.0} MB), aborting load",
1309                total as f64 / (1024.0 * 1024.0),
1310                max_bytes as f64 / (1024.0 * 1024.0)
1311            );
1312            return None;
1313        }
1314        buf.extend_from_slice(&chunk[..n]);
1315    }
1316    Some(buf)
1317}
1318
1319/// Worst-case RAM this process will spend decompressing a persisted index.
1320///
1321/// #1739: this was `max_bm25_cache_bytes() * 20` — twenty times a **disk**
1322/// budget, with no reference to the file at hand or to the machine's memory. On
1323/// the default 512 MB disk budget that authorised a 10 GB allocation for any
1324/// index, however small the file; because `ctx_search` reloads on demand,
1325/// repeated calls stacked to 20 GB RSS and froze the host.
1326///
1327/// The index is decompressed into RAM, so RAM is what has to bound it, and a
1328/// given file cannot plausibly expand past a fixed ratio of its own size.
1329fn max_decompressed_bytes(compressed_bytes: u64) -> u64 {
1330    /// postcard + zstd on an index this shape expands well under this.
1331    const MAX_EXPANSION_RATIO: u64 = 20;
1332    /// Keeps small indices loadable on hosts that report little or no RAM.
1333    const FLOOR: u64 = 64 * 1024 * 1024;
1334
1335    let file_derived = compressed_bytes
1336        .saturating_mul(MAX_EXPANSION_RATIO)
1337        .max(FLOOR);
1338    match crate::core::memory_guard::rss_limit_bytes() {
1339        Some(limit) => file_derived.min(limit.max(FLOOR)),
1340        None => file_derived,
1341    }
1342}
1343
1344fn index_dir(root: &Path) -> PathBuf {
1345    crate::core::index_namespace::vectors_dir(root)
1346}
1347
1348/// Walk depth of the corpus walk. Deeper files are never indexed.
1349const CORPUS_MAX_DEPTH: usize = 20;
1350
1351/// The rules that decide corpus membership, loaded once. Shared by
1352/// [`list_code_files`] and the `index why` diagnostic ([`coverage`]), so the
1353/// explanation can never drift from what the indexer actually does.
1354pub(crate) struct CorpusRules {
1355    filter: crate::core::index_filter::IndexFileFilter,
1356    /// `DEFAULT_BM25_IGNORES` followed by `extra_ignore_patterns`, with the
1357    /// source text kept so a diagnostic can name the pattern that matched.
1358    ignore_patterns: Vec<(String, glob::Pattern)>,
1359    max_files: usize,
1360}
1361
1362impl CorpusRules {
1363    pub(crate) fn load() -> Self {
1364        Self::from_config(&crate::core::config::Config::load())
1365    }
1366
1367    fn from_config(cfg: &crate::core::config::Config) -> Self {
1368        // #735: the declared corpus filter ([index] config + CLI overlay) decides
1369        // membership before anything is chunked; the semantic index chunks this
1370        // corpus, so it inherits the same universe.
1371        let filter = crate::core::index_filter::IndexFileFilter::resolve(cfg);
1372        let ignore_patterns = DEFAULT_BM25_IGNORES
1373            .iter()
1374            .map(|p| (*p).to_string())
1375            .chain(cfg.extra_ignore_patterns.iter().cloned())
1376            .filter_map(|p| glob::Pattern::new(&p).ok().map(|g| (p, g)))
1377            .collect();
1378        // Mirrors graph_index_max_files: 0 = unlimited, default 5000 (MAX_BM25_FILES).
1379        let max_files = if cfg.bm25_max_files == 0 {
1380            usize::MAX
1381        } else {
1382            cfg.bm25_max_files as usize
1383        };
1384        Self {
1385            filter,
1386            ignore_patterns,
1387            max_files,
1388        }
1389    }
1390
1391    /// The corpus walker: gitignore per the filter, bounded depth. Callers add
1392    /// their own `filter_entry`.
1393    fn walker(&self, root: &Path) -> ignore::WalkBuilder {
1394        let mut builder = ignore::WalkBuilder::new(root);
1395        builder
1396            // #1792: the BM25 corpus is authoritative for `ctx_compose`/`ctx_overview`,
1397            // so omitting tracked dotfiles made "no match" indistinguishable from
1398            // "not indexed".
1399            .hidden(crate::core::walk_filter::SKIP_HIDDEN_IN_CONTENT_WALK)
1400            .git_ignore(self.filter.respect_gitignore)
1401            .git_global(self.filter.respect_gitignore)
1402            .git_exclude(self.filter.respect_gitignore)
1403            .require_git(false)
1404            .max_depth(Some(CORPUS_MAX_DEPTH));
1405        builder
1406    }
1407
1408    /// First default/extra ignore pattern matching `rel`.
1409    fn ignore_pattern_for(&self, rel: &str) -> Option<&str> {
1410        self.ignore_patterns
1411            .iter()
1412            .find(|(_, p)| p.matches(rel))
1413            .map(|(src, _)| src.as_str())
1414    }
1415
1416    /// Whether the declared `[index]` filter drops `rel`. Globs match on
1417    /// forward slashes so they behave identically on Windows; the index key
1418    /// keeps the platform separator (existing indexes stay valid).
1419    fn filter_excludes(&self, rel: &str) -> bool {
1420        self.filter.is_excluded(&rel.replace('\\', "/"))
1421    }
1422}