File size: 2,764 Bytes
f4f166e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
//! Ingestion-side vector index (plan E2.7 v1): exact cosine top-k over leaf
//! vectors written during digestion. Ingestion-ONLY by construction - the
//! recall path (recall.rs / BM25) never touches this module, honoring the
//! PRD rule that the embedder's representations are not used at query time.
//! Backend swap to true HNSW later keeps this API.

use crate::error::{Error, Result};

#[derive(Default)]
pub struct VectorIndex {
    dim: usize,
    entries: Vec<(String, Vec<f32>)>,
}

impl VectorIndex {
    pub fn new(dim: usize) -> Self {
        Self { dim, entries: Vec::new() }
    }

    pub fn len(&self) -> usize {
        self.entries.len()
    }

    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Approximate resident footprint (PRD section 7 RAM accounting).
    pub fn approx_bytes(&self) -> usize {
        self.entries.iter().map(|(id, v)| id.len() + v.len() * 4 + 48).sum()
    }

    pub fn add(&mut self, id: &str, vec: Vec<f32>) -> Result<()> {
        if self.dim == 0 {
            self.dim = vec.len();
        }
        if vec.len() != self.dim {
            return Err(Error::Model(format!(
                "vector dim {} != index dim {}",
                vec.len(),
                self.dim
            )));
        }
        self.entries.push((id.to_string(), vec));
        Ok(())
    }

    pub fn search(&self, query: &[f32], k: usize) -> Vec<(String, f32)> {
        if query.len() != self.dim || self.entries.is_empty() {
            return Vec::new();
        }
        let qn: f32 = query.iter().map(|x| x * x).sum::<f32>().sqrt().max(1e-9);
        let mut scored: Vec<(String, f32)> = self
            .entries
            .iter()
            .map(|(id, v)| {
                let dot: f32 = query.iter().zip(v).map(|(a, b)| a * b).sum();
                let vn: f32 = v.iter().map(|x| x * x).sum::<f32>().sqrt().max(1e-9);
                (id.clone(), dot / (qn * vn))
            })
            .collect();
        scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
        scored.truncate(k);
        scored
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn nearest_neighbor_ranking() {
        let mut ix = VectorIndex::new(3);
        ix.add("cat", vec![1.0, 0.0, 0.0]).unwrap();
        ix.add("dog", vec![0.9, 0.1, 0.0]).unwrap();
        ix.add("car", vec![0.0, 0.0, 1.0]).unwrap();
        let hits = ix.search(&[0.95, 0.05, 0.0], 2);
        assert_eq!(hits.len(), 2);
        assert_eq!(hits[0].0, "cat");
        assert!(matches!(hits[1].0.as_str(), "dog"));
        assert!(ix.search(&[1.0, 0.0, 0.0], 3)[2].0 == "car");
        assert!(ix.approx_bytes() > 0);
        assert!(ix.add("bad", vec![1.0]).is_err());
    }
}