oxirs-vec 0.2.4

Vector index abstractions for semantic similarity and AI-augmented querying
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
//! Vamana graph for DiskANN
//!
//! Implements the Vamana graph structure used in Microsoft's DiskANN.
//! Vamana is a navigable small-world graph optimized for approximate nearest
//! neighbor search on disk-based datasets.
//!
//! ## Algorithm
//! - Each node has at most R neighbors (max_degree)
//! - Neighbors are selected using robust pruning to ensure good coverage
//! - Graph supports incremental updates and entry point management
//!
//! ## References
//! - DiskANN: Fast Accurate Billion-point Nearest Neighbor Search on a Single Node
//!   (Jayaram Subramanya et al., NeurIPS 2019)

use crate::diskann::config::PruningStrategy;
use crate::diskann::types::{DiskAnnError, DiskAnnResult, NodeId, VectorId};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, RwLock};

/// A node in the Vamana graph
#[derive(Debug, Clone, Serialize, Deserialize, oxicode::Encode, oxicode::Decode)]
pub struct VamanaNode {
    /// Node ID (internal)
    pub id: NodeId,
    /// Vector ID (external)
    pub vector_id: VectorId,
    /// List of neighbor node IDs
    pub neighbors: Vec<NodeId>,
    /// Maximum degree for this node
    pub max_degree: usize,
}

impl VamanaNode {
    /// Create a new Vamana node
    pub fn new(id: NodeId, vector_id: VectorId, max_degree: usize) -> Self {
        Self {
            id,
            vector_id,
            neighbors: Vec::with_capacity(max_degree),
            max_degree,
        }
    }

    /// Add a neighbor if not already present
    pub fn add_neighbor(&mut self, neighbor_id: NodeId) -> bool {
        if !self.neighbors.contains(&neighbor_id) && self.neighbors.len() < self.max_degree {
            self.neighbors.push(neighbor_id);
            true
        } else {
            false
        }
    }

    /// Remove a neighbor
    pub fn remove_neighbor(&mut self, neighbor_id: NodeId) -> bool {
        if let Some(pos) = self.neighbors.iter().position(|&id| id == neighbor_id) {
            self.neighbors.swap_remove(pos);
            true
        } else {
            false
        }
    }

    /// Check if neighbor limit is reached
    pub fn is_full(&self) -> bool {
        self.neighbors.len() >= self.max_degree
    }

    /// Get number of neighbors
    pub fn degree(&self) -> usize {
        self.neighbors.len()
    }

    /// Replace neighbors with pruned set
    pub fn set_neighbors(&mut self, neighbors: Vec<NodeId>) {
        self.neighbors = neighbors;
        if self.neighbors.len() > self.max_degree {
            self.neighbors.truncate(self.max_degree);
        }
    }
}

/// Vamana graph structure
#[derive(Debug, Clone, Serialize, Deserialize, oxicode::Encode, oxicode::Decode)]
pub struct VamanaGraph {
    /// Graph nodes indexed by NodeId
    nodes: HashMap<NodeId, VamanaNode>,
    /// Mapping from VectorId to NodeId
    vector_to_node: HashMap<VectorId, NodeId>,
    /// Entry points for search (medoids)
    entry_points: Vec<NodeId>,
    /// Maximum degree for nodes
    max_degree: usize,
    /// Pruning strategy
    pruning_strategy: PruningStrategy,
    /// Alpha parameter for pruning
    alpha: f32,
    /// Next available node ID
    next_node_id: NodeId,
}

impl VamanaGraph {
    /// Create a new empty Vamana graph
    pub fn new(max_degree: usize, pruning_strategy: PruningStrategy, alpha: f32) -> Self {
        Self {
            nodes: HashMap::new(),
            vector_to_node: HashMap::new(),
            entry_points: Vec::new(),
            max_degree,
            pruning_strategy,
            alpha,
            next_node_id: 0,
        }
    }

    /// Get number of nodes in graph
    pub fn num_nodes(&self) -> usize {
        self.nodes.len()
    }

    /// Get maximum degree
    pub fn max_degree(&self) -> usize {
        self.max_degree
    }

    /// Get entry points
    pub fn entry_points(&self) -> &[NodeId] {
        &self.entry_points
    }

