ares-vector 0.1.5

Embedded vector database with HNSW indexing for ARES
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
//! # ares-vector
//!
//! A pure-Rust embedded vector database with HNSW (Hierarchical Navigable Small World)
//! indexing for high-performance approximate nearest neighbor search.
//!
//! ## Features
//!
//! - **Pure Rust**: No native dependencies, compiles anywhere Rust does
//! - **HNSW Indexing**: Fast approximate nearest neighbor search
//! - **Thread-Safe**: Designed for concurrent read/write access
//! - **Persistence**: Optional disk-based storage with memory-mapped files
//! - **Multiple Distance Metrics**: Cosine, Euclidean (L2), Dot Product, Manhattan (L1)
//!
//! ## Quick Start
//!
//! ```rust,ignore
//! use ares_vector::{VectorDb, Config, DistanceMetric};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), ares_vector::Error> {
//!     // Create an in-memory database
//!     let db = VectorDb::open(Config::memory()).await?;
//!     
//!     // Create a collection for 384-dimensional vectors
//!     db.create_collection("documents", 384, DistanceMetric::Cosine).await?;
//!     
//!     // Insert vectors
//!     let embedding = vec![0.1f32; 384];
//!     db.insert("documents", "doc1", &embedding, None).await?;
//!     
//!     // Search for similar vectors
//!     let query = vec![0.1f32; 384];
//!     let results = db.search("documents", &query, 10).await?;
//!     
//!     Ok(())
//! }
//! ```
//!
//! ## Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────┐
//! │                         VectorDb                             │
//! │  ┌─────────────────────────────────────────────────────────┐│
//! │  │                    Collection                            ││
//! │  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────────┐ ││
//! │  │  │ HNSW Index  │  │  ID Mapping │  │ Metadata Store  │ ││
//! │  │  │  (search)   │  │ (str → u64) │  │  (optional)     │ ││
//! │  │  └─────────────┘  └─────────────┘  └─────────────────┘ ││
//! │  └─────────────────────────────────────────────────────────┘│
//! │                                                              │
//! │  ┌─────────────────────────────────────────────────────────┐│
//! │  │               Persistence Layer (optional)               ││
//! │  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────────┐ ││
//! │  │  │   Bincode   │  │  Snapshots  │  │  WAL (future)   │ ││
//! │  │  └─────────────┘  └─────────────┘  └─────────────────┘ ││
//! │  └─────────────────────────────────────────────────────────┘│
//! └─────────────────────────────────────────────────────────────┘
//! ```

#![warn(missing_docs)]
#![warn(clippy::all)]

pub mod collection;
pub mod config;
pub mod distance;
pub mod error;
pub mod index;
pub mod persistence;
pub mod types;

// Re-exports for convenience
pub use collection::Collection;
pub use config::Config;
pub use distance::{
    cosine_similarity, dot_product, l2_distance, normalize_vector, validate_dimensions,
    DistanceMetric,
};
pub use error::{Error, Result};
pub use types::{SearchResult, VectorId, VectorMetadata};

use std::path::Path;
use std::sync::Arc;
use tracing::{debug, info, instrument, warn};

/// The main vector database instance.
///
/// `VectorDb` manages multiple collections, each containing vectors of a specific
/// dimensionality. It provides thread-safe access to all operations.
///
/// # Thread Safety
///
/// All operations on `VectorDb` are thread-safe. Uses `scc::HashMap` for
/// lock-free concurrent access that is safe across `.await` points.
/// Multiple readers can access the database concurrently, and write
/// operations use fine-grained locking per entry.
#[derive(Clone)]
pub struct VectorDb {
    inner: Arc<VectorDbInner>,
}

struct VectorDbInner {
    config: Config,
    /// Async-safe concurrent hashmap from scc crate
    collections: scc::HashMap<String, Arc<Collection>>,
}

