alter_ego / serving /src /vector_index.rs
geraldaton20's picture
initial upload: source code (no build artifacts)
f4f166e verified
Raw History Blame Contribute Delete
2.76 kB
//! 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());
}
}