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. Clear this id's existing tags first, so a re-index
110        // after an edit (e.g. un-pinning, which removes scope:always and re-stores
111        // the node) reflects the node's CURRENT tags exactly, not the union across
112        // every stored version. Without this, a removed tag lingers in the index
113        // and over-counts on query_tag. Harmless no-op on a first insert.
114        self.bitmap.remove_all(node.id);
115        for tag in &node.tags {
116            self.bitmap.add_tag(node.id, tag);
117        }
118
119        // Temporal index
120        self.temporal.insert(node.id, node.created_at);
121
122        // Salience index
123        self.salience.insert(node.id, node.salience);
124    }
125
126    /// True when the memory's vector is indexed and live.
127    pub fn contains_vector(&self, id: MemoryId) -> bool {
128        self.hnsw.contains(id)
129    }
130
131    /// All live vector indexed memory ids.
132    pub fn vector_ids(&self) -> Vec<MemoryId> {
133        self.hnsw.ids()
134    }
135
136    /// Tombstone a vector whose backing page no longer exists; used by open
137    /// time reconciliation when a snapshot is newer than the last forget.
138    pub fn remove_vector_only(&self, id: MemoryId) {
139        let _ = self.hnsw.remove(id);
140        self.bm25.remove(id);
141    }
142
143    /// Remove a memory from all indexes.
144    pub fn remove_memory(&self, id: MemoryId, node: &MemoryNode) {
145        let _ = self.hnsw.remove(id);
146        self.bm25.remove(id);
147        self.bitmap.remove_all(id);
148        self.temporal.remove(id, node.created_at);
149        self.salience.remove(id, node.salience);
150    }
151
152    /// Hybrid search combining vector similarity, BM25 keyword matching,
153    /// tag filtering, time range, and salience.
154    ///
155    /// Strategy:
156    /// 1. Vector search (HNSW) for top candidates
157    /// 2. BM25 keyword search for top candidates
158    /// 3. Merge via Reciprocal Rank Fusion (RRF)
159    /// 4. Filter by tags and time range
160    /// 5. Boost by salience and recency
161    /// 6. Return top k results
162    pub fn hybrid_search(
163        &self,
164        query_embedding: &[f32],
165        tags: Option<&[&str]>,
166        time_range: Option<(Timestamp, Timestamp)>,
167        k: usize,
168    ) -> Vec<(MemoryId, f32)> {
169        self.hybrid_search_with_query(query_embedding, None, tags, time_range, k)
170    }
171
172    /// Hybrid search with an optional text query for BM25 matching.
173    ///
174    /// When `query_text` is provided, BM25 results are merged with vector
175    /// results via RRF. When None, behaves like vector-only search.
176    pub fn hybrid_search_with_query(
177        &self,
178        query_embedding: &[f32],
179        query_text: Option<&str>,
180        tags: Option<&[&str]>,
181        time_range: Option<(Timestamp, Timestamp)>,
182        k: usize,
183    ) -> Vec<(MemoryId, f32)> {
184        self.hybrid_search_with_query_mode(query_embedding, query_text, tags, false, time_range, k)
185    }
186
187    /// Hybrid search with configurable tag mode (AND vs OR).
188    pub fn hybrid_search_with_query_mode(
189        &self,
190        query_embedding: &[f32],
191        query_text: Option<&str>,
192        tags: Option<&[&str]>,
193        tags_or: bool,
194        time_range: Option<(Timestamp, Timestamp)>,
195        k: usize,
196    ) -> Vec<(MemoryId, f32)> {
197        if k == 0 {
198            return Vec::new();
199        }
200
201        // Build tag filter set (if tags are specified)
202        let tag_filter: Option<HashSet<MemoryId>> = tags.map(|t| {
203            if t.is_empty() {
204                HashSet::new()
205            } else if tags_or {
206                self.bitmap.query_tags_or(t).into_iter().collect()
207            } else {
208                self.bitmap.query_tags_and(t).into_iter().collect()
209            }
210        });
211
212        // Build time-range filter set
213        let time_filter: Option<HashSet<MemoryId>> =
214            time_range.map(|(start, end)| self.temporal.range(start, end).into_iter().collect());
215
216        // Combine filters into a single candidate set
217        let candidate_set: Option<HashSet<MemoryId>> = match (&tag_filter, &time_filter) {
218            (Some(tf), Some(trf)) => Some(tf.intersection(trf).copied().collect()),
219            (Some(tf), None) => Some(tf.clone()),
220            (None, Some(trf)) => Some(trf.clone()),
221            (None, None) => None,
222        };
223
224        // Pre-filtered path: when we have a candidate set and it's reasonably sized,
225        // do brute-force search directly over the candidates instead of global search + post-filter.
226        // This is critical for OR-tag queries with many tags where global top-k misses most matches.
227        let use_prefilter = candidate_set.as_ref().is_some_and(|cs| {
228            let cs_len = cs.len();
229            // Use pre-filter when candidate set is non-trivial but manageable for brute-force
230            // (up to 500K is fine — brute-force cosine on 384-dim vectors is fast)
231            cs_len > 0 && cs_len <= 500_000
232        });
233
234        let fetch_k = k * 4;
235        let rrf_k: f32 = 60.0;
236
237        let (vector_candidates, bm25_candidates) = if use_prefilter {
238            let cs = candidate_set.as_ref().unwrap();
239            let vc = self.hnsw.search_filtered(query_embedding, cs, fetch_k);
240            let bc = match query_text {
241                Some(qt) if !self.bm25.is_empty() => self.bm25.search_filtered(qt, fetch_k, cs),
242                _ => Vec::new(),
243            };
244            (vc, bc)
245        } else {
246            let vc = self.hnsw.search(query_embedding, fetch_k);
247            let bc = match query_text {
248                Some(qt) if !self.bm25.is_empty() => self.bm25.search(qt, fetch_k),
249                _ => Vec::new(),
250            };
251            (vc, bc)
252        };
253
254        if vector_candidates.is_empty() && bm25_candidates.is_empty() {
255            return Vec::new();
256        }
257
258        // Merge via RRF
259        let mut rrf_scores: HashMap<MemoryId, f32> = HashMap::new();
260
261        for (rank, (id, _)) in vector_candidates.iter().enumerate() {
262            *rrf_scores.entry(*id).or_insert(0.0) += 1.0 / (rrf_k + rank as f32);
263        }
264        for (rank, (id, _)) in bm25_candidates.iter().enumerate() {
265            *rrf_scores.entry(*id).or_insert(0.0) += 1.0 / (rrf_k + rank as f32);
266        }
267
268        // Post-filter only needed when NOT using pre-filter path
269        let mut scored: Vec<(MemoryId, f32)> = rrf_scores
270            .into_iter()
271            .filter(|(id, _)| {
272                if !use_prefilter {
273                    if let Some(ref tf) = tag_filter
274                        && !tf.contains(id)
275                    {
276                        return false;
277                    }
278                    if let Some(ref trf) = time_filter
279                        && !trf.contains(id)
280                    {
281                        return false;
282                    }
283                }
284                true
285            })
286            .map(|(id, rrf_score)| {
287                let salience = self.salience.get_salience(id).unwrap_or(0.5);
288                let recency = 0.5f32;
289
290                let combined = rrf_score * 0.7 + salience * 0.05 + recency * 0.02;
291                (id, combined)
292            })
293            .collect();
294
295        scored.sort_unstable_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
296        scored.truncate(k);
297        scored
298    }
299}
300
301impl Default for IndexManager {
302    fn default() -> Self {
303        Self::new(IndexManagerConfig::default())
304    }
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310    use mentedb_core::memory::MemoryType;
311    use mentedb_core::types::AgentId;
312
313    fn make_node(
314        embedding: Vec<f32>,
315        tags: Vec<String>,
316        salience: f32,
317        created_at: u64,
318    ) -> MemoryNode {
319        let mut node = MemoryNode::new(
320            AgentId::new(),
321            MemoryType::Episodic,
322            "test".into(),
323            embedding,
324        );
325        node.tags = tags;
326        node.salience = salience;
327        node.created_at = created_at;
328        node
329    }
330
331    #[test]
332    fn test_index_and_search() {
333        let mgr = IndexManager::default();
334        let node = make_node(vec![1.0, 0.0, 0.0, 0.0], vec!["test".into()], 0.8, 1000);
335        mgr.index_memory(&node);
336
337        let results = mgr.hybrid_search(&[1.0, 0.0, 0.0, 0.0], None, None, 1);
338        assert_eq!(results.len(), 1);
339        assert_eq!(results[0].0, node.id);
340    }
341
342    #[test]
343    fn test_tag_filter() {
344        let mgr = IndexManager::default();
345        let a = make_node(vec![1.0, 0.0, 0.0, 0.0], vec!["alpha".into()], 0.8, 1000);
346        let b = make_node(vec![0.9, 0.1, 0.0, 0.0], vec!["beta".into()], 0.8, 1000);
347        mgr.index_memory(&a);
348        mgr.index_memory(&b);
349
350        let results = mgr.hybrid_search(&[1.0, 0.0, 0.0, 0.0], Some(&["alpha"]), None, 10);
351        assert_eq!(results.len(), 1);
352        assert_eq!(results[0].0, a.id);
353    }
354
355    #[test]
356    fn test_time_filter() {
357        let mgr = IndexManager::default();
358        let a = make_node(vec![1.0, 0.0, 0.0, 0.0], vec![], 0.8, 100);
359        let b = make_node(vec![0.9, 0.1, 0.0, 0.0], vec![], 0.8, 500);
360        mgr.index_memory(&a);
361        mgr.index_memory(&b);
362
363        let results = mgr.hybrid_search(&[1.0, 0.0, 0.0, 0.0], None, Some((400, 600)), 10);
364        assert_eq!(results.len(), 1);
365        assert_eq!(results[0].0, b.id);
366    }
367
368    #[test]
369    fn test_remove_memory() {
370        let mgr = IndexManager::default();
371        let node = make_node(vec![1.0, 0.0, 0.0, 0.0], vec!["t".into()], 0.5, 100);
372        let id = node.id;
373        mgr.index_memory(&node);
374        mgr.remove_memory(id, &node);
375
376        let results = mgr.hybrid_search(&[1.0, 0.0, 0.0, 0.0], None, None, 10);
377        assert!(results.is_empty());
378    }
379
380    #[test]
381    fn test_empty_search() {
382        let mgr = IndexManager::default();
383        let results = mgr.hybrid_search(&[1.0, 0.0], None, None, 5);
384        assert!(results.is_empty());
385    }
386}