impl VectorDb {
    /// Open or create a vector database with the given configuration.
    ///
    /// # Arguments
    ///
    /// * `config` - Database configuration (memory or persistent).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // In-memory database
    /// let db = VectorDb::open(Config::memory()).await?;
    ///
    /// // Persistent database
    /// let db = VectorDb::open(Config::persistent("./data/vectors")).await?;
    /// ```
    #[instrument(skip(config), fields(persistent = config.data_path.is_some()))]
    pub async fn open(config: Config) -> Result<Self> {
        info!("Opening vector database");

        let db = Self {
            inner: Arc::new(VectorDbInner {
                config: config.clone(),
                collections: scc::HashMap::new(),
            }),
        };

        // Load existing collections from disk if persistent
        if let Some(ref path) = config.data_path {
            db.load_collections(path).await?;
        }

        Ok(db)
    }

    /// Create a new collection with the specified parameters.
    ///
    /// # Arguments
    ///
    /// * `name` - Unique name for the collection.
    /// * `dimensions` - Dimensionality of vectors (e.g., 384 for BGE-small).
    /// * `metric` - Distance metric to use for similarity calculations.
    ///
    /// # Errors
    ///
    /// Returns an error if a collection with the same name already exists.
    #[instrument(skip(self))]
    pub async fn create_collection(
        &self,
        name: &str,
        dimensions: usize,
        metric: DistanceMetric,
    ) -> Result<()> {
        info!(name, dimensions, ?metric, "Creating collection");

        // Check if collection already exists (lock-free read)
        if self.inner.collections.contains(name) {
            return Err(Error::CollectionExists(name.to_string()));
        }

        let collection = Collection::new(
            name.to_string(),
            dimensions,
            metric,
            self.inner.config.hnsw_config.clone(),
        )?;

        // Insert returns Err if key already exists (handles race condition)
        if self
            .inner
            .collections
            .insert(name.to_string(), Arc::new(collection))
            .is_err()
        {
            return Err(Error::CollectionExists(name.to_string()));
        }

        // Persist if configured
        if let Some(ref path) = self.inner.config.data_path {
            self.persist_collection_metadata(path, name).await?;
        }

        Ok(())
    }

    /// Delete a collection and all its data.
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the collection to delete.
    ///
    /// # Errors
    ///
    /// Returns an error if the collection doesn't exist.
    #[instrument(skip(self))]
    pub async fn delete_collection(&self, name: &str) -> Result<()> {
        info!(name, "Deleting collection");

        // remove returns Option<(K, V)>
        if self.inner.collections.remove(name).is_none() {
            return Err(Error::CollectionNotFound(name.to_string()));
        }

        // Remove from disk if persistent
        if let Some(ref path) = self.inner.config.data_path {
            self.delete_collection_files(path, name).await?;
        }

        Ok(())
    }

    /// Check if a collection exists.
    pub fn collection_exists(&self, name: &str) -> bool {
        self.inner.collections.contains(name)
    }

    /// List all collection names.
    pub fn list_collections(&self) -> Vec<String> {
        let mut names = Vec::new();
        self.inner.collections.scan(|k, _| {
            names.push(k.clone());
        });
        names
    }

    /// Get a reference to a collection.
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the collection.
    ///
    /// # Errors
    ///
    /// Returns an error if the collection doesn't exist.
    pub fn get_collection(&self, name: &str) -> Result<Arc<Collection>> {
        self.inner
            .collections
            .read(name, |_, v| v.clone())
            .ok_or_else(|| Error::CollectionNotFound(name.to_string()))
    }

    /// Insert a vector into a collection.
    ///
    /// # Arguments
    ///
    /// * `collection` - Name of the collection.
    /// * `id` - Unique string identifier for the vector.
    /// * `vector` - The embedding vector to insert.
    /// * `metadata` - Optional metadata to associate with the vector.
    ///
    /// # Errors
    ///
    /// Returns an error if the collection doesn't exist or the vector
    /// dimensions don't match the collection.
    #[instrument(skip(self, vector, metadata), fields(collection, id, dim = vector.len()))]
    pub async fn insert(
        &self,
        collection: &str,
        id: &str,
        vector: &[f32],
        metadata: Option<VectorMetadata>,
    ) -> Result<()> {
        let col = self.get_collection(collection)?;
        col.insert(id, vector, metadata)?;
        debug!("Inserted vector");
        Ok(())
    }

