vera2-core 0.12.16-aristoddle.1

Core engine for Vera: parsing, indexing, retrieval, storage, and embedding
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
//! Hybrid retrieval engine combining BM25 and vector search via RRF fusion.
//!
//! Runs both BM25 keyword search and vector similarity search in parallel,
//! then merges the results using Reciprocal Rank Fusion (RRF). Items appearing
//! in both result sets rank higher than single-source results.
//!
//! RRF score: `score = sum(1 / (k + rank_i))` where `k` is a constant
//! (typically 60) and `rank_i` is the 1-based rank of the item in each
//! source result list.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime};

use anyhow::{Context, Result};
use tracing::{debug, info, warn};

use crate::embedding::EmbeddingProvider;
use crate::retrieval::bm25::search_bm25_with_stores_and_filters;
use crate::retrieval::graph_augmentation::augment_pool;
use crate::retrieval::query_classifier::{QueryType, classify_query, params_for_query_type};
use crate::retrieval::query_utils::result_key;
use crate::retrieval::ranking::is_path_weighted_query;
use crate::retrieval::reranker::{Reranker, rerank_results};
use crate::retrieval::vector::{
    VectorSearchError, search_vector_with_cached_stores_timed, search_vector_with_stores_timed,
};
use crate::storage::bm25::Bm25Index;
use crate::storage::metadata::MetadataStore;
use crate::storage::vector::VectorStore;
use crate::types::{SearchFilters, SearchResult};

/// Open search stores reused for the active index directory.
pub(crate) struct SearchStores {
    pub(crate) bm25: Bm25Index,
    pub(crate) bm25_metadata: Mutex<MetadataStore>,
    pub(crate) vector_metadata: Mutex<MetadataStore>,
    vector_path: PathBuf,
    vector: Mutex<Option<CachedVectorStore>>,
    metadata_path: PathBuf,
    indexed_files: Mutex<Option<CachedIndexedFiles>>,
}

struct CachedIndexedFiles {
    stamp: MetadataDbStamp,
    files: Arc<Vec<String>>,
}

#[derive(Clone, Copy, PartialEq, Eq)]
struct MetadataDbStamp {
    db_len: Option<u64>,
    db_mtime: Option<SystemTime>,
    wal_len: Option<u64>,
    wal_mtime: Option<SystemTime>,
}

fn metadata_db_stamp(db_path: &Path) -> MetadataDbStamp {
    // WAL-mode commits append to the -wal file without touching the main
    // database file until a checkpoint, so both files must contribute.
    let wal_path = db_path.with_file_name(format!(
        "{}-wal",
        db_path
            .file_name()
            .map(|name| name.to_string_lossy().into_owned())
            .unwrap_or_default()
    ));
    let stats = |path: &Path| {
        std::fs::metadata(path)
            .ok()
            .map(|metadata| (metadata.len(), metadata.modified().ok()))
    };
    let (db_len, db_mtime) = stats(db_path).map_or((None, None), |(len, mtime)| (Some(len), mtime));
    let (wal_len, wal_mtime) =
        stats(&wal_path).map_or((None, None), |(len, mtime)| (Some(len), mtime));
    MetadataDbStamp {
        db_len,
        db_mtime,
        wal_len,
        wal_mtime,
    }
}

struct CachedVectorStore {
    dim: usize,
    stamp: VectorStoreStamp,
    store: Arc<Mutex<VectorStore>>,
}

#[derive(Clone, Copy, PartialEq, Eq)]
struct VectorStoreStamp {
    db_len: Option<u64>,
    db_mtime: Option<SystemTime>,
    manifest_mtime: Option<SystemTime>,
    manifest_generation: Option<u64>,
}

