Skip to main content

zeph_memory/
vector_store.rs

1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Abstract vector-store trait and associated types.
5//!
6//! The [`VectorStore`] trait decouples the rest of `zeph-memory` from any specific
7//! vector database. Two implementations ship in this crate:
8//!
9//! - [`crate::qdrant_ops::QdrantOps`] / [`crate::embedding_store::EmbeddingStore`] —
10//!   production Qdrant-backed store.
11//! - [`crate::db_vector_store::DbVectorStore`] — `SQLite` BLOB store for testing and offline use.
12//! - [`crate::in_memory_store::InMemoryVectorStore`] — purely in-memory store for unit tests.
13
14use std::collections::HashMap;
15use std::future::Future;
16use std::pin::Pin;
17
18/// Error type for [`VectorStore`] operations.
19#[derive(Debug, thiserror::Error)]
20pub enum VectorStoreError {
21    #[error("connection error: {0}")]
22    Connection(String),
23    #[error("collection error: {0}")]
24    Collection(String),
25    #[error("upsert error: {0}")]
26    Upsert(String),
27    #[error("search error: {0}")]
28    Search(String),
29    #[error("delete error: {0}")]
30    Delete(String),
31    #[error("scroll error: {0}")]
32    Scroll(String),
33    #[error("serialization error: {0}")]
34    Serialization(String),
35    /// Operation is not supported by this backend (e.g. `get_points` on `DbVectorStore`).
36    #[error("operation unsupported: {0}")]
37    Unsupported(String),
38}
39
40/// A vector point to be stored in or retrieved from a [`VectorStore`].
41#[derive(Debug, Clone)]
42pub struct VectorPoint {
43    /// Unique string identifier for the point (e.g. a UUID).
44    pub id: String,
45    /// Dense embedding vector.
46    pub vector: Vec<f32>,
47    /// Arbitrary JSON metadata stored alongside the vector.
48    pub payload: HashMap<String, serde_json::Value>,
49}
50
51/// Filter applied to [`VectorStore::search`] and [`VectorStore::scroll_all`].
52///
53/// All `must` conditions are `ANDed`; all `must_not` conditions are `ANDed`.
54#[derive(Debug, Clone, Default)]
55pub struct VectorFilter {
56    /// All of these conditions must match.
57    pub must: Vec<FieldCondition>,
58    /// None of these conditions must match.
59    pub must_not: Vec<FieldCondition>,
60}
61
62/// A single payload field condition in a [`VectorFilter`].
63#[derive(Debug, Clone)]
64pub struct FieldCondition {
65    /// Payload field name.
66    pub field: String,
67    /// Expected value for the field.
68    pub value: FieldValue,
69}
70
71/// Value type in a [`FieldCondition`].
72#[derive(Debug, Clone)]
73pub enum FieldValue {
74    /// Exact integer match.
75    Integer(i64),
76    /// Exact string match.
77    Text(String),
78}
79
80/// A vector point returned by [`VectorStore::search`] with an attached similarity score.
81#[derive(Debug, Clone)]
82pub struct ScoredVectorPoint {
83    /// Point identifier (matches [`VectorPoint::id`]).
84    pub id: String,
85    /// Cosine similarity score in `[0, 1]`.
86    pub score: f32,
87    /// Payload stored alongside the vector.
88    pub payload: HashMap<String, serde_json::Value>,
89}
90
91/// Shared return type alias for all [`VectorStore`] trait methods.
92///
93/// Intentionally `pub(crate)` — all [`VectorStore`] implementations are internal to this crate.
94/// If the trait is ever made externally extensible, this alias should become `pub`.
95pub(crate) type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
96
97/// Result of [`VectorStore::scroll_all`]: maps point ID → key → value payload strings.
98pub type ScrollResult = HashMap<String, HashMap<String, String>>;
99
100/// Abstraction over a vector database backend.
101///
102/// Implementations must be `Send + Sync` so they can be wrapped in `Arc` and shared
103/// across async tasks. All methods return boxed futures via `BoxFuture` to remain
104/// object-safe.
105///
106/// # Implementations
107///
108/// | Type | Notes |
109/// |------|-------|
110/// | [`crate::embedding_store::EmbeddingStore`] | Qdrant-backed; production default. |
111/// | [`crate::db_vector_store::DbVectorStore`] | SQLite BLOB; offline / CI use. |
112/// | [`crate::in_memory_store::InMemoryVectorStore`] | Fully in-process; unit tests. |
113pub trait VectorStore: Send + Sync {
114    /// Create a collection with cosine-distance vectors of `vector_size` dimensions.
115    ///
116    /// Idempotent — no error if the collection already exists with the same dimension.
117    fn ensure_collection(
118        &self,
119        collection: &str,
120        vector_size: u64,
121    ) -> BoxFuture<'_, Result<(), VectorStoreError>>;
122
123    /// Returns `true` if `collection` exists in the backend.
124    fn collection_exists(&self, collection: &str) -> BoxFuture<'_, Result<bool, VectorStoreError>>;
125
126    /// Delete a collection and all its points.
127    fn delete_collection(&self, collection: &str) -> BoxFuture<'_, Result<(), VectorStoreError>>;
128
129    /// Upsert `points` into `collection`.
130    ///
131    /// Points with existing IDs are overwritten; new IDs are inserted.
132    fn upsert(
133        &self,
134        collection: &str,
135        points: Vec<VectorPoint>,
136    ) -> BoxFuture<'_, Result<(), VectorStoreError>>;
137
138    /// Search `collection` for the `limit` nearest neighbours of `vector`.
139    ///
140    /// Returns results in descending similarity order.  An optional [`VectorFilter`]
141    /// restricts the search space to points matching the payload conditions.
142    fn search(
143        &self,
144        collection: &str,
145        vector: Vec<f32>,
146        limit: u64,
147        filter: Option<VectorFilter>,
148    ) -> BoxFuture<'_, Result<Vec<ScoredVectorPoint>, VectorStoreError>>;
149
150    /// Delete specific points from `collection` by their string IDs.
151    fn delete_by_ids(
152        &self,
153        collection: &str,
154        ids: Vec<String>,
155    ) -> BoxFuture<'_, Result<(), VectorStoreError>>;
156
157    /// Scroll (paginate) all points in `collection` and return a map of
158    /// `point_id → { key_field → value }` payload entries.
159    fn scroll_all(
160        &self,
161        collection: &str,
162        key_field: &str,
163    ) -> BoxFuture<'_, Result<ScrollResult, VectorStoreError>>;
164
165    /// Return `true` if the backend is reachable and operational.
166    fn health_check(&self) -> BoxFuture<'_, Result<bool, VectorStoreError>>;
167
168    /// Create keyword payload indexes for the given field names.
169    ///
170    /// Default implementation is a no-op (for non-Qdrant backends).
171    fn create_keyword_indexes(
172        &self,
173        _collection: &str,
174        _fields: &[&str],
175    ) -> BoxFuture<'_, Result<(), VectorStoreError>> {
176        Box::pin(async { Ok(()) })
177    }
178
179    /// Batched vector + payload retrieval by point IDs.
180    ///
181    /// Returns one [`VectorPoint`] per matched id (missing ids are silently dropped).
182    /// Backends that cannot return vectors return `Err(VectorStoreError::Unsupported)`.
183    ///
184    /// # Errors
185    ///
186    /// Returns [`VectorStoreError::Unsupported`] when the backend does not support
187    /// direct point retrieval with vectors (e.g. `DbVectorStore`, `InMemoryVectorStore`
188    /// unless overridden in tests).
189    fn get_points(
190        &self,
191        _collection: &str,
192        _ids: Vec<String>,
193    ) -> BoxFuture<'_, Result<Vec<VectorPoint>, VectorStoreError>> {
194        Box::pin(async {
195            Err(VectorStoreError::Unsupported(
196                "get_points not implemented for this backend".into(),
197            ))
198        })
199    }
200}