    /// Insert multiple vectors into a collection.
    ///
    /// This is more efficient than calling `insert` repeatedly as it batches
    /// the index updates.
    ///
    /// # Arguments
    ///
    /// * `collection` - Name of the collection.
    /// * `vectors` - Iterator of (id, vector, metadata) tuples.
    ///
    /// # Returns
    ///
    /// The number of vectors successfully inserted.
    #[instrument(skip(self, vectors), fields(collection))]
    pub async fn insert_batch<'a, I>(&self, collection: &str, vectors: I) -> Result<usize>
    where
        I: IntoIterator<Item = (&'a str, &'a [f32], Option<VectorMetadata>)>,
    {
        let col = self.get_collection(collection)?;
        let count = col.insert_batch(vectors)?;
        debug!(count, "Inserted batch");
        Ok(count)
    }

    /// Update a vector in a collection.
    ///
    /// This is equivalent to delete + insert but may be more efficient
    /// for some index implementations.
    #[instrument(skip(self, vector, metadata), fields(collection, id))]
    pub async fn update(
        &self,
        collection: &str,
        id: &str,
        vector: &[f32],
        metadata: Option<VectorMetadata>,
    ) -> Result<()> {
        let col = self.get_collection(collection)?;
        col.update(id, vector, metadata)?;
        Ok(())
    }

    /// Delete a vector from a collection.
    ///
    /// # Arguments
    ///
    /// * `collection` - Name of the collection.
    /// * `id` - ID of the vector to delete.
    ///
    /// # Returns
    ///
    /// `true` if the vector was found and deleted, `false` if it didn't exist.
    #[instrument(skip(self), fields(collection, id))]
    pub async fn delete(&self, collection: &str, id: &str) -> Result<bool> {
        let col = self.get_collection(collection)?;
        let deleted = col.delete(id)?;
        debug!(deleted, "Delete result");
        Ok(deleted)
    }

    /// Delete multiple vectors from a collection.
    ///
    /// # Returns
    ///
    /// The number of vectors actually deleted.
    #[instrument(skip(self, ids), fields(collection, count = ids.len()))]
    pub async fn delete_batch(&self, collection: &str, ids: &[&str]) -> Result<usize> {
        let col = self.get_collection(collection)?;
        let count = col.delete_batch(ids)?;
        debug!(count, "Deleted batch");
        Ok(count)
    }

    /// Search for similar vectors.
    ///
    /// # Arguments
    ///
    /// * `collection` - Name of the collection to search.
    /// * `query` - Query vector to find similar vectors to.
    /// * `limit` - Maximum number of results to return.
    ///
    /// # Returns
    ///
    /// A vector of search results, sorted by similarity (best first).
    #[instrument(skip(self, query), fields(collection, limit, dim = query.len()))]
    pub async fn search(
        &self,
        collection: &str,
        query: &[f32],
        limit: usize,
    ) -> Result<Vec<SearchResult>> {
        let col = self.get_collection(collection)?;
        let results = col.search(query, limit)?;
        debug!(count = results.len(), "Search completed");
        Ok(results)
    }

    /// Search with a minimum score threshold.
    ///
    /// # Arguments
    ///
    /// * `collection` - Name of the collection.
    /// * `query` - Query vector.
    /// * `limit` - Maximum results.
    /// * `min_score` - Minimum similarity score (0.0 to 1.0 for cosine).
    #[instrument(skip(self, query), fields(collection, limit, min_score))]
    pub async fn search_with_threshold(
        &self,
        collection: &str,
        query: &[f32],
        limit: usize,
        min_score: f32,
    ) -> Result<Vec<SearchResult>> {
        let col = self.get_collection(collection)?;
        let results = col.search_with_threshold(query, limit, min_score)?;
        Ok(results)
    }