fn vector_store_stamp(vector_path: &Path) -> VectorStoreStamp {
    let db_metadata = std::fs::metadata(vector_path).ok();
    let manifest_path = vector_path.with_file_name("vectors.manifest");
    let manifest_mtime = std::fs::metadata(&manifest_path)
        .and_then(|metadata| metadata.modified())
        .ok();
    let manifest_generation = std::fs::read(&manifest_path)
        .ok()
        .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
        .and_then(|manifest| {
            manifest
                .get("generation")
                .and_then(serde_json::Value::as_u64)
        });
    VectorStoreStamp {
        db_len: db_metadata.as_ref().map(std::fs::Metadata::len),
        db_mtime: db_metadata.and_then(|metadata| metadata.modified().ok()),
        manifest_mtime,
        manifest_generation,
    }
}

impl SearchStores {
    pub(crate) fn open(index_dir: &Path) -> Result<Self> {
        let bm25 = Bm25Index::open(&index_dir.join("bm25"))
            .context("failed to open BM25 index for search")?;
        let metadata_path = index_dir.join("metadata.db");
        let bm25_metadata = MetadataStore::open(&metadata_path)
            .context("failed to open metadata store for search")?;
        let vector_metadata = MetadataStore::open(&metadata_path)
            .context("failed to open vector metadata store for search")?;
        Ok(Self {
            bm25,
            bm25_metadata: Mutex::new(bm25_metadata),
            vector_metadata: Mutex::new(vector_metadata),
            vector_path: index_dir.join("vectors.db"),
            vector: Mutex::new(None),
            metadata_path,
            indexed_files: Mutex::new(None),
        })
    }

    /// Indexed file list, cached against the metadata database stamp.
    ///
    /// `MetadataStore::indexed_files()` runs a DISTINCT scan over every chunk
    /// row, which costs tens of milliseconds on large indexes. Searches repeat
    /// it per query through exact-match augmentation, so the list is cached
    /// and refreshed only when metadata.db (or its WAL) changes on disk.
    ///
    /// Reads the stamp before querying so a concurrent commit invalidates the
    /// entry instead of certifying a stale list. A fresh connection is used on
    /// misses so this never interacts with the `bm25_metadata` lock.
    pub(crate) fn indexed_files(&self) -> Result<Arc<Vec<String>>> {
        let stamp = metadata_db_stamp(&self.metadata_path);
        {
            let cached = self
                .indexed_files
                .lock()
                .map_err(|_| anyhow::anyhow!("indexed files cache lock poisoned"))?;
            if let Some(cached) = cached.as_ref()
                && cached.stamp == stamp
            {
                return Ok(Arc::clone(&cached.files));
            }
        }
        let files = Arc::new(
            MetadataStore::open(&self.metadata_path)
                .context("failed to open metadata store for file list")?
                .indexed_files()?,
        );
        let mut cached = self
            .indexed_files
            .lock()
            .map_err(|_| anyhow::anyhow!("indexed files cache lock poisoned"))?;
        *cached = Some(CachedIndexedFiles {
            stamp,
            files: Arc::clone(&files),
        });
        Ok(files)
    }

    pub(crate) fn vector_store(&self, dim: usize) -> Result<Arc<Mutex<VectorStore>>> {
        let mut cached = self
            .vector
            .lock()
            .map_err(|_| anyhow::anyhow!("vector store cache lock poisoned"))?;
        let stamp = vector_store_stamp(&self.vector_path);
        if let Some(cached_store) = cached.as_ref()
            && cached_store.dim == dim
            && cached_store.stamp == stamp
        {
            return Ok(Arc::clone(&cached_store.store));
        }

        let store = Arc::new(Mutex::new(
            VectorStore::open(&self.vector_path, dim).context("failed to open vector store")?,
        ));
        let stamp = vector_store_stamp(&self.vector_path);
        *cached = Some(CachedVectorStore {
            dim,
            stamp,
            store: Arc::clone(&store),
        });
        Ok(store)
    }
}

