Skip to main content

paper/core/search/
pipeline.rs

1use super::filters::SearchFilters;
2use super::hit::{Confidence, Engine, Hit};
3use super::tier0::{tier0_search_filtered, HitSource, RawHit, MIN_QUERY_LEN};
4use super::tier1::tier1_search_filtered;
5use crate::core::config::SearchConfig;
6use crate::core::index::Connection;
7use crate::core::models::{Embedder, LanguageCoverage, Reranker};
8use crate::core::text::{excerpt, is_searchable_query, query_terms, SNIPPET_CHARS};
9use anyhow::{bail, Result};
10use std::collections::HashMap;
11use std::path::PathBuf;
12
13/// Deterministic, non-generative embedder used in tests and in `--no-model`
14/// keyword-only operation.
15pub trait QueryEmbedder {
16    /// Embed a document chunk.
17    fn embed(&self, text: &str) -> Result<Vec<f32>>;
18
19    /// Embed a search query. Models with an asymmetric retrieval instruction
20    /// (BGE, E5) override this; symmetric models just use `embed`.
21    fn embed_query(&self, text: &str) -> Result<Vec<f32>> {
22        self.embed(text)
23    }
24
25    /// The model identifier (e.g. "bge-small-en-v1.5"). Used to detect
26    /// index/search model mismatches.
27    fn model_id(&self) -> &str;
28}
29
30impl QueryEmbedder for Embedder {
31    fn embed(&self, text: &str) -> Result<Vec<f32>> {
32        Embedder::embed_document(self, text)
33    }
34
35    fn embed_query(&self, text: &str) -> Result<Vec<f32>> {
36        Embedder::embed_query(self, text)
37    }
38
39    fn model_id(&self) -> &str {
40        Embedder::model_id(self)
41    }
42}
43
44/// Shared handle so the indexer and the search pipeline can reuse one model.
45pub type SharedEmbedder = std::sync::Arc<dyn QueryEmbedder + Send + Sync>;
46
47pub struct SearchPipeline {
48    conn: Connection,
49    embedder: Option<SharedEmbedder>,
50    reranker: Option<std::sync::Arc<Reranker>>,
51    config: SearchConfig,
52}
53
54impl SearchPipeline {
55    pub fn new(
56        conn: Connection,
57        embedder: Option<SharedEmbedder>,
58        reranker: Option<std::sync::Arc<Reranker>>,
59        config: SearchConfig,
60    ) -> Self {
61        Self {
62            conn,
63            embedder,
64            reranker,
65            config,
66        }
67    }
68
69    pub fn connection(&self) -> &Connection {
70        &self.conn
71    }
72
73    pub fn search(&self, query: &str, roots: &[PathBuf]) -> Result<Vec<Hit>> {
74        self.search_with(query, roots, &SearchFilters::default())
75    }
76
77    /// Search with structured filters (`--after`, `--before`, `--ext`, path).
78    pub fn search_with(
79        &self,
80        query: &str,
81        roots: &[PathBuf],
82        filters: &SearchFilters,
83    ) -> Result<Vec<Hit>> {
84        if !is_searchable_query(query) {
85            bail!(
86                "query must be at least {MIN_QUERY_LEN} characters \
87                 (one is enough for CJK and other scripts without spaces)"
88            );
89        }
90
91        // If we have an embedder and the index has a stored embedding model,
92        // they must match. This prevents silently searching with the wrong model.
93        if let Some(embedder) = &self.embedder {
94            if let Some(stored) = self.conn.stored_embedding_model()? {
95                if stored != embedder.model_id() {
96                    bail!(
97                        "embedding model mismatch: index was built with '{stored}' \
98                         but search is using '{current}'. Re-index or install the \
99                         correct model.",
100                        current = embedder.model_id()
101                    );
102                }
103            }
104        }
105
106        let kw_hits =
107            tier0_search_filtered(&self.conn, query, roots, filters, self.config.keyword_limit)?;
108
109        // Strong keyword evidence: skip the embedding model entirely. This keeps
110        // exact lookups (invoice numbers, names) fast and model-free.
111        //
112        // "Strong" means the top keyword hit carries every content word of the
113        // query, not merely "there are ten hits": ten partial `OR` matches of a
114        // vague question used to suppress semantic search exactly when it was
115        // most needed.
116        let mut sem_hits: Vec<RawHit> = Vec::new();
117        if !self.keyword_is_decisive(query, &kw_hits) {
118            if let Some(embedder) = &self.embedder {
119                let query_vec = embedder.embed_query(query)?;
120                sem_hits = tier1_search_filtered(
121                    &self.conn,
122                    &query_vec,
123                    roots,
124                    filters,
125                    self.config.semantic_limit,
126                )?
127                .into_iter()
128                .filter(|hit| hit.score >= self.config.semantic_min_score)
129                .collect();
130            }
131        }
132
133        let fused = rrf_fuse(
134            &kw_hits,
135            &sem_hits,
136            self.config.rrf_k,
137            self.config.fused_limit,
138        );
139        let relevance = relevance_map(&kw_hits, &sem_hits);
140        let terms = query_terms(query);
141        let mut hits = self.hydrate(&fused, &relevance, &terms)?;
142
143        if let Some(reranker) = self
144            .reranker
145            .as_ref()
146            .filter(|r| reranker_handles(r.coverage(), query))
147        {
148            // Only the top candidates go through the cross-encoder: it is one
149            // forward pass per pair, so reranking everything would be far slower.
150            let rest = hits.split_off(self.config.rerank_top.min(hits.len()));
151            let mut reranked = reranker.rerank(query, hits)?;
152            reranked.extend(rest);
153            hits = reranked;
154        }
155
156        for hit in &mut hits {
157            hit.confidence = self.confidence_for(hit, query, &kw_hits, &sem_hits);
158            hit.engine = Engine::Local;
159            hit.why_matched = why_matched(hit, &kw_hits, &sem_hits);
160        }
161        Ok(hits)
162    }
163
164    /// True when keyword search alone has already answered the query.
165    ///
166    /// The bar is lexical coverage of the *whole* query by the best hit, plus
167    /// enough corroborating results that this is not a fluke. A query with ten
168    /// weak partial matches still goes to the embedding model.
169    fn keyword_is_decisive(&self, query: &str, hits: &[RawHit]) -> bool {
170        if hits.len() < self.config.keyword_sufficiency_threshold {
171            return false;
172        }
173        let Some(top) = hits.first() else {
174            return false;
175        };
176        // Normalised relevance: 1.0 is the best match in this result set.
177        top.score >= 0.9 && full_term_coverage(query, &top.snippet)
178    }
179
180    /// Confidence describes the *evidence*, not the rank position.
181    ///
182    /// A lone keyword hit is not automatically strong evidence: normalising bm25
183    /// within a result set of size one would otherwise always yield 1.0.
184    fn confidence_for(
185        &self,
186        hit: &Hit,
187        query: &str,
188        keyword: &[RawHit],
189        semantic: &[RawHit],
190    ) -> Confidence {
191        let kw = keyword.iter().any(|h| h.chunk_id == hit.source_id);
192        let sem = semantic.iter().find(|h| h.chunk_id == hit.source_id);
193        match (kw, sem) {
194            // Corroborated by two independent retrievers.
195            (true, Some(_)) => Confidence::High,
196            // Every content word of the query literally appears in the chunk.
197            (true, None) if full_term_coverage(query, &hit.content) => Confidence::High,
198            (true, None) => Confidence::Medium,
199            (false, Some(sem)) if sem.score >= 0.75 => Confidence::High,
200            (false, Some(sem)) if sem.score >= 0.5 => Confidence::Medium,
201            _ => Confidence::Low,
202        }
203    }
204
205    /// Turn `(chunk_id, rrf_score)` pairs into full citations.
206    ///
207    /// RRF scores only define the *order* — they are tiny fractions like 0.016
208    /// and meaningless to a user. The displayed `score` is the underlying
209    /// normalised relevance, which is also what confidence is derived from.
210    fn hydrate(
211        &self,
212        fused: &[(i64, f32)],
213        relevance: &HashMap<i64, f32>,
214        terms: &[String],
215    ) -> Result<Vec<Hit>> {
216        let mut hits = Vec::with_capacity(fused.len());
217        let mut stmt = self.conn.inner().prepare(
218            "SELECT id, path, source_path, page, line_start, line_end, anchor, section, content
219             FROM chunks WHERE id = ?",
220        )?;
221        for &(id, score) in fused {
222            let row = stmt.query_row([id], |row| {
223                Ok(Hit {
224                    source_id: row.get(0)?,
225                    path: row.get(1)?,
226                    source_path: row.get(2)?,
227                    page: row.get(3)?,
228                    line_start: row.get(4)?,
229                    line_end: row.get(5)?,
230                    anchor: row.get(6)?,
231                    section: row.get(7)?,
232                    snippet: String::new(),
233                    content: row.get::<_, String>(8)?,
234                    score: relevance.get(&id).copied().unwrap_or(score),
235                    why_matched: String::new(),
236                    confidence: Confidence::Low,
237                    engine: Engine::Local,
238                })
239            });
240            match row {
241                Ok(mut hit) => {
242                    hit.snippet = excerpt(&hit.content, terms, SNIPPET_CHARS);
243                    hits.push(hit);
244                }
245                // A chunk can disappear between the scan and hydration.
246                Err(rusqlite::Error::QueryReturnedNoRows) => continue,
247                Err(e) => return Err(e.into()),
248            }
249        }
250        Ok(hits)
251    }
252}
253
254/// Reciprocal Rank Fusion. Results present in *both* lists accumulate two
255/// contributions and therefore outrank single-source results.
256pub fn rrf_fuse(keyword: &[RawHit], semantic: &[RawHit], k: i32, limit: usize) -> Vec<(i64, f32)> {
257    let k = k.max(1) as f32;
258    let mut scores: HashMap<i64, f32> = HashMap::new();
259    for list in [keyword, semantic] {
260        for (rank, hit) in list.iter().enumerate() {
261            *scores.entry(hit.chunk_id).or_insert(0.0) += 1.0 / (k + rank as f32 + 1.0);
262        }
263    }
264    let mut fused: Vec<(i64, f32)> = scores.into_iter().collect();
265    fused.sort_by(|a, b| {
266        b.1.partial_cmp(&a.1)
267            .unwrap_or(std::cmp::Ordering::Equal)
268            .then(a.0.cmp(&b.0))
269    });
270    fused.truncate(limit);
271    fused
272}
273
274/// Best available relevance per chunk: the semantic cosine similarity when we
275/// have one, otherwise the normalised keyword score.
276fn relevance_map(keyword: &[RawHit], semantic: &[RawHit]) -> HashMap<i64, f32> {
277    let mut map = HashMap::new();
278    for hit in keyword {
279        map.insert(hit.chunk_id, hit.score.clamp(0.0, 1.0));
280    }
281    for hit in semantic {
282        let entry = map.entry(hit.chunk_id).or_insert(0.0);
283        *entry = entry.max(hit.score.clamp(0.0, 1.0));
284    }
285    map
286}
287
288/// True when every content word of the query occurs in the text, i.e. an exact
289/// lexical match rather than a partial `OR` match.
290fn full_term_coverage(query: &str, text: &str) -> bool {
291    let text = text.to_lowercase();
292    let mut terms = query
293        .split_whitespace()
294        .map(|t| {
295            t.trim_matches(|c: char| !c.is_alphanumeric())
296                .to_lowercase()
297        })
298        .filter(|t| t.len() >= 3);
299    let Some(first) = terms.next() else {
300        return false;
301    };
302    text.contains(&first) && terms.all(|t| text.contains(&t))
303}
304
305/// Snippets are drawn from the stored `content`, not from the segmented index
306/// text: FTS5's `snippet()` would emit bigram-separated CJK and would need an
307/// unreliable desegmentation pass to look right.
308fn why_matched(hit: &Hit, keyword: &[RawHit], semantic: &[RawHit]) -> String {
309    let kw = keyword.iter().any(|h| h.chunk_id == hit.source_id);
310    let sem = semantic.iter().any(|h| h.chunk_id == hit.source_id);
311    match (kw, sem) {
312        (true, true) => "matched by keyword and semantic search".to_string(),
313        (true, false) => "matched by keyword search".to_string(),
314        (false, true) => "matched by semantic search".to_string(),
315        (false, false) => "matched".to_string(),
316    }
317}
318
319/// Used by `Hit::source` serialisation; kept here so `HitSource` stays imported.
320pub fn source_of(hit: &RawHit) -> HitSource {
321    hit.source
322}
323
324/// Whether a reranker with this language coverage should score this query.
325// shortcut: ASCII-only counts as English; an unaccented French/Spanish query still gets an English-only reranker. Upgrade to a language-ID check if that matters.
326pub fn reranker_handles(coverage: LanguageCoverage, query: &str) -> bool {
327    let cjk = |c: char| matches!(c, '\u{3040}'..='\u{30FF}' | '\u{3400}'..='\u{4DBF}' | '\u{4E00}'..='\u{9FFF}' | '\u{AC00}'..='\u{D7AF}');
328    match coverage {
329        LanguageCoverage::Multilingual => true,
330        LanguageCoverage::EnglishChinese => query
331            .chars()
332            .all(|c| !c.is_alphabetic() || c.is_ascii() || cjk(c)),
333        LanguageCoverage::English => query.chars().all(|c| !c.is_alphabetic() || c.is_ascii()),
334    }
335}
336
337#[cfg(test)]
338mod tests {
339    use super::reranker_handles;
340    use crate::core::models::LanguageCoverage::*;
341
342    #[test]
343    fn reranker_handles_by_coverage() {
344        for (q, zh) in [
345            ("invoice 2026", true),
346            ("日本語", true),
347            ("发票", true),
348            ("Grüße", false),
349            ("привет", false),
350        ] {
351            assert_eq!(reranker_handles(EnglishChinese, q), zh, "{q}");
352            assert!(reranker_handles(Multilingual, q), "{q}");
353        }
354        assert!(!reranker_handles(English, "日本語"));
355        assert!(reranker_handles(English, "invoice 2026"));
356    }
357}