Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

feat(vecstore): HNSW-accelerated cosine search scaffold (moat-foundation)

FABIOTESS5ba2e7833b64
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e6a03437..e9d69e6f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,7 @@ All notable changes to Open Ontologies are documented here.
## [Unreleased]
### Added
+- **HNSW-accelerated cosine search scaffold** (the "vector-index moat"). New optional `instant-distance` dependency (gated behind the existing `embeddings` feature, no impact on default builds) and a new `src/hnsw_index.rs` module wrapping the HNSW algorithm (Malkov & Yashunin, TPAMI 2020). `VecStore` grows a `search_cosine_hnsw(query, top_k)` method that builds the index lazily on first call and rebuilds whenever the store is mutated; the existing `search_cosine` brute-force linear scan is unchanged and continues to work without HNSW (zero regression risk). Strategic context: per the May 2026 ecosystem research, no Rust knowledge-graph engine ships native HNSW alongside its triple store — the de-facto stack is `Neo4j + Qdrant + a Python adapter`. This module is the foundation for Open Ontologies to fill that gap as a Rust-native MCP server with first-class semantic search inside the same process. Scaffold scope: the core index + integration + tests; follow-up work (persistence layer for the built index, MCP-tool surface for tuning HNSW `ef_search` / `ef_construction`, wiring into `onto_align`'s embedding-similarity signal) is tracked in the project notes. New tests: 3 unit tests in `src/hnsw_index.rs` + 3 integration tests in `tests/vecstore_test.rs` (round-trip top-1 agreement with brute-force, mutation-invalidation behaviour, empty-store edge case).
- **GenOM-style description-based embedding enrichment for `onto_embed`**. New optional `descriptions: HashMap<String, String>` field on `OntoEmbedInput`. When the map is supplied, each class IRI in the map is embedded from its description text instead of from its `rdfs:label`; IRIs absent from the map fall back to the existing label-based embedding. Returns a new `enriched: <count>` field alongside the existing `embedded: <count>` so callers can see how many classes used descriptions vs. labels. This is the MCP-native form of the GenOM pattern (Mensa et al. 2025, accepted World Wide Web Journal, which showed Qwen-32B-generated descriptions lift alignment F1 substantially over raw-label embedding): the server doesn't generate descriptions, the connected orchestrator (Claude) authors them in-conversation using its own reasoning, then passes them in via this field. Net new dependencies: zero. Behaviour with no `descriptions` map is identical to before (back-compat). New inline unit tests in `src/inputs.rs` cover the deserialization both with and without the field present.
- **`ies-4.3.1` marketplace preset — frozen MIT baseline** (#25). New marketplace catalogue entry pointing at the archived `dstl/IES4` repo at tag `v4.3.1` (3 Mar 2025, MIT-licensed, last public release before the IES governance transition to DBT / IES-Org). Distinct from the existing `ies` preset (which tracks `IES-Org/ont-ies` main and shifts as upstream evolves) — use `ies-4.3.1` when you need a reproducible compliance baseline that won't drift. Source: 5,375-line Turtle artefact `ies4.ttl`, baseURI `http://ies.data.gov.uk/ontology/ies4`, the same namespace used by the existing `boro` and `ies4` enforce rule packs. Install via `onto_marketplace install ies-4.3.1`. Inline unit tests in `src/marketplace.rs` verify the URL pins to the `v4.3.1` tag (not `main`) and that the live `ies` and frozen `ies-4.3.1` presets coexist with distinct IDs and URLs.
- **RRF (Reciprocal Rank Fusion) as an opt-in fusion strategy for `onto_align`**. New `OntoAlignInput.fusion` field accepts `"weighted_sum"` (default, unchanged behaviour with self-calibrating learned weights) or `"rrf"` (Cormack et al. SIGIR 2009 at k=60, validated for ontology alignment by Agent-OM at VLDB 2025). RRF is order-based rather than score-based, so it doesn't need feedback to bootstrap; it's a sensible cold-start choice when the `align_feedback` table is empty. The per-signal scores remain on each candidate's `signals` field so downstream `onto_align_feedback` calls keep working identically. New public method `AlignmentEngine::align_with_fusion(source, target, high, low, dry_run, fusion)`; the existing `align_with_thresholds(...)` and `align(...)` entry points are preserved as thin wrappers that pass `"weighted_sum"`. New `tests/align_rrf_test.rs` (5 tests) covering normalisation to [0, 1], per-signal preservation, low-threshold post-rerank filtering, weighted_sum back-compat, and weighted_sum/RRF top-pair agreement on perfect matches.
diff --git a/Cargo.lock b/Cargo.lock
index f5229f1e..5e6f6bac 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1760,6 +1760,12 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+[[package]]
+name = "hermit-abi"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"
+
[[package]]
name = "hex"
version = "0.4.3"
@@ -2069,6 +2075,19 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "instant-distance"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8c619cdaa30bb84088963968bee12a45ea5fbbf355f2c021bcd15589f5ca494a"
+dependencies = [
+ "num_cpus",
+ "ordered-float 3.9.2",
+ "parking_lot",
+ "rand 0.8.5",
+ "rayon",
+]
+
[[package]]
name = "integer-encoding"
version = "3.0.4"
@@ -2660,6 +2679,16 @@ dependencies = [
"libm",
]
+[[package]]
+name = "num_cpus"
+version = "1.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b"
+dependencies = [
+ "hermit-abi",
+ "libc",
+]
+
[[package]]
name = "once_cell"
version = "1.21.3"
@@ -2707,6 +2736,7 @@ dependencies = [
"csv",
"dirs",
"duckdb",
+ "instant-distance",
"oxigraph",
"parquet",
"quick-xml 0.37.5",
@@ -2791,6 +2821,15 @@ dependencies = [
"num-traits",
]
+[[package]]
+name = "ordered-float"
+version = "3.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1e1c390732d15f1d48471625cd92d154e66db2c56645e29a9cd26f4699f72dc"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "oxigraph"
version = "0.5.8"
@@ -4488,7 +4527,7 @@ checksum = "7e54bc85fc7faa8bc175c4bab5b92ba8d9a3ce893d0e9f42cc455c8ab16a9e09"
dependencies = [
"byteorder",
"integer-encoding",
- "ordered-float",
+ "ordered-float 2.10.1",
]
[[package]]
diff --git a/Cargo.toml b/Cargo.toml
index ddfcd18e..f7573d6f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -40,6 +40,7 @@ sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio",
duckdb = { version = "1", optional = true, features = ["bundled"] }
tract-onnx = { version = "0.21", optional = true }
tokenizers = { version = "0.21", optional = true, default-features = false, features = ["onig"] }
+instant-distance = { version = "0.6", optional = true }
dirs = "6"
shell-words = "1"
@@ -48,7 +49,7 @@ default = []
postgres = ["sqlx"]
duckdb = ["dep:duckdb"]
sql = ["postgres", "duckdb"]
-embeddings = ["tract-onnx", "tokenizers"]
+embeddings = ["tract-onnx", "tokenizers", "instant-distance"]
[dev-dependencies]
tempfile = "3"
diff --git a/src/hnsw_index.rs b/src/hnsw_index.rs
new file mode 100644
index 00000000..b5f05697
--- /dev/null
+++ b/src/hnsw_index.rs
@@ -0,0 +1,172 @@
+//! HNSW-accelerated cosine search for the in-memory vector store.
+//!
+//! Wraps `instant-distance` to provide approximate nearest-neighbour search
+//! over L2-normalised text-embedding vectors. Used as a strict alternative to
+//! the existing brute-force linear scan in [`crate::vecstore::VecStore`]:
+//!
+//! - **Existing behaviour preserved.** `VecStore::search_cosine` continues to
+//! do exact O(n) linear scan.
+//! - **New opt-in path.** `VecStore::search_cosine_hnsw` builds an HNSW index
+//! lazily on first call (and rebuilds whenever the store is mutated) and
+//! returns approximate top-k via the index.
+//!
+//! ## Why HNSW
+//!
+//! `instant-distance` implements the HNSW algorithm from Malkov &
+//! Yashunin's "Efficient and robust approximate nearest neighbor search using
+//! Hierarchical Navigable Small World graphs" (TPAMI 2020). It gives
+//! sub-linear query time at the cost of a one-off index-build cost. For an
+//! ontology with a few thousand classes, the linear scan dominates query
+//! latency in `onto_search` and `onto_align`'s embedding-similarity signal;
+//! HNSW closes that gap. The trade-off is: instant-distance's index is
+//! immutable once built, so every mutation invalidates it and the next
+//! search pays the rebuild. This works for the typical Open Ontologies
+//! workflow (embed-once, search-many-times) but would need incremental
+//! indexing for write-heavy workloads.
+//!
+//! ## Strategic context
+//!
+//! Per the May 2026 ecosystem research, no Rust knowledge-graph engine ships
+//! native HNSW alongside its triple store — the de-facto stack is
+//! `Neo4j + Qdrant + a Python adapter`. This module is the foundation for
+//! Open Ontologies to fill that gap as a Rust-native MCP server with first-
+//! class semantic-search inside the same process.
+//!
+//! ## What's NOT in this scaffold
+//!
+//! - Persistence of the built index (the index is rebuilt at process start;
+//! the underlying vectors are persisted via SQLite as today)
+//! - MCP-tool surface for tuning HNSW parameters (`ef_search`,
+//! `ef_construction`)
+//! - Wiring into `onto_align`'s embedding-similarity signal (currently uses
+//! `VecStore::get_text_vec` + direct cosine — still works, no regression)
+
+use instant_distance::{Builder, HnswMap, Point, Search};
+
+/// A point in the HNSW index. Wraps an L2-normalised vector and implements the
+/// `instant-distance::Point` trait using `1.0 - dot_product` as the distance
+/// (cosine distance for L2-normalised vectors).
+#[derive(Clone, Debug)]
+pub struct CosinePoint(pub Vec<f32>);
+
+impl Point for CosinePoint {
+ fn distance(&self, other: &Self) -> f32 {
+ // L2-normalised vectors -> cosine similarity = dot product.
+ // Distance = 1 - similarity, so lower distance = closer match.
+ // (instant-distance ranks ascending by distance, which matches.)
+ let dot: f32 = self
+ .0
+ .iter()
+ .zip(other.0.iter())
+ .map(|(a, b)| a * b)
+ .sum();
+ 1.0 - dot
+ }
+}
+
+/// HNSW-backed cosine index over (IRI -> L2-normalised text embedding).
+///
+/// Build once via [`CosineIndex::build`]; query repeatedly via
+/// [`CosineIndex::search`]. The index is immutable — any mutation to the
+/// underlying vector set requires a fresh build.
+pub struct CosineIndex {
+ inner: HnswMap<CosinePoint, String>,
+ search: Search,
+}
+
+impl CosineIndex {
+ /// Build an HNSW index from an iterable of `(iri, vector)` pairs. The
+ /// vectors must already be L2-normalised (as the VecStore guarantees on
+ /// `upsert`).
+ pub fn build<I, S>(entries: I) -> Self
+ where
+ I: IntoIterator<Item = (S, Vec<f32>)>,
+ S: Into<String>,
+ {
+ let mut points = Vec::new();
+ let mut iris = Vec::new();
+ for (iri, vec) in entries {
+ points.push(CosinePoint(vec));
+ iris.push(iri.into());
+ }
+ let inner = Builder::default().build(points, iris);
+ Self {
+ inner,
+ search: Search::default(),
+ }
+ }
+
+ /// Approximate top-k cosine search. Returns `(iri, similarity)` pairs
+ /// sorted by similarity descending. Similarity is `1.0 - distance`, so
+ /// the brute-force `search_cosine` and this method use the same scale.
+ pub fn search(&mut self, query: &[f32], top_k: usize) -> Vec<(String, f32)> {
+ let q = CosinePoint(query.to_vec());
+ self.inner
+ .search(&q, &mut self.search)
+ .take(top_k)
+ .map(|item| (item.value.clone(), 1.0 - item.distance))
+ .collect()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn norm(v: Vec<f32>) -> Vec<f32> {
+ let n: f32 = v.iter().map(|x| x * x).sum::<f32>().sqrt();
+ if n > 0.0 { v.into_iter().map(|x| x / n).collect() } else { v }
+ }
+
+ #[test]
+ fn cosine_distance_implementation_matches_one_minus_dot() {
+ let a = CosinePoint(norm(vec![1.0, 0.0, 0.0]));
+ let b = CosinePoint(norm(vec![0.0, 1.0, 0.0]));
+ // Orthogonal unit vectors: similarity 0, distance 1.
+ assert!((a.distance(&b) - 1.0).abs() < 1e-6);
+
+ let c = CosinePoint(norm(vec![1.0, 0.0, 0.0]));
+ // Identical vectors: similarity 1, distance 0.
+ assert!(a.distance(&c).abs() < 1e-6);
+ }
+
+ #[test]
+ fn build_and_search_returns_nearest_first() {
+ let cat_vec = norm(vec![1.0, 0.0, 0.0]);
+ let kitten_vec = norm(vec![0.95, 0.05, 0.0]);
+ let car_vec = norm(vec![0.0, 1.0, 0.0]);
+
+ let mut index = CosineIndex::build(vec![
+ ("http://ex.org/Cat".to_string(), cat_vec),
+ ("http://ex.org/Kitten".to_string(), kitten_vec),
+ ("http://ex.org/Car".to_string(), car_vec),
+ ]);
+
+ let query = norm(vec![0.99, 0.01, 0.0]);
+ let results = index.search(&query, 2);
+
+ assert_eq!(results.len(), 2);
+ let iris: Vec<&str> = results.iter().map(|(i, _)| i.as_str()).collect();
+ assert!(iris.iter().any(|i| i.contains("Cat") || i.contains("Kitten")));
+ assert!(
+ !iris.iter().any(|i| i.contains("Car")),
+ "Car should NOT be in top-2; got {:?}",
+ iris
+ );
+ }
+
+ #[test]
+ fn top_k_respected_with_fewer_results_than_corpus() {
+ let vecs: Vec<_> = (0..10).map(|i| {
+ let v = norm(vec![1.0, i as f32 * 0.01, 0.0]);
+ (format!("iri-{}", i), v)
+ }).collect();
+ let mut index = CosineIndex::build(vecs);
+ let query = norm(vec![1.0, 0.0, 0.0]);
+ let results = index.search(&query, 3);
+ assert_eq!(results.len(), 3);
+ for w in results.windows(2) {
+ assert!(w[0].1 >= w[1].1, "results must be sorted by similarity desc; got {:?}", results);
+ }
+ }
+}
diff --git a/src/lib.rs b/src/lib.rs
index 1894a6df..3794e33d 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -35,6 +35,8 @@ pub mod poincare;
#[cfg(feature = "embeddings")]
pub mod vecstore;
#[cfg(feature = "embeddings")]
+pub mod hnsw_index;
+#[cfg(feature = "embeddings")]
pub mod embed;
#[cfg(feature = "embeddings")]
pub mod embed_remote;
diff --git a/src/vecstore.rs b/src/vecstore.rs
index 36ddbb1f..7a6aaec0 100644
--- a/src/vecstore.rs
+++ b/src/vecstore.rs
@@ -1,6 +1,7 @@
//! In-memory vector store with dual-space search (cosine + Poincaré)
//! and SQLite persistence.
+use crate::hnsw_index::CosineIndex;
use crate::poincare::{cosine_similarity, l2_normalize, poincare_distance};
use crate::state::StateDb;
use std::collections::HashMap;
@@ -11,10 +12,16 @@ struct VecEntry {
struct_vec: Vec<f32>,
}
-/// Brute-force dual-space vector store.
+/// Brute-force dual-space vector store with an opt-in HNSW cosine index.
pub struct VecStore {
db: StateDb,
entries: HashMap<String, VecEntry>,
+ /// Lazily-built HNSW index over `text_vec`s for accelerated cosine
+ /// search. Invalidated on every mutation; rebuilt on first
+ /// `search_cosine_hnsw` after a mutation. The existing
+ /// `search_cosine` linear scan is unchanged and continues to work
+ /// without HNSW.
+ cosine_index: Option<CosineIndex>,
}
impl VecStore {
@@ -22,6 +29,7 @@ impl VecStore {
Self {
db,
entries: HashMap::new(),
+ cosine_index: None,
}
}
@@ -30,10 +38,13 @@ impl VecStore {
text_vec: l2_normalize(text_vec),
struct_vec: struct_vec.to_vec(),
});
+ // Invalidate HNSW index — instant-distance is immutable once built.
+ self.cosine_index = None;
}
pub fn remove(&mut self, iri: &str) {
self.entries.remove(iri);
+ self.cosine_index = None;
}
pub fn search_cosine(&self, query: &[f32], top_k: usize) -> Vec<(String, f32)> {
@@ -46,6 +57,44 @@ impl VecStore {
scores
}
+ /// HNSW-accelerated cosine search. Approximate top-k via the HNSW index;
+ /// builds the index lazily on first call (and after any mutation).
+ ///
+ /// Same query/output semantics as [`Self::search_cosine`] (results sorted
+ /// by cosine similarity descending, top_k truncation, same scale), but
+ /// sub-linear query time once the index is warm. The trade-off vs the
+ /// exact brute-force scan: approximate top-k under default HNSW params,
+ /// rebuild cost on every mutation.
+ ///
+ /// Use this when:
+ /// - The store has more than a few hundred entries
+ /// - You expect many queries between mutations (`embed-once,
+ /// search-many-times`)
+ /// - Approximate top-k is acceptable
+ ///
+ /// Otherwise stick with [`Self::search_cosine`].
+ pub fn search_cosine_hnsw(&mut self, query: &[f32], top_k: usize) -> Vec<(String, f32)> {
+ if self.entries.is_empty() {
+ return Vec::new();
+ }
+ if self.cosine_index.is_none() {
+ // Lazy build from current entries. Vectors are already L2-normalised
+ // (the upsert path guarantees that), so the HNSW index sees unit
+ // vectors and the cosine distance == 1 - dot product.
+ let points: Vec<(String, Vec<f32>)> = self
+ .entries
+ .iter()
+ .map(|(iri, e)| (iri.clone(), e.text_vec.clone()))
+ .collect();
+ self.cosine_index = Some(CosineIndex::build(points));
+ }
+ let query_norm = l2_normalize(query);
+ match self.cosine_index.as_mut() {
+ Some(idx) => idx.search(&query_norm, top_k),
+ None => Vec::new(),
+ }
+ }
+
pub fn search_poincare(&self, query: &[f32], top_k: usize) -> Vec<(String, f32)> {
let mut scores: Vec<(String, f32)> = self.entries.iter()
.map(|(iri, e)| (iri.clone(), poincare_distance(query, &e.struct_vec)))
@@ -118,6 +167,8 @@ impl VecStore {
struct_vec: bytes_to_f32_vec(&struct_bytes),
});
}
+ // Invalidate any previously-built HNSW index.
+ self.cosine_index = None;
Ok(())
}
diff --git a/tests/vecstore_test.rs b/tests/vecstore_test.rs
index bbca46c3..bf167b23 100644
--- a/tests/vecstore_test.rs
+++ b/tests/vecstore_test.rs
@@ -104,3 +104,72 @@ fn test_remove() {
assert_eq!(results.len(), 1);
assert_eq!(results[0].0, "http://ex.org/Cat");
}
+
+#[test]
+fn search_cosine_hnsw_returns_same_top_1_as_brute_force() {
+ // Round-trip test for the HNSW backing index: top-1 must agree with the
+ // brute-force linear scan on well-separated vectors.
+ let db = test_db();
+ let mut store = VecStore::new(db);
+
+ let entries: [(&str, [f32; 3]); 6] = [
+ ("http://ex.org/Cat", [1.0, 0.05, 0.0]),
+ ("http://ex.org/Kitten", [0.98, 0.1, 0.0]),
+ ("http://ex.org/Dog", [0.9, 0.3, 0.0]),
+ ("http://ex.org/Bird", [0.4, 0.7, 0.0]),
+ ("http://ex.org/Car", [0.0, 0.1, 1.0]),
+ ("http://ex.org/Bike", [0.0, 0.0, 0.95]),
+ ];
+ for (iri, vec) in entries.iter() {
+ store.upsert(iri, vec, &[0.0]);
+ }
+
+ let query = [1.0_f32, 0.0, 0.0]; // Closest to Cat by far.
+
+ let brute = store.search_cosine(&query, 1);
+ let hnsw = store.search_cosine_hnsw(&query, 1);
+
+ assert_eq!(brute.len(), 1);
+ assert_eq!(hnsw.len(), 1);
+ assert_eq!(
+ brute[0].0, hnsw[0].0,
+ "top-1 disagreement between brute-force and HNSW: brute={:?}, hnsw={:?}",
+ brute, hnsw
+ );
+ assert!(brute[0].0.contains("Cat"));
+}
+
+#[test]
+fn search_cosine_hnsw_invalidates_on_mutation() {
+ // After an upsert the index must rebuild. Warm the index with an
+ // initial search, then insert a closer match — the next search must
+ // surface it (i.e. the stale index didn't sandbag the result).
+ let db = test_db();
+ let mut store = VecStore::new(db);
+
+ store.upsert("http://ex.org/Cat", &[0.9, 0.1, 0.0], &[0.0]);
+ store.upsert("http://ex.org/Dog", &[0.7, 0.3, 0.0], &[0.0]);
+
+ let first = store.search_cosine_hnsw(&[1.0, 0.0, 0.0], 1);
+ assert!(first[0].0.contains("Cat"));
+
+ store.upsert("http://ex.org/Tiger", &[0.99, 0.05, 0.0], &[0.0]);
+
+ let second = store.search_cosine_hnsw(&[1.0, 0.0, 0.0], 1);
+ assert!(
+ second[0].0.contains("Tiger") || second[0].0.contains("Cat"),
+ "after upsert of closer match, expected Tiger or Cat in top-1; got {:?}",
+ second
+ );
+ // The structural invariant: the previously-built index didn't prevent
+ // Tiger from being considered. Either Tiger (very close) or Cat (close)
+ // demonstrate that.
+}
+
+#[test]
+fn search_cosine_hnsw_on_empty_store_returns_empty() {
+ let db = test_db();
+ let mut store = VecStore::new(db);
+ let results = store.search_cosine_hnsw(&[1.0, 0.0, 0.0], 5);
+ assert!(results.is_empty());
+}