/// Errors specific to hybrid search.
#[derive(Debug, thiserror::Error)]
pub enum HybridSearchError {
    /// Both BM25 and vector search failed.
    #[error("both BM25 and vector search failed: bm25={bm25_error}, vector={vector_error}")]
    BothFailed {
        bm25_error: String,
        vector_error: String,
    },

    /// Storage or pipeline error.
    #[error("{0}")]
    PipelineError(#[from] anyhow::Error),
}

/// Compute the number of vector candidates to fetch for a given limit and
/// query type multiplier. Ensures at least 50 candidates for any limit.
pub fn compute_vector_candidates(limit: usize, multiplier: usize) -> usize {
    limit.saturating_mul(multiplier).max(50)
}

fn compute_bm25_candidates(query: &str, limit: usize) -> usize {
    let query_type = classify_query(query);
    let token_count = query.split_whitespace().count();

    if is_path_weighted_query(query) {
        return limit.saturating_mul(5).max(100);
    }
    if query_type == QueryType::NaturalLanguage {
        return limit.saturating_mul(4).max(limit + 40);
    }
    if token_count <= 2 {
        return limit.saturating_mul(4).max(80);
    }

    limit.saturating_mul(3).max(limit + 20)
}

/// Per-stage timing data from hybrid search.
#[derive(Debug, Default)]
pub struct HybridTimings {
    pub embedding: Option<Duration>,
    pub bm25: Option<Duration>,
    pub vector: Option<Duration>,
    pub fusion: Option<Duration>,
    pub reranking: Option<Duration>,
}

/// Perform hybrid search combining BM25 and vector retrieval via RRF fusion.
///
/// Runs BM25 and vector search concurrently, then merges the results using
/// Reciprocal Rank Fusion (RRF). BM25 runs in a blocking task with its own
/// database connections while vector search (embedding + nearest-neighbor)
/// runs on the async runtime. If vector search fails (e.g., embedding API
/// unavailable), falls back to BM25-only results with a warning.
#[allow(clippy::too_many_arguments)]
pub async fn search_hybrid(
    index_dir: &Path,
    provider: &impl EmbeddingProvider,
    bm25_query: &str,
    vector_query: &str,
    filters: &SearchFilters,
    limit: usize,
    rrf_k: f64,
    stored_dim: usize,
    vector_candidates: usize,
) -> Result<(Vec<SearchResult>, HybridTimings), HybridSearchError> {
    search_hybrid_inner(
        index_dir,
        provider,
        bm25_query,
        vector_query,
        filters,
        limit,
        rrf_k,
        stored_dim,
        vector_candidates,
        None,
    )
    .await
}

/// Perform hybrid search using stores retained by a reusable search context.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn search_hybrid_with_stores(
    index_dir: &Path,
    provider: &impl EmbeddingProvider,
    bm25_query: &str,
    vector_query: &str,
    filters: &SearchFilters,
    limit: usize,
    rrf_k: f64,
    stored_dim: usize,
    vector_candidates: usize,
    stores: Arc<SearchStores>,
) -> Result<(Vec<SearchResult>, HybridTimings), HybridSearchError> {
    search_hybrid_inner(
        index_dir,
        provider,
        bm25_query,
        vector_query,
        filters,
        limit,
        rrf_k,
        stored_dim,
        vector_candidates,
        Some(stores),
    )
    .await
}

