Skip to main content

lean_ctx_ext/core/
dense_backend.rs

1// SPDX-License-Identifier: Apache-2.0
2#[cfg(feature = "embeddings")]
3use std::path::Path;
4
5#[cfg(feature = "embeddings")]
6use crate::core::bm25_index::BM25Index;
7#[cfg(any(feature = "qdrant", feature = "pgvector"))]
8use crate::core::bm25_index::ChunkKind;
9#[cfg(feature = "embeddings")]
10use crate::core::hnsw::FlatEmbeddings;
11#[cfg(feature = "embeddings")]
12use crate::core::hybrid_search::{DenseSearchResult, HybridConfig, HybridResult};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum DenseBackendKind {
16    Local,
17    #[cfg(feature = "qdrant")]
18    Qdrant,
19    #[cfg(feature = "pgvector")]
20    Pgvector,
21}
22
23impl DenseBackendKind {
24    pub fn try_from_env() -> Result<Self, String> {
25        let explicit = std::env::var("LEANCTX_DENSE_BACKEND")
26            .ok()
27            .map(|v| v.trim().to_ascii_lowercase())
28            .filter(|v| !v.is_empty());
29
30        let inferred_qdrant =
31            std::env::var("LEANCTX_QDRANT_URL").is_ok_and(|v| !v.trim().is_empty());
32        let inferred_pgvector =
33            std::env::var("LEANCTX_PGVECTOR_URL").is_ok_and(|v| !v.trim().is_empty());
34
35        let requested = explicit
36            .or_else(|| inferred_qdrant.then_some("qdrant".to_string()))
37            .or_else(|| inferred_pgvector.then_some("pgvector".to_string()));
38
39        match requested.as_deref() {
40            None | Some("local") => Ok(Self::Local),
41            Some("qdrant") => {
42                #[cfg(feature = "qdrant")]
43                {
44                    Ok(Self::Qdrant)
45                }
46                #[cfg(not(feature = "qdrant"))]
47                {
48                    Err("Dense backend 'qdrant' requested, but feature 'qdrant' is not enabled. Rebuild with --features qdrant.".to_string())
49                }
50            }
51            Some("pgvector") => {
52                #[cfg(feature = "pgvector")]
53                {
54                    Ok(Self::Pgvector)
55                }
56                #[cfg(not(feature = "pgvector"))]
57                {
58                    Err("Dense backend 'pgvector' requested, but feature 'pgvector' is not enabled. Rebuild with --features pgvector.".to_string())
59                }
60            }
61            Some(other) => Err(format!(
62                "Unknown LEANCTX_DENSE_BACKEND={other:?} (expected 'local', 'qdrant' or 'pgvector')"
63            )),
64        }
65    }
66
67    pub fn label(&self) -> &'static str {
68        match self {
69            Self::Local => "local",
70            #[cfg(feature = "qdrant")]
71            Self::Qdrant => "qdrant",
72            #[cfg(feature = "pgvector")]
73            Self::Pgvector => "pgvector",
74        }
75    }
76}
77
78#[cfg(feature = "embeddings")]
79#[allow(clippy::too_many_arguments)]
80pub fn dense_results_as_hybrid(
81    backend: DenseBackendKind,
82    root: &Path,
83    index: &BM25Index,
84    engine: &crate::core::embeddings::EmbeddingEngine,
85    aligned_embeddings: &FlatEmbeddings,
86    changed_files: &[String],
87    query: &str,
88    top_k: usize,
89    filter: Option<&dyn Fn(&str) -> bool>,
90) -> Result<Vec<HybridResult>, String> {
91    // Pack and role pinned for the whole search; a change while it ran
92    // returns nothing (`source_gate::pinned`).
93    let dense =
94        crate::core::bm25_index::source_gate::pinned(gate_root(backend, root, index), || {
95            dense_results(
96                backend,
97                root,
98                index,
99                engine,
100                aligned_embeddings,
101                changed_files,
102                query,
103                top_k,
104                filter,
105            )
106        })
107        .unwrap_or_else(|| Ok(Vec::new()))?;
108
109    Ok(dense
110        .into_iter()
111        .map(|d| HybridResult {
112            file_path: d.file_path,
113            symbol_name: d.symbol_name,
114            kind: d.kind,
115            start_line: d.start_line,
116            end_line: d.end_line,
117            snippet: d.snippet,
118            rrf_score: d.similarity as f64,
119            bm25_score: None,
120            dense_score: Some(d.similarity),
121            bm25_rank: None,
122            dense_rank: None,
123        })
124        .collect())
125}
126
127/// The root whose gate a search of `backend` decides under: the root the
128/// index was handed out for (none for a view built in the running call), and
129/// for a remote backend always the project root its rows belong to.
130#[cfg(feature = "embeddings")]
131fn gate_root<'a>(
132    backend: DenseBackendKind,
133    root: &'a Path,
134    index: &'a BM25Index,
135) -> Option<&'a Path> {
136    if matches!(backend, DenseBackendKind::Local) {
137        index.source_root.as_deref()
138    } else {
139        Some(root)
140    }
141}
142
143/// Lexical + dense search with fusion. Pack and role are pinned for the
144/// whole search — both candidate lists and every gate decision — and a
145/// change of either while it ran returns nothing (`source_gate::pinned`).
146#[cfg(feature = "embeddings")]
147#[allow(clippy::too_many_arguments)]
148pub fn hybrid_results(
149    backend: DenseBackendKind,
150    root: &Path,
151    index: &BM25Index,
152    engine: &crate::core::embeddings::EmbeddingEngine,
153    aligned_embeddings: &FlatEmbeddings,
154    changed_files: &[String],
155    query: &str,
156    top_k: usize,
157    config: &HybridConfig,
158    filter: Option<&dyn Fn(&str) -> bool>,
159    graph_file_ranks: Option<&std::collections::HashMap<String, usize>>,
160) -> Result<Vec<HybridResult>, String> {
161    crate::core::bm25_index::source_gate::pinned(gate_root(backend, root, index), || {
162        hybrid_results_pinned(
163            backend,
164            root,
165            index,
166            engine,
167            aligned_embeddings,
168            changed_files,
169            query,
170            top_k,
171            config,
172            filter,
173            graph_file_ranks,
174        )
175    })
176    .unwrap_or_else(|| Ok(Vec::new()))
177}
178
179#[cfg(feature = "embeddings")]
180#[allow(clippy::too_many_arguments)]
181fn hybrid_results_pinned(
182    backend: DenseBackendKind,
183    root: &Path,
184    index: &BM25Index,
185    engine: &crate::core::embeddings::EmbeddingEngine,
186    aligned_embeddings: &FlatEmbeddings,
187    changed_files: &[String],
188    query: &str,
189    top_k: usize,
190    config: &HybridConfig,
191    filter: Option<&dyn Fn(&str) -> bool>,
192    graph_file_ranks: Option<&std::collections::HashMap<String, usize>>,
193) -> Result<Vec<HybridResult>, String> {
194    match backend {
195        DenseBackendKind::Local => {
196            let _ = (root, changed_files);
197            let mut results = crate::core::hybrid_search::hybrid_search(
198                query,
199                index,
200                Some(engine),
201                Some(aligned_embeddings),
202                top_k,
203                config,
204                graph_file_ranks,
205            );
206            if let Some(pred) = filter {
207                results.retain(|r| pred(&r.file_path));
208            }
209            results.truncate(top_k);
210            Ok(results)
211        }
212        #[cfg(feature = "qdrant")]
213        DenseBackendKind::Qdrant => remote_hybrid_results(
214            backend,
215            root,
216            index,
217            engine,
218            aligned_embeddings,
219            changed_files,
220            query,
221            top_k,
222            config,
223            filter,
224            graph_file_ranks,
225        ),
226        #[cfg(feature = "pgvector")]
227        DenseBackendKind::Pgvector => remote_hybrid_results(
228            backend,
229            root,
230            index,
231            engine,
232            aligned_embeddings,
233            changed_files,
234            query,
235            top_k,
236            config,
237            filter,
238            graph_file_ranks,
239        ),
240    }
241}
242
243/// Shared BM25+dense RRF pipeline for remote vector backends (qdrant, pgvector):
244/// the backends differ only in where `dense_results` fetches from.
245#[cfg(all(feature = "embeddings", any(feature = "qdrant", feature = "pgvector")))]
246#[allow(clippy::too_many_arguments)]
247fn remote_hybrid_results(
248    backend: DenseBackendKind,
249    root: &Path,
250    index: &BM25Index,
251    engine: &crate::core::embeddings::EmbeddingEngine,
252    aligned_embeddings: &FlatEmbeddings,
253    changed_files: &[String],
254    query: &str,
255    top_k: usize,
256    config: &HybridConfig,
257    filter: Option<&dyn Fn(&str) -> bool>,
258    graph_file_ranks: Option<&std::collections::HashMap<String, usize>>,
259) -> Result<Vec<HybridResult>, String> {
260    let bm25_k = config.bm25_candidates.max(top_k);
261    let dense_k = config.dense_candidates.max(top_k);
262
263    let mut bm25 = index.search(query, bm25_k);
264    if let Some(pred) = filter {
265        bm25.retain(|r| pred(&r.file_path));
266    }
267
268    let dense = dense_results(
269        backend,
270        root,
271        index,
272        engine,
273        aligned_embeddings,
274        changed_files,
275        query,
276        dense_k,
277        filter,
278    )?;
279
280    let mut fused = crate::core::hybrid_search::reciprocal_rank_fusion(
281        &bm25,
282        &dense,
283        config,
284        top_k,
285        graph_file_ranks,
286    );
287    if let Some(pred) = filter {
288        fused.retain(|r| pred(&r.file_path));
289    }
290    fused.truncate(top_k);
291    Ok(fused)
292}
293
294#[cfg(feature = "embeddings")]
295#[allow(clippy::too_many_arguments)]
296fn dense_results(
297    backend: DenseBackendKind,
298    root: &Path,
299    index: &BM25Index,
300    engine: &crate::core::embeddings::EmbeddingEngine,
301    aligned_embeddings: &FlatEmbeddings,
302    changed_files: &[String],
303    query: &str,
304    top_k: usize,
305    filter: Option<&dyn Fn(&str) -> bool>,
306) -> Result<Vec<DenseSearchResult>, String> {
307    match backend {
308        DenseBackendKind::Local => {
309            let _ = (root, changed_files);
310            dense_results_local(index, engine, aligned_embeddings, query, top_k, filter)
311        }
312        #[cfg(feature = "qdrant")]
313        DenseBackendKind::Qdrant => {
314            let vecs: Vec<Vec<f32>> = (0..aligned_embeddings.n_vectors())
315                .map(|i| aligned_embeddings.get_vec(i))
316                .collect();
317            dense_results_qdrant(
318                root,
319                index,
320                engine,
321                &vecs,
322                changed_files,
323                query,
324                top_k,
325                filter,
326            )
327        }
328        #[cfg(feature = "pgvector")]
329        DenseBackendKind::Pgvector => {
330            let vecs: Vec<Vec<f32>> = (0..aligned_embeddings.n_vectors())
331                .map(|i| aligned_embeddings.get_vec(i))
332                .collect();
333            dense_results_pgvector(
334                root,
335                index,
336                engine,
337                &vecs,
338                changed_files,
339                query,
340                top_k,
341                filter,
342            )
343        }
344    }
345}
346
347#[cfg(feature = "embeddings")]
348fn dense_results_local(
349    index: &BM25Index,
350    engine: &crate::core::embeddings::EmbeddingEngine,
351    aligned_embeddings: &FlatEmbeddings,
352    query: &str,
353    top_k: usize,
354    filter: Option<&dyn Fn(&str) -> bool>,
355) -> Result<Vec<DenseSearchResult>, String> {
356    let query_embedding = engine
357        .embed_query(query)
358        .map_err(|e| format!("embedding failed: {e}"))?;
359
360    // Serve-time source gate (G04): the vector of a withdrawn source may still
361    // be the nearest one, but its chunk is not served. A gated search fetches
362    // a bounded surplus and cuts after the gate, so such a chunk neither
363    // occupies a slot nor moves the cut.
364    let mut gate = index.source_gate();
365    let fetch = if gate.is_some() {
366        crate::core::bm25_index::source_gate::overfetch(top_k)
367    } else {
368        top_k
369    };
370    let top = top_k_by_similarity(&query_embedding, aligned_embeddings, fetch, |i| {
371        let Some(pred) = filter else { return true };
372        index.chunks.get(i).is_some_and(|c| pred(&c.file_path))
373    });
374
375    Ok(top
376        .into_iter()
377        .filter_map(|(idx, sim)| {
378            let chunk = index.chunks.get(idx)?;
379            if !crate::core::bm25_index::source_gate::chunk_served(&mut gate, chunk) {
380                return None;
381            }
382            let snippet = chunk.content.lines().take(5).collect::<Vec<_>>().join("\n");
383            Some(DenseSearchResult {
384                chunk_idx: idx,
385                similarity: sim,
386                file_path: chunk.file_path.clone(),
387                symbol_name: chunk.symbol_name.clone(),
388                kind: chunk.kind.clone(),
389                start_line: chunk.start_line,
390                end_line: chunk.end_line,
391                snippet,
392            })
393        })
394        .take(top_k)
395        .collect())
396}
397
398/// Min-heap based Top-K selection over a flat embedding buffer.
399/// O(n log k) instead of O(n log n) full sort. The filter is applied inline
400/// during the scan so only matching chunks are considered — post-filtering
401/// cannot drop below `top_k` results regardless of filter selectivity.
402///
403/// Uses sequential memory access (one dereference) via `FlatEmbeddings::get`,
404/// unlike the old `Arc<[Vec<f32>]>` layout which had two-level indirection.
405#[cfg(feature = "embeddings")]
406fn top_k_by_similarity(
407    query: &[f32],
408    embeddings: &FlatEmbeddings,
409    k: usize,
410    filter: impl Fn(usize) -> bool,
411) -> Vec<(usize, f32)> {
412    use std::cmp::Ordering;
413    use std::collections::BinaryHeap;
414
415    #[derive(PartialEq)]
416    struct MinEntry(f32, usize);
417
418    impl Eq for MinEntry {}
419    impl PartialOrd for MinEntry {
420        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
421            Some(self.cmp(other))
422        }
423    }
424    impl Ord for MinEntry {
425        fn cmp(&self, other: &Self) -> Ordering {
426            other
427                .0
428                .partial_cmp(&self.0)
429                .unwrap_or(Ordering::Equal)
430                .then_with(|| self.1.cmp(&other.1))
431        }
432    }
433
434    let n = embeddings.n_vectors();
435    let mut heap: BinaryHeap<MinEntry> = BinaryHeap::with_capacity(k + 1);
436
437    for i in 0..n {
438        if !filter(i) {
439            continue;
440        }
441        let emb = embeddings.get(i);
442        let sim = crate::core::embeddings::cosine_similarity(query, emb);
443        if heap.len() < k {
444            heap.push(MinEntry(sim, i));
445        } else if let Some(min) = heap.peek()
446            && sim > min.0
447        {
448            heap.pop();
449            heap.push(MinEntry(sim, i));
450        }
451    }
452
453    let mut result: Vec<(usize, f32)> = heap.into_iter().map(|e| (e.1, e.0)).collect();
454    result.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
455    result
456}
457
458#[cfg(feature = "qdrant")]
459#[cfg(feature = "embeddings")]
460fn dense_results_qdrant(
461    root: &Path,
462    index: &BM25Index,
463    engine: &crate::core::embeddings::EmbeddingEngine,
464    aligned_embeddings: &[Vec<f32>],
465    changed_files: &[String],
466    query: &str,
467    top_k: usize,
468    filter: Option<&dyn Fn(&str) -> bool>,
469) -> Result<Vec<DenseSearchResult>, String> {
470    let store = crate::core::qdrant_store::QdrantStore::from_env()?;
471    let collection = store.collection_name(root, engine.dimensions())?;
472    let created_new = store.ensure_collection(&collection, engine.dimensions())?;
473    store.sync_index(
474        &collection,
475        index,
476        aligned_embeddings,
477        changed_files,
478        created_new,
479    )?;
480
481    let query_vec = engine
482        .embed_query(query)
483        .map_err(|e| format!("embedding failed: {e}"))?;
484
485    // A row of a source the admitted reader no longer returns is not served,
486    // path and symbol name included (G04). Where a source authority is
487    // required the backend ranks admitted sources only (`remote_candidates`).
488    let mut gate = crate::core::bm25_index::source_gate::SourceGate::new(root, "ctx_search")
489        .with_origins(&index.provider_origins);
490    let hits = remote_candidates(
491        &mut gate,
492        index,
493        query,
494        top_k,
495        |limit, sources| match sources {
496            Some(sources) => store.search_within(&collection, &query_vec, limit, sources),
497            None => store.search(&collection, &query_vec, limit),
498        },
499    )?;
500    let mut out = Vec::with_capacity(top_k.min(hits.len()));
501    let mut undigested = Vec::new();
502    for hit in hits {
503        if out.len() >= top_k {
504            break;
505        }
506        if let Some(pred) = filter
507            && !pred(&hit.file_path)
508        {
509            continue;
510        }
511        let row = RemoteRow {
512            source: &hit.file_path,
513            start_line: hit.start_line,
514            end_line: hit.end_line,
515            content_digest: hit.content_digest.as_deref(),
516        };
517        let Some(snippet) = remote_row_snippet(&mut gate, index, root, &row, &mut undigested)
518        else {
519            continue;
520        };
521        out.push(DenseSearchResult {
522            chunk_idx: 0,
523            similarity: hit.score,
524            file_path: hit.file_path,
525            symbol_name: hit.symbol_name,
526            kind: hit.kind,
527            start_line: hit.start_line,
528            end_line: hit.end_line,
529            snippet,
530        });
531    }
532    forget_deleted_sources(root, &gate, |gone| {
533        store.sync_index(&collection, &BM25Index::new(), &[], gone, false)
534    });
535    resync_undigested(undigested, |sources| {
536        store.sync_index(&collection, index, aligned_embeddings, sources, false)
537    });
538    Ok(out)
539}
540
541#[cfg(feature = "pgvector")]
542#[cfg(feature = "embeddings")]
543#[allow(clippy::too_many_arguments)]
544fn dense_results_pgvector(
545    root: &Path,
546    index: &BM25Index,
547    engine: &crate::core::embeddings::EmbeddingEngine,
548    aligned_embeddings: &[Vec<f32>],
549    changed_files: &[String],
550    query: &str,
551    top_k: usize,
552    filter: Option<&dyn Fn(&str) -> bool>,
553) -> Result<Vec<DenseSearchResult>, String> {
554    let store = crate::core::pgvector_store::PgvectorStore::from_env()?;
555    let table = store.table_name(root, engine.dimensions())?;
556    let created_new = store.ensure_table(&table, engine.dimensions())?;
557    store.sync_index(
558        &table,
559        index,
560        aligned_embeddings,
561        changed_files,
562        created_new,
563    )?;
564
565    let query_vec = engine
566        .embed_query(query)
567        .map_err(|e| format!("embedding failed: {e}"))?;
568
569    // As `dense_results_qdrant`: admitted sources only where a source
570    // authority is required, a bounded surplus cut after the gate otherwise.
571    let mut gate = crate::core::bm25_index::source_gate::SourceGate::new(root, "ctx_search")
572        .with_origins(&index.provider_origins);
573    let hits = remote_candidates(
574        &mut gate,
575        index,
576        query,
577        top_k,
578        |limit, sources| match sources {
579            Some(sources) => store.search_within(&table, &query_vec, limit, sources),
580            None => store.search(&table, &query_vec, limit),
581        },
582    )?;
583    let mut out = Vec::with_capacity(top_k.min(hits.len()));
584    let mut undigested = Vec::new();
585    for hit in hits {
586        if out.len() >= top_k {
587            break;
588        }
589        if let Some(pred) = filter
590            && !pred(&hit.file_path)
591        {
592            continue;
593        }
594        let row = RemoteRow {
595            source: &hit.file_path,
596            start_line: hit.start_line,
597            end_line: hit.end_line,
598            content_digest: hit.content_digest.as_deref(),
599        };
600        let Some(snippet) = remote_row_snippet(&mut gate, index, root, &row, &mut undigested)
601        else {
602            continue;
603        };
604        out.push(DenseSearchResult {
605            chunk_idx: 0,
606            similarity: hit.score,
607            file_path: hit.file_path,
608            symbol_name: hit.symbol_name,
609            kind: hit.kind,
610            start_line: hit.start_line,
611            end_line: hit.end_line,
612            snippet,
613        });
614    }
615    forget_deleted_sources(root, &gate, |gone| {
616        store.sync_index(&table, &BM25Index::new(), &[], gone, false)
617    });
618    resync_undigested(undigested, |sources| {
619        store.sync_index(&table, index, aligned_embeddings, sources, false)
620    });
621    Ok(out)
622}
623
624/// The rows a remote dense search is served from, best first.
625///
626/// Without protection (Community developer mode): the backend's nearest
627/// rows with a bounded surplus; the caller gates them and cuts afterwards —
628/// today's behaviour.
629///
630/// Where a source authority is required the backend must not rank what may
631/// not be served, and no unrestricted request is sent at all. The admitted
632/// sources are decided FIRST, from what the Engine holds locally — the
633/// sources of `index`, the index the remote table is synchronised from —
634/// through the gate, in the deterministic bounded order of
635/// `BM25Index::admitted_sources` (lexical candidates of the query, then the
636/// rest by path, at most the gate's bound). The ONE request is then
637/// restricted, in the backend, to those sources (`search_within`: a payload
638/// filter in Qdrant, a bound variable in PostgreSQL, on the `file_path`
639/// every row has carried since the tables exist). Rows of refused,
640/// undecided or locally unknown sources are not ranked: no score, no place
641/// before the limit.
642///
643/// No admitted source: no request, nothing served. A restriction the
644/// backend cannot take (too large to bind) is an error, never an unfiltered
645/// ranking. A corpus of more sources than the bound is searched in its
646/// first sources of that order only (truncated closed). Cost under
647/// protection: up to the bound in admitted source reads before the request
648/// (the lexical search of the same call decides through its own gate).
649#[cfg(all(feature = "embeddings", any(feature = "qdrant", feature = "pgvector")))]
650fn remote_candidates<Hit>(
651    gate: &mut crate::core::bm25_index::source_gate::SourceGate,
652    index: &BM25Index,
653    query: &str,
654    top_k: usize,
655    search: impl Fn(usize, Option<&[String]>) -> Result<Vec<Hit>, String>,
656) -> Result<Vec<Hit>, String> {
657    let fetch = crate::core::bm25_index::source_gate::overfetch(top_k);
658    if !gate.protected() {
659        return search(fetch, None);
660    }
661    let admitted = index.admitted_sources(query, gate);
662    if admitted.is_empty() {
663        return Ok(Vec::new());
664    }
665    search(fetch, Some(&admitted))
666}
667
668/// What a remote row says about the chunk it was written for.
669#[cfg(any(feature = "qdrant", feature = "pgvector"))]
670struct RemoteRow<'a> {
671    source: &'a str,
672    start_line: usize,
673    end_line: usize,
674    /// `external_origin::chunk_digest` of the chunk, on rows written since
675    /// the stores keep it.
676    content_digest: Option<&'a str>,
677}
678
679/// The snippet of a remote row that may be served now; `None` when it may
680/// not.
681///
682/// A row of a project file is served while the admitted reader still
683/// returns the lines it names. A row of an external chunk (`scheme://…`)
684/// has no file to read; where a source authority is required it is served
685/// only as the chunk the local index holds: the row's content digest must
686/// be the digest of a chunk of that source in `index`, and the gate must
687/// serve that chunk — for an origin bound to one text that is the digest in
688/// the origin on record. A row without a digest (written before the stores
689/// kept one) is not served there and its source is noted in `undigested`
690/// for re-synchronisation; it is never served unverified.
691#[cfg(any(feature = "qdrant", feature = "pgvector"))]
692fn remote_row_snippet(
693    gate: &mut crate::core::bm25_index::source_gate::SourceGate,
694    index: &BM25Index,
695    root: &Path,
696    row: &RemoteRow<'_>,
697    undigested: &mut Vec<String>,
698) -> Option<String> {
699    use crate::core::bm25_index::external_origin::chunk_digest;
700    if row.source.contains("://") && gate.protected() {
701        let Some(digest) = row.content_digest else {
702            undigested.push(row.source.to_owned());
703            return None;
704        };
705        let chunk = index.chunks.iter().find(|chunk| {
706            chunk.file_path == row.source && chunk_digest(&chunk.content) == digest
707        })?;
708        return gate
709            .serves_with(
710                &chunk.file_path,
711                &chunk.content,
712                chunk.input_origin.as_ref(),
713            )
714            .then(|| chunk.content.lines().take(5).collect::<Vec<_>>().join("\n"));
715    }
716    let snippet = snippet_from_disk(root, row.source, row.start_line, row.end_line, 5);
717    gate.serves(row.source, &snippet).then_some(snippet)
718}
719
720/// Write the rows of external sources that were found without a content
721/// digest again, through the store's replace path (`sync_index` deletes the
722/// source's rows and upserts its current chunks, now with their digest).
723/// Bounded and best effort: until it succeeds those rows stay unserved.
724#[cfg(any(feature = "qdrant", feature = "pgvector"))]
725fn resync_undigested(
726    mut sources: Vec<String>,
727    resync: impl FnOnce(&[String]) -> Result<(), String>,
728) {
729    /// Sources one search writes again.
730    const MAX_RESYNCED_SOURCES: usize = 8;
731    sources.sort();
732    sources.dedup();
733    sources.truncate(MAX_RESYNCED_SOURCES);
734    if !sources.is_empty() && resync(&sources).is_err() {
735        tracing::debug!("[dense] rows without a content digest could not be written again");
736    }
737}
738
739/// Remove the rows of the sources `gate` refused that no longer exist from a
740/// remote table, through the store's own replace path (`sync_index` deletes a
741/// changed file's rows and upserts its chunks — none, for an empty index).
742/// Only a deleted source: admission is the reader's, the table is shared, so
743/// a refusal for this reader must not remove a row for another. Bounded and
744/// best effort — a failed delete leaves rows the gate keeps refusing.
745#[cfg(any(feature = "qdrant", feature = "pgvector"))]
746fn forget_deleted_sources(
747    root: &Path,
748    gate: &crate::core::bm25_index::source_gate::SourceGate,
749    delete: impl FnOnce(&[String]) -> Result<(), String>,
750) {
751    /// Deleted sources one search removes from the remote table.
752    const MAX_DELETED_SOURCES: usize = 8;
753    let mut gone: Vec<String> = gate
754        .refused_sources()
755        .filter(|source| !source.contains("://") && !root.join(source).exists())
756        .map(str::to_owned)
757        .collect();
758    gone.sort();
759    gone.truncate(MAX_DELETED_SOURCES);
760    if !gone.is_empty() && delete(&gone).is_err() {
761        tracing::debug!("[dense] rows of deleted sources could not be removed");
762    }
763}
764
765#[cfg(any(feature = "qdrant", feature = "pgvector"))]
766fn snippet_from_disk(
767    root: &Path,
768    rel_path: &str,
769    start_line: usize,
770    end_line: usize,
771    max_lines: usize,
772) -> String {
773    let Ok(path) = crate::core::pathjail::jail_path(&root.join(rel_path), root) else {
774        return String::new();
775    };
776    // Snippets are served to the model: admitted text only (G5).
777    let Some(content) = crate::core::context_admission::stores::admitted_store_text(&path) else {
778        return String::new();
779    };
780    let lines: Vec<&str> = content.lines().collect();
781    if lines.is_empty() {
782        return String::new();
783    }
784    let start = start_line.saturating_sub(1).min(lines.len());
785    let end = end_line.max(start_line).min(lines.len());
786    let mut slice = &lines[start..end];
787    if slice.len() > max_lines {
788        slice = &slice[..max_lines];
789    }
790    slice.join("\n")
791}
792
793#[cfg(any(feature = "qdrant", feature = "pgvector"))]
794pub fn kind_to_str(kind: &ChunkKind) -> &'static str {
795    match kind {
796        ChunkKind::Function => "Function",
797        ChunkKind::Struct => "Struct",
798        ChunkKind::Impl => "Impl",
799        ChunkKind::Module => "Module",
800        ChunkKind::Class => "Class",
801        ChunkKind::Method => "Method",
802        ChunkKind::Issue => "Issue",
803        ChunkKind::PullRequest => "PullRequest",
804        ChunkKind::WikiPage => "WikiPage",
805        ChunkKind::DbSchema => "DbSchema",
806        ChunkKind::ApiEndpoint => "ApiEndpoint",
807        ChunkKind::Ticket => "Ticket",
808        ChunkKind::ExternalOther => "ExternalOther",
809        ChunkKind::Other => "Other",
810    }
811}
812
813#[cfg(any(feature = "qdrant", feature = "pgvector"))]
814pub fn kind_from_str(s: &str) -> ChunkKind {
815    match s {
816        "Function" => ChunkKind::Function,
817        "Struct" => ChunkKind::Struct,
818        "Impl" => ChunkKind::Impl,
819        "Module" => ChunkKind::Module,
820        "Class" => ChunkKind::Class,
821        "Method" => ChunkKind::Method,
822        "Issue" => ChunkKind::Issue,
823        "PullRequest" => ChunkKind::PullRequest,
824        "WikiPage" => ChunkKind::WikiPage,
825        "DbSchema" => ChunkKind::DbSchema,
826        "ApiEndpoint" => ChunkKind::ApiEndpoint,
827        "Ticket" => ChunkKind::Ticket,
828        "ExternalOther" => ChunkKind::ExternalOther,
829        _ => ChunkKind::Other,
830    }
831}
832
833#[cfg(test)]
834pub mod tests {
835    use super::*;
836    fn set_env(key: &str, value: Option<&str>) -> Option<String> {
837        let old = std::env::var(key).ok();
838        match value {
839            Some(v) => crate::test_env::set_var(key, v),
840            None => crate::test_env::remove_var(key),
841        }
842        old
843    }
844
845    fn restore_env(key: &str, old: Option<String>) {
846        match old {
847            Some(v) => crate::test_env::set_var(key, v),
848            None => crate::test_env::remove_var(key),
849        }
850    }
851
852    #[test]
853    fn dense_backend_defaults_to_local() {
854        let _g = crate::core::data_dir::test_env_lock();
855        let old_backend = set_env("LEANCTX_DENSE_BACKEND", None);
856        let old_url = set_env("LEANCTX_QDRANT_URL", None);
857        let old_pg = set_env("LEANCTX_PGVECTOR_URL", None);
858
859        let got = DenseBackendKind::try_from_env().unwrap();
860        assert_eq!(got, DenseBackendKind::Local);
861
862        restore_env("LEANCTX_DENSE_BACKEND", old_backend);
863        restore_env("LEANCTX_QDRANT_URL", old_url);
864        restore_env("LEANCTX_PGVECTOR_URL", old_pg);
865    }
866
867    #[test]
868    fn dense_backend_unknown_value_errors() {
869        let _g = crate::core::data_dir::test_env_lock();
870        let old_backend = set_env("LEANCTX_DENSE_BACKEND", Some("wat"));
871        let old_url = set_env("LEANCTX_QDRANT_URL", None);
872
873        let err = DenseBackendKind::try_from_env().unwrap_err();
874        assert!(err.contains("Unknown LEANCTX_DENSE_BACKEND"));
875
876        restore_env("LEANCTX_DENSE_BACKEND", old_backend);
877        restore_env("LEANCTX_QDRANT_URL", old_url);
878    }
879
880    #[cfg(feature = "qdrant")]
881    #[test]
882    fn dense_backend_infers_qdrant_from_url() {
883        let _g = crate::core::data_dir::test_env_lock();
884        let old_backend = set_env("LEANCTX_DENSE_BACKEND", None);
885        let old_url = set_env("LEANCTX_QDRANT_URL", Some("http://127.0.0.1:6333"));
886        let old_pg = set_env("LEANCTX_PGVECTOR_URL", None);
887
888        let got = DenseBackendKind::try_from_env().unwrap();
889        assert_eq!(got, DenseBackendKind::Qdrant);
890
891        restore_env("LEANCTX_DENSE_BACKEND", old_backend);
892        restore_env("LEANCTX_QDRANT_URL", old_url);
893        restore_env("LEANCTX_PGVECTOR_URL", old_pg);
894    }
895
896    #[cfg(feature = "pgvector")]
897    #[test]
898    fn dense_backend_infers_pgvector_from_url() {
899        let _g = crate::core::data_dir::test_env_lock();
900        let old_backend = set_env("LEANCTX_DENSE_BACKEND", None);
901        let old_url = set_env("LEANCTX_QDRANT_URL", None);
902        let old_pg = set_env("LEANCTX_PGVECTOR_URL", Some("postgres://localhost/lctx"));
903
904        let got = DenseBackendKind::try_from_env().unwrap();
905        assert_eq!(got, DenseBackendKind::Pgvector);
906
907        restore_env("LEANCTX_DENSE_BACKEND", old_backend);
908        restore_env("LEANCTX_QDRANT_URL", old_url);
909        restore_env("LEANCTX_PGVECTOR_URL", old_pg);
910    }
911
912    #[cfg(all(feature = "qdrant", feature = "pgvector"))]
913    #[test]
914    fn dense_backend_qdrant_wins_when_both_urls_set() {
915        let _g = crate::core::data_dir::test_env_lock();
916        let old_backend = set_env("LEANCTX_DENSE_BACKEND", None);
917        let old_url = set_env("LEANCTX_QDRANT_URL", Some("http://127.0.0.1:6333"));
918        let old_pg = set_env("LEANCTX_PGVECTOR_URL", Some("postgres://localhost/lctx"));
919
920        let got = DenseBackendKind::try_from_env().unwrap();
921        assert_eq!(got, DenseBackendKind::Qdrant);
922
923        // Explicit selection overrides inference order.
924        crate::test_env::set_var("LEANCTX_DENSE_BACKEND", "pgvector");
925        let got = DenseBackendKind::try_from_env().unwrap();
926        assert_eq!(got, DenseBackendKind::Pgvector);
927
928        restore_env("LEANCTX_DENSE_BACKEND", old_backend);
929        restore_env("LEANCTX_QDRANT_URL", old_url);
930        restore_env("LEANCTX_PGVECTOR_URL", old_pg);
931    }
932
933    #[cfg(not(feature = "qdrant"))]
934    #[test]
935    fn dense_backend_qdrant_requires_feature() {
936        let _g = crate::core::data_dir::test_env_lock();
937        let old_backend = set_env("LEANCTX_DENSE_BACKEND", Some("qdrant"));
938        let old_url = set_env("LEANCTX_QDRANT_URL", None);
939
940        let err = DenseBackendKind::try_from_env().unwrap_err();
941        assert!(err.contains("feature 'qdrant' is not enabled"));
942
943        restore_env("LEANCTX_DENSE_BACKEND", old_backend);
944        restore_env("LEANCTX_QDRANT_URL", old_url);
945    }
946
947    #[cfg(not(feature = "pgvector"))]
948    #[test]
949    fn dense_backend_pgvector_requires_feature() {
950        let _g = crate::core::data_dir::test_env_lock();
951        let old_backend = set_env("LEANCTX_DENSE_BACKEND", Some("pgvector"));
952        let old_url = set_env("LEANCTX_QDRANT_URL", None);
953
954        let err = DenseBackendKind::try_from_env().unwrap_err();
955        assert!(err.contains("feature 'pgvector' is not enabled"));
956
957        restore_env("LEANCTX_DENSE_BACKEND", old_backend);
958        restore_env("LEANCTX_QDRANT_URL", old_url);
959    }
960}