1use std::collections::HashMap;
9use std::fmt;
10use std::str::FromStr;
11
12use crate::bm25::Bm25Index;
13use crate::chunk::CodeChunk;
14use crate::index::SearchIndex;
15
16#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
18pub enum SearchMode {
19 #[default]
21 Hybrid,
22 Semantic,
24 Keyword,
26}
27
28impl fmt::Display for SearchMode {
29 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30 match self {
31 Self::Hybrid => f.write_str("hybrid"),
32 Self::Semantic => f.write_str("semantic"),
33 Self::Keyword => f.write_str("keyword"),
34 }
35 }
36}
37
38#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct ParseSearchModeError(String);
41
42impl fmt::Display for ParseSearchModeError {
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 write!(
45 f,
46 "unknown search mode {:?}; expected hybrid, semantic, or keyword",
47 self.0
48 )
49 }
50}
51
52impl std::error::Error for ParseSearchModeError {}
53
54impl FromStr for SearchMode {
55 type Err = ParseSearchModeError;
56
57 fn from_str(s: &str) -> Result<Self, Self::Err> {
58 match s {
59 "hybrid" => Ok(Self::Hybrid),
60 "semantic" => Ok(Self::Semantic),
61 "keyword" => Ok(Self::Keyword),
62 other => Err(ParseSearchModeError(other.to_string())),
63 }
64 }
65}
66
67pub struct HybridIndex {
72 pub semantic: SearchIndex,
74 bm25: Bm25Index,
76}
77
78impl HybridIndex {
79 pub fn new(
90 chunks: Vec<CodeChunk>,
91 embeddings: &[Vec<f32>],
92 cascade_dim: Option<usize>,
93 ) -> crate::Result<Self> {
94 let bm25 = Bm25Index::build(&chunks)?;
95 let semantic = SearchIndex::new(chunks, embeddings, cascade_dim);
96 Ok(Self { semantic, bm25 })
97 }
98
99 #[must_use]
104 pub fn from_parts(semantic: SearchIndex, bm25: Bm25Index) -> Self {
105 Self { semantic, bm25 }
106 }
107
108 #[must_use]
122 pub fn search(
123 &self,
124 query_embedding: &[f32],
125 query_text: &str,
126 top_k: usize,
127 threshold: f32,
128 mode: SearchMode,
129 ) -> Vec<(usize, f32)> {
130 let mut raw = match mode {
131 SearchMode::Semantic => {
132 self.semantic
134 .rank_turboquant(query_embedding, top_k.max(100), 0.0)
135 }
136 SearchMode::Keyword => self.bm25.search(query_text, top_k.max(100)),
137 SearchMode::Hybrid => {
138 let sem = self
139 .semantic
140 .rank_turboquant(query_embedding, top_k.max(100), 0.0);
141 let kw = self.bm25.search(query_text, top_k.max(100));
142 rrf_fuse(&sem, &kw, 60.0)
143 }
144 };
145
146 if let (Some(max), Some(min)) = (raw.first().map(|(_, s)| *s), raw.last().map(|(_, s)| *s))
148 {
149 let range = max - min;
150 if range > f32::EPSILON {
151 for (_, score) in &mut raw {
152 *score = (*score - min) / range;
153 }
154 } else {
155 for (_, score) in &mut raw {
157 *score = 1.0;
158 }
159 }
160 }
161
162 raw.retain(|(_, score)| *score >= threshold);
164 raw.truncate(top_k);
165 raw
166 }
167
168 #[must_use]
170 pub fn chunks(&self) -> &[CodeChunk] {
171 &self.semantic.chunks
172 }
173}
174
175#[must_use]
187pub fn rrf_fuse(semantic: &[(usize, f32)], bm25: &[(usize, f32)], k: f32) -> Vec<(usize, f32)> {
188 let mut scores: HashMap<usize, f32> = HashMap::new();
189
190 for (rank, &(idx, _)) in semantic.iter().enumerate() {
191 *scores.entry(idx).or_insert(0.0) += 1.0 / (k + rank as f32 + 1.0);
192 }
193 for (rank, &(idx, _)) in bm25.iter().enumerate() {
194 *scores.entry(idx).or_insert(0.0) += 1.0 / (k + rank as f32 + 1.0);
195 }
196
197 let mut results: Vec<(usize, f32)> = scores.into_iter().collect();
198 results.sort_unstable_by(|a, b| {
199 b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)) });
201 results
202}
203
204#[cfg(test)]
205mod tests {
206 use super::*;
207
208 #[test]
209 fn rrf_union_semantics() {
210 let sem = vec![(0, 0.9), (1, 0.8), (2, 0.7)];
214 let bm25 = vec![(3, 10.0), (0, 8.0), (4, 6.0)];
215
216 let fused = rrf_fuse(&sem, &bm25, 60.0);
217
218 let indices: Vec<usize> = fused.iter().map(|&(i, _)| i).collect();
219
220 for expected in [0, 1, 2, 3, 4] {
222 assert!(
223 indices.contains(&expected),
224 "chunk {expected} missing from fused results"
225 );
226 }
227 assert_eq!(fused.len(), 5);
228
229 assert_eq!(indices[0], 0, "chunk 0 should rank first");
231 }
232
233 #[test]
234 fn rrf_single_list() {
235 let sem = vec![(0, 0.9), (1, 0.8)];
237 let bm25: Vec<(usize, f32)> = vec![];
238
239 let fused = rrf_fuse(&sem, &bm25, 60.0);
240
241 assert_eq!(fused.len(), 2);
242 assert_eq!(fused[0].0, 0);
244 assert_eq!(fused[1].0, 1);
245 assert!(fused[0].1 > fused[1].1);
246 }
247
248 #[test]
249 fn search_mode_roundtrip() {
250 assert_eq!("hybrid".parse::<SearchMode>().unwrap(), SearchMode::Hybrid);
251 assert_eq!(
252 "semantic".parse::<SearchMode>().unwrap(),
253 SearchMode::Semantic
254 );
255 assert_eq!(
256 "keyword".parse::<SearchMode>().unwrap(),
257 SearchMode::Keyword
258 );
259
260 let err = "invalid".parse::<SearchMode>();
261 assert!(err.is_err(), "expected parse error for 'invalid'");
262 let msg = err.unwrap_err().to_string();
263 assert!(
264 msg.contains("invalid"),
265 "error message should echo the bad input"
266 );
267 }
268
269 #[test]
270 fn search_mode_display() {
271 assert_eq!(SearchMode::Hybrid.to_string(), "hybrid");
272 assert_eq!(SearchMode::Semantic.to_string(), "semantic");
273 assert_eq!(SearchMode::Keyword.to_string(), "keyword");
274 }
275}