khive-retrieval 0.2.3

Hybrid retrieval composer (HNSW + BM25 + fusion + graph + cross-encoder) with deterministic scoring
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
//! Adapters bridging `khive-storage-traits` backends to retrieval search traits.
//!
//! The retrieval crate defines [`VectorSearch`] and [`KeywordSearch`] as async
//! traits with an associated `Id` type. The `khive-storage-traits` crate defines
//! [`VectorStore`] and [`TextSearch`] as async persistence traits using `Uuid`.
//!
//! This module provides adapter types that implement the retrieval search traits
//! by delegating to storage-traits backends:
//!
//! - [`StorageVectorSearch`]: wraps `Arc<dyn VectorStore>` -> `VectorSearch<Id = Uuid>`
//! - [`StorageKeywordSearch`]: wraps `Arc<dyn TextSearch>` -> `KeywordSearch<Id = Uuid>`
//!
//! This makes [`HybridSearcher`] work with persistent backends (sqlite-vec, FTS5)
//! alongside the existing in-memory backends (HNSW, BM25).
//!
//! # Example
//!
//! ```rust,ignore
//! use khive_db::StorageBackend;
//! use khive_retrieval::adapters::{StorageVectorSearch, StorageKeywordSearch};
//! use khive_retrieval::hybrid::{VectorSearch, KeywordSearch};
//!
//! let backend = StorageBackend::memory().unwrap();
//! let vec_store = backend.vectors("model", 384).unwrap();
//! let text_store = backend.text("docs").unwrap();
//!
//! let vector_search = StorageVectorSearch::new(vec_store);
//! let keyword_search = StorageKeywordSearch::new(text_store);
//!
//! // Both implement the retrieval search traits with Id = Uuid
//! let hits = vector_search.vector_search(&query_embedding, 10).await?;
//! let kw_hits = keyword_search.keyword_search("some query", 10).await?;
//! ```

use std::sync::Arc;

use async_trait::async_trait;
use khive_score::DeterministicScore;
use khive_storage::types::{TextQueryMode, TextSearchRequest, VectorSearchRequest};
use khive_storage::{TextSearch, VectorStore};
use uuid::Uuid;

use crate::error::{Result, RetrievalError};
use crate::hybrid::{KeywordSearch, VectorSearch};

// ---------------------------------------------------------------------------
// Error conversion
// ---------------------------------------------------------------------------

/// Convert a `StorageError` into a `RetrievalError`.
///
/// Maps storage-level errors to the closest retrieval error variant:
/// - Vector-related storage errors -> `Hnsw` (vector search context)
/// - Text-related storage errors -> `Bm25` (keyword search context)
/// - Timeout/pool errors -> transient retrieval errors
/// - Everything else -> generic error string
fn storage_err_to_retrieval(
    err: khive_storage::StorageError,
    context: &'static str,
) -> RetrievalError {
    use khive_storage::StorageError;

    match &err {
        StorageError::Timeout { .. } => {
            // Map to a transient retrieval error
            RetrievalError::Hnsw(format!("{context}: {err}"))
        }
        StorageError::InvalidInput { message, .. } => {
            RetrievalError::InvalidQuery(format!("{context}: {message}"))
        }
        _ => {
            // Generic mapping -- preserve the full error message
            RetrievalError::Hnsw(format!("{context}: {err}"))
        }
    }
}

// ---------------------------------------------------------------------------
// StorageVectorSearch
// ---------------------------------------------------------------------------

/// Adapter implementing [`VectorSearch`] by delegating to a [`VectorStore`].
///
/// Wraps an `Arc<dyn VectorStore>` (e.g., `SqliteVecStore`) and implements
/// the retrieval `VectorSearch` trait with `Id = Uuid`.
///
/// The adapter is `Send + Sync` and can be shared across tasks.
pub struct StorageVectorSearch {
    store: Arc<dyn VectorStore>,
}

impl StorageVectorSearch {
    /// Create a new adapter wrapping the given vector store.
    pub fn new(store: Arc<dyn VectorStore>) -> Self {
        Self { store }
    }
}

#[async_trait]
impl VectorSearch for StorageVectorSearch {
    type Id = Uuid;

    async fn vector_search(
        &self,
        embedding: &[f32],
        top_k: usize,
    ) -> Result<Vec<(Uuid, DeterministicScore)>> {
        let request = VectorSearchRequest {
            query_vectors: vec![embedding.to_vec()],
            top_k: top_k as u32,
            namespace: None,
            kind: None,
            embedding_model: None,
            filter: None,
            backend_hints: None,
        };

        let hits = self
            .store
            .search(request)
            .await
            .map_err(|e| storage_err_to_retrieval(e, "vector search"))?;

        Ok(hits
            .into_iter()
            .map(|hit| (hit.subject_id, hit.score))
            .collect())
    }
}

// ---------------------------------------------------------------------------
// StorageKeywordSearch
// ---------------------------------------------------------------------------

