Skip to main content

lean_ctx/core/bm25_index/
source_gate.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Current source rights for index entries at the moment they are served
3//! (G04).
4//!
5//! An index chunk is text copied out of a source at build time. The index
6//! knows which file it came from (`CodeChunk::file_path`) but nothing in the
7//! chunk changes when that file is deleted, restricted, reclassified or
8//! redacted by a rule that did not exist at the build. The digest an index is
9//! bound to (`BM25Index::admission_policy`) covers the gateway policy only,
10//! and a staleness check is a rebuild trigger, not an authorization.
11//!
12//! So an index its store loaded or handed out is asked again for every chunk
13//! it is about to serve: the source is read NOW through the admitted rooted
14//! reader (`core::admitted_sources::read` — path jail, role, project policy,
15//! gateway, decided on the original bytes), and the chunk is served only if
16//! that read is storable and still contains the chunk's text. A source that
17//! is gone, outside the root, withheld, restricted, lossily decoded, changed
18//! or now rewritten at that place does not serve the chunk. This is the same
19//! question `context_admission::stored::serve_stored` asks of a bound copy;
20//! the reader is the one admission, not a second one.
21//!
22//! Where a source authority is required (`source_authority_required`, asked
23//! for the gate's own project), a provider chunk (`scheme://…`) whose origin
24//! the index has on record (`provider_origin`) is asked of its provider the
25//! same way; without protection it follows the originless rule below. The item is
26//! reacquired NOW through `ProviderOrigin::current_chunks` — the check the
27//! knowledge store and the checkpoint import already use (provider tool
28//! allowed for the role and the project policy, same project, providers
29//! enabled, the provider's reuse binding unchanged, the item still returned
30//! and unchanged, content under the project policy) — then passed through the
31//! store admission it was written through, and the chunk is served only if
32//! that text still contains it. One provider request per distinct item,
33//! bounded per gate; over the bound, or without an answer, it is not served.
34//!
35//! The other chunks without a readable text file have an origin of their
36//! own kind on record (`external_origin`), asked the same way:
37//!
38//! - delivered tool output (where a source authority is required): the
39//!   origin is bound to this chunk and the lineage of its delivery holds
40//!   (`archive::delivered::Lineage::still_admitted` — complete, every source
41//!   re-read under the current policy and role and unchanged). Its sources
42//!   are then published to the running call like a file read;
43//! - downstream tool output (where a source authority is required): closed.
44//!   A tool call cannot be replayed, so nothing proves the text current;
45//!   it is not served, not ranked and not counted until downstream tools
46//!   have a re-read contract (`external_origin::DownstreamOrigin`);
47//! - an extracted document (in every mode, a changed file is stale for
48//!   everyone): the rooted reader's path decision admits the file and its
49//!   bytes are the ones the extraction read (`DocumentOrigin::unchanged`).
50//!
51//! In each case the chunk's text must also pass the content admission
52//! unchanged. A served chunk of a provider or a document has no file
53//! lineage: it marks the call's source set unknown.
54//!
55//! A chunk with no origin on record — a chunk written before origins were
56//! kept, a recomputed source that records none — has no source authority
57//! and follows the originless rule of `serve_stored`: withheld while
58//! protection is active in any layer, re-admitted under the content rules in
59//! Community developer mode (an extracted document must also still exist).
60//!
61//! ONE gateway snapshot per gate: the gateway rules are captured when the
62//! gate is built (or handed in by a caller that already judged something
63//! under a snapshot, `SourceGate::with_admission`) and every decision of
64//! the gate uses them — file reads, provider re-admission, the content
65//! admission of chunk text, originless decisions. A configuration that
66//! changes and changes back during a call cannot admit a source the
67//! snapshot refuses. The project pack and the role are those current at
68//! each decision (a caller that needs them pinned holds a source view).
69//!
70//! The reads run inside the call's source capture and Decision Receipt: a
71//! served chunk gives the result an ordinary file lineage, and a refusal is
72//! counted like any other admission of that call. Nothing is cached beyond
73//! one gate; a gate lives for one search.
74
75use std::collections::HashMap;
76use std::path::{Path, PathBuf};
77use std::sync::Arc;
78
79use super::external_origin::ChunkOrigin;
80use super::{BM25Index, ChunkOrigins, CodeChunk, SearchResult};
81use crate::core::context_admission::stores::StoreAdmission;
82use crate::core::providers::provenance::{ProviderOrigin, with_reuse_deadline_until};
83
84/// Tool identity the sources of a search index are re-read for.
85pub(super) const SEARCH_TOOL: &str = "ctx_search";
86
87/// Delivery lineages one gate re-checks (each re-reads every source of one
88/// delivery). Over it an undecided tool-output chunk is refused.
89const MAX_LINEAGE_CHECKS: usize = 16;
90
91/// Distinct sources one gate reads AND remembers — one bound for both. Over
92/// it the gate refuses (fail closed): a source it has not decided yet is not
93/// read, not served and not added to the memo; sources already decided keep
94/// their decision. Fewer results, never an unchecked one, never unbounded
95/// memory.
96pub(crate) const MAX_SOURCES: usize = 128;
97
98/// Provider items one gate reacquires (each is a provider request with the
99/// provider's own deadline). Over it an undecided provider chunk is refused.
100const MAX_PROVIDER_CHECKS: usize = 16;
101
102/// Time one gate — one search — may spend on provider re-acquisition, counted
103/// from its first provider request. A hard bound: no request is started
104/// after it, and a request in flight ends at it
105/// (`providers::provenance::with_reuse_deadline_until` — the earlier of this
106/// deadline and the provider's own). The provider chunks left undecided are
107/// refused (not remembered) and the search returns what was decided. Three
108/// seconds keeps an interactive search answerable while leaving room for a
109/// few items of a healthy provider.
110const PROVIDER_BUDGET: std::time::Duration = std::time::Duration::from_secs(3);
111
112/// The serve-time check of one search over one index.
113pub struct SourceGate {
114    root: PathBuf,
115    tool: &'static str,
116    /// Per source asked so far: the admitted text as the reader returns it
117    /// now, with line endings normalised; `None` when it is not admitted.
118    sources: HashMap<String, Option<String>>,
119    /// Per source whose origin is not compared with a source text (delivered
120    /// or downstream tool output, a document): whether its authority holds.
121    authorities: HashMap<String, bool>,
122    /// The gateway rules every decision of this gate is made under.
123    admission: StoreAdmission,
124    /// Origins the index has on record, by chunk source.
125    origins: Arc<ChunkOrigins>,
126    provider_checks: usize,
127    lineage_checks: usize,
128    /// End of this gate's provider budget, set at its first provider
129    /// request ([`PROVIDER_BUDGET`]).
130    provider_deadline: Option<std::time::Instant>,
131    /// The root as the request scope names it (canonical when resolvable).
132    scope_root: PathBuf,
133    /// Whether a source authority is required for the project of this
134    /// gate's root; asked once per gate.
135    protected: Option<bool>,
136    withheld: usize,
137}
138
139impl SourceGate {
140    /// A gate that captures the gateway rules as they are configured now
141    /// (`carrier::gateway_snapshot`, unobserved) and decides everything
142    /// under them.
143    // pub only for lean-ctx-engine-ext; not public API
144    #[doc(hidden)]
145    pub fn new(root: &Path, tool: &'static str) -> Self {
146        Self::with_admission(
147            root,
148            tool,
149            &crate::core::context_admission::carrier::gateway_snapshot(),
150        )
151    }
152
153    /// A gate that decides under the gateway snapshot its caller already
154    /// holds: what the caller judged under `admission` and the sources this
155    /// gate reads are then judged under the same gateway rules.
156    pub(crate) fn with_admission(
157        root: &Path,
158        tool: &'static str,
159        admission: &StoreAdmission,
160    ) -> Self {
161        Self {
162            root: root.to_path_buf(),
163            tool,
164            sources: HashMap::new(),
165            authorities: HashMap::new(),
166            admission: admission.clone(),
167            origins: Arc::default(),
168            provider_checks: 0,
169            lineage_checks: 0,
170            provider_deadline: None,
171            scope_root: root.canonicalize().unwrap_or_else(|_| root.to_path_buf()),
172            protected: None,
173            withheld: 0,
174        }
175    }
176
177    /// Run `operation` in the project scope of this gate's root: the gate
178    /// decides for the index it belongs to, whatever project the calling
179    /// request or the working directory names. A request already bound to
180    /// this project keeps its scope untouched (and with it an open source
181    /// view). Under a request bound to ANOTHER project with a source view
182    /// open, `policy::runtime::active()` answers deny-all for the rebound
183    /// scope and invalidates that view: the gate then sees protection, and
184    /// the enclosing operation ends with an error — closed, never the other
185    /// project's rules applied to this index.
186    fn in_root_scope<T>(&self, operation: impl FnOnce() -> T) -> T {
187        use crate::core::policy::runtime::REQUEST_PROJECT;
188        let bound = REQUEST_PROJECT
189            .try_with(|slot| slot.borrow().clone())
190            .ok()
191            .flatten();
192        if bound.is_some_and(|bound| {
193            bound == self.scope_root || bound.canonicalize().is_ok_and(|b| b == self.scope_root)
194        }) {
195            return operation();
196        }
197        REQUEST_PROJECT.sync_scope(
198            std::cell::RefCell::new(Some(self.scope_root.clone())),
199            operation,
200        )
201    }
202
203    /// Whether protection is active in some layer for this gate's project
204    /// (`stored::source_authority_required_under`): the gateway side is read
205    /// from THIS gate's snapshot — the mode cannot differ from the rules the
206    /// gate admits under —, the pack side from the project policy in scope
207    /// (pinned for the whole search by [`pinned`]). Asked once per gate.
208    // pub only for lean-ctx-engine-ext; not public API
209    #[doc(hidden)]
210    pub fn protected(&mut self) -> bool {
211        if let Some(protected) = self.protected {
212            return protected;
213        }
214        let protected = self.in_root_scope(|| {
215            crate::core::context_admission::stored::source_authority_required_under(
216                self.admission.admission_policy(),
217            )
218        });
219        self.protected = Some(protected);
220        protected
221    }
222
223    /// This gate for an index that has `origins` on record.
224    #[must_use]
225    // pub only for lean-ctx-engine-ext; not public API
226    #[doc(hidden)]
227    pub fn with_origins(mut self, origins: &Arc<ChunkOrigins>) -> Self {
228        self.origins = Arc::clone(origins);
229        self
230    }
231
232    /// Whether this gate already holds as many decisions as it may.
233    fn over_bound(&self) -> bool {
234        self.sources.len() + self.authorities.len() >= MAX_SOURCES
235    }
236
237    /// The decision for a source whose origin is not compared with a source
238    /// text, asked once per gate in the gate's project scope. Over the bound:
239    /// refused, neither asked nor remembered.
240    fn authority_holds(&mut self, source: &str, check: impl FnOnce(&Self) -> bool) -> bool {
241        if let Some(&holds) = self.authorities.get(source) {
242            return holds;
243        }
244        if self.over_bound() {
245            return false;
246        }
247        let holds = self.in_root_scope(|| check(self));
248        self.authorities.insert(source.to_owned(), holds);
249        holds
250    }
251
252    /// Whether the content admission, under this gate's gateway snapshot and
253    /// the current project policy, leaves `text` exactly as it is and lets
254    /// it be kept: a copy the rules would withhold, restrict or rewrite is
255    /// not the copy the index holds. `label` is the source the text was
256    /// admitted under when it has one (a path, an `mcp://` reference).
257    fn admits_verbatim(&self, text: &str, label: Option<&str>) -> bool {
258        use crate::core::context_admission as admission;
259        self.in_root_scope(|| {
260            let admitted = match label {
261                Some(label) => admission::admit_source_with_snapshot(
262                    text,
263                    label,
264                    false,
265                    admission::OutputCompleteness::complete(),
266                    &self.admission,
267                )
268                .ok(),
269                None => admission::carrier::admit_carrier_text_under(
270                    text,
271                    Some(self.admission.admission_policy()),
272                    &admission::carrier::STORED,
273                )
274                .ok(),
275            };
276            admitted.is_some_and(|admitted| admitted.storable && admitted.text == text)
277        })
278    }
279
280    /// The originless rule (`serve_stored` without a binding) under this
281    /// gate's snapshot: withheld where a source authority is required,
282    /// otherwise the content admission alone.
283    fn originless(&mut self, text: &str) -> bool {
284        !self.protected() && self.admits_verbatim(text, None)
285    }
286
287    /// A chunk was served whose source the call's capture cannot name (a
288    /// provider item, a downstream result, a document): where a source
289    /// authority is required the call's source set is then unknown, never
290    /// silently the files alone. Always `true`.
291    fn served_without_file_lineage(&mut self) -> bool {
292        if self.protected() {
293            crate::core::archive::authority::mark_unbound();
294        }
295        true
296    }
297
298    /// The decision already on record for `text` of `source`, without a read
299    /// and without counting: `None` while the source is undecided.
300    pub(super) fn decided(&self, source: &str, text: &str) -> Option<bool> {
301        let admitted = self.sources.get(source)?;
302        Some(
303            admitted
304                .as_deref()
305                .is_some_and(|current| current.contains(normalised(text).as_str())),
306        )
307    }
308
309    /// The sources this gate decided are not admitted now.
310    // pub only for lean-ctx-engine-ext; not public API
311    #[doc(hidden)]
312    pub fn refused_sources(&self) -> impl Iterator<Item = &str> {
313        self.sources
314            .iter()
315            .filter(|(_, admitted)| admitted.is_none())
316            .map(|(source, _)| source.as_str())
317    }
318
319    /// Whether `text`, derived from `source` (a path relative to the root,
320    /// or an external reference), may be served now.
321    // pub only for lean-ctx-engine-ext; not public API
322    #[doc(hidden)]
323    pub fn serves(&mut self, source: &str, text: &str) -> bool {
324        self.serves_with(source, text, None)
325    }
326
327    /// [`Self::serves`] for a decision that delivers nothing (the ranking
328    /// corpus, the dense backend's source filter): the origin ledger is left
329    /// alone, so only the chunks a result actually carries taint the session.
330    pub(crate) fn admits_unserved(&mut self, source: &str, text: &str) -> bool {
331        let admitted = self.decide(source, text);
332        if !admitted {
333            self.withheld += 1;
334        }
335        admitted
336    }
337
338    /// [`Self::serves`] for a chunk with its recorded origin. A served chunk
339    /// of an external source (`scheme://`) is noted in the call's origin
340    /// ledger with its origin, or as unknown when it has none (an index
341    /// written before origins were kept, pz21 §1.6): the release point then
342    /// fences it.
343    // pub only for lean-ctx-engine-ext; not public API
344    #[doc(hidden)]
345    pub fn serves_with(
346        &mut self,
347        source: &str,
348        text: &str,
349        input_origin: Option<&crate::core::context_admission::origin::InputOrigin>,
350    ) -> bool {
351        let served = self.decide(source, text);
352        if served {
353            Self::note_served(source, input_origin);
354        } else {
355            self.withheld += 1;
356        }
357        served
358    }
359
360    /// Note a served chunk of an external source (`scheme://`, or one with a
361    /// recorded origin) in the call's origin ledger.
362    pub(crate) fn note_served(
363        source: &str,
364        input_origin: Option<&crate::core::context_admission::origin::InputOrigin>,
365    ) {
366        if source.contains("://") || input_origin.is_some() {
367            crate::core::context_admission::capture::note_origin(
368                &crate::core::context_admission::stores::class_of_path(
369                    Path::new(source),
370                    input_origin,
371                ),
372            );
373        }
374    }
375
376    /// Entries this gate refused. A count only: no path, no text.
377    #[cfg(test)]
378    pub(crate) fn withheld(&self) -> usize {
379        self.withheld
380    }
381
382    fn decide(&mut self, source: &str, text: &str) -> bool {
383        let external = source.contains("://");
384        let document = !external && crate::core::binary_detect::has_binary_extension(source);
385        let origins = Arc::clone(&self.origins);
386        let recorded = origins.get(source);
387        if let (true, Some(ChunkOrigin::Document(origin))) = (document, recorded) {
388            // In every mode: a document whose bytes changed is stale.
389            let label = self.root.join(source);
390            return self.authority_holds(source, |gate| {
391                origin.unchanged(&gate.root, source, gate.tool)
392            }) && self.admits_verbatim(text, label.to_str())
393                && self.served_without_file_lineage();
394        }
395        // An external origin is asked only where a source authority is
396        // required. Without protection (Community developer mode) an
397        // external chunk follows the originless rule: content re-admitted,
398        // no provider round trip, search usable offline.
399        let origin = match recorded {
400            Some(recorded) if external && self.protected() => match recorded {
401                ChunkOrigin::Provider(origin) => Some(&**origin),
402                ChunkOrigin::Delivery(origin) => {
403                    if !origin.binds(text) {
404                        return false;
405                    }
406                    if !self.authorities.contains_key(source) {
407                        if self.lineage_checks >= MAX_LINEAGE_CHECKS {
408                            return false;
409                        }
410                        self.lineage_checks += 1;
411                    }
412                    let served = self.authority_holds(source, |_| origin.still_admitted())
413                        && self.admits_verbatim(text, None);
414                    if served {
415                        origin.publish();
416                    }
417                    return served;
418                }
419                // Closed: a downstream result cannot be re-read, so nothing
420                // proves it current. That its server and tool are still
421                // allowed is not such a proof (`DownstreamOrigin`). The
422                // refusal is the originless one, `store.no_source_authority`.
423                ChunkOrigin::Downstream(_) => return false,
424                ChunkOrigin::Document(_) => None,
425            },
426            _ => None,
427        };
428        if origin.is_none() && (external || document) {
429            // No source that is asked: the originless rule, judged for this
430            // gate's project. An extracted document must at least still exist.
431            return (external || self.root.join(source).is_file()) && self.originless(text);
432        }
433        if let Some(served) = self.decided(source, text) {
434            return served && (origin.is_none() || self.served_without_file_lineage());
435        }
436        if self.over_bound() {
437            // Over the bound: refused, neither read nor remembered.
438            return false;
439        }
440        let admitted = match origin {
441            Some(origin) => {
442                let deadline = *self
443                    .provider_deadline
444                    .get_or_insert_with(|| std::time::Instant::now() + PROVIDER_BUDGET);
445                if self.provider_checks >= MAX_PROVIDER_CHECKS
446                    || std::time::Instant::now() >= deadline
447                {
448                    // Over the budget: refused, neither asked nor remembered.
449                    return false;
450                }
451                self.provider_checks += 1;
452                let admitted = self.read_provider(origin, deadline);
453                if admitted.is_none() && std::time::Instant::now() >= deadline {
454                    // Cut off by the budget, not answered: not a decision.
455                    return false;
456                }
457                admitted
458            }
459            None => self.read(source),
460        };
461        self.sources.insert(source.to_owned(), admitted);
462        self.decided(source, text).unwrap_or(false)
463            && (origin.is_none() || self.served_without_file_lineage())
464    }
465
466    /// What the provider returns for `origin` NOW, as the store admission
467    /// would keep it; `None` when the item is not admitted to this reader.
468    fn read_provider(
469        &self,
470        origin: &ProviderOrigin,
471        deadline: std::time::Instant,
472    ) -> Option<String> {
473        let root = self.root.to_str()?;
474        let view = match crate::core::policy::runtime::with_project_source_view(root, || {
475            with_reuse_deadline_until(Some(deadline), || origin.current_chunks(root))
476        }) {
477            Ok(Ok(view)) => view,
478            Ok(Err(refusal)) => {
479                // The kind only, never the item: a search must not tell an
480                // item it withholds from one that does not exist (K02). The
481                // call's receipt records the refused re-check (C04).
482                crate::core::context_admission::record_recheck_refusal(
483                    &self.admission,
484                    refusal.validity,
485                );
486                return None;
487            }
488            Err(_) => return None,
489        };
490        let mut current = String::new();
491        for chunk in &view.chunks {
492            let admitted = self.admission.admit(
493                &chunk.content,
494                Path::new(&chunk.file_path),
495                chunk.input_origin.as_ref(),
496            )?;
497            current.push_str(&normalised(&admitted));
498            current.push('\n');
499        }
500        Some(current)
501    }
502
503    /// The text of `source` as the admitted reader returns it now, when the
504    /// original may be kept in a derived store (complete, not restricted).
505    /// The gateway rules are this gate's snapshot; each read is bounded by
506    /// the read cap (the gate never shared a byte budget across sources).
507    fn read(&self, source: &str) -> Option<String> {
508        let path = self.root.join(source);
509        // NOTE the argument order of this entry: root first.
510        let read = crate::core::admitted_sources::read_with_admission(
511            self.root.to_str()?,
512            path.to_str()?,
513            self.tool,
514            &self.admission,
515        );
516        read.storable().map(normalised)
517    }
518}
519
520/// Line endings are not content: an index keeps `\n`-joined lines of a
521/// source that may use `\r\n`.
522fn normalised(text: &str) -> String {
523    text.lines().collect::<Vec<_>>().join("\n")
524}
525
526/// Whether `chunk` may be served through `gate`. Without a gate — a view
527/// built in the running call from sources the reader returned then — every
528/// chunk is served.
529pub fn chunk_served(gate: &mut Option<SourceGate>, chunk: &CodeChunk) -> bool {
530    gate.as_mut().is_none_or(|gate| {
531        gate.serves_with(
532            &chunk.file_path,
533            &chunk.content,
534            chunk.input_origin.as_ref(),
535        )
536    })
537}
538
539impl BM25Index {
540    /// This index as its store hands it out for `root`: every search over it
541    /// is gated ([`Self::source_gate`]).
542    #[must_use]
543    // pub only for lean-ctx-engine-ext; not public API
544    #[doc(hidden)]
545    pub fn rooted_at(mut self, root: &Path) -> Self {
546        self.source_root = Some(root.to_path_buf());
547        self
548    }
549
550    /// The gate of one search: `None` for an index without a root.
551    pub fn source_gate(&self) -> Option<SourceGate> {
552        self.source_root
553            .as_deref()
554            .map(|root| SourceGate::new(root, SEARCH_TOOL).with_origins(&self.provider_origins))
555    }
556
557    /// The `top_k` best chunks for `query` that may be served now. Pack and
558    /// role are pinned for the whole search (`pinned`); if either changed
559    /// while it ran, nothing is returned.
560    pub fn search(&self, query: &str, top_k: usize) -> Vec<SearchResult> {
561        pinned(self.source_root.as_deref(), || {
562            self.search_gated(query, top_k, &mut self.source_gate())
563        })
564        .unwrap_or_default()
565    }
566}
567
568/// Run one search over an index handed out for `root` with the project pack
569/// and the role pinned from its first decision to its last
570/// (`policy::runtime::with_project_source_view`): every gate decision inside
571/// sees one pack and one role, and a change of either while the search ran
572/// makes the view report it — the result is then `None` and the caller
573/// returns nothing. Nested calls share the outermost view.
574///
575/// A request bound to ANOTHER project keeps its own view; the gate's
576/// rebinding to its root then answers deny-all and invalidates that view
577/// (`SourceGate::in_root_scope`), so such a search also ends in `None`. A
578/// root that cannot be resolved has no view: `None`. Without a root (a view
579/// built in the running call, no gate) the search runs as it is.
580pub fn pinned<T>(root: Option<&Path>, search: impl FnOnce() -> T) -> Option<T> {
581    let Some(root) = root else {
582        return Some(search());
583    };
584    // An index of a root the request's Workspace does not contain (detached,
585    // or never attached) serves nothing (#2120).
586    if !crate::core::workspace_authority::root_authorized(root) {
587        return None;
588    }
589    crate::core::policy::runtime::with_project_source_view(root.to_str()?, search).ok()
590}
591
592/// How many candidates a similarity search fetches to serve `top_k` through
593/// a gate: a refused candidate must not cost a result slot, and the walk
594/// stays bounded. More refusals than the surplus mean fewer results.
595#[cfg(feature = "embeddings")]
596// pub only for lean-ctx-engine-ext; not public API
597#[doc(hidden)]
598pub fn overfetch(top_k: usize) -> usize {
599    top_k.saturating_add(top_k.clamp(16, MAX_SOURCES))
600}
601
602#[cfg(test)]
603mod tests {
604    use super::*;
605    use crate::core::policy::runtime::TestPolicyOverride;
606
607    /// A chunk of a persisted index is served while the admitted reader still
608    /// returns its text, and is no longer served once the source is withdrawn:
609    /// deleted, or rewritten so that the stored text is no longer in it. The
610    /// next chunk takes its place; an index without a root is not asked.
611    #[test]
612    fn a_loaded_index_serves_a_chunk_only_while_its_source_admits_it() {
613        let _data = crate::core::data_dir::isolated_data_dir();
614        let _community = TestPolicyOverride::set(None);
615        let project = tempfile::tempdir().expect("project");
616        let root = project.path();
617        let withdrawn = root.join("billing.rs");
618        std::fs::write(
619            &withdrawn,
620            "pub fn settle_canary() -> u32 {\n    let reconciliation = 7319;\n    reconciliation\n}\n",
621        )
622        .expect("source");
623        std::fs::write(
624            root.join("ledger.rs"),
625            "pub fn settle_ledger() -> u32 {\n    let reconciliation = 42;\n    reconciliation\n}\n",
626        )
627        .expect("source");
628
629        let built = BM25Index::build_from_directory(root);
630        built.save(root).expect("persisted");
631        let files = |index: &BM25Index| -> Vec<String> {
632            index
633                .search("reconciliation", 10)
634                .into_iter()
635                .map(|hit| hit.file_path)
636                .collect()
637        };
638
639        let loaded = BM25Index::load(root).expect("index of the current policy");
640        assert!(loaded.source_root.is_some());
641        let served = files(&loaded);
642        assert!(served.iter().any(|file| file == "billing.rs"), "{served:?}");
643        assert!(served.iter().any(|file| file == "ledger.rs"), "{served:?}");
644        assert!(!loaded.search("settle_canary", 5).is_empty());
645        // The same chunks without a root (taken before the source is
646        // withdrawn: a search that finds it deleted evicts it from the store).
647        let unrooted = BM25Index::load_persisted(root).expect("persisted file");
648
649        // Rewritten: the stored text is no longer what the reader returns.
650        std::fs::write(&withdrawn, "pub fn unrelated() {}\n").expect("rewrite");
651        let mut gate = loaded.source_gate();
652        let hits = loaded.search_gated("reconciliation", 10, &mut gate);
653        assert!(hits.iter().all(|hit| hit.file_path == "ledger.rs"));
654        assert!(!hits.is_empty());
655        assert!(gate.as_ref().is_some_and(|gate| gate.withheld() >= 1));
656
657        // Deleted: nothing of it is served, name and path included, and the
658        // chunk of the other source takes the slot.
659        std::fs::remove_file(&withdrawn).expect("delete");
660        let served = files(&loaded);
661        assert!(!served.is_empty());
662        assert!(served.iter().all(|file| file == "ledger.rs"), "{served:?}");
663        assert!(loaded.search("settle_canary", 5).is_empty());
664
665        // Over the bound: an undecided source is refused and not remembered.
666        let mut full = SourceGate::new(root, SEARCH_TOOL);
667        for n in 0..MAX_SOURCES {
668            full.sources.insert(format!("known-{n}.rs"), None);
669        }
670        assert!(!full.serves("ledger.rs", "reconciliation"));
671        assert_eq!(full.sources.len(), MAX_SOURCES);
672
673        // Without a root: a fresh view, not asked again.
674        assert!(unrooted.source_root.is_none());
675        assert!(files(&unrooted).iter().any(|file| file == "billing.rs"));
676    }
677}