Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,8 @@ members = [
"crates/ruvllm_retrieval_diffusion",
# RAIRS IVF: Redundant Assignment + Amplified Inverse Residual (ADR-193)
"crates/ruvector-rairs",
# GCVS: Graph-Coherence Vector Search with coherence-gated BFS (ADR-194)
"crates/ruvector-gcvs",
]
resolver = "2"

Expand Down
45 changes: 45 additions & 0 deletions crates/ruvector-gcvs/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
[package]
name = "ruvector-gcvs"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true
repository.workspace = true
description = "Graph-Coherence Vector Search: ANN retrieval augmented with coherence-gated graph traversal"

[[bin]]
name = "benchmark"
path = "src/main.rs"

[features]
default = []
rayon = ["dep:rayon"]

[dependencies]
thiserror = { workspace = true }
rand = { workspace = true }
rand_distr = { workspace = true }
rayon = { workspace = true, optional = true }
serde = { workspace = true }
serde_json = { workspace = true }

[dev-dependencies]
rand = { workspace = true }

[lints.rust]
unexpected_cfgs = { level = "allow", priority = -1 }
unused_imports = "allow"
dead_code = "allow"
unused_variables = "allow"
unused_mut = "allow"
missing_docs = "allow"

[lints.clippy]
pedantic = { level = "allow", priority = -2 }
correctness = { level = "deny", priority = -1 }
suspicious = { level = "deny", priority = -1 }
too_many_arguments = "allow"
cast_possible_truncation = "allow"
cast_precision_loss = "allow"
cast_sign_loss = "allow"
float_cmp = "allow"
15 changes: 15 additions & 0 deletions crates/ruvector-gcvs/src/distance.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/// L2 squared distance between two vectors.
pub fn l2_sq(a: &[f32], b: &[f32]) -> f32 {
a.iter().zip(b.iter()).map(|(x, y)| (x - y) * (x - y)).sum()
}

/// Cosine similarity in [-1, 1]. Returns 0 for zero vectors.
pub fn cosine(a: &[f32], b: &[f32]) -> f32 {
let dot: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
let na: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
let nb: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
if na < 1e-9 || nb < 1e-9 {
return 0.0;
}
(dot / (na * nb)).clamp(-1.0, 1.0)
}
61 changes: 61 additions & 0 deletions crates/ruvector-gcvs/src/flat.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/// Variant 1 — FlatSearch (baseline).
///
/// Brute-force cosine similarity scan over all stored vectors.
/// O(N·D) per query; exact recall = 100% by definition when no graph is needed.
use crate::{distance::cosine, GcvsError, GcvsIndex, Hit, Result};
use std::collections::HashMap;

pub struct FlatSearch {
dim: usize,
vectors: HashMap<usize, Vec<f32>>,
}

impl FlatSearch {
pub fn new(dim: usize) -> Self {
Self {
dim,
vectors: HashMap::new(),
}
}
}

impl GcvsIndex for FlatSearch {
fn insert(&mut self, id: usize, vector: Vec<f32>) -> Result<()> {
if vector.len() != self.dim {
return Err(GcvsError::DimMismatch {
expected: self.dim,
got: vector.len(),
});
}
self.vectors.insert(id, vector);
Ok(())
}

fn search(&self, query: &[f32], k: usize) -> Result<Vec<Hit>> {
if k == 0 {
return Err(GcvsError::InvalidK);
}
if self.vectors.is_empty() {
return Err(GcvsError::Empty);
}
let mut scored: Vec<Hit> = self
.vectors
.iter()
.map(|(&id, v)| Hit {
id,
score: cosine(query, v),
})
.collect();
scored.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap());
scored.truncate(k);
Ok(scored)
}

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

fn name(&self) -> &'static str {
"FlatSearch (baseline)"
}
}
31 changes: 31 additions & 0 deletions crates/ruvector-gcvs/src/graph.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
use std::collections::HashMap;

/// Sparse adjacency list graph over vector IDs.
#[derive(Default, Clone)]
pub struct Graph {
/// edges[id] = list of neighbour ids
edges: HashMap<usize, Vec<usize>>,
}