/// Adapter implementing [`KeywordSearch`] by delegating to a [`TextSearch`].
///
/// Wraps an `Arc<dyn TextSearch>` (e.g., `Fts5TextSearch`) and implements
/// the retrieval `KeywordSearch` trait with `Id = Uuid`.
///
/// Uses `TextQueryMode::Plain` for keyword queries by default. The snippet
/// length is set to 0 since retrieval only needs IDs and scores.
pub struct StorageKeywordSearch {
    search: Arc<dyn TextSearch>,
}

impl StorageKeywordSearch {
    /// Create a new adapter wrapping the given text search backend.
    pub fn new(search: Arc<dyn TextSearch>) -> Self {
        Self { search }
    }
}

#[async_trait]
impl KeywordSearch for StorageKeywordSearch {
    type Id = Uuid;

    async fn keyword_search(
        &self,
        text: &str,
        top_k: usize,
    ) -> Result<Vec<(Uuid, DeterministicScore)>> {
        let request = TextSearchRequest {
            query: text.to_string(),
            mode: TextQueryMode::Plain,
            filter: None,
            top_k: top_k as u32,
            snippet_chars: 0, // retrieval only needs IDs + scores
        };

        let hits = self
            .search
            .search(request)
            .await
            .map_err(|e| storage_err_to_retrieval(e, "keyword search"))?;

        Ok(hits
            .into_iter()
            .map(|hit| (hit.subject_id, hit.score))
            .collect())
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use khive_db::StorageBackend;
    use khive_storage::types::TextDocument;
    use khive_types::SubstrateKind;

    /// Helper: create a memory-backed StorageBackend.
    fn test_backend() -> StorageBackend {
        StorageBackend::memory().expect("memory backend")
    }

    // -----------------------------------------------------------------------
    // StorageVectorSearch tests
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn vector_search_basic_roundtrip() {
        let backend = test_backend();
        let store = backend.vectors("test_vs", 3).unwrap();

        // Insert two vectors
        let id1 = Uuid::new_v4();
        let id2 = Uuid::new_v4();
        store
            .insert(
                id1,
                SubstrateKind::Entity,
                "local",
                "content",
                vec![vec![1.0, 0.0, 0.0]],
            )
            .await
            .unwrap();
        store
            .insert(
                id2,
                SubstrateKind::Entity,
                "local",
                "content",
                vec![vec![0.0, 1.0, 0.0]],
            )
            .await
            .unwrap();

        // Wrap in adapter and use VectorSearch trait
        let adapter = StorageVectorSearch::new(store);
        let hits = adapter.vector_search(&[1.0, 0.0, 0.0], 2).await.unwrap();

        assert_eq!(hits.len(), 2);
        // Closest to [1,0,0] should be id1
        assert_eq!(hits[0].0, id1);
        // Score should be high (cosine similarity ~1.0)
        assert!(hits[0].1.to_f64() > 0.9);
    }

    #[tokio::test]
    async fn vector_search_respects_top_k() {
        let backend = test_backend();
        let store = backend.vectors("test_topk", 3).unwrap();

        // Insert 5 vectors
        for _ in 0..5 {
            store
                .insert(
                    Uuid::new_v4(),
                    SubstrateKind::Entity,
                    "local",
                    "content",
                    vec![vec![1.0, 0.0, 0.0]],
                )
                .await
                .unwrap();
        }

        let adapter = StorageVectorSearch::new(store);
        let hits = adapter.vector_search(&[1.0, 0.0, 0.0], 3).await.unwrap();

        assert_eq!(hits.len(), 3);
    }

    #[tokio::test]
    async fn vector_search_empty_store() {
        let backend = test_backend();
        let store = backend.vectors("test_empty", 3).unwrap();

        let adapter = StorageVectorSearch::new(store);
        let hits = adapter.vector_search(&[1.0, 0.0, 0.0], 5).await.unwrap();

        assert!(hits.is_empty());
    }

    #[tokio::test]
    async fn vector_search_returns_deterministic_scores() {
        let backend = test_backend();
        let store = backend.vectors("test_det", 3).unwrap();

        let id = Uuid::new_v4();
        store
            .insert(
                id,
                SubstrateKind::Entity,
                "local",
                "content",
                vec![vec![1.0, 0.0, 0.0]],
            )
            .await
            .unwrap();

        let adapter = StorageVectorSearch::new(store);

        // Run twice -- scores must be identical (deterministic)
        let hits1 = adapter.vector_search(&[1.0, 0.0, 0.0], 1).await.unwrap();
        let hits2 = adapter.vector_search(&[1.0, 0.0, 0.0], 1).await.unwrap();

        assert_eq!(hits1[0].1, hits2[0].1);
    }

    // -----------------------------------------------------------------------
    // StorageKeywordSearch tests
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn keyword_search_basic_roundtrip() {
        let backend = test_backend();
        let store = backend.text("test_ks").unwrap();

        let id1 = Uuid::new_v4();
        let id2 = Uuid::new_v4();

        store
            .upsert_document(TextDocument {
                subject_id: id1,
                kind: SubstrateKind::Entity,
                namespace: "test".to_string(),
                title: Some("Rust Programming".to_string()),
                body: "Rust is a systems programming language.".to_string(),
                tags: vec![],
                metadata: None,
                updated_at: chrono::Utc::now(),
            })
            .await
            .unwrap();

        store
            .upsert_document(TextDocument {
                subject_id: id2,
                kind: SubstrateKind::Entity,
                namespace: "test".to_string(),
                title: Some("Python Guide".to_string()),
                body: "Python is a high-level programming language.".to_string(),
                tags: vec![],
                metadata: None,
                updated_at: chrono::Utc::now(),
            })
            .await
            .unwrap();

        // Wrap in adapter and use KeywordSearch trait
        let adapter = StorageKeywordSearch::new(store);
        let hits = adapter.keyword_search("Rust", 10).await.unwrap();

        // Should find the Rust document
        assert!(!hits.is_empty());
        assert_eq!(hits[0].0, id1);
        assert!(hits[0].1.to_f64() > 0.0);
    }

    #[tokio::test]
    async fn keyword_search_respects_top_k() {
        let backend = test_backend();
        let store = backend.text("test_ks_topk").unwrap();

        // Insert 5 documents all containing "programming"
        for i in 0..5 {
            store
                .upsert_document(TextDocument {
                    subject_id: Uuid::new_v4(),
                    kind: SubstrateKind::Note,
                    namespace: "test".to_string(),
                    title: Some(format!("Doc {}", i)),
                    body: format!("Programming topic number {}.", i),
                    tags: vec![],
                    metadata: None,
                    updated_at: chrono::Utc::now(),
                })
                .await
                .unwrap();
        }

        let adapter = StorageKeywordSearch::new(store);
        let hits = adapter.keyword_search("programming", 3).await.unwrap();

        assert!(hits.len() <= 3);
    }

    #[tokio::test]
    async fn keyword_search_empty_store() {
        let backend = test_backend();
        let store = backend.text("test_ks_empty").unwrap();

        let adapter = StorageKeywordSearch::new(store);
        let hits = adapter.keyword_search("anything", 5).await.unwrap();

        assert!(hits.is_empty());
    }

    #[tokio::test]
    async fn keyword_search_no_match() {
        let backend = test_backend();
        let store = backend.text("test_ks_nomatch").unwrap();

        store
            .upsert_document(TextDocument {
                subject_id: Uuid::new_v4(),
                kind: SubstrateKind::Entity,
                namespace: "test".to_string(),
                title: Some("Alpha".to_string()),
                body: "Alpha article content.".to_string(),
                tags: vec![],
                metadata: None,
                updated_at: chrono::Utc::now(),
            })
            .await
            .unwrap();

        let adapter = StorageKeywordSearch::new(store);
        let hits = adapter
            .keyword_search("nonexistent_xyz_term", 5)
            .await
            .unwrap();

        assert!(hits.is_empty());
    }

    // -----------------------------------------------------------------------
    // Integration: both adapters with fusion
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn adapters_produce_fusible_results() {
        use crate::hybrid::{fuse_search_results, HybridConfig};

        let backend = test_backend();
        let vec_store = backend.vectors("test_fuse", 3).unwrap();
        let text_store = backend.text("test_fuse").unwrap();

        let id = Uuid::new_v4();

        // Insert into both stores
        vec_store
            .insert(
                id,
                SubstrateKind::Note,
                "local",
                "content",
                vec![vec![1.0, 0.0, 0.0]],
            )
            .await
            .unwrap();
        text_store
            .upsert_document(TextDocument {
                subject_id: id,
                kind: SubstrateKind::Note,
                namespace: "test".to_string(),
                title: Some("Test".to_string()),
                body: "Test document for fusion.".to_string(),
                tags: vec![],
                metadata: None,
                updated_at: chrono::Utc::now(),
            })
            .await
            .unwrap();

        let vec_adapter = StorageVectorSearch::new(vec_store);
        let kw_adapter = StorageKeywordSearch::new(text_store);

        let vec_hits = vec_adapter
            .vector_search(&[1.0, 0.0, 0.0], 5)
            .await
            .unwrap();
        let kw_hits = kw_adapter.keyword_search("Test", 5).await.unwrap();

        // Both should return the same UUID
        assert!(!vec_hits.is_empty());
        assert!(!kw_hits.is_empty());
        assert_eq!(vec_hits[0].0, id);
        assert_eq!(kw_hits[0].0, id);

        // Fuse the results -- same Id type (Uuid) means fusion works
        let config = HybridConfig::new(10);
        let fused = fuse_search_results(vec![vec_hits, kw_hits], &config);

        assert!(!fused.is_empty());
        // The single shared UUID should appear in fused results
        assert_eq!(fused[0].0, id);
    }
}