#[allow(clippy::too_many_arguments)]
async fn search_hybrid_inner(
    index_dir: &Path,
    provider: &impl EmbeddingProvider,
    bm25_query: &str,
    vector_query: &str,
    filters: &SearchFilters,
    limit: usize,
    rrf_k: f64,
    stored_dim: usize,
    vector_candidates: usize,
    stores: Option<Arc<SearchStores>>,
) -> Result<(Vec<SearchResult>, HybridTimings), HybridSearchError> {
    let query_type = classify_query(bm25_query);
    let query_params = params_for_query_type(query_type);
    let bm25_candidates = compute_bm25_candidates(bm25_query, limit);
    let mut timings = HybridTimings::default();

    // Spawn BM25 search in a blocking task. Reusable search contexts retain
    // the Tantivy reader and SQLite connection; direct callers keep the
    // original open-per-call behavior.
    let bm25_dir = index_dir.join("bm25");
    let metadata_path = index_dir.join("metadata.db");
    let bm25_query = bm25_query.to_string();
    let bm25_filters = filters.clone();
    let stores_for_bm25 = stores.clone();
    let bm25_handle = tokio::task::spawn_blocking(move || {
        let start = Instant::now();
        let result = match stores_for_bm25 {
            Some(stores) => stores
                .bm25_metadata
                .lock()
                .map_err(|_| anyhow::anyhow!("metadata store lock poisoned"))
                .and_then(|store| {
                    search_bm25_with_stores_and_filters(
                        &stores.bm25,
                        &store,
                        &bm25_query,
                        &bm25_filters,
                        bm25_candidates,
                    )
                }),
            None => Bm25Index::open(&bm25_dir)
                .context("failed to open BM25 index for search")
                .and_then(|index| {
                    let store = MetadataStore::open(&metadata_path)
                        .context("failed to open metadata store for BM25 search")?;
                    search_bm25_with_stores_and_filters(
                        &index,
                        &store,
                        &bm25_query,
                        &bm25_filters,
                        bm25_candidates,
                    )
                }),
        };
        (result, start.elapsed())
    });

    // Run vector search concurrently on the async runtime.
    // Filters are applied after the kNN fetch, so a selective filter can
    // discard every hit in the default window. Over-fetch when filters are
    // active so filtered chunks beyond the window can still reach fusion.
    let vector_fetch = if filters.is_empty() {
        vector_candidates
    } else {
        vector_candidates.saturating_mul(4).max(200)
    };
    let vector_start = Instant::now();
    let vector_outcome = match stores {
        Some(stores) => match stores.vector_store(stored_dim) {
            Ok(vector_store) => {
                match search_vector_with_cached_stores_timed(
                    vector_store.as_ref(),
                    &stores.vector_metadata,
                    provider,
                    vector_query,
                    vector_fetch,
                )
                .await
                {
                    Ok((mut results, embed_elapsed)) => {
                        if !filters.is_empty() {
                            results.retain(|result| filters.matches(result));
                        }
                        Ok((results, embed_elapsed))
                    }
                    Err(err) => Err(err),
                }
            }
            Err(err) => Err(VectorSearchError::StorageError(err)),
        },
        None => match VectorStore::open(&index_dir.join("vectors.db"), stored_dim) {
            Ok(vector_store) => {
                let vector_metadata_result = MetadataStore::open(&index_dir.join("metadata.db"))
                    .context("failed to open metadata store");
                match vector_metadata_result {
                    Ok(vector_metadata) => {
                        match search_vector_with_stores_timed(
                            &vector_store,
                            &vector_metadata,
                            provider,
                            vector_query,
                            vector_fetch,
                        )
                        .await
                        {
                            Ok((mut results, embed_elapsed)) => {
                                if !filters.is_empty() {
                                    results.retain(|result| filters.matches(result));
                                }
                                Ok((results, embed_elapsed))
                            }
                            Err(err) => Err(err),
                        }
                    }
                    Err(err) => Err(VectorSearchError::StorageError(err)),
                }
            }
            Err(err) => Err(VectorSearchError::StorageError(
                err.context("failed to open vector store"),
            )),
        },
    };
    let embed_elapsed = vector_outcome
        .as_ref()
        .ok()
        .map(|(_, embed_elapsed)| *embed_elapsed);
    charge_vector_span(&mut timings, vector_start.elapsed(), embed_elapsed);
    let vector_results = vector_outcome.map(|(results, _)| results);

    // Await the BM25 result (should already be done or nearly done).
    let (bm25_results, bm25_elapsed) = bm25_handle.await.map_err(|e| {
        HybridSearchError::PipelineError(anyhow::anyhow!("BM25 task panicked: {e}"))
    })?;
    timings.bm25 = Some(bm25_elapsed);

    match (bm25_results, vector_results) {
        (Ok(bm25), Ok(vector)) => {
            debug!(
                bm25_count = bm25.len(),
                vector_count = vector.len(),
                query_type = ?query_type,
                bm25_weight = query_params.bm25_weight,
                vector_weight = query_params.vector_weight,
                "merging BM25 and vector results via weighted RRF"
            );
            let fusion_start = Instant::now();
            let fused = fuse_rrf_weighted(
                &bm25,
                &vector,
                rrf_k,
                limit,
                query_params.bm25_weight,
                query_params.vector_weight,
            );
            timings.fusion = Some(fusion_start.elapsed());
            Ok((fused, timings))
        }
        (Ok(bm25), Err(vec_err)) => {
            warn!(
                error = %vec_err,
                "vector search failed, falling back to BM25-only results"
            );
            let mut results = bm25;
            results.truncate(limit);
            Ok((results, timings))
        }
        (Err(bm25_err), Ok(vector)) => {
            warn!(
                error = %bm25_err,
                "BM25 search failed, falling back to vector-only results"
            );
            let mut results = vector;
            results.truncate(limit);
            Ok((results, timings))
        }
        (Err(bm25_err), Err(vec_err)) => Err(HybridSearchError::BothFailed {
            bm25_error: format!("{bm25_err:#}"),
            vector_error: format!("{vec_err:#}"),
        }),
    }
}