    /// Set entry points
    pub fn set_entry_points(&mut self, entry_points: Vec<NodeId>) {
        self.entry_points = entry_points;
    }

    /// Add entry point
    pub fn add_entry_point(&mut self, node_id: NodeId) -> DiskAnnResult<()> {
        if !self.nodes.contains_key(&node_id) {
            return Err(DiskAnnError::GraphError {
                message: format!("Node {} does not exist", node_id),
            });
        }
        if !self.entry_points.contains(&node_id) {
            self.entry_points.push(node_id);
        }
        Ok(())
    }

    /// Get node by ID
    pub fn get_node(&self, node_id: NodeId) -> Option<&VamanaNode> {
        self.nodes.get(&node_id)
    }

    /// Get mutable node by ID
    pub fn get_node_mut(&mut self, node_id: NodeId) -> Option<&mut VamanaNode> {
        self.nodes.get_mut(&node_id)
    }

    /// Get node ID by vector ID
    pub fn get_node_id(&self, vector_id: &VectorId) -> Option<NodeId> {
        self.vector_to_node.get(vector_id).copied()
    }

    /// Add a new node to the graph
    pub fn add_node(&mut self, vector_id: VectorId) -> DiskAnnResult<NodeId> {
        if self.vector_to_node.contains_key(&vector_id) {
            return Err(DiskAnnError::GraphError {
                message: format!("Vector {} already exists", vector_id),
            });
        }

        let node_id = self.next_node_id;
        self.next_node_id += 1;

        let node = VamanaNode::new(node_id, vector_id.clone(), self.max_degree);
        self.nodes.insert(node_id, node);
        self.vector_to_node.insert(vector_id, node_id);

        // If this is the first node, make it an entry point
        if self.entry_points.is_empty() {
            self.entry_points.push(node_id);
        }

        Ok(node_id)
    }

    /// Remove a node from the graph
    pub fn remove_node(&mut self, node_id: NodeId) -> DiskAnnResult<()> {
        let node = self
            .nodes
            .remove(&node_id)
            .ok_or_else(|| DiskAnnError::GraphError {
                message: format!("Node {} does not exist", node_id),
            })?;

        self.vector_to_node.remove(&node.vector_id);

        // Remove from entry points
        self.entry_points.retain(|&id| id != node_id);

        // Remove all edges pointing to this node
        for other_node in self.nodes.values_mut() {
            other_node.remove_neighbor(node_id);
        }

        Ok(())
    }

    /// Add a directed edge from source to target
    pub fn add_edge(&mut self, source: NodeId, target: NodeId) -> DiskAnnResult<bool> {
        if source == target {
            return Ok(false); // Self-loops not allowed
        }

        // Check target exists first
        if !self.nodes.contains_key(&target) {
            return Err(DiskAnnError::GraphError {
                message: format!("Target node {} does not exist", target),
            });
        }

        // Then get mutable reference to source
        let source_node = self
            .get_node_mut(source)
            .ok_or_else(|| DiskAnnError::GraphError {
                message: format!("Source node {} does not exist", source),
            })?;

        Ok(source_node.add_neighbor(target))
    }

    /// Remove a directed edge from source to target
    pub fn remove_edge(&mut self, source: NodeId, target: NodeId) -> DiskAnnResult<bool> {
        let source_node = self
            .get_node_mut(source)
            .ok_or_else(|| DiskAnnError::GraphError {
                message: format!("Source node {} does not exist", source),
            })?;

        Ok(source_node.remove_neighbor(target))
    }

