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