ripvec_core/hybrid.rs
1//! Hybrid semantic + keyword search with Reciprocal Rank Fusion (RRF).
2//!
3//! [`HybridIndex`] wraps a [`SearchIndex`] (dense vector search) and a
4//! [`Bm25Index`] (BM25 keyword search) and fuses their ranked results via
5//! Reciprocal Rank Fusion so that chunks appearing high in either list
6//! bubble to the top of the combined ranking.
7
8use 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/// Controls which retrieval strategy is used during search.
17#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
18pub enum SearchMode {
19 /// Fuse semantic (vector) and keyword (BM25) results via RRF.
20 #[default]
21 Hybrid,
22 /// Dense vector cosine-similarity ranking only.
23 Semantic,
24 /// BM25 keyword ranking only.
25 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/// Error returned when a `SearchMode` string cannot be parsed.
39#[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
67/// Combined semantic + keyword search index with RRF fusion.
68///
69/// Build once from chunks and pre-computed embeddings; query repeatedly
70/// via [`search`](Self::search).
71pub struct HybridIndex {
72 /// Semantic (dense vector) search index.
73 pub semantic: SearchIndex,
74 /// BM25 keyword search index.
75 bm25: Bm25Index,
76}
77
78impl HybridIndex {
79 /// Build a `HybridIndex` from raw chunks and their pre-computed embeddings.
80 ///
81 /// Constructs both the [`SearchIndex`] and [`Bm25Index`] in one call.
82 /// `cascade_dim` is forwarded to [`SearchIndex::new`] for optional MRL
83 /// cascade pre-filtering.
84 ///
85 /// # Errors
86 ///
87 /// Returns an error if the BM25 index cannot be built (e.g., tantivy
88 /// schema or writer failure).
89 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 /// Assemble a `HybridIndex` from pre-built components.
100 ///
101 /// Useful when the caller has already constructed the sub-indices
102 /// separately (e.g., loaded from a cache).
103 #[must_use]
104 pub fn from_parts(semantic: SearchIndex, bm25: Bm25Index) -> Self {
105 Self { semantic, bm25 }
106 }
107
108 /// Search the index and return `(chunk_index, score)` pairs.
109 ///
110 /// Dispatches based on `mode`:
111 /// - [`SearchMode::Semantic`] — pure dense vector search via
112 /// [`SearchIndex::rank`].
113 /// - [`SearchMode::Keyword`] — pure BM25 keyword search, truncated to
114 /// `top_k`.
115 /// - [`SearchMode::Hybrid`] — retrieves both ranked lists, fuses them
116 /// with [`rrf_fuse`], then truncates to `top_k`.
117 ///
118 /// Scores are min-max normalized to `[0, 1]` regardless of mode, so
119 /// a threshold of 0.5 always means "above midpoint of the score range"
120 /// whether the underlying scores are cosine similarity, BM25, or RRF.
121 #[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 // Fetch more than top_k so normalization has a meaningful range.
133 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 // Min-max normalize scores to [0, 1] so threshold is model-agnostic.
147 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 // All scores identical — normalize to 1.0
156 for (_, score) in &mut raw {
157 *score = 1.0;
158 }
159 }
160 }
161
162 // Apply threshold on normalized scores, then truncate
163 raw.retain(|(_, score)| *score >= threshold);
164 raw.truncate(top_k);
165 raw
166 }
167
168 /// All chunks in the index.
169 #[must_use]
170 pub fn chunks(&self) -> &[CodeChunk] {
171 &self.semantic.chunks
172 }
173}
174
175impl crate::searchable::SearchableIndex for HybridIndex {
176 fn chunks(&self) -> &[CodeChunk] {
177 HybridIndex::chunks(self)
178 }
179
180 fn search(&self, query_text: &str, top_k: usize, mode: SearchMode) -> Vec<(usize, f32)> {
181 // Trait-shape search: no caller-supplied query embedding.
182 // BM25 handles text directly. Semantic and hybrid modes would
183 // require an embedded query vector — without one they would
184 // search against a zero vector, which matches nothing
185 // useful — so we route all three modes through keyword. The
186 // caller wanting semantic results should use
187 // `search_from_chunk` (the canonical goto-definition pattern)
188 // which supplies the source chunk's embedding.
189 let _ = mode;
190 HybridIndex::search(self, &[], query_text, top_k, 0.0, SearchMode::Keyword)
191 }
192
193 fn search_from_chunk(
194 &self,
195 chunk_idx: usize,
196 query_text: &str,
197 top_k: usize,
198 mode: SearchMode,
199 ) -> Vec<(usize, f32)> {
200 let embedding = self.semantic.embedding(chunk_idx).unwrap_or_default();
201 let effective_mode = if embedding.is_empty() {
202 SearchMode::Keyword
203 } else {
204 mode
205 };
206 HybridIndex::search(self, &embedding, query_text, top_k, 0.0, effective_mode)
207 }
208}
209
210/// Reciprocal Rank Fusion of two ranked lists.
211///
212/// Each entry in `semantic` and `bm25` is `(chunk_index, _score)`.
213/// The fused score for a chunk is the sum of `1 / (k + rank + 1)` across
214/// every list the chunk appears in, where `rank` is 0-based.
215///
216/// Returns all chunks that appear in either list, sorted descending by
217/// fused RRF score.
218///
219/// `k` should typically be 60.0 — a conventional constant that smooths the
220/// ranking boost for the very top results.
221#[must_use]
222pub fn rrf_fuse(semantic: &[(usize, f32)], bm25: &[(usize, f32)], k: f32) -> Vec<(usize, f32)> {
223 let mut scores: HashMap<usize, f32> = HashMap::new();
224
225 for (rank, &(idx, _)) in semantic.iter().enumerate() {
226 *scores.entry(idx).or_insert(0.0) += 1.0 / (k + rank as f32 + 1.0);
227 }
228 for (rank, &(idx, _)) in bm25.iter().enumerate() {
229 *scores.entry(idx).or_insert(0.0) += 1.0 / (k + rank as f32 + 1.0);
230 }
231
232 let mut results: Vec<(usize, f32)> = scores.into_iter().collect();
233 results.sort_unstable_by(|a, b| {
234 b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)) // stable tie-break by chunk index
235 });
236 results
237}
238
239/// Sigmoid steepness for the PageRank percentile boost. Lower values
240/// produce a sharper transition between "below median" (low boost) and
241/// "above median" (full boost).
242const PAGERANK_SIGMOID_STEEPNESS: f32 = 0.15;
243
244/// Sigmoid-shaped multiplicative boost factor for a single PageRank
245/// **percentile** in the corpus (not the raw rank value).
246///
247/// Returns the multiplier (so the final score is `dense_score * factor`).
248///
249/// ```text
250/// factor = 1 + alpha * sigmoid((percentile - 0.5) / s)
251/// sigmoid(z) = 1 / (1 + exp(-z))
252/// ```
253///
254/// where `s = PAGERANK_SIGMOID_STEEPNESS`.
255///
256/// ## Why this shape, with examples
257///
258/// The first attempt used a logarithmic saturation curve on raw rank
259/// values. That failed because raw ranks in a top-K result set
260/// concentrate in a tiny band (max ≈ 0.028 in Tokio), producing
261/// uniformly tiny boosts. The next attempt added a "presence floor"
262/// for `rank > 0`, which failed because tests also have tiny-but-
263/// positive PR from PageRank's damping term — both impl and test
264/// cleared the floor equally.
265///
266/// Switching the input to **percentile in the corpus** fixes both
267/// pathologies. A test with no inbound edges sits in the bottom decile
268/// of the PR distribution (percentile ≈ 0.05); a typical
269/// implementation file sits above the median. The sigmoid then makes
270/// the transition between "below median" (no boost) and "above median"
271/// (near-full boost) sharp:
272///
273/// | percentile | sigmoid | boost (α=0.5) |
274/// |------------|---------|---------------|
275/// | 0.05 (low test) | 0.04 | 1.02× |
276/// | 0.30 | 0.21 | 1.10× |
277/// | 0.50 (median) | 0.50 | 1.25× |
278/// | 0.70 | 0.79 | 1.40× |
279/// | 0.95 (top impl)| 0.95 | 1.47× |
280///
281/// Ceiling at `1 + α` — with `α = 0.5` that's 1.5×, bounded enough to
282/// keep PageRank a tiebreaker rather than a dominator: an irrelevant
283/// top-PR file with dense score 0.6 gets `0.6 × 1.5 = 0.9` and still
284/// loses to a relevant low-PR file scoring above 0.9.
285///
286/// This matches the two design constraints:
287/// 1. A test (low percentile) should not be lifted above an impl
288/// (high percentile) on similar dense scores. Sigmoid centered at
289/// 0.5 makes "below median" almost-no-boost.
290/// 2. A heavily-imported file shouldn't dominate. The sigmoid plateau
291/// above `percentile > 0.85` means a singularly-popular file gets
292/// barely more boost than a moderately-popular one.
293#[must_use]
294pub fn pagerank_boost_factor(percentile: f32, alpha: f32) -> f32 {
295 if percentile <= 0.0 || alpha <= 0.0 {
296 return 1.0;
297 }
298 let z = (percentile.clamp(0.0, 1.0) - 0.5) / PAGERANK_SIGMOID_STEEPNESS;
299 let sigmoid = 1.0 / (1.0 + (-z).exp());
300 1.0 + alpha * sigmoid
301}
302
303/// Apply a multiplicative PageRank boost to search results.
304///
305/// For each result, looks up the chunk's PageRank percentile and applies
306/// the sigmoid boost from [`pagerank_boost_factor`].
307///
308/// Results are re-sorted after boosting.
309///
310/// `pagerank_by_file` maps relative file paths to their **PageRank
311/// percentile** in the corpus distribution — not the raw rank value.
312/// Build it via [`pagerank_lookup`], which switched to percentile in
313/// service of the sigmoid curve.
314///
315/// `alpha` controls the maximum boost (ceiling = `1 + alpha`). The
316/// `alpha` field from [`RepoGraph`] is recommended (auto-tuned from
317/// graph density).
318pub fn boost_with_pagerank<S: std::hash::BuildHasher>(
319 results: &mut [(usize, f32)],
320 chunks: &[CodeChunk],
321 pagerank_by_file: &HashMap<String, f32, S>,
322 alpha: f32,
323) {
324 // Operates on `&mut [_]` (not `&mut Vec<_>`) so we can't delegate
325 // to `crate::ranking::PageRankBoost::apply` directly (the trait
326 // method takes `&mut Vec` to allow truncation layers). Replicate
327 // the boost loop inline; both paths share `lookup_rank` +
328 // `pagerank_boost_factor` so the curve stays consistent.
329 for (idx, score) in results.iter_mut() {
330 if let Some(chunk) = chunks.get(*idx) {
331 let rank = lookup_rank(pagerank_by_file, &chunk.file_path, &chunk.name);
332 *score *= pagerank_boost_factor(rank, alpha);
333 }
334 }
335 results.sort_unstable_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
336}
337
338/// `boost_with_pagerank` variant that operates on `SearchResult` directly,
339/// for callers that don't have the raw `(usize, f32)` pair at hand.
340///
341/// Same boost math as [`boost_with_pagerank`]; re-sorts in place.
342pub fn boost_with_pagerank_results<S: std::hash::BuildHasher>(
343 results: &mut [crate::embed::SearchResult],
344 pagerank_by_file: &HashMap<String, f32, S>,
345 alpha: f32,
346) {
347 // SearchResult shape; inline math like `boost_with_pagerank`.
348 for r in results.iter_mut() {
349 let rank = lookup_rank(pagerank_by_file, &r.chunk.file_path, &r.chunk.name);
350 r.similarity *= pagerank_boost_factor(rank, alpha);
351 }
352 results.sort_unstable_by(|a, b| b.similarity.total_cmp(&a.similarity));
353}
354
355/// Resolve a chunk's PageRank score from a path that may be rooted
356/// differently than the graph keys.
357///
358/// Background: `RepoGraph` stores `FileNode.path` as `path.strip_prefix(root)`
359/// where `root` is the **canonicalized** corpus root. Chunk
360/// `file_path` is `path.display()` where `path` came from the walker —
361/// which uses the caller-supplied root **as-is** (not canonicalized).
362/// When the caller passes `tests/corpus/code/tokio`, chunk paths look
363/// like `tests/corpus/code/tokio/tokio/src/.../foo.rs` while graph
364/// keys look like `tokio/src/.../foo.rs`. Direct lookup never hits.
365///
366/// This function tries: definition-level exact (`"file::name"`),
367/// file-level exact, then walks the chunk path one segment at a time
368/// from the left and retries each suffix. First match wins.
369///
370/// (The proper fix is to normalize chunk paths at chunk-creation time
371/// to be relative to the canonicalized corpus root; that's a larger
372/// refactor planned alongside the `RankingLayer` work. Suffix matching
373/// is the surgical patch that makes PageRank actually function.)
374/// Re-exported under a longer name for use from the
375/// [`crate::ranking`] module. Kept as a `pub(crate)` symbol so it
376/// doesn't leak into the public surface; the canonical access point
377/// is [`crate::ranking::PageRankBoost`].
378pub(crate) fn lookup_rank_for_chunk<S: std::hash::BuildHasher>(
379 pr: &HashMap<String, f32, S>,
380 file_path: &str,
381 name: &str,
382) -> f32 {
383 lookup_rank(pr, file_path, name)
384}
385
386fn lookup_rank<S: std::hash::BuildHasher>(
387 pr: &HashMap<String, f32, S>,
388 file_path: &str,
389 name: &str,
390) -> f32 {
391 let def_key = format!("{file_path}::{name}");
392 if let Some(&r) = pr.get(&def_key) {
393 return r;
394 }
395 if let Some(&r) = pr.get(file_path) {
396 return r;
397 }
398 // Slide a left-edge cursor through the path. For
399 // `a/b/c/d/foo.rs` try `b/c/d/foo.rs`, then `c/d/foo.rs`, etc.
400 // Path components are typically <= 8 levels, so this is cheap.
401 let mut rest = file_path;
402 while let Some(idx) = rest.find('/') {
403 rest = &rest[idx + 1..];
404 if rest.is_empty() {
405 break;
406 }
407 let def_key = format!("{rest}::{name}");
408 if let Some(&r) = pr.get(&def_key) {
409 return r;
410 }
411 if let Some(&r) = pr.get(rest) {
412 return r;
413 }
414 }
415 0.0
416}
417
418/// Build a normalized PageRank lookup table from a [`RepoGraph`].
419///
420/// Returns a map from `"file_path::def_name"` to definition-level PageRank
421/// normalized to `[0, 1]`. Also inserts file-level entries (`"file_path"`)
422/// as aggregated fallback for chunks that don't match a specific definition.
423#[must_use]
424pub fn pagerank_lookup(graph: &crate::repo_map::RepoGraph) -> HashMap<String, f32> {
425 // Switched from `rank / max_rank` (proportional) to percentile in
426 // the corpus distribution. Rationale: a top-K result set typically
427 // contains files whose raw ranks are all in a tiny band near zero
428 // (Tokio: max in top-10 was 0.028 out of 1.0). Proportional
429 // normalization gave uniformly tiny boosts. Percentile separates
430 // "bottom decile (tests, leaves)" from "top half (impls, hubs)"
431 // crisply, and pairs with the sigmoid in `pagerank_boost_factor`
432 // to put the rank-transition where the action is.
433 //
434 // Definition-level and file-level percentiles use independent
435 // distributions: `def_ranks` and `base_ranks`. A file that has no
436 // defs still gets a file-level percentile from `base_ranks`.
437 let def_pct = make_percentile_fn(&graph.def_ranks);
438 let base_pct = make_percentile_fn(&graph.base_ranks);
439 let mut map = HashMap::new();
440 for (file_idx, file) in graph.files.iter().enumerate() {
441 for (def_idx, def) in file.defs.iter().enumerate() {
442 let flat = graph.def_offsets[file_idx] + def_idx;
443 if let Some(&rank) = graph.def_ranks.get(flat) {
444 let key = format!("{}::{}", file.path, def.name);
445 map.insert(key, def_pct(rank));
446 }
447 }
448 if file_idx < graph.base_ranks.len() {
449 map.insert(file.path.clone(), base_pct(graph.base_ranks[file_idx]));
450 }
451 }
452 map
453}
454
455/// Build a `value → percentile` function from a slice of rank values.
456///
457/// Sorts a copy once at build time, then each lookup is a binary search
458/// over the sorted slice. Returns the empirical CDF: the fraction of
459/// values strictly less than the queried value. Handles empty input
460/// and `NaN` defensively.
461fn make_percentile_fn(values: &[f32]) -> impl Fn(f32) -> f32 + '_ {
462 let mut sorted: Vec<f32> = values.iter().copied().filter(|v| v.is_finite()).collect();
463 sorted.sort_unstable_by(f32::total_cmp);
464 move |value: f32| {
465 if sorted.is_empty() {
466 return 0.0;
467 }
468 // partition_point returns the count of elements strictly less
469 // than `value` (because the predicate is `<`).
470 let count_below = sorted.partition_point(|&v| v < value);
471 #[expect(
472 clippy::cast_precision_loss,
473 reason = "rank counts well below f32 precision threshold"
474 )]
475 let pct = count_below as f32 / sorted.len() as f32;
476 pct
477 }
478}
479
480#[cfg(test)]
481mod tests {
482 use super::*;
483
484 #[test]
485 fn rrf_union_semantics() {
486 // sem: [0, 1, 2], bm25: [3, 0, 4]
487 // Chunk 0 appears in both lists → highest RRF score.
488 // Chunks 1, 2, 3, 4 appear in exactly one list → all five appear.
489 let sem = vec![(0, 0.9), (1, 0.8), (2, 0.7)];
490 let bm25 = vec![(3, 10.0), (0, 8.0), (4, 6.0)];
491
492 let fused = rrf_fuse(&sem, &bm25, 60.0);
493
494 let indices: Vec<usize> = fused.iter().map(|&(i, _)| i).collect();
495
496 // All 5 unique chunks must appear
497 for expected in [0, 1, 2, 3, 4] {
498 assert!(
499 indices.contains(&expected),
500 "chunk {expected} missing from fused results"
501 );
502 }
503 assert_eq!(fused.len(), 5);
504
505 // Chunk 0 must rank first (double-list bonus)
506 assert_eq!(indices[0], 0, "chunk 0 should rank first");
507 }
508
509 #[test]
510 fn rrf_single_list() {
511 // Only semantic results; BM25 is empty.
512 let sem = vec![(0, 0.9), (1, 0.8)];
513 let bm25: Vec<(usize, f32)> = vec![];
514
515 let fused = rrf_fuse(&sem, &bm25, 60.0);
516
517 assert_eq!(fused.len(), 2);
518 // Chunk 0 ranked first in sem list → higher RRF score than chunk 1
519 assert_eq!(fused[0].0, 0);
520 assert_eq!(fused[1].0, 1);
521 assert!(fused[0].1 > fused[1].1);
522 }
523
524 #[test]
525 fn search_mode_roundtrip() {
526 assert_eq!("hybrid".parse::<SearchMode>().unwrap(), SearchMode::Hybrid);
527 assert_eq!(
528 "semantic".parse::<SearchMode>().unwrap(),
529 SearchMode::Semantic
530 );
531 assert_eq!(
532 "keyword".parse::<SearchMode>().unwrap(),
533 SearchMode::Keyword
534 );
535
536 let err = "invalid".parse::<SearchMode>();
537 assert!(err.is_err(), "expected parse error for 'invalid'");
538 let msg = err.unwrap_err().to_string();
539 assert!(
540 msg.contains("invalid"),
541 "error message should echo the bad input"
542 );
543 }
544
545 #[test]
546 fn search_mode_display() {
547 assert_eq!(SearchMode::Hybrid.to_string(), "hybrid");
548 assert_eq!(SearchMode::Semantic.to_string(), "semantic");
549 assert_eq!(SearchMode::Keyword.to_string(), "keyword");
550 }
551
552 #[test]
553 fn pagerank_boost_amplifies_relevant() {
554 let chunks = vec![
555 CodeChunk {
556 file_path: "important.rs".into(),
557 name: "a".into(),
558 kind: "function".into(),
559 start_line: 1,
560 end_line: 10,
561 content: String::new(),
562 enriched_content: String::new(),
563 },
564 CodeChunk {
565 file_path: "obscure.rs".into(),
566 name: "b".into(),
567 kind: "function".into(),
568 start_line: 1,
569 end_line: 10,
570 content: String::new(),
571 enriched_content: String::new(),
572 },
573 ];
574
575 // Both start with same score; important.rs has high PageRank
576 let mut results = vec![(0, 0.8_f32), (1, 0.8)];
577 let mut pr = HashMap::new();
578 pr.insert("important.rs".to_string(), 1.0); // max PageRank
579 pr.insert("obscure.rs".to_string(), 0.1); // low PageRank
580
581 boost_with_pagerank(&mut results, &chunks, &pr, 0.3);
582
583 // important.rs should now rank higher
584 assert_eq!(
585 results[0].0, 0,
586 "important.rs should rank first after boost"
587 );
588 assert!(results[0].1 > results[1].1);
589
590 // Boost values reflect the sigmoid-on-percentile curve in
591 // `pagerank_boost_factor` (alpha=0.3 here):
592 // - percentile=1.0: sigmoid(3.33) ≈ 0.965, boost ≈ 1.29 → 1.032
593 // - percentile=0.1: sigmoid(-2.67) ≈ 0.065, boost ≈ 1.02 → 0.816
594 assert!(
595 (results[0].1 - 1.032).abs() < 0.01,
596 "rank=1.0 boost: expected ~1.032, got {}",
597 results[0].1
598 );
599 assert!(
600 (results[1].1 - 0.816).abs() < 0.01,
601 "rank=0.1 boost: expected ~0.816, got {}",
602 results[1].1
603 );
604 }
605
606 #[test]
607 fn pagerank_boost_zero_relevance_stays_zero() {
608 let chunks = vec![CodeChunk {
609 file_path: "important.rs".into(),
610 name: "a".into(),
611 kind: "function".into(),
612 start_line: 1,
613 end_line: 10,
614 content: String::new(),
615 enriched_content: String::new(),
616 }];
617
618 let mut results = vec![(0, 0.0_f32)];
619 let mut pr = HashMap::new();
620 pr.insert("important.rs".to_string(), 1.0);
621
622 boost_with_pagerank(&mut results, &chunks, &pr, 0.3);
623
624 // Zero score stays zero regardless of PageRank
625 assert!(results[0].1.abs() < f32::EPSILON);
626 }
627
628 #[test]
629 fn pagerank_boost_unknown_file_no_effect() {
630 let chunks = vec![CodeChunk {
631 file_path: "unknown.rs".into(),
632 name: "a".into(),
633 kind: "function".into(),
634 start_line: 1,
635 end_line: 10,
636 content: String::new(),
637 enriched_content: String::new(),
638 }];
639
640 let mut results = vec![(0, 0.5_f32)];
641 let pr = HashMap::new(); // empty — no PageRank data
642
643 boost_with_pagerank(&mut results, &chunks, &pr, 0.3);
644
645 // No PageRank data → no boost
646 assert!((results[0].1 - 0.5).abs() < f32::EPSILON);
647 }
648}