    /// Prune neighbors of a node using the configured strategy
    ///
    /// # Arguments
    /// * `node_id` - Node whose neighbors to prune
    /// * `candidates` - Candidate neighbors with their distances
    /// * `distance_fn` - Function to compute distance between node IDs
    pub fn prune_neighbors<F>(
        &mut self,
        node_id: NodeId,
        candidates: &[(NodeId, f32)],
        distance_fn: &F,
    ) -> DiskAnnResult<()>
    where
        F: Fn(NodeId, NodeId) -> f32,
    {
        if candidates.is_empty() {
            return Ok(());
        }

        let pruned = match self.pruning_strategy {
            PruningStrategy::Alpha => {
                self.alpha_prune(node_id, candidates, self.max_degree, self.alpha)
            }
            PruningStrategy::Robust => self.robust_prune(
                node_id,
                candidates,
                distance_fn,
                self.max_degree,
                self.alpha,
            ),
            PruningStrategy::Hybrid => {
                // Use robust pruning for first half, alpha for second half
                let mid = self.max_degree / 2;
                let mut robust =
                    self.robust_prune(node_id, candidates, distance_fn, mid, self.alpha);

                // Get remaining candidates
                let robust_set: HashSet<_> = robust.iter().copied().collect();
                let remaining: Vec<_> = candidates
                    .iter()
                    .filter(|(id, _)| !robust_set.contains(id))
                    .copied()
                    .collect();

                let mut alpha =
                    self.alpha_prune(node_id, &remaining, self.max_degree - mid, self.alpha);
                robust.append(&mut alpha);
                robust
            }
        };

        // Update node's neighbors
        if let Some(node) = self.get_node_mut(node_id) {
            node.set_neighbors(pruned);
        }

        Ok(())
    }

    /// Alpha pruning: select R closest neighbors within alpha * distance to closest
    fn alpha_prune(
        &self,
        _node_id: NodeId,
        candidates: &[(NodeId, f32)],
        max_neighbors: usize,
        alpha: f32,
    ) -> Vec<NodeId> {
        if candidates.is_empty() {
            return Vec::new();
        }

        let mut sorted = candidates.to_vec();
        sorted.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));

        let threshold = sorted[0].1 * alpha;
        sorted
            .into_iter()
            .filter(|(_, dist)| *dist <= threshold)
            .take(max_neighbors)
            .map(|(id, _)| id)
            .collect()
    }

    /// Robust pruning: diversified neighbor selection for better graph connectivity
    fn robust_prune<F>(
        &self,
        node_id: NodeId,
        candidates: &[(NodeId, f32)],
        distance_fn: &F,
        max_neighbors: usize,
        alpha: f32,
    ) -> Vec<NodeId>
    where
        F: Fn(NodeId, NodeId) -> f32,
    {
        if candidates.is_empty() {
            return Vec::new();
        }

        let mut sorted = candidates.to_vec();
        sorted.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));

        let mut selected = Vec::new();
        let mut selected_set = HashSet::new();

        for (candidate_id, candidate_dist) in &sorted {
            if selected.len() >= max_neighbors {
                break;
            }

            if *candidate_id == node_id || selected_set.contains(candidate_id) {
                continue;
            }

            // Check if candidate is closer to query than to any selected neighbor
            let mut should_add = true;
            for &selected_id in &selected {
                let inter_distance = distance_fn(*candidate_id, selected_id);
                if inter_distance < alpha * candidate_dist {
                    should_add = false;
                    break;
                }
            }

            if should_add {
                selected.push(*candidate_id);
                selected_set.insert(*candidate_id);
            }
        }

        // If we don't have enough neighbors, add closest remaining ones
        if selected.len() < max_neighbors {
            for (candidate_id, _) in &sorted {
                if selected.len() >= max_neighbors {
                    break;
                }
                if *candidate_id != node_id && !selected_set.contains(candidate_id) {
                    selected.push(*candidate_id);
                    selected_set.insert(*candidate_id);
                }
            }
        }

        selected
    }

    /// Get all neighbors of a node
    pub fn get_neighbors(&self, node_id: NodeId) -> Option<&[NodeId]> {
        self.nodes
            .get(&node_id)
            .map(|node| node.neighbors.as_slice())
    }

    /// Get graph statistics
    pub fn stats(&self) -> GraphStats {
        let total_nodes = self.nodes.len();
        let total_edges: usize = self.nodes.values().map(|n| n.degree()).sum();
        let avg_degree = if total_nodes > 0 {
            total_edges as f64 / total_nodes as f64
        } else {
            0.0
        };

        let max_degree_actual = self.nodes.values().map(|n| n.degree()).max().unwrap_or(0);
        let min_degree_actual = self.nodes.values().map(|n| n.degree()).min().unwrap_or(0);

        GraphStats {
            num_nodes: total_nodes,
            num_edges: total_edges,
            avg_degree,
            max_degree_configured: self.max_degree,
            max_degree_actual,
            min_degree_actual,
            num_entry_points: self.entry_points.len(),
        }
    }

    /// Validate graph integrity
    pub fn validate(&self) -> DiskAnnResult<()> {
        // Check all edges point to existing nodes
        for (node_id, node) in &self.nodes {
            for &neighbor_id in &node.neighbors {
                if !self.nodes.contains_key(&neighbor_id) {
                    return Err(DiskAnnError::GraphError {
                        message: format!(
                            "Node {} has edge to non-existent node {}",
                            node_id, neighbor_id
                        ),
                    });
                }
            }

            // Check degree constraint
            if node.neighbors.len() > node.max_degree {
                return Err(DiskAnnError::GraphError {
                    message: format!(
                        "Node {} has {} neighbors, exceeding max degree {}",
                        node_id,
                        node.neighbors.len(),
                        node.max_degree
                    ),
                });
            }

            // Check for self-loops
            if node.neighbors.contains(node_id) {
                return Err(DiskAnnError::GraphError {
                    message: format!("Node {} has self-loop", node_id),
                });
            }

            // Check for duplicates
            let mut seen = HashSet::new();
            for &neighbor_id in &node.neighbors {
                if !seen.insert(neighbor_id) {
                    return Err(DiskAnnError::GraphError {
                        message: format!("Node {} has duplicate neighbor {}", node_id, neighbor_id),
                    });
                }
            }
        }

        // Check entry points exist
        for &entry_id in &self.entry_points {
            if !self.nodes.contains_key(&entry_id) {
                return Err(DiskAnnError::GraphError {
                    message: format!("Entry point {} does not exist", entry_id),
                });
            }
        }

        Ok(())
    }
}

