1use async_trait::async_trait;
10use chrono::Utc;
11use ragfs_core::{
12 Chunk, DirectoryScope, FileRecord, SearchQuery, SearchResult, StoreError, StoreStats,
13 VectorStore, dir_path_matches_scope,
14};
15use std::collections::HashMap;
16use std::path::{Path, PathBuf};
17use std::sync::Arc;
18use tokio::sync::RwLock;
19use tracing::debug;
20use uuid::Uuid;
21
22pub struct MemoryStore {
45 dimension: usize,
46 chunks: Arc<RwLock<HashMap<Uuid, Chunk>>>,
47 files: Arc<RwLock<HashMap<PathBuf, FileRecord>>>,
48 initialized: Arc<RwLock<bool>>,
49 index_revision: Arc<RwLock<u64>>,
50}
51
52impl MemoryStore {
53 #[must_use]
55 pub fn new(dimension: usize) -> Self {
56 Self {
57 dimension,
58 chunks: Arc::new(RwLock::new(HashMap::new())),
59 files: Arc::new(RwLock::new(HashMap::new())),
60 initialized: Arc::new(RwLock::new(false)),
61 index_revision: Arc::new(RwLock::new(1)),
62 }
63 }
64
65 fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
67 if a.len() != b.len() {
68 return 0.0;
69 }
70
71 let dot: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
72 let norm_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
73 let norm_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
74
75 if norm_a == 0.0 || norm_b == 0.0 {
76 return 0.0;
77 }
78
79 dot / (norm_a * norm_b)
80 }
81
82 async fn bump_index_revision(&self) {
83 let mut revision = self.index_revision.write().await;
84 *revision = revision.saturating_add(1);
85 }
86}
87
88impl Default for MemoryStore {
89 fn default() -> Self {
90 Self::new(384)
91 }
92}
93
94#[async_trait]
95impl VectorStore for MemoryStore {
96 async fn init(&self) -> Result<(), StoreError> {
97 let mut initialized = self.initialized.write().await;
98 *initialized = true;
99 debug!("MemoryStore initialized (dimension: {})", self.dimension);
100 Ok(())
101 }
102
103 async fn upsert_chunks(&self, chunks: &[Chunk]) -> Result<(), StoreError> {
104 if chunks.is_empty() {
105 return Ok(());
106 }
107 for chunk in chunks {
108 chunk.metadata.media.validate().map_err(StoreError::Query)?;
109 }
110 let mut store = self.chunks.write().await;
111 for chunk in chunks {
112 store.insert(chunk.id, chunk.clone());
113 }
114 drop(store);
115 self.bump_index_revision().await;
116 debug!("Upserted {} chunks", chunks.len());
117 Ok(())
118 }
119
120 async fn search(&self, query: SearchQuery) -> Result<Vec<SearchResult>, StoreError> {
121 let chunks = self.chunks.read().await;
122 let mut results: Vec<(f32, &Chunk)> = Vec::new();
123
124 for chunk in chunks.values() {
126 if let Some(ref scope) = query.scope_prefix
127 && !dir_path_matches_scope(&chunk.dir_path, scope)
128 {
129 continue;
130 }
131 if let Some(embedding) = &chunk.embedding {
132 let score = Self::cosine_similarity(&query.embedding, embedding);
133 results.push((score, chunk));
134 }
135 }
136
137 results.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
139
140 let top_k = results
142 .into_iter()
143 .take(query.limit)
144 .map(|(score, chunk)| SearchResult {
145 media: chunk.metadata.media.clone(),
146 chunk_id: chunk.id,
147 file_path: chunk.file_path.clone(),
148 content: chunk.content.clone(),
149 score,
150 byte_range: chunk.byte_range.clone(),
151 line_range: chunk.line_range.clone(),
152 metadata: chunk.metadata.extra.clone(),
153 })
154 .collect();
155
156 Ok(top_k)
157 }
158
159 async fn hybrid_search(&self, query: SearchQuery) -> Result<Vec<SearchResult>, StoreError> {
160 self.search(query).await
163 }
164
165 async fn delete_by_file_path(&self, path: &Path) -> Result<u64, StoreError> {
166 let mut chunks = self.chunks.write().await;
167 let mut files = self.files.write().await;
168
169 let before = chunks.len();
170 chunks.retain(|_, chunk| chunk.file_path != path);
171 let deleted = (before - chunks.len()) as u64;
172
173 files.remove(path);
174 drop(chunks);
175 drop(files);
176 self.bump_index_revision().await;
177
178 debug!("Deleted {} chunks for {:?}", deleted, path);
179 Ok(deleted)
180 }
181
182 async fn update_file_path(&self, from: &Path, to: &Path) -> Result<u64, StoreError> {
183 let mut chunks = self.chunks.write().await;
184 let mut files = self.files.write().await;
185 let mut updated = 0u64;
186
187 for chunk in chunks.values_mut() {
189 if chunk.file_path == from {
190 let root = DirectoryScope::infer_root(&chunk.file_path, &chunk.dir_path);
191 let scope = DirectoryScope::from_paths(to, root.as_deref());
192 chunk.file_path = to.to_path_buf();
193 chunk.dir_path = scope.dir_path;
194 chunk.dir_depth = scope.dir_depth;
195 chunk.path_components = scope.path_components;
196 updated += 1;
197 }
198 }
199
200 if let Some(mut record) = files.remove(from) {
202 record.path = to.to_path_buf();
203 files.insert(to.to_path_buf(), record);
204 }
205
206 drop(chunks);
207 drop(files);
208 if updated > 0 {
209 self.bump_index_revision().await;
210 }
211
212 debug!("Updated {} chunks from {:?} to {:?}", updated, from, to);
213 Ok(updated)
214 }
215
216 async fn get_chunks_for_file(&self, path: &Path) -> Result<Vec<Chunk>, StoreError> {
217 let chunks = self.chunks.read().await;
218 let file_chunks: Vec<Chunk> = chunks
219 .values()
220 .filter(|chunk| chunk.file_path == path)
221 .cloned()
222 .collect();
223 Ok(file_chunks)
224 }
225
226 async fn get_file(&self, path: &Path) -> Result<Option<FileRecord>, StoreError> {
227 let files = self.files.read().await;
228 Ok(files.get(path).cloned())
229 }
230
231 async fn upsert_file(&self, record: &FileRecord) -> Result<(), StoreError> {
232 let mut files = self.files.write().await;
233 files.insert(record.path.clone(), record.clone());
234 debug!("Upserted file record for {:?}", record.path);
235 Ok(())
236 }
237
238 async fn stats(&self) -> Result<StoreStats, StoreError> {
239 let chunks = self.chunks.read().await;
240 let files = self.files.read().await;
241
242 Ok(StoreStats {
243 total_chunks: chunks.len() as u64,
244 total_files: files.len() as u64,
245 index_size_bytes: 0, last_updated: Some(Utc::now()),
247 index_revision: *self.index_revision.read().await,
248 })
249 }
250
251 async fn get_all_chunks(&self) -> Result<Vec<Chunk>, StoreError> {
252 let chunks = self.chunks.read().await;
253 Ok(chunks.values().cloned().collect())
254 }
255
256 async fn get_all_files(&self) -> Result<Vec<FileRecord>, StoreError> {
257 let files = self.files.read().await;
258 Ok(files.values().cloned().collect())
259 }
260}
261
262#[cfg(test)]
263mod tests {
264 use super::*;
265 use ragfs_core::{ChunkMetadata, ContentType, DistanceMetric};
266
267 fn create_test_chunk(id: Uuid, file_id: Uuid, path: &str, embedding: Vec<f32>) -> Chunk {
268 let file_path = PathBuf::from(path);
269 let scope = DirectoryScope::from_file_path(&file_path);
270 Chunk {
271 id,
272 file_id,
273 file_path,
274 content: "test content".to_string(),
275 content_type: ContentType::Text,
276 mime_type: Some("text/plain".to_string()),
277 chunk_index: 0,
278 byte_range: 0..12,
279 line_range: Some(0..1),
280 parent_chunk_id: None,
281 depth: 0,
282 embedding: Some(embedding),
283 dir_path: scope.dir_path,
284 dir_depth: scope.dir_depth,
285 path_components: scope.path_components,
286 metadata: ChunkMetadata::default(),
287 }
288 }
289
290 fn create_scoped_chunk(
291 path: &str,
292 root: Option<&Path>,
293 embedding: Vec<f32>,
294 content: &str,
295 ) -> Chunk {
296 let file_path = PathBuf::from(path);
297 let scope = DirectoryScope::from_paths(&file_path, root);
298 Chunk {
299 id: Uuid::new_v4(),
300 file_id: Uuid::new_v4(),
301 file_path,
302 content: content.to_string(),
303 content_type: ContentType::Text,
304 mime_type: Some("text/plain".to_string()),
305 chunk_index: 0,
306 byte_range: 0..content.len() as u64,
307 line_range: Some(0..1),
308 parent_chunk_id: None,
309 depth: 0,
310 embedding: Some(embedding),
311 dir_path: scope.dir_path,
312 dir_depth: scope.dir_depth,
313 path_components: scope.path_components,
314 metadata: ChunkMetadata::default(),
315 }
316 }
317
318 #[tokio::test]
319 async fn test_memory_store_new() {
320 let store = MemoryStore::new(384);
321 assert_eq!(store.dimension, 384);
322 }
323
324 #[tokio::test]
325 async fn test_memory_store_init() {
326 let store = MemoryStore::new(384);
327 let result = store.init().await;
328 assert!(result.is_ok());
329 }
330
331 #[tokio::test]
332 async fn test_memory_store_upsert_and_stats() {
333 let store = MemoryStore::new(3);
334 store.init().await.unwrap();
335
336 let file_id = Uuid::new_v4();
337 let chunks = vec![
338 create_test_chunk(
339 Uuid::new_v4(),
340 file_id,
341 "/test/file.txt",
342 vec![1.0, 0.0, 0.0],
343 ),
344 create_test_chunk(
345 Uuid::new_v4(),
346 file_id,
347 "/test/file.txt",
348 vec![0.0, 1.0, 0.0],
349 ),
350 ];
351
352 store.upsert_chunks(&chunks).await.unwrap();
353
354 let stats = store.stats().await.unwrap();
355 assert_eq!(stats.total_chunks, 2);
356 }
357
358 #[tokio::test]
359 async fn test_memory_store_search() {
360 let store = MemoryStore::new(3);
361 store.init().await.unwrap();
362
363 let file_id = Uuid::new_v4();
364 let chunk1_id = Uuid::new_v4();
365 let chunks = vec![
366 create_test_chunk(chunk1_id, file_id, "/test/file.txt", vec![1.0, 0.0, 0.0]),
367 create_test_chunk(
368 Uuid::new_v4(),
369 file_id,
370 "/test/file.txt",
371 vec![0.0, 1.0, 0.0],
372 ),
373 create_test_chunk(
374 Uuid::new_v4(),
375 file_id,
376 "/test/file.txt",
377 vec![0.0, 0.0, 1.0],
378 ),
379 ];
380
381 store.upsert_chunks(&chunks).await.unwrap();
382
383 let query = SearchQuery {
384 embedding: vec![1.0, 0.0, 0.0],
385 text: None,
386 limit: 2,
387 filters: vec![],
388 metric: Default::default(),
389 scope_prefix: None,
390 };
391
392 let results = store.search(query).await.unwrap();
393 assert_eq!(results.len(), 2);
394 assert_eq!(results[0].chunk_id, chunk1_id);
395 assert!((results[0].score - 1.0).abs() < 0.001);
396 }
397
398 #[tokio::test]
399 async fn test_memory_store_delete_by_file_path() {
400 let store = MemoryStore::new(3);
401 store.init().await.unwrap();
402
403 let chunks = vec![
404 create_test_chunk(
405 Uuid::new_v4(),
406 Uuid::new_v4(),
407 "/test/file1.txt",
408 vec![1.0, 0.0, 0.0],
409 ),
410 create_test_chunk(
411 Uuid::new_v4(),
412 Uuid::new_v4(),
413 "/test/file2.txt",
414 vec![0.0, 1.0, 0.0],
415 ),
416 ];
417
418 store.upsert_chunks(&chunks).await.unwrap();
419
420 let deleted = store
421 .delete_by_file_path(Path::new("/test/file1.txt"))
422 .await
423 .unwrap();
424 assert_eq!(deleted, 1);
425
426 let stats = store.stats().await.unwrap();
427 assert_eq!(stats.total_chunks, 1);
428 }
429
430 #[tokio::test]
431 async fn test_memory_store_get_all_chunks() {
432 let store = MemoryStore::new(3);
433 store.init().await.unwrap();
434
435 let file_id = Uuid::new_v4();
436 let chunks = vec![
437 create_test_chunk(
438 Uuid::new_v4(),
439 file_id,
440 "/test/file.txt",
441 vec![1.0, 0.0, 0.0],
442 ),
443 create_test_chunk(
444 Uuid::new_v4(),
445 file_id,
446 "/test/file.txt",
447 vec![0.0, 1.0, 0.0],
448 ),
449 ];
450
451 store.upsert_chunks(&chunks).await.unwrap();
452
453 let all_chunks = store.get_all_chunks().await.unwrap();
454 assert_eq!(all_chunks.len(), 2);
455 }
456
457 #[tokio::test]
458 async fn test_memory_store_scoped_search() {
459 let store = MemoryStore::new(3);
460 store.init().await.unwrap();
461 let root = Path::new("/project");
462 let embedding = vec![1.0, 0.0, 0.0];
463 store
464 .upsert_chunks(&[
465 create_scoped_chunk(
466 "/project/src/auth/login.rs",
467 Some(root),
468 embedding.clone(),
469 "login",
470 ),
471 create_scoped_chunk(
472 "/project/src/auth/oauth/token.rs",
473 Some(root),
474 embedding.clone(),
475 "oauth",
476 ),
477 create_scoped_chunk("/project/src/db.rs", Some(root), embedding.clone(), "db"),
478 create_scoped_chunk(
479 "/project/docs/readme.md",
480 Some(root),
481 embedding.clone(),
482 "docs",
483 ),
484 ])
485 .await
486 .unwrap();
487
488 let stored = store
489 .get_chunks_for_file(Path::new("/project/src/auth/login.rs"))
490 .await
491 .unwrap();
492 assert_eq!(stored[0].dir_path, "src/auth");
493 assert!(!stored[0].dir_path.starts_with('/'));
494
495 let exact = store
496 .search(SearchQuery {
497 embedding: embedding.clone(),
498 text: None,
499 limit: 10,
500 filters: vec![],
501 metric: DistanceMetric::Cosine,
502 scope_prefix: Some("src/auth".to_string()),
503 })
504 .await
505 .unwrap();
506 assert_eq!(exact.len(), 2);
507 assert!(
508 exact
509 .iter()
510 .any(|r| r.file_path.ends_with("src/auth/login.rs"))
511 );
512 assert!(
513 exact
514 .iter()
515 .any(|r| r.file_path.ends_with("src/auth/oauth/token.rs"))
516 );
517
518 let src = store
519 .search(SearchQuery {
520 embedding: embedding.clone(),
521 text: None,
522 limit: 10,
523 filters: vec![],
524 metric: DistanceMetric::Cosine,
525 scope_prefix: Some("src".to_string()),
526 })
527 .await
528 .unwrap();
529 assert_eq!(src.len(), 3);
530 assert!(src.iter().any(|r| r.file_path.ends_with("src/db.rs")));
531
532 let docs = store
533 .search(SearchQuery {
534 embedding,
535 text: None,
536 limit: 10,
537 filters: vec![],
538 metric: DistanceMetric::Cosine,
539 scope_prefix: Some("docs".to_string()),
540 })
541 .await
542 .unwrap();
543 assert_eq!(docs.len(), 1);
544 assert!(docs[0].file_path.ends_with("docs/readme.md"));
545 }
546
547 #[tokio::test]
548 async fn index_revision_changes_on_writes_not_reads() {
549 let store = MemoryStore::new(3);
550 store.init().await.unwrap();
551 let initial = store.stats().await.unwrap().index_revision;
552 assert_eq!(initial, 1);
553
554 let after_read = store.stats().await.unwrap().index_revision;
555 assert_eq!(after_read, initial);
556
557 let query = SearchQuery {
558 embedding: vec![1.0, 0.0, 0.0],
559 text: None,
560 limit: 1,
561 filters: vec![],
562 metric: Default::default(),
563 scope_prefix: None,
564 };
565 store.search(query.clone()).await.unwrap();
566 store.hybrid_search(query).await.unwrap();
567 store.get_all_chunks().await.unwrap();
568 assert_eq!(store.stats().await.unwrap().index_revision, initial);
569
570 let chunk = create_test_chunk(
571 Uuid::new_v4(),
572 Uuid::new_v4(),
573 "/test/file.txt",
574 vec![1.0, 0.0, 0.0],
575 );
576 store.upsert_chunks(&[chunk]).await.unwrap();
577 let after_add = store.stats().await.unwrap().index_revision;
578 assert!(after_add > initial, "add must bump revision");
579
580 store.upsert_chunks(&[]).await.unwrap();
581 assert_eq!(
582 store.stats().await.unwrap().index_revision,
583 after_add,
584 "empty upsert is not an index write"
585 );
586
587 store
588 .update_file_path(Path::new("/test/file.txt"), Path::new("/test/renamed.txt"))
589 .await
590 .unwrap();
591 let after_update = store.stats().await.unwrap().index_revision;
592 assert!(after_update > after_add, "rename must bump revision");
593
594 store
595 .delete_by_file_path(Path::new("/test/renamed.txt"))
596 .await
597 .unwrap();
598 let after_delete = store.stats().await.unwrap().index_revision;
599 assert!(after_delete > after_update, "delete must bump revision");
600 }
601
602 #[test]
603 fn test_cosine_similarity() {
604 let sim = MemoryStore::cosine_similarity(&[1.0, 0.0, 0.0], &[1.0, 0.0, 0.0]);
606 assert!((sim - 1.0).abs() < 0.001);
607
608 let sim = MemoryStore::cosine_similarity(&[1.0, 0.0, 0.0], &[0.0, 1.0, 0.0]);
610 assert!(sim.abs() < 0.001);
611
612 let sim = MemoryStore::cosine_similarity(&[1.0, 0.0, 0.0], &[-1.0, 0.0, 0.0]);
614 assert!((sim - (-1.0)).abs() < 0.001);
615 }
616}