/// Perform hybrid search with cross-encoder reranking.
///
/// Runs the full hybrid pipeline (BM25 + vector → RRF fusion), then
/// sends the top candidates to a cross-encoder reranker for more accurate
/// relevance scoring.
///
/// **Graceful degradation:**
/// - If the reranker API is unavailable (timeout, 5xx, connection error),
///   returns unreranked results with a warning logged to stderr.
/// - If the embedding API is unavailable, falls back to BM25-only results
///   (handled by the inner `search_hybrid` call).
///
/// # Arguments
/// - `index_dir` — Path to the `.vera` index directory
/// - `provider` — Embedding provider for vector search
/// - `reranker` — Reranker for result refinement
/// - `bm25_query` — Raw query text for the BM25 side (never intent-prefixed)
/// - `vector_query` — Query text for embedding and reranking (may carry intent)
/// - `filters` — Post-retrieval filters applied before fusion and reranking
/// - `fetch_limit` — Maximum number of candidates to retain through fusion
/// - `result_limit` — Maximum number of results to return to the user
/// - `rrf_k` — RRF constant (typically 60.0)
/// - `stored_dim` — Dimensionality of stored vectors
/// - `rerank_candidates` — Number of candidates to send to the reranker
/// - `vector_candidates` — Number of vector candidates to fetch (query-type-aware)
#[allow(clippy::too_many_arguments)]
pub async fn search_hybrid_reranked(
    index_dir: &Path,
    provider: &impl EmbeddingProvider,
    reranker: &impl Reranker,
    bm25_query: &str,
    vector_query: &str,
    filters: &SearchFilters,
    fetch_limit: usize,
    result_limit: usize,
    rrf_k: f64,
    stored_dim: usize,
    rerank_candidates: usize,
    vector_candidates: usize,
) -> Result<(Vec<SearchResult>, HybridTimings), HybridSearchError> {
    search_hybrid_reranked_with_augmentation(
        index_dir,
        provider,
        reranker,
        bm25_query,
        vector_query,
        filters,
        fetch_limit,
        result_limit,
        rrf_k,
        stored_dim,
        rerank_candidates,
        vector_candidates,
        false,
    )
    .await
}