    /// Get a vector by ID.
    ///
    /// # Returns
    ///
    /// The vector and its metadata if found.
    pub async fn get(
        &self,
        collection: &str,
        id: &str,
    ) -> Result<Option<(Vec<f32>, Option<VectorMetadata>)>> {
        let col = self.get_collection(collection)?;
        Ok(col.get(id))
    }

    /// Check if a vector exists.
    pub fn contains(&self, collection: &str, id: &str) -> Result<bool> {
        let col = self.get_collection(collection)?;
        Ok(col.contains(id))
    }

    /// Get the number of vectors in a collection.
    pub fn count(&self, collection: &str) -> Result<usize> {
        let col = self.get_collection(collection)?;
        Ok(col.len())
    }

    /// Get collection statistics.
    pub fn collection_stats(&self, collection: &str) -> Result<CollectionStats> {
        let col = self.get_collection(collection)?;
        Ok(col.stats())
    }

    /// Persist the current state to disk.
    ///
    /// This is only relevant for persistent databases. For in-memory databases,
    /// this is a no-op.
    #[instrument(skip(self))]
    pub async fn persist(&self) -> Result<()> {
        let Some(ref path) = self.inner.config.data_path else {
            debug!("Skipping persist for in-memory database");
            return Ok(());
        };

        info!("Persisting database to disk");

        // Collect names and collections for persistence
        let mut to_persist: Vec<(String, Arc<Collection>)> = Vec::new();
        self.inner.collections.scan(|name, collection| {
            to_persist.push((name.clone(), collection.clone()));
        });

        for (name, collection) in to_persist {
            self.persist_collection(path, &name, &collection).await?;
        }

        Ok(())
    }

    /// Force a compaction of the HNSW indices.
    ///
    /// This can reclaim space after many deletions.
    #[instrument(skip(self))]
    pub async fn compact(&self, collection: &str) -> Result<()> {
        let col = self.get_collection(collection)?;
        col.compact()?;
        Ok(())
    }

    // Internal: Load collections from disk
    async fn load_collections(&self, path: &Path) -> Result<()> {
        if !path.exists() {
            tokio::fs::create_dir_all(path).await?;
            return Ok(());
        }

        // Load collection metadata and indices
        let metadata_path = path.join("collections.json");
        if !metadata_path.exists() {
            return Ok(());
        }

        let data = tokio::fs::read_to_string(&metadata_path).await?;
        let collection_names: Vec<String> = serde_json::from_str(&data)
            .map_err(|e| Error::Persistence(format!("Failed to parse collections.json: {}", e)))?;

        for name in collection_names {
            match self.load_collection(path, &name).await {
                Ok(collection) => {
                    // scc::HashMap::insert returns Err if key exists, Ok otherwise
                    let _ = self
                        .inner
                        .collections
                        .insert(name.clone(), Arc::new(collection));
                    info!(name, "Loaded collection");
                }
                Err(e) => {
                    warn!(name, error = %e, "Failed to load collection, skipping");
                }
            }
        }

        Ok(())
    }

    async fn load_collection(&self, base_path: &Path, name: &str) -> Result<Collection> {
        persistence::load_collection(base_path, name).await
    }

    async fn persist_collection(
        &self,
        base_path: &Path,
        name: &str,
        collection: &Collection,
    ) -> Result<()> {
        persistence::save_collection(base_path, name, collection).await
    }

    async fn persist_collection_metadata(&self, base_path: &Path, _name: &str) -> Result<()> {
        let collections = self.list_collections();
        let metadata_path = base_path.join("collections.json");
        let data = serde_json::to_string_pretty(&collections)
            .map_err(|e| Error::Persistence(format!("Failed to serialize collections: {}", e)))?;
        tokio::fs::write(&metadata_path, data).await?;
        Ok(())
    }

    async fn delete_collection_files(&self, base_path: &Path, name: &str) -> Result<()> {
        let collection_path = base_path.join(name);
        if collection_path.exists() {
            tokio::fs::remove_dir_all(&collection_path).await?;
        }
        // Update metadata
        self.persist_collection_metadata(base_path, name).await?;
        Ok(())
    }
}

