Skip to main content

lc_vector_stores/
hybrid_native.rs

1// lc-vector-stores/src/hybrid_native.rs
2//! Engine-native hybrid search (0.21.0 S4.3).
3//!
4//! 2026 direction: hybrid fusion (RRF / DBSF) executed **inside the vector
5//! engine** — one round trip, no client-side merge. Qdrant's Query API
6//! (≥ 1.10) fuses multiple `prefetch` branches server-side. Engines without
7//! the capability keep using the universal client-side fallback
8//! (`lc_rag::UnifiedHybridIndex` / `reciprocal_rank_fusion`).
9//!
10//! Capability is declared per store type via [`NativeHybridSearch`]. The
11//! qdrant-client crate (1.18) speaks the Query API, so the request-shape
12//! contract is enforced by the typed builder; result mapping is unit-tested
13//! against constructed `ScoredPoint`s, and the end-to-end path has an
14//! `#[ignore]`d integration test for environments with a live server.
15
16use crate::{MetadataFilter, SearchResult, VectorStoreError};
17use async_trait::async_trait;
18
19/// Server-side fusion method.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum FusionMethod {
22    /// Reciprocal Rank Fusion (default parameters, server-side).
23    Rrf,
24    /// Distribution-Based Score Fusion.
25    Dbsf,
26}
27
28impl From<FusionMethod> for qdrant_client::qdrant::Fusion {
29    fn from(method: FusionMethod) -> Self {
30        match method {
31            FusionMethod::Rrf => qdrant_client::qdrant::Fusion::Rrf,
32            FusionMethod::Dbsf => qdrant_client::qdrant::Fusion::Dbsf,
33        }
34    }
35}
36
37/// Native hybrid query: multiple dense query branches fused by the engine.
38#[derive(Debug, Clone)]
39pub struct NativeHybridQuery {
40    /// One query vector per branch (e.g. dense + a second retriever view).
41    /// At least two branches are required — a single branch has nothing to fuse.
42    pub query_vectors: Vec<Vec<f32>>,
43    /// Final result count.
44    pub limit: usize,
45    /// Per-branch candidate limit (defaults to `limit * 2`, min 10).
46    pub prefetch_limit: Option<usize>,
47    /// Fusion method (default RRF).
48    pub fusion: FusionMethod,
49    /// Optional payload filter applied to every branch.
50    pub filter: Option<MetadataFilter>,
51}
52
53impl NativeHybridQuery {
54    /// Creates a query from ≥ 2 branches with defaults (RRF).
55    pub fn new(query_vectors: Vec<Vec<f32>>, limit: usize) -> Result<Self, VectorStoreError> {
56        if query_vectors.len() < 2 {
57            return Err(VectorStoreError::ConfigError(format!(
58                "native hybrid fusion requires at least 2 query branches, got {}",
59                query_vectors.len()
60            )));
61        }
62        let dim = query_vectors[0].len();
63        if query_vectors.iter().any(|v| v.len() != dim) {
64            return Err(VectorStoreError::ConfigError(
65                "native hybrid branches must share one vector dimension".to_string(),
66            ));
67        }
68        Ok(Self {
69            query_vectors,
70            limit,
71            prefetch_limit: None,
72            fusion: FusionMethod::Rrf,
73            filter: None,
74        })
75    }
76
77    /// Sets the per-branch prefetch limit.
78    pub fn with_prefetch_limit(mut self, prefetch_limit: usize) -> Self {
79        self.prefetch_limit = Some(prefetch_limit);
80        self
81    }
82
83    /// Sets the fusion method.
84    pub fn with_fusion(mut self, fusion: FusionMethod) -> Self {
85        self.fusion = fusion;
86        self
87    }
88
89    /// Effective per-branch prefetch limit.
90    pub fn effective_prefetch_limit(&self) -> u64 {
91        self.prefetch_limit.unwrap_or((self.limit * 2).max(10)) as u64
92    }
93}
94
95/// Capability trait: engine-native hybrid fusion.
96///
97/// Default implementation reports "not supported" so existing store types are
98/// opt-in by construction. Callers check
99/// [`NativeHybridSearch::supports_native_hybrid`] before issuing a query; a
100/// mismatch returns a config error instead of a silent client fallback.
101/// The Qdrant implementation lives in [`crate::qdrant`] (fields/methods are
102/// crate-visible there).
103#[async_trait]
104pub trait NativeHybridSearch: Send + Sync {
105    /// Whether this store can fuse hybrid branches server-side.
106    fn supports_native_hybrid(&self) -> bool {
107        false
108    }
109
110    /// Runs the engine-native fusion query.
111    async fn native_hybrid_search(
112        &self,
113        query: &NativeHybridQuery,
114    ) -> Result<Vec<SearchResult>, VectorStoreError> {
115        let _ = query;
116        Err(VectorStoreError::ConfigError(
117            "this vector store does not support engine-native hybrid fusion; \
118             use the client-side RRF fallback (lc_rag::UnifiedHybridIndex)"
119                .to_string(),
120        ))
121    }
122}
123
124/// Test fixture shared across the crate's test modules: a `ScoredPoint` with
125/// the payload conventions the mapping relies on.
126#[cfg(test)]
127pub(crate) mod fixtures {
128    use qdrant_client::qdrant::{PointId, ScoredPoint};
129    use std::collections::HashMap;
130
131    pub(crate) fn scored_point(id: u64, score: f32, content: &str, source: &str) -> ScoredPoint {
132        let mut payload = HashMap::new();
133        payload.insert(
134            "content".to_string(),
135            qdrant_client::qdrant::Value::from(content),
136        );
137        payload.insert(
138            "source".to_string(),
139            qdrant_client::qdrant::Value::from(source),
140        );
141        ScoredPoint {
142            id: Some(PointId::from(id.to_string())),
143            score,
144            payload,
145            ..Default::default()
146        }
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153    use crate::hybrid_native::fixtures::scored_point;
154
155    /// Mapping follows the same payload conventions as plain search:
156    /// `content` → document content, `doc_id` → id, other string fields → metadata.
157    #[test]
158    fn scored_point_maps_to_search_result() {
159        let result =
160            crate::qdrant::scored_point_to_result(scored_point(1, 0.98, "rust doc", "docs"));
161        assert_eq!(result.document.content, "rust doc");
162        assert_eq!(result.document.id, None, "no doc_id payload → no id");
163        assert_eq!(result.score, 0.98);
164        assert_eq!(
165            result
166                .document
167                .metadata
168                .get("source")
169                .and_then(|v| v.as_str()),
170            Some("docs")
171        );
172        assert!(
173            !result.document.metadata.contains_key("content"),
174            "content is not duplicated into metadata"
175        );
176    }
177
178    /// `doc_id` payload becomes the document id.
179    #[test]
180    fn doc_id_payload_becomes_document_id() {
181        let mut point = scored_point(2, 0.9, "hello", "docs");
182        point.payload.insert(
183            "doc_id".to_string(),
184            qdrant_client::qdrant::Value::from("doc-42"),
185        );
186        let result = crate::qdrant::scored_point_to_result(point);
187        assert_eq!(result.document.id.as_deref(), Some("doc-42"));
188    }
189
190    #[test]
191    fn fusion_maps_to_proto() {
192        assert_eq!(
193            qdrant_client::qdrant::Fusion::from(FusionMethod::Rrf),
194            qdrant_client::qdrant::Fusion::Rrf
195        );
196        assert_eq!(
197            qdrant_client::qdrant::Fusion::from(FusionMethod::Dbsf),
198            qdrant_client::qdrant::Fusion::Dbsf
199        );
200    }
201
202    /// Query validation: ≥ 2 branches, single shared dimension.
203    #[test]
204    fn query_validates_branches() {
205        assert!(
206            NativeHybridQuery::new(vec![vec![1.0]], 5).is_err(),
207            "1 branch"
208        );
209        assert!(
210            NativeHybridQuery::new(vec![vec![1.0, 0.0], vec![1.0, 0.0, 0.0]], 5).is_err(),
211            "mixed dimensions"
212        );
213        let ok = NativeHybridQuery::new(vec![vec![1.0, 0.0], vec![0.0, 1.0]], 5).unwrap();
214        assert_eq!(ok.limit, 5);
215        assert_eq!(ok.fusion, FusionMethod::Rrf, "default fusion");
216    }
217
218    /// Prefetch limit defaults to `max(limit * 2, 10)`.
219    #[test]
220    fn prefetch_limit_defaults() {
221        let small = NativeHybridQuery::new(vec![vec![1.0], vec![0.0]], 3).unwrap();
222        assert_eq!(small.effective_prefetch_limit(), 10, "floor applies");
223        let large = NativeHybridQuery::new(vec![vec![1.0], vec![0.0]], 20).unwrap();
224        assert_eq!(large.effective_prefetch_limit(), 40, "limit * 2");
225        let explicit = NativeHybridQuery::new(vec![vec![1.0], vec![0.0]], 20)
226            .unwrap()
227            .with_prefetch_limit(7);
228        assert_eq!(explicit.effective_prefetch_limit(), 7);
229    }
230
231    /// Default capability: stores that do not implement the capability report
232    /// false and return an explicit config error (never a silent fallback).
233    #[tokio::test]
234    async fn default_capability_is_unsupported() {
235        struct Noop;
236        #[async_trait]
237        impl NativeHybridSearch for Noop {}
238        assert!(!Noop.supports_native_hybrid());
239        let query = NativeHybridQuery::new(vec![vec![1.0], vec![0.0]], 5).unwrap();
240        let err = Noop.native_hybrid_search(&query).await.unwrap_err();
241        assert!(
242            err.to_string().contains("client-side RRF fallback"),
243            "error must point to the fallback: {err}"
244        );
245    }
246}