/// Perform reranked hybrid search using stores retained by a reusable context.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn search_hybrid_reranked_with_stores(
    index_dir: &Path,
    provider: &impl EmbeddingProvider,
    reranker: &impl Reranker,
    bm25_query: &str,
    vector_query: &str,
    filters: &SearchFilters,
    fetch_limit: usize,
    result_limit: usize,
    rrf_k: f64,
    stored_dim: usize,
    rerank_candidates: usize,
    vector_candidates: usize,
    graph_augmentation_enabled: bool,
    stores: Arc<SearchStores>,
) -> Result<(Vec<SearchResult>, HybridTimings), HybridSearchError> {
    search_hybrid_reranked_inner(
        index_dir,
        provider,
        reranker,
        bm25_query,
        vector_query,
        filters,
        fetch_limit,
        result_limit,
        rrf_k,
        stored_dim,
        rerank_candidates,
        vector_candidates,
        graph_augmentation_enabled,
        Some(stores),
    )
    .await
}

/// Perform hybrid search with optional experimental graph augmentation.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn search_hybrid_reranked_with_augmentation(
    index_dir: &Path,
    provider: &impl EmbeddingProvider,
    reranker: &impl Reranker,
    bm25_query: &str,
    vector_query: &str,
    filters: &SearchFilters,
    fetch_limit: usize,
    result_limit: usize,
    rrf_k: f64,
    stored_dim: usize,
    rerank_candidates: usize,
    vector_candidates: usize,
    graph_augmentation_enabled: bool,
) -> Result<(Vec<SearchResult>, HybridTimings), HybridSearchError> {
    search_hybrid_reranked_inner(
        index_dir,
        provider,
        reranker,
        bm25_query,
        vector_query,
        filters,
        fetch_limit,
        result_limit,
        rrf_k,
        stored_dim,
        rerank_candidates,
        vector_candidates,
        graph_augmentation_enabled,
        None,
    )
    .await
}

#[allow(clippy::too_many_arguments)]
async fn search_hybrid_reranked_inner(
    index_dir: &Path,
    provider: &impl EmbeddingProvider,
    reranker: &impl Reranker,
    bm25_query: &str,
    vector_query: &str,
    filters: &SearchFilters,
    fetch_limit: usize,
    result_limit: usize,
    rrf_k: f64,
    stored_dim: usize,
    rerank_candidates: usize,
    vector_candidates: usize,
    graph_augmentation_enabled: bool,
    stores: Option<Arc<SearchStores>>,
) -> Result<(Vec<SearchResult>, HybridTimings), HybridSearchError> {
    let fusion_limit = rerank_candidates.max(fetch_limit);

    let (mut hybrid_results, mut timings) = match stores {
        Some(stores) => {
            search_hybrid_with_stores(
                index_dir,
                provider,
                bm25_query,
                vector_query,
                filters,
                fusion_limit,
                rrf_k,
                stored_dim,
                vector_candidates,
                stores,
            )
            .await?
        }
        None => {
            search_hybrid(
                index_dir,
                provider,
                bm25_query,
                vector_query,
                filters,
                fusion_limit,
                rrf_k,
                stored_dim,
                vector_candidates,
            )
            .await?
        }
    };

    let augmented_count = if graph_augmentation_enabled {
        augment_pool(index_dir, &mut hybrid_results, filters)
    } else {
        0
    };

    if hybrid_results.is_empty() {
        return Ok((hybrid_results, timings));
    }

    if hybrid_results.len() <= result_limit && augmented_count == 0 {
        return Ok((hybrid_results, timings));
    }

    let rerank_start = Instant::now();
    // When graph candidates were appended, score the whole expanded pool so
    // candidates beyond the normal rerank prefix still compete semantically.
    let rerank_limit = if augmented_count > 0 {
        hybrid_results.len()
    } else {
        rerank_candidates
    };
    match rerank_results(reranker, vector_query, &hybrid_results, rerank_limit).await {
        Ok(mut reranked) => {
            timings.reranking = Some(rerank_start.elapsed());
            info!(
                query = vector_query,
                candidates = hybrid_results.len(),
                reranked = reranked.len(),
                "reranking complete"
            );
            reranked = merge_reranked_results(reranked, hybrid_results, rerank_limit, fetch_limit);
            Ok((reranked, timings))
        }
        Err(rerank_err) => {
            timings.reranking = Some(rerank_start.elapsed());
            warn!(
                error = %rerank_err,
                "reranker unavailable, returning unreranked results"
            );
            eprintln!(
                "Warning: reranker unavailable ({rerank_err}), returning unreranked results."
            );
            let mut results = hybrid_results;
            results.truncate(fetch_limit);
            Ok((results, timings))
        }
    }
}

