Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
feat(vecstore): TurboQuant cosine index backend behind the `turbovec` feature
FABIOTESSfb9771f4f324
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 42efd6eb..41af0ab3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,73 @@ All notable changes to Open Ontologies are documented here.## [Unreleased]### Added+- **TurboQuant cosine index backend** (new optional `turbovec` feature, off by+ default, implies `embeddings`). A second index backend for the text half of+ the vector store, built on Google Research's TurboQuant quantiser+ (arXiv:2504.19874) via the `turbovec` crate, alongside the existing+ `instant-distance` HNSW graph. New `src/turbo_index.rs` with+ `TurboCosineIndex` (`build`, `upsert`, `remove`, `search`, `search_within`,+ `to_bytes`, `from_bytes`), and three new `VecStore` entry points+ (`search_cosine_turbo`, `persist_turbo_index`, `load_turbo_index`) plus the+ `turbo_index_len` accessor.++ The motivation is mutation cost, not compression. An `instant-distance`+ graph is immutable, so every `VecStore::upsert` sets `cosine_index = None`+ and the next search pays a full rebuild; an ontology whose embeddings arrive+ incrementally pays that rebuild once per class. TurboQuant has no training+ phase and no graph, so an insert is an append and a removal is O(1), and+ `upsert`/`remove` now maintain the live index rather than dropping it.++ The quantised index is a candidate generator, never the answer.+ `search_cosine_turbo` pulls a shortlist four times wider than the request+ (floor of `top_k + 32`), re-scores every candidate against the float32+ vector the store already holds, and returns that, so no approximate+ similarity number reaches a caller and the result is identical to the exact+ brute-force scan whenever the shortlist covers the true top-k. That identity+ is asserted directly against `search_cosine` in the tests rather than+ assumed.++ Scope limits, both deliberate. (1) `PoincareIndex` is untouched and stays on+ `instant-distance`: TurboQuant scores inner products, and hyperbolic+ distance is not an inner product on the ambient coordinates. (2) The store+ still holds float32 vectors in memory, because the exact re-score and+ `search_cosine` need them, so this change does not yet realise TurboQuant's+ memory win. Evicting float32 to SQLite with load-on-demand for the re-score+ is the follow-on.++ Implementation notes: vectors are zero-padded to the next multiple of 8+ (`turbovec` requires `dim % 8 == 0`; zero padding leaves every inner product+ unchanged). IRIs map to `u64` ids that are never recycled, so a stale+ allowlist entry naming a removed id fails loudly rather than resolving to+ whatever vector took its place; the id counter is serialised with the index+ so a reload cannot restart allocation at 0. A query is validated before it+ reaches the kernel: `turbovec`'s allowlist-free `search` is the panicking+ form, so a non-finite coordinate from a misbehaving embedding provider, or a+ query whose dimensionality disagrees with the index, is reported as no+ results rather than panicking the server or being silently truncated into a+ plausible-looking ranking against the wrong vector. Persistence reuses the existing+ `hnsw_index_cache` table under `kind = 'turbo_cosine'` with no schema+ change, and both load guards are unchanged: `model_fp` rejects an index+ built under a different embedding configuration, `entries_hash` rejects one+ whose entry set has moved on. 17 new tests in `tests/turbovec_index_test.rs`+ covering top-1 agreement with the exact scan, incremental add/replace/remove,+ byte round-trip, id allocation after a reload, allowlist search (including+ unknown and empty allowlists), sub-8 dimensionality padding, non-finite and+ wrong-width query rejection, the VecStore score-identity guarantee, index+ warmth across mutations, SQLite round-trip and stale-cache rejection, plus an+ `#[ignore]`d measurement against HNSW.++ Measured at 10,000 vectors x 768 dims on an M3 Max (`docs/embeddings.md` has+ the table): build 116 s vs 178 ms, one added embedding 137 s vs 52 us, query+ 4.7 ms vs 0.25 ms, serialised index 34.1 MB vs 5.2 MB against 30.7 MB of raw+ float32. recall@10 is 91.6% for HNSW and 100% for the re-scored TurboQuant+ shortlist, and the control says that gap is structural rather than a matter+ of shortlist width: giving HNSW 40 candidates instead of 10 leaves its recall+ at exactly 91.6%, because the entries it misses are ones the graph walk never+ reaches. The corpus is isotropic random vectors, which is close to the worst+ case for a graph index and kinder data would narrow the gap, so the claim is+ that flat-scan recall is data-independent, not that HNSW loses 8% on a real+ ontology.- **Four extension surfaces** (ECOSYSTEM.md maps them). (1) **Communitymarketplace packs**: `onto_marketplace` now merges an open runtime-fetchedregistry (`community/registry.json`, override withdiff --git a/Cargo.lock b/Cargo.lockindex c41a6f34..eb3b6aa5 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -94,7 +94,7 @@ version = "1.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"dependencies = [- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -105,7 +105,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"dependencies = ["anstyle","once_cell_polyfill",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -126,6 +126,15 @@ version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fb5dfbc6d8d2675589ccbe4d0fd61df2419075625f8c1a62325e718e2b0049f9"+[[package]]+name = "approx"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6"+dependencies = [+ "num-traits",+]+[[package]]name = "arbitrary"version = "1.4.2"@@ -745,6 +754,12 @@ dependencies = ["syn 1.0.109",]+[[package]]+name = "bytemuck"+version = "1.25.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"+[[package]]name = "byteorder"version = "1.5.0"@@ -1315,7 +1330,7 @@ dependencies = ["libc","option-ext","redox_users",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -1408,7 +1423,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"dependencies = ["libc",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -2557,6 +2572,35 @@ dependencies = ["syn 2.0.118",]+[[package]]+name = "nalgebra"+version = "0.32.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7b5c17de023a86f59ed79891b2e5d5a94c705dbe904a5b5c9c952ea6221b03e4"+dependencies = [+ "approx",+ "matrixmultiply",+ "nalgebra-macros",+ "num-complex",+ "num-rational",+ "num-traits",+ "rand 0.8.6",+ "rand_distr",+ "simba",+ "typenum",+]++[[package]]+name = "nalgebra-macros"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "254a5372af8fc138e36684761d3c0cdb758a4410e938babcff1c860ce14ddbfc"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]+[[package]]name = "native-tls"version = "0.2.18"@@ -2623,7 +2667,7 @@ version = "0.50.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"dependencies = [- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -2788,6 +2832,7 @@ dependencies = ["tracing","tracing-subscriber","tract-onnx",+ "turbovec","wasmi","wat",]@@ -2859,6 +2904,15 @@ dependencies = ["num-traits",]+[[package]]+name = "ordered-float"+version = "4.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7bb71e1b3fa6ca1c61f383464aaf2bb0e2f8e772a1f01d486832464de363b951"+dependencies = [+ "num-traits",+]+[[package]]name = "oxigraph"version = "0.5.9"@@ -3789,7 +3843,7 @@ dependencies = ["errno","libc","linux-raw-sys 0.12.1",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -3845,6 +3899,15 @@ version = "1.0.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "dd29631678d6fb0903b69223673e122c32e9ae559d0960a38d574695ebc0ea15"+[[package]]+name = "safe_arch"+version = "0.7.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96b02de82ddbe1b636e6170c21be622223aea188ef2e139be0a5b219ec215323"+dependencies = [+ "bytemuck",+]+[[package]]name = "safetensors"version = "0.6.2"@@ -4116,6 +4179,19 @@ dependencies = ["libc",]+[[package]]+name = "simba"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "061507c94fc6ab4ba1c9a0305018408e312e17c041eb63bef8aa726fa33aceae"+dependencies = [+ "approx",+ "num-complex",+ "num-traits",+ "paste",+ "wide",+]+[[package]]name = "simd-adler32"version = "0.3.9"@@ -4156,7 +4232,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51"dependencies = ["libc",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -4381,6 +4457,18 @@ version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"+[[package]]+name = "statrs"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f697a07e4606a0a25c044de247e583a330dbb1731d11bc7350b81f48ad567255"+dependencies = [+ "approx",+ "nalgebra",+ "num-traits",+ "rand 0.8.6",+]+[[package]]name = "strength_reduce"version = "0.2.4"@@ -4542,7 +4630,7 @@ dependencies = ["getrandom 0.4.3","once_cell","rustix 1.1.4",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -5105,6 +5193,19 @@ version = "0.2.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"+[[package]]+name = "turbovec"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1131bbaacc5d3c093f09c2e3b470f03bbd218b1a0843140ae6a71a8c692b9ece"+dependencies = [+ "ordered-float 4.6.0",+ "rand 0.8.6",+ "rand_chacha 0.3.1",+ "rayon",+ "statrs",+]+[[package]]name = "twox-hash"version = "1.6.3"@@ -5475,6 +5576,16 @@ dependencies = ["wasite",]+[[package]]+name = "wide"+version = "0.7.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ce5da8ecb62bcd8ec8b7ea19f69a51275e91299be594ea5cc6ef7819e16cd03"+dependencies = [+ "bytemuck",+ "safe_arch",+]+[[package]]name = "winapi"version = "0.3.9"@@ -5497,7 +5608,7 @@ version = "0.1.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"dependencies = [- "windows-sys 0.48.0",+ "windows-sys 0.61.2",][[package]]diff --git a/Cargo.toml b/Cargo.tomlindex e333b076..dcf31749 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -45,6 +45,7 @@ bincode = { version = "1.3", optional = true }sha2 = "0.10"dirs = "6"wasmi = { version = "1.1.0", optional = true }+turbovec = { version = "1.0.0", default-features = false, optional = true }[features]default = []@@ -63,6 +64,14 @@ causal-pywhy = []# in-process behind onto_plugin_list / onto_plugin_call. Pure-Rust interpreter# (wasmi) with fuel metering — no system deps, the binary stays self-contained.plugins = ["dep:wasmi"]+# TurboQuant-backed cosine index (Google Research arXiv:2504.19874) as an+# alternative to the immutable instant-distance HNSW graph. Two properties the+# HNSW index cannot offer: incremental add/remove without a full rebuild, and+# 2-4 bit quantised storage. Implies `embeddings` because it replaces one of+# that feature's two index backends; the Poincare index stays on+# instant-distance (TurboQuant scores inner products, and hyperbolic distance+# is not an inner product on the ambient coordinates).+turbovec = ["dep:turbovec", "embeddings"][dev-dependencies]tempfile = "3"diff --git a/docs/embeddings.md b/docs/embeddings.mdindex 1206a1cd..e3663f29 100644--- a/docs/embeddings.md+++ b/docs/embeddings.md@@ -28,6 +28,79 @@ The embedding model (~33MB) is downloaded on `open-ontologies init`. All inferen| `structure` | Poincare distance on structural embeddings only || `product` | Weighted combination of both (default, alpha=0.5) |+## Cosine index backends++The text (cosine) half of the store has two interchangeable index backends.+The structural (Poincare) half has one, and will keep having one: TurboQuant+scores inner products, and hyperbolic distance is not an inner product on the+ambient coordinates.++| | `embeddings` (default) | `turbovec` |+| --- | --- | --- |+| Algorithm | HNSW graph (`instant-distance`) | TurboQuant quantiser (`turbovec`, arXiv:2504.19874) |+| Entry point | `VecStore::search_cosine_hnsw` | `VecStore::search_cosine_turbo` |+| Cost of one added embedding | Full graph rebuild, the graph is immutable | One append |+| Cost of one removal | Full graph rebuild | O(1) |+| Storage | float32 in the graph | 4 bit codes plus a per-vector scale |+| Scores returned | Exact for whichever entries the graph walk reaches | Exact, the shortlist is re-scored against float32 |+| Approximation lives in | Which entries the walk reaches | Which entries the quantised shortlist contains |++Build it with `cargo build --features turbovec`. The feature implies+`embeddings`; it replaces one backend rather than the whole subsystem, and the+exact brute-force `search_cosine` stays available under both.++`search_cosine_turbo` treats the quantised index as a candidate generator+only. It pulls a shortlist four times wider than the request (floor of+`top_k + 32`), re-scores every candidate against the float32 vector the store+already holds, and returns that. So a quantised similarity number never+reaches a caller, and the result is identical to the exact scan whenever the+shortlist covers the true top-k.++Both backends persist into `hnsw_index_cache` under their own `kind`+(`cosine`, `poincare`, `turbo_cosine`), and both are gated by the same two+checks on load: `model_fp` rejects an index built under a different embedding+configuration, and `entries_hash` rejects one whose entry set has moved on.++### Measured++10,000 vectors x 768 dims, Apple M3 Max, release build,+`cargo test --release --features turbovec -- --ignored --nocapture`+(`measure_turbo_against_hnsw` in `tests/turbovec_index_test.rs`).++| | HNSW | TurboQuant |+| --- | --- | --- |+| Build | 116 s | 178 ms |+| One added embedding | 137 s (full rebuild) | 52 us |+| Query, top-10 | 4.7 ms | 0.25 ms (pulling 40 candidates) |+| recall@10 as wired | 91.6% | 100% |+| recall@10, 40 candidates re-scored to 10 | 91.6% | 100% |+| Serialised index | 34.1 MB | 5.2 MB |++Raw float32 for that corpus is 30.7 MB, so the HNSW blob is larger than the+vectors it indexes and the TurboQuant one is a sixth of them. Build and+rebuild times move by a factor of several between runs depending on machine+load; the query, recall and size figures are stable.++Read the two recall rows together, because that is the control. Asking HNSW+for 40 candidates instead of 10 and re-scoring changes nothing: the entries it+misses are ones its graph walk never reaches, so no amount of over-fetching+recovers them, and `ef_search` (default 100) is the only lever. The flat+quantised scan has no such failure mode by construction, because it scores+every vector. That is a structural difference, not a tuning one.++One caveat on those recall numbers: the corpus is isotropic random vectors,+which is close to the worst case for a graph index. Every pairwise cosine sits+near zero, so ranks 10 and 11 are separated by noise and there is no cluster+structure for the walk to exploit. Real text embeddings are kinder to HNSW.+The point is not that HNSW loses 8% on your ontology; it is that its recall is+data-dependent while the flat index's is not.++**When to pick which.** HNSW if the ontology is embedded once and then only+queried. TurboQuant if embeddings arrive incrementally (the rebuild is what+you are paying for, not the query), or if the corpus is large enough that+float32 storage is the constraint: at 768 dims a 4 bit code is 388 bytes+against 3,072.+## ProvidersThe text-embedding side is pluggable via `[embeddings] provider`:diff --git a/src/lib.rs b/src/lib.rsindex 506c6008..3b947995 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -81,6 +81,8 @@ pub mod state;pub mod structembed;pub mod tableaux;pub mod toolfilter;+#[cfg(feature = "turbovec")]+pub mod turbo_index;#[cfg(feature = "embeddings")]pub mod vecstore;pub mod webhook;diff --git a/src/turbo_index.rs b/src/turbo_index.rsnew file mode 100644index 00000000..0058cc72--- /dev/null+++ b/src/turbo_index.rs@@ -0,0 +1,308 @@+//! TurboQuant-backed cosine index over (IRI -> L2-normalised text embedding).+//!+//! An alternative backend to [`crate::hnsw_index::CosineIndex`], built on+//! Google Research's TurboQuant quantizer (arXiv:2504.19874) via the+//! `turbovec` crate. It exists because the instant-distance HNSW graph is+//! immutable: every `VecStore::upsert` drops the index and the next search+//! pays a full rebuild. TurboQuant has no training phase and no graph, so an+//! add is an append and a remove is O(1).+//!+//! Two things this index is *not*:+//!+//! - It is not exact. Scores are inner products over 2-4 bit codes. Callers+//! that surface a similarity number re-score the returned candidates+//! against the float32 vectors they already hold; this type is a candidate+//! generator.+//! - It is not a replacement for [`crate::hnsw_index::PoincareIndex`].+//! TurboQuant quantises for inner product, and hyperbolic distance is not+//! an inner product on the ambient coordinates.++use serde::{Deserialize, Serialize};+use std::collections::HashMap;+use turbovec::IdMapIndex;++/// Bit width of the quantised codes. 4 is the highest TurboQuant offers and+/// the best-recall setting; 2 and 3 trade recall for memory.+pub const DEFAULT_BIT_WIDTH: usize = 4;++/// Round a dimensionality up to the next multiple of 8.+///+/// `turbovec` requires `dim % 8 == 0`. Embedding models in practice emit+/// multiples of 8 already (384, 768, 1024, 1536), but the vector store accepts+/// any width, so vectors are zero-padded to the next multiple. Padding with+/// zeros leaves every inner product unchanged.+fn padded_dim(raw_dim: usize) -> usize {+ raw_dim.div_ceil(8) * 8+}++/// TurboQuant-backed cosine index keyed by IRI.+pub struct TurboCosineIndex {+ inner: IdMapIndex,+ iri_to_id: HashMap<String, u64>,+ id_to_iri: HashMap<u64, String>,+ next_id: u64,+ /// Padded width the index was constructed with.+ dim: usize,+ /// Unpadded width callers supply.+ raw_dim: usize,+}++impl TurboCosineIndex {+ /// Build an index from an iterable of `(iri, vector)` pairs. Vectors must+ /// already be L2-normalised, as `VecStore::upsert` guarantees, so that the+ /// inner products TurboQuant scores are cosine similarities.+ pub fn build<I, S>(entries: I) -> anyhow::Result<Self>+ where+ I: IntoIterator<Item = (S, Vec<f32>)>,+ S: Into<String>,+ {+ let entries: Vec<(String, Vec<f32>)> =+ entries.into_iter().map(|(i, v)| (i.into(), v)).collect();+ let raw_dim = entries+ .first()+ .map(|(_, v)| v.len())+ .ok_or_else(|| anyhow::anyhow!("cannot build a TurboCosineIndex from zero entries"))?;+ let dim = padded_dim(raw_dim);++ let mut flat = Vec::with_capacity(entries.len() * dim);+ let mut ids = Vec::with_capacity(entries.len());+ let mut iri_to_id = HashMap::with_capacity(entries.len());+ let mut id_to_iri = HashMap::with_capacity(entries.len());+ for (next_id, (iri, vec)) in entries.into_iter().enumerate() {+ if vec.len() != raw_dim {+ anyhow::bail!(+ "vector for {iri} has dim {}, expected {raw_dim}",+ vec.len()+ );+ }+ let id = next_id as u64;+ flat.extend_from_slice(&vec);+ flat.resize(flat.len() + (dim - raw_dim), 0.0);+ ids.push(id);+ iri_to_id.insert(iri.clone(), id);+ id_to_iri.insert(id, iri);+ }++ let mut inner = IdMapIndex::new(dim, DEFAULT_BIT_WIDTH)+ .map_err(|e| anyhow::anyhow!("turbovec index construction failed: {e}"))?;+ inner+ .add_with_ids(&flat, &ids)+ .map_err(|e| anyhow::anyhow!("turbovec add failed: {e}"))?;++ let next_id = ids.len() as u64;+ Ok(Self {+ inner,+ iri_to_id,+ id_to_iri,+ next_id,+ dim,+ raw_dim,+ })+ }++ /// Insert or replace one `(iri, vector)` pair.+ ///+ /// This is the reason the type exists. `instant-distance` graphs are+ /// immutable, so `VecStore::upsert` has to drop the whole cosine index and+ /// pay a full rebuild on the next search. Here an insert is an append and+ /// a replace is a remove followed by an append, both against a live index.+ ///+ /// A replaced IRI gets a fresh id rather than reusing its old one: ids are+ /// never recycled, so a stale allowlist entry naming a removed id fails+ /// loudly (`SearchError::UnknownId`) instead of quietly resolving to+ /// whatever vector took its place.+ pub fn upsert(&mut self, iri: &str, vector: &[f32]) -> anyhow::Result<()> {+ if vector.len() != self.raw_dim {+ anyhow::bail!(+ "vector for {iri} has dim {}, index dim is {}",+ vector.len(),+ self.raw_dim+ );+ }+ if let Some(old_id) = self.iri_to_id.remove(iri) {+ self.inner.remove(old_id);+ self.id_to_iri.remove(&old_id);+ }++ let id = self.next_id;+ self.next_id += 1;+ let mut padded = Vec::with_capacity(self.dim);+ padded.extend_from_slice(vector);+ padded.resize(self.dim, 0.0);+ self.inner+ .add_with_ids(&padded, &[id])+ .map_err(|e| anyhow::anyhow!("turbovec add failed for {iri}: {e}"))?;+ self.iri_to_id.insert(iri.to_string(), id);+ self.id_to_iri.insert(id, iri.to_string());+ Ok(())+ }++ /// Remove one IRI. Returns whether it was present.+ pub fn remove(&mut self, iri: &str) -> bool {+ match self.iri_to_id.remove(iri) {+ Some(id) => {+ self.id_to_iri.remove(&id);+ self.inner.remove(id)+ }+ None => false,+ }+ }++ /// Number of indexed vectors.+ pub fn len(&self) -> usize {+ self.inner.len()+ }++ /// Whether the index holds no vectors.+ pub fn is_empty(&self) -> bool {+ self.inner.is_empty()+ }++ /// Serialise the index for persistence in the `hnsw_index_cache` SQLite+ /// blob column, alongside its IRI table.+ ///+ /// `turbovec`'s own `to_bytes` carries the codes and the `u64` ids but+ /// knows nothing about IRIs, so the id table and the id counter travel+ /// with it. The counter matters: reloading without it would restart id+ /// allocation at 0 and hand a live id to a different IRI.+ pub fn to_bytes(&self) -> anyhow::Result<Vec<u8>> {+ let payload = PersistedIndex {+ format_version: PERSIST_FORMAT_VERSION,+ raw_dim: self.raw_dim,+ next_id: self.next_id,+ id_to_iri: self+ .id_to_iri+ .iter()+ .map(|(id, iri)| (*id, iri.clone()))+ .collect(),+ index_bytes: self.inner.to_bytes(),+ };+ Ok(bincode::serialize(&payload)?)+ }++ /// Reconstruct an index from [`Self::to_bytes`] output.+ pub fn from_bytes(bytes: &[u8]) -> anyhow::Result<Self> {+ let payload: PersistedIndex = bincode::deserialize(bytes)?;+ if payload.format_version != PERSIST_FORMAT_VERSION {+ anyhow::bail!(+ "turbovec index blob is format version {}, this build reads {PERSIST_FORMAT_VERSION}",+ payload.format_version+ );+ }+ let inner = IdMapIndex::from_bytes(&payload.index_bytes)+ .map_err(|e| anyhow::anyhow!("turbovec index blob is corrupt: {e}"))?;+ let id_to_iri: HashMap<u64, String> = payload.id_to_iri.into_iter().collect();+ let iri_to_id = id_to_iri+ .iter()+ .map(|(id, iri)| (iri.clone(), *id))+ .collect();+ Ok(Self {+ inner,+ iri_to_id,+ id_to_iri,+ next_id: payload.next_id,+ dim: padded_dim(payload.raw_dim),+ raw_dim: payload.raw_dim,+ })+ }++ /// Top-k search restricted to a set of IRIs, for `onto_align`'s+ /// candidate-shortlist pass.+ ///+ /// The restriction is honoured inside the SIMD kernel rather than by+ /// over-fetching and discarding, so a selective allowlist costs less than+ /// an unrestricted search rather than the same. IRIs the index does not+ /// hold are dropped: a caller shortlisting against a graph that has moved+ /// on should get the intersection, not an error.+ pub fn search_within(+ &self,+ query: &[f32],+ top_k: usize,+ allowed: &[String],+ ) -> anyhow::Result<Vec<(String, f32)>> {+ if self.inner.is_empty() || top_k == 0 || !self.query_is_scoreable(query) {+ return Ok(Vec::new());+ }+ let ids: Vec<u64> = allowed+ .iter()+ .filter_map(|iri| self.iri_to_id.get(iri).copied())+ .collect();+ if ids.is_empty() {+ return Ok(Vec::new());+ }+ let q = self.pad_query(query);+ let (scores, hit_ids) = self+ .inner+ .search_with_allowlist(&q, top_k, Some(&ids))+ .map_err(|e| anyhow::anyhow!("turbovec allowlist search failed: {e}"))?;+ Ok(hit_ids+ .into_iter()+ .zip(scores)+ .filter_map(|(id, score)| self.id_to_iri.get(&id).map(|iri| (iri.clone(), score)))+ .collect())+ }++ /// Whether a query vector can be scored at all.+ ///+ /// `turbovec`'s allowlist-free `search` is the panicking form and panics+ /// on a non-finite or overflow-range coordinate. An embedding provider+ /// that returns a NaN must not be able to take the server down through+ /// this path, and a query with no representable direction has no answer+ /// worth returning, so it is rejected here and reported as no results.+ fn query_is_scoreable(&self, query: &[f32]) -> bool {+ if query.len() != self.raw_dim {+ tracing::warn!(+ "turbovec query rejected: dim {} does not match the index dim {}. \+ Returning no results rather than scoring a truncated or padded query.",+ query.len(),+ self.raw_dim+ );+ return false;+ }+ let ok = query.iter().all(|v| v.is_finite() && v.abs() < 1e16);+ if !ok {+ tracing::warn!(+ "turbovec query rejected: a coordinate is non-finite or out of \+ scoring range. Returning no results rather than scoring it."+ );+ }+ ok+ }++ /// Zero-pad a query to the index's padded width.+ fn pad_query(&self, query: &[f32]) -> Vec<f32> {+ let mut q = Vec::with_capacity(self.dim);+ q.extend_from_slice(query);+ q.resize(self.dim, 0.0);+ q+ }++ /// Approximate top-k cosine search. Returns `(iri, similarity)` pairs+ /// sorted by similarity descending, on the same scale as the brute-force+ /// `VecStore::search_cosine` but quantised.+ pub fn search(&self, query: &[f32], top_k: usize) -> Vec<(String, f32)> {+ if self.inner.is_empty() || top_k == 0 || !self.query_is_scoreable(query) {+ return Vec::new();+ }+ let q = self.pad_query(query);+ let (scores, ids) = self.inner.search(&q, top_k);+ ids.into_iter()+ .zip(scores)+ .filter_map(|(id, score)| self.id_to_iri.get(&id).map(|iri| (iri.clone(), score)))+ .collect()+ }+}++/// Bump when the on-disk layout changes so a stale blob is rejected rather+/// than misread. `turbovec` versions its own payload independently.+const PERSIST_FORMAT_VERSION: u32 = 1;++/// What [`TurboCosineIndex::to_bytes`] writes and [`TurboCosineIndex::from_bytes`] reads.+#[derive(Serialize, Deserialize)]+struct PersistedIndex {+ format_version: u32,+ raw_dim: usize,+ next_id: u64,+ id_to_iri: Vec<(u64, String)>,+ index_bytes: Vec<u8>,+}diff --git a/src/vecstore.rs b/src/vecstore.rsindex 0c8ada29..957c9de0 100644--- a/src/vecstore.rs+++ b/src/vecstore.rs@@ -36,6 +36,11 @@ pub struct VecStore {/// `None` the fingerprint checks are skipped entirely, so an unconfigured/// store behaves exactly as it did before this column existed.embeddings_fp: Option<String>,+ /// Lazily-built TurboQuant index over `text_vec`s. Unlike the two HNSW+ /// indices above it is *not* invalidated by a mutation: `upsert` and+ /// `remove` maintain it in place, which is the entire reason it exists.+ #[cfg(feature = "turbovec")]+ turbo_index: Option<crate::turbo_index::TurboCosineIndex>,}impl VecStore {@@ -46,6 +51,8 @@ impl VecStore {cosine_index: None,poincare_index: None,embeddings_fp: None,+ #[cfg(feature = "turbovec")]+ turbo_index: None,}}@@ -83,19 +90,37 @@ impl VecStore {}pub fn upsert(&mut self, iri: &str, text_vec: &[f32], struct_vec: &[f32]) {+ let normalised = l2_normalize(text_vec);self.entries.insert(iri.to_string(), VecEntry {- text_vec: l2_normalize(text_vec),+ text_vec: normalised.clone(),struct_vec: struct_vec.to_vec(),});// Invalidate BOTH HNSW indices — instant-distance is immutable.self.cosine_index = None;self.poincare_index = None;+ // The TurboQuant index is not immutable, so it is updated rather than+ // dropped. A failure here (a dimensionality that disagrees with the+ // index the store was built with) drops the index instead of being+ // swallowed, so the next search rebuilds from scratch and stays+ // correct rather than silently missing the new entry.+ #[cfg(feature = "turbovec")]+ if self+ .turbo_index+ .as_mut()+ .is_some_and(|idx| idx.upsert(iri, &normalised).is_err())+ {+ self.turbo_index = None;+ }}pub fn remove(&mut self, iri: &str) {self.entries.remove(iri);self.cosine_index = None;self.poincare_index = None;+ #[cfg(feature = "turbovec")]+ if let Some(idx) = self.turbo_index.as_mut() {+ idx.remove(iri);+ }}pub fn search_cosine(&self, query: &[f32], top_k: usize) -> Vec<(String, f32)> {@@ -490,6 +515,143 @@ impl VecStore {Ok(true)}+ /// Exact top-k cosine search, accelerated by the TurboQuant index.+ ///+ /// The index is a candidate generator, not the answer: it returns a+ /// shortlist several times wider than `top_k` scored over 2-4 bit codes,+ /// and every candidate is then re-scored against the float32 vector the+ /// store already holds. So the result is identical to+ /// [`Self::search_cosine`] whenever the shortlist covers the true top-k,+ /// and no approximate similarity number ever reaches a caller.+ ///+ /// Builds the index on first call. Unlike [`Self::search_cosine_hnsw`],+ /// subsequent mutations do not force a rebuild.+ #[cfg(feature = "turbovec")]+ pub fn search_cosine_turbo(&mut self, query: &[f32], top_k: usize) -> Vec<(String, f32)> {+ if self.entries.is_empty() || top_k == 0 {+ return Vec::new();+ }+ if self.turbo_index.is_none() {+ match self.build_turbo_index() {+ Ok(idx) => self.turbo_index = Some(idx),+ Err(e) => {+ tracing::warn!("turbovec index build failed ({e}); falling back to the exact scan");+ return self.search_cosine(query, top_k);+ }+ }+ }+ let query_norm = l2_normalize(query);+ let shortlist = match self.turbo_index.as_ref() {+ Some(idx) => idx.search(&query_norm, Self::shortlist_width(top_k)),+ None => return self.search_cosine(query, top_k),+ };+ // Re-score the shortlist exactly. The quantised score is discarded.+ let mut rescored: Vec<(String, f32)> = shortlist+ .into_iter()+ .filter_map(|(iri, _quantised)| {+ self.entries+ .get(&iri)+ .map(|e| (iri.clone(), cosine_similarity(&query_norm, &e.text_vec)))+ })+ .collect();+ rescored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));+ rescored.truncate(top_k);+ rescored+ }++ /// How many quantised candidates to pull for a requested `top_k`.+ ///+ /// Four times the request plus a floor of 32: the multiplier covers the+ /// quantisation error on large requests, the floor covers small ones,+ /// where 4 x 3 candidates would leave no margin at all.+ #[cfg(feature = "turbovec")]+ fn shortlist_width(top_k: usize) -> usize {+ (top_k.saturating_mul(4)).max(top_k.saturating_add(32))+ }++ #[cfg(feature = "turbovec")]+ fn build_turbo_index(&self) -> anyhow::Result<crate::turbo_index::TurboCosineIndex> {+ let points: Vec<(String, Vec<f32>)> = self+ .entries+ .iter()+ .map(|(iri, e)| (iri.clone(), e.text_vec.clone()))+ .collect();+ crate::turbo_index::TurboCosineIndex::build(points)+ }++ /// Number of vectors in the live TurboQuant index, or `None` when it has+ /// not been built yet.+ #[cfg(feature = "turbovec")]+ pub fn turbo_index_len(&self) -> Option<usize> {+ self.turbo_index.as_ref().map(|idx| idx.len())+ }++ /// Persist the TurboQuant index into the shared index-cache table under+ /// its own `kind`, so it coexists with the two HNSW caches rather than+ /// competing with them for the row.+ #[cfg(feature = "turbovec")]+ pub fn persist_turbo_index(&mut self) -> anyhow::Result<()> {+ if self.entries.is_empty() {+ return Ok(());+ }+ if self.turbo_index.is_none() {+ self.turbo_index = Some(self.build_turbo_index()?);+ }+ let bytes = match self.turbo_index.as_ref() {+ Some(idx) => idx.to_bytes()?,+ None => return Ok(()),+ };+ let fp = self.entries_fingerprint();+ let count = self.entries.len() as i64;+ let conn = self.db.conn();+ conn.execute(+ "INSERT OR REPLACE INTO hnsw_index_cache (kind, entries_hash, entry_count, serialised, model_fp) \+ VALUES ('turbo_cosine', ?1, ?2, ?3, ?4)",+ rusqlite::params![fp, count, bytes, self.embeddings_fp],+ )?;+ Ok(())+ }++ /// Load a persisted TurboQuant index. Returns whether one was adopted.+ ///+ /// Both guards from the HNSW load path apply unchanged: `model_fp` catches+ /// an index built under a different embedding configuration, and+ /// `entries_hash` catches an entry set that has moved on since the cache+ /// was written.+ #[cfg(feature = "turbovec")]+ pub fn load_turbo_index(&mut self) -> anyhow::Result<bool> {+ let conn = self.db.conn();+ let row: Option<(Vec<u8>, Vec<u8>, Option<String>)> = conn+ .query_row(+ "SELECT entries_hash, serialised, model_fp FROM hnsw_index_cache WHERE kind = 'turbo_cosine'",+ [],+ |row| {+ Ok((+ row.get::<_, Vec<u8>>(0)?,+ row.get::<_, Vec<u8>>(1)?,+ row.get::<_, Option<String>>(2)?,+ ))+ },+ )+ .ok();+ let (stored_hash, bytes, stored_fp) = match row {+ Some(x) => x,+ None => return Ok(false),+ };+ if !self.fingerprint_matches(stored_fp.as_deref()) {+ tracing::warn!(+ "cached TurboQuant index was built under a different embedding configuration \+ — discarding it and rebuilding. One-off cost per configuration change."+ );+ return Ok(false);+ }+ if stored_hash != self.entries_fingerprint() {+ return Ok(false);+ }+ self.turbo_index = Some(crate::turbo_index::TurboCosineIndex::from_bytes(&bytes)?);+ Ok(true)+ }+pub fn persist(&self) -> anyhow::Result<()> {let conn = self.db.conn();let tx = conn.unchecked_transaction()?;diff --git a/tests/turbovec_index_test.rs b/tests/turbovec_index_test.rsnew file mode 100644index 00000000..d9176c42--- /dev/null+++ b/tests/turbovec_index_test.rs@@ -0,0 +1,477 @@+#![cfg(feature = "turbovec")]++//! Tests for the TurboQuant-backed cosine index.+//!+//! The reference for every ranking assertion is the brute-force exact cosine+//! scan already in `VecStore::search_cosine`: the quantised index is a+//! candidate generator, and it is only useful if its shortlist contains what+//! the exact scan would have returned.++use open_ontologies::poincare::l2_normalize;+use open_ontologies::turbo_index::TurboCosineIndex;++/// Deterministic pseudo-random unit vectors, so a failure is reproducible.+fn synth_vectors(n: usize, dim: usize) -> Vec<(String, Vec<f32>)> {+ let mut out = Vec::with_capacity(n);+ let mut state: u64 = 0x9E37_79B9_7F4A_7C15;+ for i in 0..n {+ let v: Vec<f32> = (0..dim)+ .map(|_| {+ state = state+ .wrapping_mul(6364136223846793005)+ .wrapping_add(1442695040888963407);+ ((state >> 33) as f32 / (1u64 << 31) as f32) - 0.5+ })+ .collect();+ out.push((format!("http://ex.org/C{i}"), l2_normalize(&v)));+ }+ out+}++fn exact_top1(entries: &[(String, Vec<f32>)], query: &[f32]) -> String {+ entries+ .iter()+ .map(|(iri, v)| {+ let dot: f32 = query.iter().zip(v.iter()).map(|(a, b)| a * b).sum();+ (iri.clone(), dot)+ })+ .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap())+ .unwrap()+ .0+}++#[test]+fn top1_agrees_with_brute_force_cosine() {+ let entries = synth_vectors(500, 64);+ let index = TurboCosineIndex::build(entries.clone()).unwrap();++ // Query near a known entry so there is an unambiguous winner.+ let query = entries[42].1.clone();++ let results = index.search(&query, 5);+ assert_eq!(results.len(), 5, "expected 5 candidates, got {}", results.len());+ assert_eq!(+ results[0].0,+ exact_top1(&entries, &query),+ "quantised top-1 disagrees with the exact cosine scan"+ );+}++#[test]+fn upsert_is_searchable_without_a_rebuild() {+ let entries = synth_vectors(200, 64);+ let mut index = TurboCosineIndex::build(entries.clone()).unwrap();++ // A direction no existing entry occupies: the first basis vector.+ let mut newcomer = vec![0.0f32; 64];+ newcomer[0] = 1.0;+ index.upsert("http://ex.org/Newcomer", &newcomer).unwrap();++ let results = index.search(&newcomer, 1);+ assert_eq!(+ results[0].0, "http://ex.org/Newcomer",+ "an upserted vector must be searchable without rebuilding the index"+ );+ assert_eq!(index.len(), 201);+}++#[test]+fn upsert_of_an_existing_iri_replaces_its_vector() {+ let entries = synth_vectors(50, 64);+ let mut index = TurboCosineIndex::build(entries.clone()).unwrap();++ let mut moved = vec![0.0f32; 64];+ moved[0] = 1.0;+ index.upsert("http://ex.org/C7", &moved).unwrap();++ assert_eq!(index.len(), 50, "replacing an IRI must not grow the index");+ let results = index.search(&moved, 1);+ assert_eq!(results[0].0, "http://ex.org/C7");+}++#[test]+fn remove_drops_the_entry() {+ let entries = synth_vectors(50, 64);+ let mut index = TurboCosineIndex::build(entries.clone()).unwrap();++ let target = entries[7].1.clone();+ assert_eq!(index.search(&target, 1)[0].0, "http://ex.org/C7");++ assert!(index.remove("http://ex.org/C7"));+ assert_eq!(index.len(), 49);+ assert!(+ index.search(&target, 10).iter().all(|(iri, _)| iri != "http://ex.org/C7"),+ "a removed IRI must not come back in results"+ );+ assert!(!index.remove("http://ex.org/C7"), "removing twice reports false");+}++#[test]+fn round_trips_through_bytes() {+ let entries = synth_vectors(300, 64);+ let mut index = TurboCosineIndex::build(entries.clone()).unwrap();+ index.remove("http://ex.org/C3");++ let bytes = index.to_bytes().unwrap();+ let reloaded = TurboCosineIndex::from_bytes(&bytes).unwrap();++ assert_eq!(reloaded.len(), index.len());+ let query = entries[11].1.clone();+ assert_eq!(+ reloaded.search(&query, 10),+ index.search(&query, 10),+ "a reloaded index must rank identically to the one it was serialised from"+ );+}++#[test]+fn upsert_after_a_reload_does_not_reuse_a_stale_id() {+ let entries = synth_vectors(20, 64);+ let index = TurboCosineIndex::build(entries.clone()).unwrap();+ let mut reloaded = TurboCosineIndex::from_bytes(&index.to_bytes().unwrap()).unwrap();++ let mut newcomer = vec![0.0f32; 64];+ newcomer[0] = 1.0;+ reloaded.upsert("http://ex.org/Newcomer", &newcomer).unwrap();++ assert_eq!(reloaded.len(), 21);+ assert_eq!(reloaded.search(&newcomer, 1)[0].0, "http://ex.org/Newcomer");+}++#[test]+fn search_within_restricts_results_to_the_allowlist() {+ let entries = synth_vectors(200, 64);+ let index = TurboCosineIndex::build(entries.clone()).unwrap();++ let query = entries[0].1.clone();+ let allowed = vec![+ "http://ex.org/C150".to_string(),+ "http://ex.org/C151".to_string(),+ "http://ex.org/C152".to_string(),+ ];++ let results = index.search_within(&query, 10, &allowed).unwrap();+ assert_eq!(results.len(), 3, "effective k is capped by the allowlist size");+ assert!(+ results.iter().all(|(iri, _)| allowed.contains(iri)),+ "results escaped the allowlist: {results:?}"+ );+}++#[test]+fn search_within_ignores_unknown_iris_rather_than_failing() {+ let entries = synth_vectors(20, 64);+ let index = TurboCosineIndex::build(entries.clone()).unwrap();++ let allowed = vec!["http://ex.org/C1".to_string(), "http://ex.org/Ghost".to_string()];+ let results = index.search_within(&entries[1].1, 10, &allowed).unwrap();++ assert_eq!(results.len(), 1);+ assert_eq!(results[0].0, "http://ex.org/C1");+}++#[test]+fn search_within_an_empty_allowlist_returns_nothing() {+ let entries = synth_vectors(20, 64);+ let index = TurboCosineIndex::build(entries.clone()).unwrap();+ assert!(index.search_within(&entries[0].1, 10, &[]).unwrap().is_empty());+}++#[test]+fn a_dim_that_is_not_a_multiple_of_eight_is_padded() {+ // turbovec requires dim % 8 == 0; the vector store accepts any width.+ let entries = vec![+ ("http://ex.org/Dog".to_string(), l2_normalize(&[0.9, 0.1, 0.0])),+ ("http://ex.org/Cat".to_string(), l2_normalize(&[0.8, 0.2, 0.0])),+ ("http://ex.org/Car".to_string(), l2_normalize(&[0.0, 0.0, 1.0])),+ ];+ let index = TurboCosineIndex::build(entries).unwrap();++ let results = index.search(&l2_normalize(&[0.0, 0.0, 1.0]), 1);+ assert_eq!(results[0].0, "http://ex.org/Car");+}++#[test]+fn a_non_finite_query_returns_nothing_rather_than_panicking() {+ // turbovec's allowlist-free `search` is the panicking form, and it panics+ // on a non-finite query coordinate. A broken embedding provider must not+ // be able to take down the MCP server through this path.+ let entries = synth_vectors(20, 64);+ let index = TurboCosineIndex::build(entries).unwrap();++ let mut nan_query = vec![0.1f32; 64];+ nan_query[3] = f32::NAN;+ assert!(index.search(&nan_query, 5).is_empty());++ let mut inf_query = vec![0.1f32; 64];+ inf_query[3] = f32::INFINITY;+ assert!(index.search(&inf_query, 5).is_empty());+ assert!(index+ .search_within(&inf_query, 5, &["http://ex.org/C1".to_string()])+ .unwrap()+ .is_empty());+}++#[test]+fn a_query_of_the_wrong_dimensionality_returns_nothing_rather_than_being_truncated() {+ let entries = synth_vectors(20, 64);+ let index = TurboCosineIndex::build(entries).unwrap();++ // Silently truncating or padding a mismatched query would return a+ // plausible-looking ranking computed against the wrong vector.+ assert!(index.search(&vec![0.1f32; 128], 5).is_empty());+ assert!(index.search(&vec![0.1f32; 32], 5).is_empty());+ assert!(index+ .search_within(&vec![0.1f32; 128], 5, &["http://ex.org/C1".to_string()])+ .unwrap()+ .is_empty());+}++// ---------------------------------------------------------------------------+// VecStore integration+// ---------------------------------------------------------------------------++use open_ontologies::state::StateDb;+use open_ontologies::vecstore::VecStore;++fn test_db() -> StateDb {+ let tmp = tempfile::NamedTempFile::new().unwrap();+ let path = tmp.path().to_path_buf();+ std::mem::forget(tmp);+ StateDb::open(&path).unwrap()+}++fn populated_store(n: usize, dim: usize) -> (VecStore, Vec<(String, Vec<f32>)>) {+ let entries = synth_vectors(n, dim);+ let mut store = VecStore::new(test_db());+ for (iri, v) in &entries {+ store.upsert(iri, v, &[0.1, 0.1]);+ }+ (store, entries)+}++#[test]+fn turbo_search_returns_the_same_ranking_and_scores_as_the_exact_scan() {+ let (mut store, entries) = populated_store(400, 64);+ let query = entries[99].1.clone();++ let exact = store.search_cosine(&query, 10);+ let turbo = store.search_cosine_turbo(&query, 10);++ assert_eq!(+ turbo, exact,+ "the turbo path re-scores its candidates exactly, so it must not \+ differ from the brute-force scan in either order or score"+ );+}++#[test]+fn upsert_keeps_the_turbo_index_warm_instead_of_dropping_it() {+ let (mut store, _entries) = populated_store(100, 64);+ // Warm the index.+ let _ = store.search_cosine_turbo(&vec![0.1; 64], 5);+ assert_eq!(store.turbo_index_len(), Some(100));++ let mut newcomer = vec![0.0f32; 64];+ newcomer[0] = 1.0;+ store.upsert("http://ex.org/Newcomer", &newcomer, &[0.1, 0.1]);++ assert_eq!(+ store.turbo_index_len(),+ Some(101),+ "upsert must extend the live turbo index, not invalidate it"+ );+ assert_eq!(+ store.search_cosine_turbo(&newcomer, 1)[0].0,+ "http://ex.org/Newcomer"+ );+}++#[test]+fn remove_updates_the_turbo_index_in_place() {+ let (mut store, entries) = populated_store(100, 64);+ let _ = store.search_cosine_turbo(&entries[0].1, 5);++ store.remove("http://ex.org/C5");++ assert_eq!(store.turbo_index_len(), Some(99));+ assert!(store+ .search_cosine_turbo(&entries[5].1, 10)+ .iter()+ .all(|(iri, _)| iri != "http://ex.org/C5"));+}++#[test]+fn the_turbo_index_survives_a_process_restart_through_sqlite() {+ let tmp = tempfile::NamedTempFile::new().unwrap();+ let path = tmp.path().to_path_buf();+ std::mem::forget(tmp);++ let entries = synth_vectors(200, 64);+ {+ let mut store = VecStore::new(StateDb::open(&path).unwrap());+ for (iri, v) in &entries {+ store.upsert(iri, v, &[0.1, 0.1]);+ }+ let _ = store.search_cosine_turbo(&entries[0].1, 5);+ store.persist().unwrap();+ store.persist_turbo_index().unwrap();+ }++ let mut reloaded = VecStore::new(StateDb::open(&path).unwrap());+ reloaded.load_from_db().unwrap();+ assert!(+ reloaded.load_turbo_index().unwrap(),+ "a persisted turbo index should reload rather than rebuild"+ );+ assert_eq!(reloaded.turbo_index_len(), Some(200));+}++#[test]+fn a_stale_turbo_index_cache_is_rejected() {+ let tmp = tempfile::NamedTempFile::new().unwrap();+ let path = tmp.path().to_path_buf();+ std::mem::forget(tmp);++ let entries = synth_vectors(50, 64);+ {+ let mut store = VecStore::new(StateDb::open(&path).unwrap());+ for (iri, v) in &entries {+ store.upsert(iri, v, &[0.1, 0.1]);+ }+ let _ = store.search_cosine_turbo(&entries[0].1, 5);+ store.persist_turbo_index().unwrap();+ // Entries move on without the cache being refreshed.+ store.upsert("http://ex.org/Extra", &vec![0.5; 64], &[0.1, 0.1]);+ store.persist().unwrap();+ }++ let mut reloaded = VecStore::new(StateDb::open(&path).unwrap());+ reloaded.load_from_db().unwrap();+ assert!(+ !reloaded.load_turbo_index().unwrap(),+ "an index cache whose entry set has moved on must be refused"+ );+}++// ---------------------------------------------------------------------------+// Measurement. `cargo test --release --features turbovec -- --ignored --nocapture`+// ---------------------------------------------------------------------------++#[test]+#[ignore = "measurement, not an assertion; run explicitly in release"]+fn measure_turbo_against_hnsw() {+ use open_ontologies::hnsw_index::CosineIndex;+ use std::time::Instant;++ const N: usize = 10_000;+ const DIM: usize = 768;+ const TOP_K: usize = 10;++ let entries = synth_vectors(N, DIM);+ println!("\n{N} vectors x {DIM} dims\n");++ let t = Instant::now();+ let mut hnsw = CosineIndex::build(entries.clone());+ let hnsw_build = t.elapsed();++ let t = Instant::now();+ let mut turbo = TurboCosineIndex::build(entries.clone()).unwrap();+ let turbo_build = t.elapsed();+ println!("build hnsw {hnsw_build:>10.2?} turbo {turbo_build:>10.2?}");++ // The cost of one added embedding: instant-distance is immutable, so the+ // whole graph is rebuilt; turbovec appends.+ let mut newcomer = vec![0.0f32; DIM];+ newcomer[0] = 1.0;+ let t = Instant::now();+ let _rebuilt = CosineIndex::build(entries.clone());+ let hnsw_upsert = t.elapsed();+ let t = Instant::now();+ turbo.upsert("http://ex.org/Newcomer", &newcomer).unwrap();+ let turbo_upsert = t.elapsed();+ println!(+ "one upsert hnsw {hnsw_upsert:>10.2?} turbo {turbo_upsert:>10.2?} ({:.0}x)",+ hnsw_upsert.as_secs_f64() / turbo_upsert.as_secs_f64()+ );++ let queries: Vec<Vec<f32>> = (0..200).map(|i| entries[i * 97 % N].1.clone()).collect();++ let t = Instant::now();+ for q in &queries {+ let _ = hnsw.search(q, TOP_K);+ }+ let hnsw_q = t.elapsed() / queries.len() as u32;+ let t = Instant::now();+ for q in &queries {+ let _ = turbo.search(q, TOP_K * 4);+ }+ let turbo_q = t.elapsed() / queries.len() as u32;+ println!("query hnsw {hnsw_q:>10.2?} turbo {turbo_q:>10.2?} (turbo pulls 4x candidates)");++ // Recall of the exact top-k inside each index's returned set.+ let mut hnsw_hits = 0usize;+ let mut hnsw_wide_hits = 0usize;+ let mut turbo_hits = 0usize;+ let mut total = 0usize;+ for q in &queries {+ let mut exact: Vec<(String, f32)> = entries+ .iter()+ .map(|(iri, v)| (iri.clone(), q.iter().zip(v).map(|(a, b)| a * b).sum::<f32>()))+ .collect();+ exact.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());+ let truth: Vec<&String> = exact.iter().take(TOP_K).map(|(i, _)| i).collect();++ let h: Vec<String> = hnsw.search(q, TOP_K).into_iter().map(|(i, _)| i).collect();+ let h_wide: Vec<String> = hnsw+ .search(q, TOP_K * 4)+ .into_iter()+ .map(|(i, _)| i)+ .collect();+ let tv: Vec<String> = turbo+ .search(q, TOP_K * 4)+ .into_iter()+ .map(|(i, _)| i)+ .collect();+ for iri in &truth {+ total += 1;+ if h.contains(iri) {+ hnsw_hits += 1;+ }+ if h_wide.contains(iri) {+ hnsw_wide_hits += 1;+ }+ if tv.contains(iri) {+ turbo_hits += 1;+ }+ }+ }+ // Three numbers, because the interesting question is whether an accuracy+ // difference comes from TurboQuant or merely from over-querying and+ // re-scoring, a pattern the HNSW backend could adopt too.+ println!(+ "recall@{TOP_K} hnsw {:>9.1}% (as wired: {TOP_K} returned, {TOP_K} kept)",+ 100.0 * hnsw_hits as f64 / total as f64+ );+ println!(+ " hnsw {:>9.1}% (control: {} returned, re-scored to {TOP_K})",+ 100.0 * hnsw_wide_hits as f64 / total as f64,+ TOP_K * 4+ );+ println!(+ " turbo {:>9.1}% (as wired: {} returned, re-scored to {TOP_K})",+ 100.0 * turbo_hits as f64 / total as f64,+ TOP_K * 4+ );++ let hnsw_bytes = hnsw.to_bytes().unwrap().len();+ let turbo_bytes = turbo.to_bytes().unwrap().len();+ let f32_bytes = N * DIM * 4;+ println!(+ "serialised hnsw {:>7.1} MB turbo {:>7.1} MB raw float32 {:>7.1} MB",+ hnsw_bytes as f64 / 1e6,+ turbo_bytes as f64 / 1e6,+ f32_bytes as f64 / 1e6+ );+ println!();+}