ruvector-core 2.2.0

High-performance Rust vector database core with HNSW indexing
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
//! Integration tests for end-to-end workflows
//!
//! These tests verify that all components work together correctly.

use ruvector_core::types::{DbOptions, DistanceMetric, HnswConfig, SearchQuery};
use ruvector_core::{VectorDB, VectorEntry};
use std::collections::HashMap;
use tempfile::tempdir;

// ============================================================================
// End-to-End Workflow Tests
// ============================================================================

#[test]
fn test_complete_insert_search_workflow() {
    let dir = tempdir().unwrap();
    let mut options = DbOptions::default();
    options.storage_path = dir.path().join("test.db").to_string_lossy().to_string();
    options.dimensions = 128;
    options.distance_metric = DistanceMetric::Cosine;
    options.hnsw_config = Some(HnswConfig {
        m: 16,
        ef_construction: 100,
        ef_search: 50,
        max_elements: 100_000,
    });

    let db = VectorDB::new(options).unwrap();

    // Insert training data
    let vectors: Vec<VectorEntry> = (0..100)
        .map(|i| {
            let mut metadata = HashMap::new();
            metadata.insert("index".to_string(), serde_json::json!(i));

            VectorEntry {
                id: Some(format!("vec_{}", i)),
                vector: (0..128).map(|j| ((i + j) as f32) * 0.01).collect(),
                metadata: Some(metadata),
            }
        })
        .collect();

    let ids = db.insert_batch(vectors).unwrap();
    assert_eq!(ids.len(), 100);

    // Search for similar vectors
    let query: Vec<f32> = (0..128).map(|j| (j as f32) * 0.01).collect();
    let results = db
        .search(SearchQuery {
            vector: query,
            k: 10,
            filter: None,
            ef_search: Some(100),
        })
        .unwrap();

    assert_eq!(results.len(), 10);
    assert!(results[0].vector.is_some());
    assert!(results[0].metadata.is_some());
}

#[test]
fn test_batch_operations_10k_vectors() {
    let dir = tempdir().unwrap();
    let mut options = DbOptions::default();
    options.storage_path = dir.path().join("test.db").to_string_lossy().to_string();
    options.dimensions = 384;
    options.distance_metric = DistanceMetric::Euclidean;
    options.hnsw_config = Some(HnswConfig::default());

    let db = VectorDB::new(options).unwrap();

    // Generate 10K vectors
    println!("Generating 10K vectors...");
    let vectors: Vec<VectorEntry> = (0..10_000)
        .map(|i| VectorEntry {
            id: Some(format!("vec_{}", i)),
            vector: (0..384).map(|j| ((i + j) as f32) * 0.001).collect(),
            metadata: None,
        })
        .collect();

    // Batch insert
    println!("Batch inserting 10K vectors...");
    let start = std::time::Instant::now();
    let ids = db.insert_batch(vectors).unwrap();
    let duration = start.elapsed();
    println!("Batch insert took: {:?}", duration);

    assert_eq!(ids.len(), 10_000);
    assert_eq!(db.len().unwrap(), 10_000);

    // Perform multiple searches
    println!("Performing searches...");
    for i in 0..10 {
        let query: Vec<f32> = (0..384).map(|j| ((i * 100 + j) as f32) * 0.001).collect();
        let results = db
            .search(SearchQuery {
                vector: query,
                k: 10,
                filter: None,
                ef_search: None,
            })
            .unwrap();

        assert_eq!(results.len(), 10);
    }
}

#[test]
fn test_persistence_and_reload() {
    let dir = tempdir().unwrap();
    let db_path = dir
        .path()
        .join("persistent.db")
        .to_string_lossy()
        .to_string();

    // Create and populate database
    {
        let mut options = DbOptions::default();
        options.storage_path = db_path.clone();
        options.dimensions = 3;
        options.hnsw_config = None; // Use flat index for simpler persistence test

        let db = VectorDB::new(options).unwrap();

        for i in 0..10 {
            db.insert(VectorEntry {
                id: Some(format!("vec_{}", i)),
                vector: vec![i as f32, (i * 2) as f32, (i * 3) as f32],
                metadata: None,
            })
            .unwrap();
        }

        assert_eq!(db.len().unwrap(), 10);
    }

    // Reload database
    {
        let mut options = DbOptions::default();
        options.storage_path = db_path.clone();
        options.dimensions = 3;
        options.hnsw_config = None;

        let db = VectorDB::new(options).unwrap();

        // Verify data persisted
        assert_eq!(db.len().unwrap(), 10);

        let entry = db.get("vec_5").unwrap().unwrap();
        assert_eq!(entry.vector, vec![5.0, 10.0, 15.0]);
    }
}