impl Default for VamanaGraph {
    fn default() -> Self {
        Self::new(64, PruningStrategy::Robust, 1.2)
    }
}

/// Graph statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GraphStats {
    pub num_nodes: usize,
    pub num_edges: usize,
    pub avg_degree: f64,
    pub max_degree_configured: usize,
    pub max_degree_actual: usize,
    pub min_degree_actual: usize,
    pub num_entry_points: usize,
}

/// Thread-safe wrapper for VamanaGraph
#[derive(Debug, Clone)]
pub struct VamanaGraphHandle {
    graph: Arc<RwLock<VamanaGraph>>,
}

impl VamanaGraphHandle {
    pub fn new(graph: VamanaGraph) -> Self {
        Self {
            graph: Arc::new(RwLock::new(graph)),
        }
    }

    pub fn read<F, R>(&self, f: F) -> DiskAnnResult<R>
    where
        F: FnOnce(&VamanaGraph) -> R,
    {
        let graph = self
            .graph
            .read()
            .map_err(|_| DiskAnnError::ConcurrentModification)?;
        Ok(f(&graph))
    }

    pub fn write<F, R>(&self, f: F) -> DiskAnnResult<R>
    where
        F: FnOnce(&mut VamanaGraph) -> R,
    {
        let mut graph = self
            .graph
            .write()
            .map_err(|_| DiskAnnError::ConcurrentModification)?;
        Ok(f(&mut graph))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

    #[test]
    fn test_vamana_node() {
        let mut node = VamanaNode::new(0, "vec0".to_string(), 3);
        assert_eq!(node.id, 0);
        assert_eq!(node.degree(), 0);
        assert!(!node.is_full());

        assert!(node.add_neighbor(1));
        assert!(node.add_neighbor(2));
        assert!(node.add_neighbor(3));
        assert_eq!(node.degree(), 3);
        assert!(node.is_full());

        assert!(!node.add_neighbor(4)); // Full
        assert!(!node.add_neighbor(1)); // Duplicate

        assert!(node.remove_neighbor(2));
        assert_eq!(node.degree(), 2);
        assert!(!node.remove_neighbor(2)); // Not present
    }

    #[test]
    fn test_vamana_graph_basic() -> Result<()> {
        let mut graph = VamanaGraph::new(3, PruningStrategy::Alpha, 1.2);
        assert_eq!(graph.num_nodes(), 0);

        let node0 = graph.add_node("vec0".to_string())?;
        let node1 = graph.add_node("vec1".to_string())?;
        assert_eq!(graph.num_nodes(), 2);

        let __val = graph.add_edge(node0, node1)?;
        assert!(__val);
        assert!(!graph.add_edge(node0, node0).expect("test value")); // Self-loop

        let neighbors = graph
            .get_neighbors(node0)
            .expect("node0 should have neighbors");
        assert_eq!(neighbors.len(), 1);
        assert_eq!(neighbors[0], node1);
        Ok(())
    }

    #[test]
    fn test_alpha_pruning() {
        let graph = VamanaGraph::new(3, PruningStrategy::Alpha, 1.5);

        let candidates = vec![(1, 1.0), (2, 1.2), (3, 1.4), (4, 2.0), (5, 3.0)];

        let pruned = graph.alpha_prune(0, &candidates, 3, 1.5);
        assert!(pruned.len() <= 3);
        assert!(pruned.contains(&1)); // Closest
    }

    #[test]
    fn test_robust_pruning() {
        let graph = VamanaGraph::new(3, PruningStrategy::Robust, 1.2);

        let candidates = vec![(1, 1.0), (2, 1.5), (3, 2.0)];

        let distance_fn = |a: NodeId, b: NodeId| (a as i32 - b as i32).abs() as f32;
        let pruned = graph.robust_prune(0, &candidates, &distance_fn, 3, 1.2);

        assert!(pruned.len() <= 3);
        assert!(pruned.contains(&1));
    }

    #[test]
    fn test_entry_points() -> Result<()> {
        let mut graph = VamanaGraph::new(3, PruningStrategy::Alpha, 1.2);
        let _node0 = graph.add_node("vec0".to_string())?;
        let node1 = graph.add_node("vec1".to_string())?;

        assert_eq!(graph.entry_points().len(), 1); // First node is entry point

        graph.add_entry_point(node1)?;
        assert_eq!(graph.entry_points().len(), 2);
        Ok(())
    }

    #[test]
    fn test_graph_validation() -> Result<()> {
        let mut graph = VamanaGraph::new(3, PruningStrategy::Alpha, 1.2);
        let node0 = graph.add_node("vec0".to_string())?;
        let node1 = graph.add_node("vec1".to_string())?;

        graph.add_edge(node0, node1)?;
        assert!(graph.validate().is_ok());

        // Remove node1 but leave edge - should fail validation
        graph.nodes.remove(&node1);
        assert!(graph.validate().is_err());
        Ok(())
    }

    #[test]
    fn test_graph_stats() -> Result<()> {
        let mut graph = VamanaGraph::new(3, PruningStrategy::Alpha, 1.2);
        let node0 = graph.add_node("vec0".to_string())?;
        let node1 = graph.add_node("vec1".to_string())?;
        let node2 = graph.add_node("vec2".to_string())?;

        graph.add_edge(node0, node1)?;
        graph.add_edge(node0, node2)?;
        graph.add_edge(node1, node2)?;

        let stats = graph.stats();
        assert_eq!(stats.num_nodes, 3);
        assert_eq!(stats.num_edges, 3);
        assert!(stats.avg_degree > 0.0);
        Ok(())
    }

    #[test]
    fn test_remove_node() -> Result<()> {
        let mut graph = VamanaGraph::new(3, PruningStrategy::Alpha, 1.2);
        let node0 = graph.add_node("vec0".to_string())?;
        let node1 = graph.add_node("vec1".to_string())?;

        graph.add_edge(node0, node1)?;
        assert_eq!(graph.num_nodes(), 2);

        graph.remove_node(node1)?;
        assert_eq!(graph.num_nodes(), 1);
        assert!(graph.get_neighbors(node0).expect("test value").is_empty());
        Ok(())
    }

    #[test]
    fn test_thread_safe_handle() -> Result<()> {
        let graph = VamanaGraph::new(3, PruningStrategy::Alpha, 1.2);
        let handle = VamanaGraphHandle::new(graph);

        let node_id = handle.write(|g| g.add_node("vec0".to_string()))??;
        let count = handle.read(|g| g.num_nodes())?;

        assert_eq!(count, 1);
        assert_eq!(node_id, 0);
        Ok(())
    }
}