1#[cfg(feature = "embeddings")]
8use std::collections::{HashMap, HashSet};
9
10#[cfg(feature = "embeddings")]
11use crate::core::bm25_index::{BM25Index, tokenize_for_index};
12
13#[derive(Debug, Clone, PartialEq)]
15pub struct SpladeResult {
16 pub chunk_idx: usize,
17 pub file_path: String,
18 pub symbol_name: String,
19 pub combined_score: f64,
20 pub bm25_score: f64,
21 pub expansion_score: f64,
22}
23
24#[cfg(feature = "embeddings")]
26fn expansion_dictionary() -> HashMap<&'static str, Vec<(&'static str, f64)>> {
27 HashMap::from([
28 (
29 "auth",
30 vec![
31 ("authentication", 1.0),
32 ("token", 0.9),
33 ("jwt", 0.85),
34 ("login", 0.8),
35 ("session", 0.85),
36 ("oauth", 0.75),
37 ("credential", 0.7),
38 ],
39 ),
40 (
41 "async",
42 vec![
43 ("await", 1.0),
44 ("future", 0.85),
45 ("promise", 0.75),
46 ("tokio", 0.65),
47 ("concurrent", 0.7),
48 ],
49 ),
50 (
51 "error",
52 vec![
53 ("err", 0.95),
54 ("result", 0.75),
55 ("panic", 0.55),
56 ("exception", 0.65),
57 ("unwrap", 0.5),
58 ],
59 ),
60 (
61 "http",
62 vec![
63 ("request", 0.85),
64 ("response", 0.85),
65 ("rest", 0.65),
66 ("json", 0.7),
67 ("header", 0.6),
68 ],
69 ),
70 (
71 "db",
72 vec![
73 ("database", 1.0),
74 ("sql", 0.85),
75 ("query", 0.75),
76 ("transaction", 0.65),
77 ("migration", 0.55),
78 ],
79 ),
80 (
81 "test",
82 vec![
83 ("mock", 0.75),
84 ("fixture", 0.6),
85 ("assert", 0.85),
86 ("expect", 0.65),
87 ],
88 ),
89 (
90 "config",
91 vec![
92 ("configuration", 1.0),
93 ("env", 0.75),
94 ("setting", 0.65),
95 ("toml", 0.55),
96 ],
97 ),
98 (
99 "cache",
100 vec![
101 ("memo", 0.65),
102 ("redis", 0.55),
103 ("ttl", 0.6),
104 ("invalidate", 0.55),
105 ],
106 ),
107 ])
108}
109
110#[cfg(feature = "embeddings")]
111fn build_expanded_weights(query_tokens: &[String]) -> HashMap<String, f64> {
112 let dict = expansion_dictionary();
113 let mut out: HashMap<String, f64> = HashMap::new();
114
115 for t in query_tokens {
116 let lower = t.to_lowercase();
117 let entry = out.entry(lower.clone()).or_insert(1.0);
118 *entry = (*entry).max(1.0);
119
120 if let Some(rel) = dict.get(lower.as_str()) {
121 for (syn, w) in rel {
122 let le = out.entry((*syn).to_string()).or_insert(0.0);
123 *le = (*le).max(*w);
124 }
125 }
126 }
127 out
128}
129
130#[cfg(feature = "embeddings")]
131fn expansion_bm25_for_chunk(
132 index: &BM25Index,
133 chunk_idx: usize,
134 expanded: &HashMap<String, f64>,
135 original_terms: &HashSet<String>,
136) -> f64 {
137 if index.doc_count == 0 {
138 return 0.0;
139 }
140
141 let doc_len = index.chunks[chunk_idx].token_count as f64;
142 let norm_len = doc_len / index.avg_doc_len.max(1.0);
143
144 const K1: f64 = 1.2;
145 const B: f64 = 0.75;
146
147 let mut sum = 0.0;
148 for (term, ew) in expanded {
149 if original_terms.contains(term) {
150 continue;
151 }
152 let df = *index.doc_freqs.get(term).unwrap_or(&0) as f64;
153 if df == 0.0 {
154 continue;
155 }
156
157 let idf = ((index.doc_count as f64 - df + 0.5) / (df + 0.5) + 1.0).ln();
158 let tf = index.inverted.get(term).map_or(0.0, |postings| {
159 postings
160 .iter()
161 .filter(|(idx, _)| *idx == chunk_idx)
162 .map(|(_, w)| *w)
163 .sum::<f64>()
164 });
165
166 if tf == 0.0 {
167 continue;
168 }
169
170 let bm25_t = idf * (tf * (K1 + 1.0)) / (tf + K1 * (1.0 - B + B * norm_len));
171 sum += ew * bm25_t;
172 }
173 sum
174}
175
176#[cfg(feature = "embeddings")]
178pub fn hybrid_retrieve(query: &str, bm25_index: &BM25Index, top_k: usize) -> Vec<SpladeResult> {
179 if bm25_index.doc_count == 0 || top_k == 0 {
180 return Vec::new();
181 }
182
183 let query_tokens = tokenize_for_index(query);
184 if query_tokens.is_empty() {
185 return Vec::new();
186 }
187
188 let original_terms: HashSet<String> = query_tokens.iter().map(|s| s.to_lowercase()).collect();
189
190 let expanded = build_expanded_weights(&query_tokens);
191
192 let stage1 = bm25_index.search(query, 100.min(bm25_index.doc_count.max(1)));
193
194 let bm25_by_chunk: HashMap<usize, f64> =
195 stage1.iter().map(|r| (r.chunk_idx, r.score)).collect();
196
197 let chunk_indices: Vec<usize> = bm25_by_chunk.keys().copied().collect();
198 if chunk_indices.is_empty() {
199 return Vec::new();
200 }
201
202 let mut expansion_scores: HashMap<usize, f64> = HashMap::new();
203 for &idx in &chunk_indices {
204 let es = expansion_bm25_for_chunk(bm25_index, idx, &expanded, &original_terms);
205 expansion_scores.insert(idx, es);
206 }
207
208 let max_bm25 = bm25_by_chunk.values().copied().fold(0.0_f64, f64::max);
209 let max_exp = expansion_scores.values().copied().fold(0.0_f64, f64::max);
210
211 let norm_bm25 = |s: f64| -> f64 { if max_bm25 > 1e-12 { s / max_bm25 } else { 0.0 } };
212 let norm_exp = |s: f64| -> f64 { if max_exp > 1e-12 { s / max_exp } else { 0.0 } };
213
214 const W_BM25: f64 = 0.65;
215 const W_EXP: f64 = 0.35;
216
217 let mut results: Vec<SpladeResult> = chunk_indices
218 .into_iter()
219 .map(|chunk_idx| {
220 let chunk = &bm25_index.chunks[chunk_idx];
221 let bm25_score = bm25_by_chunk.get(&chunk_idx).copied().unwrap_or(0.0);
222 let expansion_score = expansion_scores.get(&chunk_idx).copied().unwrap_or(0.0);
223 let combined_score = W_BM25 * norm_bm25(bm25_score) + W_EXP * norm_exp(expansion_score);
224
225 SpladeResult {
226 chunk_idx,
227 file_path: chunk.file_path.clone(),
228 symbol_name: chunk.symbol_name.clone(),
229 combined_score,
230 bm25_score,
231 expansion_score,
232 }
233 })
234 .collect();
235
236 results.sort_by(|a, b| {
237 b.combined_score
238 .partial_cmp(&a.combined_score)
239 .unwrap_or(std::cmp::Ordering::Equal)
240 .then_with(|| {
241 b.bm25_score
242 .partial_cmp(&a.bm25_score)
243 .unwrap_or(std::cmp::Ordering::Equal)
244 })
245 .then_with(|| a.file_path.cmp(&b.file_path))
246 .then_with(|| a.symbol_name.cmp(&b.symbol_name))
247 });
248
249 results.truncate(top_k);
250 results
251}
252
253#[cfg(all(test, feature = "embeddings"))]
254mod tests {
255 use super::*;
256 use crate::core::bm25_index::{ChunkKind, CodeChunk};
257
258 fn sample_index() -> BM25Index {
259 BM25Index::from_chunks_for_test(vec![
260 CodeChunk { input_origin: None,
261 file_path: "login.rs".into(),
262 symbol_name: "login_user".into(),
263 kind: ChunkKind::Function,
264 start_line: 1,
265 end_line: 3,
266 content: "pub fn login_user() { session_token authentication jwt oauth login credential }"
267 .into(),
268 tokens: vec![],
269 token_count: 0,
270 },
271 CodeChunk { input_origin: None,
272 file_path: "cache.rs".into(),
273 symbol_name: "memo_cache".into(),
274 kind: ChunkKind::Function,
275 start_line: 1,
276 end_line: 3,
277 content: "pub fn memo_cache() { redis ttl invalidate memo cache }".into(),
278 tokens: vec![],
279 token_count: 0,
280 },
281 CodeChunk { input_origin: None,
282 file_path: "auth.rs".into(),
283 symbol_name: "oauth_flow".into(),
284 kind: ChunkKind::Function,
285 start_line: 1,
286 end_line: 3,
287 content: "pub fn oauth_flow() { credential authentication token jwt session }".into(),
288 tokens: vec![],
289 token_count: 0,
290 },
291 ])
292 }
293
294 #[test]
295 fn hybrid_prefers_expansion_overlap() {
296 let index = sample_index();
297
298 let hits = hybrid_retrieve("auth login", &index, 5);
299 assert!(!hits.is_empty(), "`hits` is empty");
300 let top_path = hits[0].file_path.clone();
301 assert!(
302 top_path.ends_with("login.rs") || top_path.ends_with("auth.rs"),
303 "expected auth-expanded chunk first, got {hits:?}"
304 );
305 }
306
307 #[test]
308 fn expansion_boosts_related_terms() {
309 let index = sample_index();
310 let hybrid = hybrid_retrieve("jwt auth", &index, 10);
312
313 assert!(!hybrid.is_empty(), "`hybrid` is empty");
314 assert!(
315 hybrid[0].expansion_score >= 0.0,
316 "expansion_score should be non-negative"
317 );
318 }
319
320 #[test]
321 fn empty_query_returns_empty() {
322 let index = sample_index();
323 {
324 let found = &hybrid_retrieve("", &index, 5);
325 assert!(found.is_empty(), "{found:?}");
326 }
327 }
328
329 #[test]
330 fn splade_result_fields_populated() {
331 let index = sample_index();
332
333 let hybrid = hybrid_retrieve("auth session", &index, 3);
334 let r = &hybrid[0];
335 assert!(r.chunk_idx < index.chunks.len());
336 assert!(!r.file_path.is_empty(), "`r.file_path` is empty");
337 assert!(r.combined_score.is_finite());
338 assert!(r.bm25_score.is_finite());
339 assert!(r.expansion_score.is_finite());
340 }
341}