fn merge_reranked_results(
    mut reranked: Vec<SearchResult>,
    hybrid_results: Vec<SearchResult>,
    rerank_limit: usize,
    fetch_limit: usize,
) -> Vec<SearchResult> {
    let rerank_prefix_len = rerank_limit.min(hybrid_results.len());
    let mut present = reranked.iter().map(result_key).collect::<HashSet<_>>();
    let mut score_ceiling = reranked.last().map(|result| result.score);

    let mut append_unscored = |mut result: SearchResult| {
        if !present.insert(result_key(&result)) {
            return;
        }
        // RRF and reranker scores have different scales. Keep unscored candidates below the
        // reranked prefix so the public score order still matches the result order.
        if let Some(ceiling) = score_ceiling {
            result.score = result.score.min(ceiling);
        }
        score_ceiling = Some(result.score);
        reranked.push(result);
    };

    // A short reranker response can omit candidates from the prefix. Append those first,
    // preserving their original hybrid order, before the normal untouched tail.
    for result in hybrid_results.iter().take(rerank_prefix_len) {
        append_unscored(result.clone());
    }
    for result in hybrid_results.into_iter().skip(rerank_prefix_len) {
        append_unscored(result);
    }

    reranked.truncate(fetch_limit);
    reranked
}

/// Perform hybrid search using pre-opened stores (useful for testing).
///
/// Takes pre-computed BM25 and vector results and fuses them via RRF.
/// This is the core fusion logic, separated from I/O for testability.
pub fn fuse_rrf(
    bm25_results: &[SearchResult],
    vector_results: &[SearchResult],
    rrf_k: f64,
    limit: usize,
) -> Vec<SearchResult> {
    fuse_rrf_multi_weighted(&[bm25_results, vector_results], &[1.0, 1.0], rrf_k, limit)
}

/// Fuse BM25 and vector results with explicit per-source weights.
///
/// Identifier queries pass a higher BM25 weight (2.5) so lexical matches
/// dominate; NL queries use equal weights (1.0, 1.0).
pub fn fuse_rrf_weighted(
    bm25_results: &[SearchResult],
    vector_results: &[SearchResult],
    rrf_k: f64,
    limit: usize,
    bm25_weight: f64,
    vector_weight: f64,
) -> Vec<SearchResult> {
    fuse_rrf_multi_weighted(
        &[bm25_results, vector_results],
        &[bm25_weight, vector_weight],
        rrf_k,
        limit,
    )
}

