Skip to main content

mentedb_index/
manager.rs

1//! Composite index manager that owns and coordinates all index types.
2
3use std::collections::{HashMap, HashSet};
4use std::path::Path;
5
6use mentedb_core::MemoryNode;
7use mentedb_core::error::MenteResult;
8use mentedb_core::types::{MemoryId, Timestamp};
9
10use crate::bitmap::BitmapIndex;
11use crate::bm25::Bm25Index;
12use crate::hnsw::{HnswConfig, HnswIndex};
13use crate::salience::SalienceIndex;
14use crate::temporal::TemporalIndex;
15
16/// Configuration for the composite index manager.
17#[derive(Default)]
18pub struct IndexManagerConfig {
19    /// HNSW configuration parameters.
20    pub hnsw: HnswConfig,
21}
22
23/// Owns all index types and provides unified indexing and hybrid search.
24pub struct IndexManager {
25    /// Vector similarity index.
26    pub hnsw: HnswIndex,
27    /// BM25 full-text index for keyword search.
28    pub bm25: Bm25Index,
29    /// Tag and attribute bitmap index.
30    pub bitmap: BitmapIndex,
31    /// Timestamp range index.
32    pub temporal: TemporalIndex,
33    /// Importance score index.
34    pub salience: SalienceIndex,
35}
36
37impl IndexManager {
38    /// Create a new index manager with the given configuration.
39    pub fn new(config: IndexManagerConfig) -> Self {
40        Self {
41            hnsw: HnswIndex::new(config.hnsw),
42            bm25: Bm25Index::new(),
43            bitmap: BitmapIndex::new(),
44            temporal: TemporalIndex::new(),
45            salience: SalienceIndex::new(),
46        }
47    }
48
49    /// Save all indexes to the given directory (bincode format).
50    pub fn save(&self, dir: &Path) -> MenteResult<()> {
51        std::fs::create_dir_all(dir)?;
52        self.hnsw.save(&dir.join("hnsw.bin"))?;
53        self.bm25.save(&dir.join("bm25.bin"))?;
54        self.bitmap.save(&dir.join("bitmap.bin"))?;
55        self.temporal.save(&dir.join("temporal.bin"))?;
56        self.salience.save(&dir.join("salience.bin"))?;
57        Ok(())
58    }
59
60    /// Load all indexes from the given directory. Tries `.bin` first, falls back to `.json`.
61    pub fn load(dir: &Path) -> MenteResult<Self> {
62        let hnsw_path = Self::resolve_path(dir, "hnsw");
63        let hnsw = HnswIndex::load(&hnsw_path, HnswConfig::default().ef_search)?;
64
65        let bm25_bin = dir.join("bm25.bin");
66        let bm25_json = dir.join("bm25.json");
67        let bm25 = if bm25_bin.exists() {
68            Bm25Index::load(&bm25_bin)?
69        } else if bm25_json.exists() {
70            Bm25Index::load(&bm25_json)?
71        } else {
72            Bm25Index::new()
73        };
74
75        let bitmap = BitmapIndex::load(&Self::resolve_path(dir, "bitmap"))?;
76        let temporal = TemporalIndex::load(&Self::resolve_path(dir, "temporal"))?;
77        let salience = SalienceIndex::load(&Self::resolve_path(dir, "salience"))?;
78        Ok(Self {
79            hnsw,
80            bm25,
81            bitmap,
82            temporal,
83            salience,
84        })
85    }
86
87    /// Resolve index file path: prefer `.bin`, fall back to `.json`.
88    fn resolve_path(dir: &Path, name: &str) -> std::path::PathBuf {
89        let bin = dir.join(format!("{name}.bin"));
90        if bin.exists() {
91            bin
92        } else {
93            dir.join(format!("{name}.json"))
94        }
95    }
96
97    /// Index a memory node across all indexes.
98    pub fn index_memory(&self, node: &MemoryNode) {
99        // Vector index
100        if !node.embedding.is_empty() {
101            let _ = self.hnsw.insert(node.id, &node.embedding);
102        }
103
104        // BM25 full-text index
105        if !node.content.is_empty() {
106            self.bm25.insert(node.id, &node.content);
107        }
108
109        // Tag bitmap index
110        for tag in &node.tags {
111            self.bitmap.add_tag(node.id, tag);
112        }
113
114        // Temporal index
115        self.temporal.insert(node.id, node.created_at);
116
117        // Salience index
118        self.salience.insert(node.id, node.salience);
119    }
120
121    /// Remove a memory from all indexes.
122    pub fn remove_memory(&self, id: MemoryId, node: &MemoryNode) {
123        let _ = self.hnsw.remove(id);
124        self.bm25.remove(id);
125        self.bitmap.remove_all(id);
126        self.temporal.remove(id, node.created_at);
127        self.salience.remove(id, node.salience);
128    }
129
130    /// Hybrid search combining vector similarity, BM25 keyword matching,
131    /// tag filtering, time range, and salience.
132    ///
133    /// Strategy:
134    /// 1. Vector search (HNSW) for top candidates
135    /// 2. BM25 keyword search for top candidates
136    /// 3. Merge via Reciprocal Rank Fusion (RRF)
137    /// 4. Filter by tags and time range
138    /// 5. Boost by salience and recency
139    /// 6. Return top k results
140    pub fn hybrid_search(
141        &self,
142        query_embedding: &[f32],
143        tags: Option<&[&str]>,
144        time_range: Option<(Timestamp, Timestamp)>,
145        k: usize,
146    ) -> Vec<(MemoryId, f32)> {
147        self.hybrid_search_with_query(query_embedding, None, tags, time_range, k)
148    }
149
150    /// Hybrid search with an optional text query for BM25 matching.
151    ///
152    /// When `query_text` is provided, BM25 results are merged with vector
153    /// results via RRF. When None, behaves like vector-only search.
154    pub fn hybrid_search_with_query(
155        &self,
156        query_embedding: &[f32],
157        query_text: Option<&str>,
158        tags: Option<&[&str]>,
159        time_range: Option<(Timestamp, Timestamp)>,
160        k: usize,
161    ) -> Vec<(MemoryId, f32)> {
162        if k == 0 {
163            return Vec::new();
164        }
165
166        let fetch_k = k * 4;
167        let rrf_k: f32 = 60.0;
168
169        // Step 1: Vector search candidates
170        let vector_candidates = self.hnsw.search(query_embedding, fetch_k);
171
172        // Step 2: BM25 search candidates (if query text provided and index has docs)
173        let bm25_candidates = match query_text {
174            Some(qt) if !self.bm25.is_empty() => self.bm25.search(qt, fetch_k),
175            _ => Vec::new(),
176        };
177
178        if vector_candidates.is_empty() && bm25_candidates.is_empty() {
179            return Vec::new();
180        }
181
182        // Step 3: Merge via RRF
183        let mut rrf_scores: HashMap<MemoryId, f32> = HashMap::new();
184
185        for (rank, (id, _)) in vector_candidates.iter().enumerate() {
186            *rrf_scores.entry(*id).or_insert(0.0) += 1.0 / (rrf_k + rank as f32);
187        }
188        for (rank, (id, _)) in bm25_candidates.iter().enumerate() {
189            *rrf_scores.entry(*id).or_insert(0.0) += 1.0 / (rrf_k + rank as f32);
190        }
191
192        // Build set of tag-filtered ids (if tags are specified)
193        let tag_filter: Option<HashSet<MemoryId>> = tags.map(|t| {
194            if t.is_empty() {
195                HashSet::new()
196            } else {
197                self.bitmap.query_tags_and(t).into_iter().collect()
198            }
199        });
200
201        // Build set of time-range-filtered ids (if time range is specified)
202        let time_filter: Option<HashSet<MemoryId>> =
203            time_range.map(|(start, end)| self.temporal.range(start, end).into_iter().collect());
204
205        // Step 4: Filter and boost with salience/recency
206        let max_ts = rrf_scores
207            .keys()
208            .filter_map(|id| self.temporal.get_timestamp(*id))
209            .max()
210            .unwrap_or(1) as f64;
211
212        let mut scored: Vec<(MemoryId, f32)> = rrf_scores
213            .into_iter()
214            .filter(|(id, _)| {
215                if let Some(ref tf) = tag_filter
216                    && !tf.contains(id)
217                {
218                    return false;
219                }
220                if let Some(ref trf) = time_filter
221                    && !trf.contains(id)
222                {
223                    return false;
224                }
225                true
226            })
227            .map(|(id, rrf_score)| {
228                let salience = self.salience.get_salience(id).unwrap_or(0.5);
229                let ts = self.temporal.get_timestamp(id).unwrap_or(0) as f64;
230                let recency = if max_ts > 0.0 {
231                    (ts / max_ts) as f32
232                } else {
233                    0.0
234                };
235
236                // RRF is the primary signal, salience and recency are light boosts
237                let combined = rrf_score * 0.7 + salience * 0.05 + recency * 0.02;
238                (id, combined)
239            })
240            .collect();
241
242        // Sort descending by combined score
243        scored.sort_unstable_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
244        scored.truncate(k);
245        scored
246    }
247}
248
249impl Default for IndexManager {
250    fn default() -> Self {
251        Self::new(IndexManagerConfig::default())
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258    use mentedb_core::memory::MemoryType;
259    use mentedb_core::types::AgentId;
260
261    fn make_node(
262        embedding: Vec<f32>,
263        tags: Vec<String>,
264        salience: f32,
265        created_at: u64,
266    ) -> MemoryNode {
267        let mut node = MemoryNode::new(
268            AgentId::new(),
269            MemoryType::Episodic,
270            "test".into(),
271            embedding,
272        );
273        node.tags = tags;
274        node.salience = salience;
275        node.created_at = created_at;
276        node
277    }
278
279    #[test]
280    fn test_index_and_search() {
281        let mgr = IndexManager::default();
282        let node = make_node(vec![1.0, 0.0, 0.0, 0.0], vec!["test".into()], 0.8, 1000);
283        mgr.index_memory(&node);
284
285        let results = mgr.hybrid_search(&[1.0, 0.0, 0.0, 0.0], None, None, 1);
286        assert_eq!(results.len(), 1);
287        assert_eq!(results[0].0, node.id);
288    }
289
290    #[test]
291    fn test_tag_filter() {
292        let mgr = IndexManager::default();
293        let a = make_node(vec![1.0, 0.0, 0.0, 0.0], vec!["alpha".into()], 0.8, 1000);
294        let b = make_node(vec![0.9, 0.1, 0.0, 0.0], vec!["beta".into()], 0.8, 1000);
295        mgr.index_memory(&a);
296        mgr.index_memory(&b);
297
298        let results = mgr.hybrid_search(&[1.0, 0.0, 0.0, 0.0], Some(&["alpha"]), None, 10);
299        assert_eq!(results.len(), 1);
300        assert_eq!(results[0].0, a.id);
301    }
302
303    #[test]
304    fn test_time_filter() {
305        let mgr = IndexManager::default();
306        let a = make_node(vec![1.0, 0.0, 0.0, 0.0], vec![], 0.8, 100);
307        let b = make_node(vec![0.9, 0.1, 0.0, 0.0], vec![], 0.8, 500);
308        mgr.index_memory(&a);
309        mgr.index_memory(&b);
310
311        let results = mgr.hybrid_search(&[1.0, 0.0, 0.0, 0.0], None, Some((400, 600)), 10);
312        assert_eq!(results.len(), 1);
313        assert_eq!(results[0].0, b.id);
314    }
315
316    #[test]
317    fn test_remove_memory() {
318        let mgr = IndexManager::default();
319        let node = make_node(vec![1.0, 0.0, 0.0, 0.0], vec!["t".into()], 0.5, 100);
320        let id = node.id;
321        mgr.index_memory(&node);
322        mgr.remove_memory(id, &node);
323
324        let results = mgr.hybrid_search(&[1.0, 0.0, 0.0, 0.0], None, None, 10);
325        assert!(results.is_empty());
326    }
327
328    #[test]
329    fn test_empty_search() {
330        let mgr = IndexManager::default();
331        let results = mgr.hybrid_search(&[1.0, 0.0], None, None, 5);
332        assert!(results.is_empty());
333    }
334}