#[test]
fn test_mixed_operations_workflow() {
    let dir = tempdir().unwrap();
    let mut options = DbOptions::default();
    options.storage_path = dir.path().join("test.db").to_string_lossy().to_string();
    options.dimensions = 64;

    let db = VectorDB::new(options).unwrap();

    // Insert initial batch
    let initial: Vec<VectorEntry> = (0..50)
        .map(|i| VectorEntry {
            id: Some(format!("vec_{}", i)),
            vector: (0..64).map(|j| ((i + j) as f32) * 0.1).collect(),
            metadata: None,
        })
        .collect();

    db.insert_batch(initial).unwrap();
    assert_eq!(db.len().unwrap(), 50);

    // Delete some vectors
    for i in 0..10 {
        db.delete(&format!("vec_{}", i)).unwrap();
    }
    assert_eq!(db.len().unwrap(), 40);

    // Insert more individual vectors
    for i in 50..60 {
        db.insert(VectorEntry {
            id: Some(format!("vec_{}", i)),
            vector: (0..64).map(|j| ((i + j) as f32) * 0.1).collect(),
            metadata: None,
        })
        .unwrap();
    }
    assert_eq!(db.len().unwrap(), 50);

    // Search
    let query: Vec<f32> = (0..64).map(|j| (j as f32) * 0.1).collect();
    let results = db
        .search(SearchQuery {
            vector: query,
            k: 20,
            filter: None,
            ef_search: None,
        })
        .unwrap();

    assert!(results.len() > 0);
}

// ============================================================================
// Different Distance Metrics
// ============================================================================

#[test]
fn test_all_distance_metrics() {
    let metrics = vec![
        DistanceMetric::Euclidean,
        DistanceMetric::Cosine,
        DistanceMetric::DotProduct,
        DistanceMetric::Manhattan,
    ];

    for metric in metrics {
        let dir = tempdir().unwrap();
        let mut options = DbOptions::default();
        options.storage_path = dir.path().join("test.db").to_string_lossy().to_string();
        options.dimensions = 32;
        options.distance_metric = metric;
        options.hnsw_config = None;

        let db = VectorDB::new(options).unwrap();

        // Insert test vectors
        for i in 0..20 {
            db.insert(VectorEntry {
                id: Some(format!("vec_{}", i)),
                vector: (0..32).map(|j| ((i + j) as f32) * 0.1).collect(),
                metadata: None,
            })
            .unwrap();
        }

        // Search
        let query: Vec<f32> = (0..32).map(|j| (j as f32) * 0.1).collect();
        let results = db
            .search(SearchQuery {
                vector: query,
                k: 5,
                filter: None,
                ef_search: None,
            })
            .unwrap();

        assert_eq!(results.len(), 5, "Failed for metric {:?}", metric);

        // Verify scores are in ascending order (lower is better for distance)
        for i in 0..results.len() - 1 {
            assert!(
                results[i].score <= results[i + 1].score,
                "Results not sorted for metric {:?}: {} > {}",
                metric,
                results[i].score,
                results[i + 1].score
            );
        }
    }
}

// ============================================================================
// HNSW Configuration Tests
// ============================================================================

#[test]
fn test_hnsw_different_configurations() {
    let configs = vec![
        HnswConfig {
            m: 8,
            ef_construction: 50,
            ef_search: 50,
            max_elements: 1000,
        },
        HnswConfig {
            m: 16,
            ef_construction: 100,
            ef_search: 100,
            max_elements: 1000,
        },
        HnswConfig {
            m: 32,
            ef_construction: 200,
            ef_search: 200,
            max_elements: 1000,
        },
    ];

    for config in configs {
        let dir = tempdir().unwrap();
        let mut options = DbOptions::default();
        options.storage_path = dir.path().join("test.db").to_string_lossy().to_string();
        options.dimensions = 64;
        options.hnsw_config = Some(config.clone());

        let db = VectorDB::new(options).unwrap();

        // Insert vectors
        let vectors: Vec<VectorEntry> = (0..100)
            .map(|i| VectorEntry {
                id: Some(format!("vec_{}", i)),
                vector: (0..64).map(|j| ((i + j) as f32) * 0.01).collect(),
                metadata: None,
            })
            .collect();

        db.insert_batch(vectors).unwrap();

        // Search with different ef_search values
        let query: Vec<f32> = (0..64).map(|j| (j as f32) * 0.01).collect();
        let results = db
            .search(SearchQuery {
                vector: query,
                k: 10,
                filter: None,
                ef_search: Some(config.ef_search),
            })
            .unwrap();

        assert_eq!(results.len(), 10, "Failed for config M={}", config.m);
    }
}

