Skip to main content

adk_rag/
inmemory.rs

1//! In-memory vector store using cosine similarity.
2//!
3//! This module provides [`InMemoryVectorStore`], a zero-dependency vector store
4//! backed by a `HashMap` protected by a `tokio::sync::RwLock`. It is suitable
5//! for development, testing, and small-scale use cases.
6
7use std::collections::HashMap;
8
9use async_trait::async_trait;
10use tokio::sync::RwLock;
11
12use crate::document::{Chunk, SearchResult};
13use crate::error::{RagError, Result};
14use crate::filter::Filter;
15use crate::scope::Scope;
16use crate::vectorstore::{CollectionSpec, VectorQuery, VectorStore};
17
18/// Chunk ID → chunk, for one scope of one collection.
19type ScopeChunks = HashMap<String, Chunk>;
20
21/// An in-memory vector store using cosine similarity for search.
22///
23/// Collections are stored as nested `HashMap`s: collection name → scope → chunk ID → chunk.
24/// All operations are async-safe via `tokio::sync::RwLock`. Search returns results by
25/// descending score, and results of equal score by ascending chunk ID.
26///
27/// # Example
28///
29/// ```rust
30/// use adk_rag::{CollectionSpec, InMemoryVectorStore, Scope, VectorStore};
31///
32/// # #[tokio::main]
33/// # async fn main() -> adk_rag::Result<()> {
34/// let store = InMemoryVectorStore::new();
35/// store.create_collection("docs", &CollectionSpec::new(384)).await?;
36/// assert_eq!(store.count("docs", &Scope::single_tenant(), None).await?, 0);
37/// # Ok(())
38/// # }
39/// ```
40#[derive(Debug, Default)]
41pub struct InMemoryVectorStore {
42    collections: RwLock<HashMap<String, HashMap<Scope, ScopeChunks>>>,
43}
44
45impl InMemoryVectorStore {
46    /// Create a new empty in-memory vector store.
47    pub fn new() -> Self {
48        Self::default()
49    }
50}
51
52fn missing_collection(collection: &str) -> RagError {
53    RagError::VectorStoreError {
54        backend: "InMemory".to_string(),
55        message: format!("collection '{collection}' does not exist"),
56    }
57}
58
59/// Compute cosine similarity between two vectors.
60///
61/// Both vectors are L2-normalized before computing the dot product.
62/// Returns 0.0 if either vector has zero magnitude.
63fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
64    let dot: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
65    let norm_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
66    let norm_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
67    if norm_a == 0.0 || norm_b == 0.0 {
68        return 0.0;
69    }
70    dot / (norm_a * norm_b)
71}
72
73#[async_trait]
74impl VectorStore for InMemoryVectorStore {
75    async fn create_collection(&self, name: &str, spec: &CollectionSpec) -> Result<()> {
76        spec.validate()?;
77        let mut collections = self.collections.write().await;
78        collections.entry(name.to_string()).or_default();
79        Ok(())
80    }
81
82    async fn delete_collection(&self, name: &str) -> Result<()> {
83        let mut collections = self.collections.write().await;
84        collections.remove(name);
85        Ok(())
86    }
87
88    async fn upsert(&self, collection: &str, scope: &Scope, chunks: &[Chunk]) -> Result<()> {
89        let mut collections = self.collections.write().await;
90        let scopes =
91            collections.get_mut(collection).ok_or_else(|| missing_collection(collection))?;
92        let store = scopes.entry(scope.clone()).or_default();
93        for chunk in chunks {
94            store.insert(chunk.id.clone(), chunk.clone());
95        }
96        Ok(())
97    }
98
99    async fn delete(&self, collection: &str, scope: &Scope, ids: &[&str]) -> Result<()> {
100        let mut collections = self.collections.write().await;
101        let scopes =
102            collections.get_mut(collection).ok_or_else(|| missing_collection(collection))?;
103        if let Some(store) = scopes.get_mut(scope) {
104            for id in ids {
105                store.remove(*id);
106            }
107        }
108        Ok(())
109    }
110
111    async fn search(
112        &self,
113        collection: &str,
114        scope: &Scope,
115        query: &VectorQuery<'_>,
116    ) -> Result<Vec<SearchResult>> {
117        if let Some(filter) = query.filter {
118            filter.validate()?;
119        }
120        let collections = self.collections.read().await;
121        let scopes = collections.get(collection).ok_or_else(|| missing_collection(collection))?;
122
123        let mut scored: Vec<SearchResult> = scopes
124            .get(scope)
125            .into_iter()
126            .flat_map(HashMap::values)
127            .filter(|chunk| query.filter.is_none_or(|filter| filter.matches(chunk)))
128            .map(|chunk| {
129                let score = cosine_similarity(&chunk.embedding, query.embedding);
130                SearchResult { chunk: chunk.clone(), score }
131            })
132            .collect();
133
134        // Map order changes from one process to the next, so equal scores fall back to the
135        // chunk id and a query always returns the same chunks in the same order.
136        scored.sort_by(|a, b| {
137            b.score
138                .partial_cmp(&a.score)
139                .unwrap_or(std::cmp::Ordering::Equal)
140                .then_with(|| a.chunk.id.cmp(&b.chunk.id))
141        });
142        scored.truncate(query.top_k);
143        Ok(scored)
144    }
145
146    async fn count(&self, collection: &str, scope: &Scope, filter: Option<&Filter>) -> Result<u64> {
147        if let Some(filter) = filter {
148            filter.validate()?;
149        }
150        let collections = self.collections.read().await;
151        let scopes = collections.get(collection).ok_or_else(|| missing_collection(collection))?;
152        let matching = scopes
153            .get(scope)
154            .into_iter()
155            .flat_map(HashMap::values)
156            .filter(|chunk| filter.is_none_or(|filter| filter.matches(chunk)))
157            .count();
158        Ok(matching as u64)
159    }
160
161    async fn delete_where(&self, collection: &str, scope: &Scope, filter: &Filter) -> Result<u64> {
162        filter.validate()?;
163        let mut collections = self.collections.write().await;
164        let scopes =
165            collections.get_mut(collection).ok_or_else(|| missing_collection(collection))?;
166        let Some(store) = scopes.get_mut(scope) else {
167            return Ok(0);
168        };
169        let before = store.len();
170        store.retain(|_, chunk| !filter.matches(chunk));
171        Ok((before - store.len()) as u64)
172    }
173
174    async fn purge_scope(&self, collection: &str, scope: &Scope) -> Result<u64> {
175        let mut collections = self.collections.write().await;
176        let scopes =
177            collections.get_mut(collection).ok_or_else(|| missing_collection(collection))?;
178        Ok(scopes.remove(scope).map_or(0, |store| store.len() as u64))
179    }
180}