/// Statistics about a collection.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CollectionStats {
    /// Name of the collection.
    pub name: String,
    /// Number of vectors in the collection.
    pub vector_count: usize,
    /// Dimensionality of vectors.
    pub dimensions: usize,
    /// Distance metric used.
    pub metric: DistanceMetric,
    /// Approximate memory usage in bytes.
    pub memory_bytes: usize,
    /// HNSW index parameters.
    pub hnsw_params: HnswParams,
}

/// HNSW index parameters.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct HnswParams {
    /// Maximum number of connections per layer.
    pub m: usize,
    /// Size of the dynamic candidate list during construction.
    pub ef_construction: usize,
    /// Size of the dynamic candidate list during search.
    pub ef_search: usize,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_create_and_search() {
        let db = VectorDb::open(Config::memory()).await.unwrap();

        db.create_collection("test", 3, DistanceMetric::Cosine)
            .await
            .unwrap();

        db.insert("test", "vec1", &[1.0, 0.0, 0.0], None)
            .await
            .unwrap();
        db.insert("test", "vec2", &[0.0, 1.0, 0.0], None)
            .await
            .unwrap();
        db.insert("test", "vec3", &[0.9, 0.1, 0.0], None)
            .await
            .unwrap();

        let results = db.search("test", &[1.0, 0.0, 0.0], 10).await.unwrap();

        assert!(!results.is_empty());
        assert_eq!(results[0].id, "vec1");
    }

    #[tokio::test]
    async fn test_collection_lifecycle() {
        let db = VectorDb::open(Config::memory()).await.unwrap();

        assert!(!db.collection_exists("test"));

        db.create_collection("test", 128, DistanceMetric::Euclidean)
            .await
            .unwrap();
        assert!(db.collection_exists("test"));

        db.delete_collection("test").await.unwrap();
        assert!(!db.collection_exists("test"));
    }

    #[tokio::test]
    async fn test_duplicate_collection_error() {
        let db = VectorDb::open(Config::memory()).await.unwrap();

        db.create_collection("test", 128, DistanceMetric::Cosine)
            .await
            .unwrap();

        let result = db
            .create_collection("test", 128, DistanceMetric::Cosine)
            .await;
        assert!(matches!(result, Err(Error::CollectionExists(_))));
    }

    #[tokio::test]
    async fn test_list_collections_and_stats() {
        let db = VectorDb::open(Config::memory()).await.unwrap();
        assert!(db.list_collections().is_empty());

        db.create_collection("docs", 3, DistanceMetric::Cosine)
            .await
            .unwrap();
        db.insert("docs", "a", &[1.0, 0.0, 0.0], None)
            .await
            .unwrap();

        let mut names = db.list_collections();
        names.sort();
        assert_eq!(names, vec!["docs".to_string()]);

        let stats = db.collection_stats("docs").unwrap();
        assert_eq!(stats.name, "docs");
        assert_eq!(stats.dimensions, 3);
        assert_eq!(stats.vector_count, 1);
        assert_eq!(stats.metric, DistanceMetric::Cosine);
        assert!(stats.memory_bytes > 0);
        assert_eq!(stats.hnsw_params.m, Config::default().hnsw_config.m);
    }

    #[tokio::test]
    async fn test_collection_not_found_errors() {
        let db = VectorDb::open(Config::memory()).await.unwrap();

        let search = db.search("missing", &[1.0], 1).await;
        assert!(matches!(search, Err(Error::CollectionNotFound(_))));

        let stats = db.collection_stats("missing");
        assert!(matches!(stats, Err(Error::CollectionNotFound(_))));
    }

    #[tokio::test]
    async fn test_hnsw_params_in_stats() {
        let db = VectorDb::open(Config::memory()).await.unwrap();
        db.create_collection("x", 2, DistanceMetric::Manhattan)
            .await
            .unwrap();

        let stats = db.collection_stats("x").unwrap();
        let cfg = Config::default().hnsw_config;
        assert_eq!(stats.hnsw_params.ef_construction, cfg.ef_construction);
        assert_eq!(stats.hnsw_params.ef_search, cfg.ef_search);
    }
}