// ============================================================================
// Metadata Filtering Tests
// ============================================================================

#[test]
fn test_complex_metadata_filtering() {
    let dir = tempdir().unwrap();
    let mut options = DbOptions::default();
    options.storage_path = dir.path().join("test.db").to_string_lossy().to_string();
    options.dimensions = 16;
    options.hnsw_config = None;

    let db = VectorDB::new(options).unwrap();

    // Insert vectors with different categories and values
    for i in 0..50 {
        let mut metadata = HashMap::new();
        metadata.insert("category".to_string(), serde_json::json!(i % 3));
        metadata.insert("value".to_string(), serde_json::json!(i / 10));

        db.insert(VectorEntry {
            id: Some(format!("vec_{}", i)),
            vector: (0..16).map(|j| ((i + j) as f32) * 0.1).collect(),
            metadata: Some(metadata),
        })
        .unwrap();
    }

    // Search with single filter
    let mut filter1 = HashMap::new();
    filter1.insert("category".to_string(), serde_json::json!(0));

    let query: Vec<f32> = (0..16).map(|j| (j as f32) * 0.1).collect();
    let results1 = db
        .search(SearchQuery {
            vector: query.clone(),
            k: 100,
            filter: Some(filter1),
            ef_search: None,
        })
        .unwrap();

    // Should only get vectors where i % 3 == 0
    for result in &results1 {
        let meta = result.metadata.as_ref().unwrap();
        assert_eq!(meta.get("category").unwrap(), &serde_json::json!(0));
    }

    // Search with different filter
    let mut filter2 = HashMap::new();
    filter2.insert("value".to_string(), serde_json::json!(2));

    let results2 = db
        .search(SearchQuery {
            vector: query,
            k: 100,
            filter: Some(filter2),
            ef_search: None,
        })
        .unwrap();

    // Should only get vectors where i / 10 == 2 (i.e., i in 20..30)
    for result in &results2 {
        let meta = result.metadata.as_ref().unwrap();
        assert_eq!(meta.get("value").unwrap(), &serde_json::json!(2));
    }
}

// ============================================================================
// Error Handling Tests
// ============================================================================

#[test]
fn test_dimension_validation() {
    let dir = tempdir().unwrap();
    let mut options = DbOptions::default();
    options.storage_path = dir.path().join("test.db").to_string_lossy().to_string();
    options.dimensions = 64;

    let db = VectorDB::new(options).unwrap();

    // Try to insert vector with wrong dimensions
    let result = db.insert(VectorEntry {
        id: None,
        vector: vec![1.0, 2.0, 3.0], // Only 3 dimensions, should be 64
        metadata: None,
    });

    assert!(result.is_err());
}

#[test]
fn test_search_with_wrong_dimension() {
    let dir = tempdir().unwrap();
    let mut options = DbOptions::default();
    options.storage_path = dir.path().join("test.db").to_string_lossy().to_string();
    options.dimensions = 64;
    options.hnsw_config = None;

    let db = VectorDB::new(options).unwrap();

    // Insert some vectors
    db.insert(VectorEntry {
        id: Some("v1".to_string()),
        vector: (0..64).map(|i| i as f32).collect(),
        metadata: None,
    })
    .unwrap();

    // Try to search with wrong dimension query
    // Note: This might not error in the current implementation, but should be validated
    let query = vec![1.0, 2.0, 3.0]; // Wrong dimension
    let result = db.search(SearchQuery {
        vector: query,
        k: 10,
        filter: None,
        ef_search: None,
    });

    // Depending on implementation, this might error or return empty results
    // The important thing is it doesn't panic
    let _ = result;
}