khive-storage 0.4.0

Storage capability traits: SqlAccess, VectorStore, TextSearch. Zero implementations — only contracts.
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
//! Integration tests for VectorStore default-method behavior.
//!
//! These tests were moved from `src/vectors.rs` (inline section was 420 lines,
//! exceeding the 300-line gate in the coding standards).

use std::sync::atomic::{AtomicBool, Ordering};

use async_trait::async_trait;
use uuid::Uuid;

use khive_score::DeterministicScore;
use khive_storage::types::{
    BatchWriteSummary, IndexRebuildScope, OrphanSweepConfig, VectorIndexKind, VectorMetadataFilter,
    VectorSearchHit, VectorSearchRequest, VectorStoreInfo,
};
use khive_storage::{StorageError, VectorStore};
use khive_types::SubstrateKind;

use khive_storage::capability::StorageCapability;
use khive_storage::types::{PropertyFilter, PropertyOp, StorageResult, VectorRecord};

// ---------------------------------------------------------------------------
// Minimal test fake
// ---------------------------------------------------------------------------

struct TestVectorStore {
    /// When `true`, `delete` returns an error.
    fail_delete: AtomicBool,
    /// When `true`, `insert` returns an error.
    fail_insert: AtomicBool,
    /// Tracks whether `delete` was called (set by the last `delete` call).
    delete_called: AtomicBool,
    /// Tracks whether `insert` was called (set by the last `insert` call).
    insert_called: AtomicBool,
}

impl TestVectorStore {
    fn new() -> Self {
        Self {
            fail_delete: AtomicBool::new(false),
            fail_insert: AtomicBool::new(false),
            delete_called: AtomicBool::new(false),
            insert_called: AtomicBool::new(false),
        }
    }

    fn with_fail_delete() -> Self {
        let s = Self::new();
        s.fail_delete.store(true, Ordering::SeqCst);
        s
    }

    fn with_fail_insert() -> Self {
        let s = Self::new();
        s.fail_insert.store(true, Ordering::SeqCst);
        s
    }
}

#[async_trait]
impl VectorStore for TestVectorStore {
    async fn insert(
        &self,
        _subject_id: Uuid,
        _kind: SubstrateKind,
        _namespace: &str,
        _field: &str,
        _vectors: Vec<Vec<f32>>,
    ) -> StorageResult<()> {
        self.insert_called.store(true, Ordering::SeqCst);
        if self.fail_insert.load(Ordering::SeqCst) {
            return Err(StorageError::InvalidInput {
                capability: StorageCapability::Vectors,
                operation: "insert".into(),
                message: "injected insert failure".into(),
            });
        }
        Ok(())
    }

    async fn insert_batch(&self, records: Vec<VectorRecord>) -> StorageResult<BatchWriteSummary> {
        Ok(BatchWriteSummary {
            attempted: records.len() as u64,
            affected: records.len() as u64,
            failed: 0,
            first_error: String::new(),
        })
    }

    async fn delete(&self, _subject_id: Uuid) -> StorageResult<bool> {
        self.delete_called.store(true, Ordering::SeqCst);
        if self.fail_delete.load(Ordering::SeqCst) {
            return Err(StorageError::InvalidInput {
                capability: StorageCapability::Vectors,
                operation: "delete".into(),
                message: "injected delete failure".into(),
            });
        }
        Ok(true)
    }

    async fn count(&self) -> StorageResult<u64> {
        Ok(0)
    }

    async fn search(&self, _request: VectorSearchRequest) -> StorageResult<Vec<VectorSearchHit>> {
        Ok(vec![VectorSearchHit {
            subject_id: Uuid::nil(),
            score: DeterministicScore::from_f64(0.9),
            rank: 1,
        }])
    }

    async fn info(&self) -> StorageResult<VectorStoreInfo> {
        Ok(VectorStoreInfo {
            model_name: "test".into(),
            dimensions: 4,
            index_kind: VectorIndexKind::SqliteVec,
            entry_count: 0,
            needs_rebuild: false,
            last_rebuild_at: None,
        })
    }

    async fn rebuild(&self, _scope: IndexRebuildScope) -> StorageResult<VectorStoreInfo> {
        self.info().await
    }
}

// ---------------------------------------------------------------------------
// Test cases — capabilities
// ---------------------------------------------------------------------------