impl Graph {
pub fn new() -> Self {
Self::default()
}

pub fn add_edge(&mut self, from: usize, to: usize) {
self.edges.entry(from).or_default().push(to);
self.edges.entry(to).or_default().push(from);
}

pub fn neighbours(&self, id: usize) -> &[usize] {
self.edges.get(&id).map(|v| v.as_slice()).unwrap_or(&[])
}

pub fn edge_count(&self) -> usize {
self.edges.values().map(|v| v.len()).sum::<usize>() / 2
}

pub fn node_count(&self) -> usize {
self.edges.len()
}
}
110 changes: 110 additions & 0 deletions crates/ruvector-gcvs/src/graph_aug.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/// Variant 2 — GraphAugSearch.
///
/// Step 1: vector scan for seed candidates (top seed_k by cosine similarity).
/// Step 2: BFS through the graph up to `bfs_depth` hops, collecting additional candidates.
/// Step 3: re-rank all candidates by exact cosine similarity, return top-k.
///
/// Graph edges encode semantic relationships beyond raw embedding distance —
/// e.g., cross-cluster knowledge graph edges or agent memory associations.
/// This finds results that are reachable through the graph but not the nearest
/// vectors in embedding space.
use crate::{distance::cosine, graph::Graph, GcvsError, GcvsIndex, Hit, Result};
use std::collections::{HashMap, HashSet, VecDeque};

pub struct GraphAugSearch {
dim: usize,
vectors: HashMap<usize, Vec<f32>>,
graph: Graph,
seed_k: usize,
bfs_depth: usize,
}

impl GraphAugSearch {
/// `seed_k` — number of vector-scan seeds before BFS expansion.
/// `bfs_depth` — maximum BFS hop depth from each seed.
pub fn new(dim: usize, seed_k: usize, bfs_depth: usize) -> Self {
Self {
dim,
vectors: HashMap::new(),
graph: Graph::new(),
seed_k,
bfs_depth,
}
}

pub fn add_edge(&mut self, from: usize, to: usize) {
self.graph.add_edge(from, to);
}

fn bfs_expand(&self, seeds: &[usize], max_depth: usize) -> HashSet<usize> {
let mut visited: HashSet<usize> = seeds.iter().copied().collect();
let mut queue: VecDeque<(usize, usize)> = seeds.iter().map(|&s| (s, 0usize)).collect();
while let Some((node, depth)) = queue.pop_front() {
if depth >= max_depth {
continue;
}
for &nb in self.graph.neighbours(node) {
if visited.insert(nb) {
queue.push_back((nb, depth + 1));
}
}
}
visited
}
}

impl GcvsIndex for GraphAugSearch {
fn insert(&mut self, id: usize, vector: Vec<f32>) -> Result<()> {
if vector.len() != self.dim {
return Err(GcvsError::DimMismatch {
expected: self.dim,
got: vector.len(),
});
}
self.vectors.insert(id, vector);
Ok(())
}

fn search(&self, query: &[f32], k: usize) -> Result<Vec<Hit>> {
if k == 0 {
return Err(GcvsError::InvalidK);
}
if self.vectors.is_empty() {
return Err(GcvsError::Empty);
}

// Step 1: vector scan for seeds.
let mut scored: Vec<(usize, f32)> = self
.vectors
.iter()
.map(|(&id, v)| (id, cosine(query, v)))
.collect();
scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
let seed_ids: Vec<usize> = scored.iter().take(self.seed_k).map(|&(id, _)| id).collect();

// Step 2: BFS expansion.
let candidate_ids = self.bfs_expand(&seed_ids, self.bfs_depth);

// Step 3: re-rank expanded candidate set.
let mut candidates: Vec<Hit> = candidate_ids
.into_iter()
.filter_map(|id| {
self.vectors.get(&id).map(|v| Hit {
id,
score: cosine(query, v),
})
})
.collect();
candidates.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap());
candidates.truncate(k);
Ok(candidates)
}

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

fn name(&self) -> &'static str {
"GraphAugSearch (BFS expansion)"
}
}
Loading
Loading