/// Fuse multiple ranked result lists with weighted reciprocal rank fusion.
///
/// Each result set has an associated weight that scales its RRF contribution.
/// A weight of 2.0 means that set's scores count double in the final ranking.
///
/// Equal scores are broken by `(file_path, line_start, line_end)` ascending, so the
/// output is a function of the inputs alone and does not vary between processes.
pub fn fuse_rrf_multi_weighted(
    result_sets: &[&[SearchResult]],
    weights: &[f64],
    rrf_k: f64,
    limit: usize,
) -> Vec<SearchResult> {
    let mut fused: HashMap<String, (f64, SearchResult)> = HashMap::new();

    for (set_idx, result_set) in result_sets.iter().enumerate() {
        let weight = weights.get(set_idx).copied().unwrap_or(1.0);
        for (rank_0, result) in result_set.iter().enumerate() {
            let key = result_key(result);
            let rrf_score = weight / (rrf_k + (rank_0 + 1) as f64);

            fused
                .entry(key)
                .and_modify(|(score, _)| *score += rrf_score)
                .or_insert_with(|| (rrf_score, result.clone()));
        }
    }

    let mut ranked: Vec<(f64, SearchResult)> = fused.into_values().collect();
    // Ties are structural, not incidental: with equal source weights a result found only
    // in set A at rank r and one found only in set B at rank r score bit-identically.
    // `into_values` yields a per-process-random order, so a score-only sort would make the
    // output depend on the HashMap seed rather than on the index. Break ties on the same
    // (file_path, line_start, line_end) triple that keys the map, which is distinct for
    // every surviving entry and therefore a total order.
    ranked.sort_by(|a, b| {
        b.0.partial_cmp(&a.0)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| {
                (&a.1.file_path, a.1.line_start, a.1.line_end).cmp(&(
                    &b.1.file_path,
                    b.1.line_start,
                    b.1.line_end,
                ))
            })
    });

    ranked
        .into_iter()
        .take(limit)
        .map(|(rrf_score, mut result)| {
            result.score = rrf_score;
            result
        })
        .collect()
}

/// Charge the one wall-clock span that covers the vector arm to the two stages
/// `--timing` reports.
///
/// The query embedding runs inside the vector search, so both stages come out
/// of `vector_span`. `embedding` gets the model cost and `vector` gets the
/// remainder, which is the storage cost: opening both stores, the KNN query and
/// metadata hydration. A vector search that failed has no embedding measurement
/// to report, so the whole span stays on `vector`.
///
/// The two must partition the span rather than each be given all of it, which
/// is what issue #105 was: the same value reported twice made either stage
/// unattributable. Both fields are written here rather than at the call site so
/// that partition is decided in one place a test can reach: a caller that only
/// received the two values could still charge the span twice.
fn charge_vector_span(
    timings: &mut HybridTimings,
    vector_span: Duration,
    embed_elapsed: Option<Duration>,
) {
    timings.embedding = embed_elapsed;
    timings.vector = Some(vector_span.saturating_sub(embed_elapsed.unwrap_or_default()));
}

#[cfg(test)]
#[path = "hybrid_tests.rs"]
mod tests;

#[cfg(test)]
mod shortfall_tests {
    use super::*;
    use crate::types::Language;

    fn result(index: usize) -> SearchResult {
        SearchResult {
            file_path: format!("candidate-{index}.rs"),
            line_start: 1,
            line_end: 1,
            content: format!("candidate {index}"),
            language: Language::Rust,
            score: 1.0 - index as f64 / 100.0,
            symbol_name: None,
            symbol_type: None,
        }
    }

    #[test]
    fn reranker_shortfall_appends_missing_candidates_in_hybrid_order() {
        let hybrid_results: Vec<_> = (0..20).map(result).collect();
        let scored_indices = (0..7).chain(13..20);
        let reranked = scored_indices
            .enumerate()
            .map(|(rank, index)| {
                let mut result = hybrid_results[index].clone();
                result.score = 100.0 - rank as f64;
                result
            })
            .collect();

        let merged = merge_reranked_results(reranked, hybrid_results, 20, 20);

        assert_eq!(merged.len(), 20);
        let missing_tail: Vec<_> = merged[14..]
            .iter()
            .map(|result| result.content.as_str())
            .collect();
        assert_eq!(
            missing_tail,
            vec![
                "candidate 7",
                "candidate 8",
                "candidate 9",
                "candidate 10",
                "candidate 11",
                "candidate 12",
            ]
        );
    }
}