/// STORAGE-AUD-001 / #485: the backend-neutral trait default must not
/// advertise sqlite-vec-specific capabilities. A minimal `VectorStore` that
/// does not override `capabilities()` must report an unknown dimension
/// ceiling and no advertised index kind.
#[tokio::test]
async fn capabilities_default_is_neutral() {
    let store = TestVectorStore::new();
    let caps = store.capabilities();
    assert!(!caps.supports_filter);
    assert!(!caps.supports_batch_search);
    assert!(!caps.supports_quantization);
    assert!(!caps.supports_update);
    assert!(!caps.supports_orphan_sweep);
    assert_eq!(
        caps.max_dimensions, None,
        "backend-neutral default must not advertise a dimension ceiling"
    );
    assert!(
        caps.index_kinds.is_empty(),
        "backend-neutral default must not advertise an index kind"
    );
}

// ---------------------------------------------------------------------------
// Test cases — search_with_filter
// ---------------------------------------------------------------------------

#[tokio::test]
async fn search_with_filter_empty_filter_delegates_to_search() {
    let store = TestVectorStore::new();
    let req = VectorSearchRequest {
        query_vectors: vec![vec![0.1, 0.2, 0.3, 0.4]],
        top_k: 5,
        namespace: None,
        kind: None,
        embedding_model: None,
        filter: None,
        backend_hints: None,
    };
    let filter = VectorMetadataFilter::default(); // all fields empty
    let result = store.search_with_filter(&req, &filter).await;
    assert!(result.is_ok());
    let hits = result.unwrap();
    // search() on TestVectorStore returns exactly one hit
    assert_eq!(hits.len(), 1);
}

#[tokio::test]
async fn search_with_filter_non_empty_filter_returns_unsupported() {
    let store = TestVectorStore::new();
    let req = VectorSearchRequest {
        query_vectors: vec![vec![0.1, 0.2, 0.3, 0.4]],
        top_k: 5,
        namespace: None,
        kind: None,
        embedding_model: None,
        filter: None,
        backend_hints: None,
    };
    let filter = VectorMetadataFilter {
        namespaces: vec!["ns:agent".into()],
        kinds: vec![],
        property_filters: vec![],
    };
    let result = store.search_with_filter(&req, &filter).await;
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        matches!(err, StorageError::Unsupported { .. }),
        "expected Unsupported, got {err:?}"
    );
}

// ---------------------------------------------------------------------------
// Test cases — search_batch
// ---------------------------------------------------------------------------

#[tokio::test]
async fn search_batch_returns_one_result_per_request() {
    let store = TestVectorStore::new();
    let requests = vec![
        VectorSearchRequest {
            query_vectors: vec![vec![0.1, 0.2, 0.3, 0.4]],
            top_k: 3,
            namespace: None,
            kind: None,
            embedding_model: None,
            filter: None,
            backend_hints: None,
        },
        VectorSearchRequest {
            query_vectors: vec![vec![0.5, 0.6, 0.7, 0.8]],
            top_k: 3,
            namespace: None,
            kind: None,
            embedding_model: None,
            filter: None,
            backend_hints: None,
        },
    ];
    let result = store.search_batch(&requests).await;
    assert!(result.is_ok());
    let batched = result.unwrap();
    assert_eq!(batched.len(), 2, "should return one result set per request");
    for inner in &batched {
        assert!(inner.is_ok(), "each inner result should be Ok");
        assert_eq!(
            inner.as_ref().unwrap().len(),
            1,
            "each Ok should have one hit"
        );
    }
}

#[tokio::test]
async fn search_batch_isolates_per_query_errors() {
    // A store that always fails search — the outer Ok must still be returned,
    // and the failed inner result must carry the error.
    struct FailingSearch;

    #[async_trait]
    impl VectorStore for FailingSearch {
        async fn insert(
            &self,
            _: Uuid,
            _: SubstrateKind,
            _: &str,
            _: &str,
            _: Vec<Vec<f32>>,
        ) -> StorageResult<()> {
            Ok(())
        }
        async fn insert_batch(&self, _: Vec<VectorRecord>) -> StorageResult<BatchWriteSummary> {
            Ok(BatchWriteSummary::default())
        }
        async fn delete(&self, _: Uuid) -> StorageResult<bool> {
            Ok(false)
        }
        async fn count(&self) -> StorageResult<u64> {
            Ok(0)
        }
        async fn search(&self, _: VectorSearchRequest) -> StorageResult<Vec<VectorSearchHit>> {
            Err(StorageError::InvalidInput {
                capability: StorageCapability::Vectors,
                operation: "search".into(),
                message: "injected search failure".into(),
            })
        }
        async fn info(&self) -> StorageResult<VectorStoreInfo> {
            Ok(VectorStoreInfo {
                model_name: "fail".into(),
                dimensions: 4,
                index_kind: VectorIndexKind::SqliteVec,
                entry_count: 0,
                needs_rebuild: false,
                last_rebuild_at: None,
            })
        }
        async fn rebuild(&self, _: IndexRebuildScope) -> StorageResult<VectorStoreInfo> {
            self.info().await
        }
    }

    let store = FailingSearch;
    let requests = vec![VectorSearchRequest {
        query_vectors: vec![vec![0.1]],
        top_k: 1,
        namespace: None,
        kind: None,
        embedding_model: None,
        filter: None,
        backend_hints: None,
    }];
    // Outer result is Ok; the error is in the inner vec.
    let result = store.search_batch(&requests).await;
    assert!(result.is_ok(), "outer result must be Ok for batch");
    let batched = result.unwrap();
    assert_eq!(batched.len(), 1);
    assert!(batched[0].is_err(), "inner result must carry the error");
}

// ---------------------------------------------------------------------------
// Test cases — orphan_sweep
// ---------------------------------------------------------------------------

#[tokio::test]
async fn orphan_sweep_default_returns_unsupported() {
    let store = TestVectorStore::new();
    let config = OrphanSweepConfig {
        subject_id_allowlist: None,
        namespaces: vec![],
        substrate_kinds: vec![],
        max_delete: 100,
        dry_run: true,
    };
    let result = store.orphan_sweep(&config).await;
    assert!(
        matches!(result, Err(StorageError::Unsupported { .. })),
        "expected Unsupported, got {result:?}"
    );
    assert!(!store.capabilities().supports_orphan_sweep);
}

// ---------------------------------------------------------------------------
// Test cases — update
// ---------------------------------------------------------------------------

#[tokio::test]
async fn update_calls_delete_then_insert() {
    let store = TestVectorStore::new();
    let id = Uuid::new_v4();
    let result = store
        .update(
            id,
            SubstrateKind::Entity,
            "ns:test",
            "body",
            vec![vec![0.1, 0.2]],
        )
        .await;
    assert!(result.is_ok());
    assert!(
        store.delete_called.load(Ordering::SeqCst),
        "delete must be called"
    );
    assert!(
        store.insert_called.load(Ordering::SeqCst),
        "insert must be called after delete"
    );
}

#[tokio::test]
async fn update_propagates_delete_failure() {
    let store = TestVectorStore::with_fail_delete();
    let id = Uuid::new_v4();
    let result = store
        .update(
            id,
            SubstrateKind::Entity,
            "ns:test",
            "body",
            vec![vec![0.1, 0.2]],
        )
        .await;
    assert!(result.is_err());
    assert!(
        store.delete_called.load(Ordering::SeqCst),
        "delete must be attempted"
    );
    assert!(
        !store.insert_called.load(Ordering::SeqCst),
        "insert must NOT be called when delete fails"
    );
}

#[tokio::test]
async fn update_propagates_insert_failure() {
    let store = TestVectorStore::with_fail_insert();
    let id = Uuid::new_v4();
    let result = store
        .update(
            id,
            SubstrateKind::Entity,
            "ns:test",
            "body",
            vec![vec![0.1, 0.2]],
        )
        .await;
    assert!(result.is_err());
    assert!(
        store.insert_called.load(Ordering::SeqCst),
        "insert must be attempted"
    );
}

// ---------------------------------------------------------------------------
// Test cases — VectorMetadataFilter helpers
// ---------------------------------------------------------------------------

#[tokio::test]
async fn vector_metadata_filter_is_empty_with_property_filters() {
    let empty = VectorMetadataFilter::default();
    assert!(empty.is_empty());

    let with_ns = VectorMetadataFilter {
        namespaces: vec!["ns".into()],
        ..Default::default()
    };
    assert!(!with_ns.is_empty());

    let with_prop = VectorMetadataFilter {
        property_filters: vec![PropertyFilter {
            key: "k".into(),
            op: PropertyOp::Eq,
            value: serde_json::Value::Bool(true),
        }],
        ..Default::default()
    };
    assert!(!with_prop.is_empty());
}