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): evict float32 text vectors; re-measure recall on real corpora
FABIOTESS316e6547deb3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 41af0ab3..74d572a1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,47 @@ All notable changes to Open Ontologies are documented here.## [Unreleased]### Added+- **Optional eviction of float32 text vectors from memory**+ (`VecStore::with_text_vectors_evicted`, `turbovec` feature). Without it the+ TurboQuant backend's compression is a smaller SQLite blob rather than less+ RAM, because the 4 bit codes and the float32 vectors they were made from are+ both resident. In eviction mode the float32 lives only in the `embeddings`+ table: upserts write through to the row before touching memory, removals+ delete it, and reads load on demand. Three new accessors carry every path+ that used to reach into the entry map directly: `fetch_text_vecs` pulls just+ the shortlist for the exact re-score (the hot path, one query rather than one+ round trip per candidate), `all_text_vecs` streams the whole set IRI-sorted+ for the paths that genuinely need every vector, and the public+ `load_text_vec` returns one owned vector in either mode. New+ `resident_text_vector_bytes()` reports what is still held.++ `entries_fingerprint` is now public and reads through `all_text_vecs`, so an+ evicted store and a resident one over the same database hash the same stream+ and can share persisted index caches; a test asserts that equality.+ `get_text_vec` still returns a borrowed slice and therefore returns `None`+ under eviction, which is why `align.rs` and `onto_compare` were moved to+ `load_text_vec`: left alone they would have silently scored every pair at+ 0.0. Eviction is only coherent with the TurboQuant backend, since an+ `instant-distance` graph holds its own float32 copy of every point. 8 tests+ in `tests/vecstore_eviction_test.rs`, each asserting an evicted store returns+ exactly what a resident one built from identical data returns, plus an+ `#[ignore]`d measurement of what the mode costs per query.++ Measured at 20,000 vectors x 384 dims on an M3 Max: 30.7 MB of resident+ float32 goes to zero, `search_cosine_turbo` costs about 75 us more per query+ (312 us to 387 us) for the shortlist fetch, and the exact `search_cosine`+ scan costs 2.4x more (16.4 ms to 39.4 ms) because it reads every row. Evict+ when the workload queries through the turbo path; do not evict when it leans+ on the exact scan.++### Fixed+- **`search_cosine` and `search_product` no longer clone the entire corpus per+ query.** Routing them through the new whole-set accessor initially copied+ every float32 vector on every call, which cost 20 ms per query at 20,000 x+ 384 and made a resident store measurably slower than an evicted one. The+ accessor now yields `Cow` and borrows when the vectors are resident: the+ exact scan went from 36.6 ms to 16.4 ms. Caught by the eviction measurement,+ not by the tests, which only assert results.- **TurboQuant cosine index backend** (new optional `turbovec` feature, off bydefault, implies `embeddings`). A second index backend for the text half ofthe vector store, built on Google Research's TurboQuant quantiser@@ -62,16 +103,23 @@ All notable changes to Open Ontologies are documented here.`#[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+ the tables): build 116 s vs 178 ms, one added embedding 137 s vs 52 us, query4.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.+ float32.++ The recall picture is worth stating carefully, because the first measurement+ overstated it. On that synthetic corpus recall@10 is 91.6% for HNSW and 100%+ for the re-scored TurboQuant shortlist, and the control shows the gap is+ structural rather than a matter of shortlist width: giving HNSW 40 candidates+ instead of 10 leaves it at exactly 91.6%, because the entries it misses are+ ones the graph walk never reaches. But isotropic random vectors are close to+ the worst case for a graph index, and on a real corpus the gap all but+ vanishes. `measure_recall_on_a_real_corpus` embeds 10,000 real ontology+ labels with the shipped local MiniLM model over two contrasting real corpora,+ a topical taxonomy (mean pairwise cosine 0.25) and a set of real-world entity+ names (0.34), against ~0 for the synthetic corpus. HNSW scores 99.9% and+ 99.8% there, against 100% for TurboQuant. So recall is not a reason to switch backends; mutation cost and+ index size are.- **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/docs/embeddings.md b/docs/embeddings.mdindex e3663f29..366d0108 100644--- a/docs/embeddings.md+++ b/docs/embeddings.md@@ -63,9 +63,8 @@ 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`).+10,000 vectors x 768 dims of isotropic random data, Apple M3 Max, release+build, `measure_turbo_against_hnsw` in `tests/turbovec_index_test.rs`:| | HNSW | TurboQuant || --- | --- | --- |@@ -77,23 +76,34 @@ configuration, and `entries_hash` rejects one whose entry set has moved on.| 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.+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.++**Do not read the recall rows as a reason to switch.** They come from+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. On a real corpus the+gap all but disappears. `measure_recall_on_a_real_corpus` embeds 10,000 real+ontology labels with the shipped local MiniLM model over two contrasting real+corpora, one a topical taxonomy and one a set of real-world entity names:++| Corpus (10,000 labels, 384 dims) | mean pairwise cosine | HNSW as wired | HNSW, 40 re-scored to 10 | TurboQuant |+| --- | --- | --- | --- | --- |+| Learning-standards labels | 0.25 | 99.9% | 99.9% | 100% |+| Securities-register entity names | 0.34 | 99.8% | 99.8% | 100% |+| Isotropic random (for contrast) | ~0 | 91.6% | 91.6% | 100% |++So HNSW's recall is data-dependent and TurboQuant's is not, but on data that+looks like anything you would actually embed, HNSW is already effectively+exact. The honest reasons to prefer the TurboQuant backend are mutation cost+and index size, not accuracy.++The one structural point the synthetic run does establish: over-fetching does+not help a graph index. Giving HNSW 40 candidates instead of 10 leaves its+recall unchanged to the digit in both corpora, because the entries it misses+are ones the walk never reaches and `ef_search` is the only lever. A flat+quantised scan cannot have that failure mode, because it scores every vector.**When to pick which.** HNSW if the ontology is embedded once and then onlyqueried. TurboQuant if embeddings arrive incrementally (the rebuild is what@@ -101,6 +111,51 @@ you are paying for, not the query), or if the corpus is large enough thatfloat32 storage is the constraint: at 768 dims a 4 bit code is 388 bytesagainst 3,072.+### Evicting float32 text vectors++`VecStore` normally keeps every float32 text vector in memory for the lifetime+of the process. That makes TurboQuant's compression a smaller SQLite blob+rather than less RAM, because the codes and the vectors they were made from+are both resident.++```rust+let store = VecStore::new(db).with_text_vectors_evicted();+```++In eviction mode the float32 lives only in the `embeddings` table. Upserts+write through to the row before touching memory, removals delete it, and reads+load on demand: `fetch_text_vecs` pulls just the shortlist for the exact+re-score, `all_text_vecs` streams the whole set for the paths that genuinely+need every vector (the exact scan, the product search, index builds, the+fingerprint). `resident_text_vector_bytes()` reports what is still held, and it+is zero under eviction.++Two things to know before turning it on:++- **It is only coherent with the TurboQuant backend.** An `instant-distance`+ graph holds its own float32 copy of every point, so evicting the store's copy+ while querying through HNSW moves the memory rather than saving it.+- **`get_text_vec` returns `None` under eviction**, because there is no+ in-memory vector to borrow. `load_text_vec` returns an owned vector and works+ in both modes; every internal caller uses it.++An evicted store and a resident one over the same database produce the same+entry-set fingerprint, so they can share persisted index caches.++Measured at 20,000 vectors x 384 dims on an M3 Max+(`measure_eviction_cost` in `tests/vecstore_eviction_test.rs`):++| | Resident | Evicted |+| --- | --- | --- |+| float32 held in memory | 30.7 MB | 0 MB |+| `search_cosine_turbo`, top-10 | 312 us | 387 us (1.2x) |+| `search_cosine`, exact scan | 16.4 ms | 39.4 ms (2.4x) |++The turbo path pays about 75 us per query for the shortlist fetch, which is the+trade the mode exists to make. The exact scan pays much more, because it reads+every row: if a workload leans on `search_cosine` rather than+`search_cosine_turbo`, do not evict.+## ProvidersThe text-embedding side is pluggable via `[embeddings] provider`:diff --git a/src/align.rs b/src/align.rsindex c36d385d..5a6edc28 100644--- a/src/align.rs+++ b/src/align.rs@@ -435,7 +435,7 @@ impl AlignmentEngine {std::collections::HashMap::new();let mut any_used = false;for sc in &source_classes {- if let Some(src_vec) = vs.get_text_vec(&sc.iri).map(|v| v.to_vec()) {+ if let Some(src_vec) = vs.load_text_vec(&sc.iri) {let shortlist = vs.search_cosine_hnsw(&src_vec, HNSW_TOP_K);if !shortlist.is_empty() {let filtered: std::collections::HashSet<String> = shortlist@@ -491,8 +491,11 @@ impl AlignmentEngine {let embedding_sim = {if let Some(ref vs) = self.vecstore {let vs = vs.lock().unwrap();- match (vs.get_text_vec(&sc.iri), vs.get_text_vec(&tc.iri)) {- (Some(a), Some(b)) => Self::embedding_similarity_score(a, b),+ // `load_text_vec`, not `get_text_vec`: the latter can+ // only answer for a resident store, and would silently+ // score every pair at 0.0 under text-vector eviction.+ match (vs.load_text_vec(&sc.iri), vs.load_text_vec(&tc.iri)) {+ (Some(a), Some(b)) => Self::embedding_similarity_score(&a, &b),_ => 0.0,}} else {diff --git a/src/server.rs b/src/server.rsindex d179c63b..b2545b6a 100644--- a/src/server.rs+++ b/src/server.rs@@ -2656,8 +2656,9 @@ impl OpenOntologiesServer {{let vecstore = self.vecstore.lock().unwrap();- let text_a = vecstore.get_text_vec(&input.iri_a);- let text_b = vecstore.get_text_vec(&input.iri_b);+ // Owned loads, so this works under text-vector eviction too.+ let text_a = vecstore.load_text_vec(&input.iri_a);+ let text_b = vecstore.load_text_vec(&input.iri_b);let struct_a = vecstore.get_struct_vec(&input.iri_a);let struct_b = vecstore.get_struct_vec(&input.iri_b);@@ -2666,7 +2667,7 @@ impl OpenOntologiesServer {if text_a.is_none() { &input.iri_a } else { &input.iri_b });}- let cos = crate::poincare::cosine_similarity(text_a.unwrap(), text_b.unwrap());+ let cos = crate::poincare::cosine_similarity(&text_a.unwrap(), &text_b.unwrap());let poinc = if let (Some(a), Some(b)) = (struct_a, struct_b) {crate::poincare::poincare_distance(a, b)} else {diff --git a/src/vecstore.rs b/src/vecstore.rsindex 957c9de0..09564353 100644--- a/src/vecstore.rs+++ b/src/vecstore.rs@@ -8,7 +8,12 @@ use std::collections::HashMap;#[derive(Clone)]struct VecEntry {- text_vec: Vec<f32>,+ /// `None` when the store is evicting text vectors: the float32 lives only+ /// in the `embeddings` table and is loaded on demand.+ text_vec: Option<Vec<f32>>,+ /// Retained in both modes. The dimensionality is needed by callers that+ /// only want to know the shape, and an evicted entry has no vector to ask.+ text_dim: usize,struct_vec: Vec<f32>,}@@ -41,6 +46,15 @@ pub struct VecStore {/// `remove` maintain it in place, which is the entire reason it exists.#[cfg(feature = "turbovec")]turbo_index: Option<crate::turbo_index::TurboCosineIndex>,+ /// When true, float32 text vectors are not retained in memory. They are+ /// written through to the `embeddings` table on upsert and loaded back on+ /// demand: a shortlist per query for the exact re-score, the whole set for+ /// paths that genuinely need every vector.+ ///+ /// Only worth turning on with the TurboQuant backend. The HNSW graph holds+ /// its own float32 copies of every point, so evicting the store's copy+ /// while querying through HNSW moves the memory rather than saving it.+ evict_text: bool,}impl VecStore {@@ -53,9 +67,28 @@ impl VecStore {embeddings_fp: None,#[cfg(feature = "turbovec")]turbo_index: None,+ evict_text: false,}}+ /// Stop retaining float32 text vectors in memory.+ ///+ /// Set it before loading or upserting anything. See the `evict_text` field+ /// for what it costs and when it pays.+ pub fn with_text_vectors_evicted(mut self) -> Self {+ self.evict_text = true;+ self+ }++ /// Bytes of float32 text vector currently held in memory. Zero in eviction+ /// mode, which is the whole point of it.+ pub fn resident_text_vector_bytes(&self) -> usize {+ self.entries+ .values()+ .map(|e| e.text_vec.as_ref().map_or(0, |v| v.len() * 4))+ .sum()+ }+/// Record which embedding configuration produced (and will produce) the/// vectors in this store.///@@ -91,8 +124,17 @@ impl VecStore {pub fn upsert(&mut self, iri: &str, text_vec: &[f32], struct_vec: &[f32]) {let normalised = l2_normalize(text_vec);+ // In eviction mode the row IS the storage, so it is written before the+ // in-memory bookkeeping: a later read must never find an entry whose+ // vector was never persisted.+ if self.evict_text+ && let Err(e) = self.write_through(iri, &normalised, struct_vec)+ {+ tracing::error!("failed to persist embedding for {iri}: {e}");+ }self.entries.insert(iri.to_string(), VecEntry {- text_vec: normalised.clone(),+ text_vec: if self.evict_text { None } else { Some(normalised.clone()) },+ text_dim: normalised.len(),struct_vec: struct_vec.to_vec(),});// Invalidate BOTH HNSW indices — instant-distance is immutable.@@ -114,6 +156,12 @@ impl VecStore {}pub fn remove(&mut self, iri: &str) {+ if self.evict_text && self.entries.contains_key(iri) {+ let conn = self.db.conn();+ if let Err(e) = conn.execute("DELETE FROM embeddings WHERE iri = ?1", [iri]) {+ tracing::error!("failed to delete embedding row for {iri}: {e}");+ }+ }self.entries.remove(iri);self.cosine_index = None;self.poincare_index = None;@@ -123,10 +171,159 @@ impl VecStore {}}+ /// Write one entry straight to the `embeddings` table. Eviction mode only:+ /// with vectors resident, `persist` does this in bulk instead.+ fn write_through(&self, iri: &str, text_vec: &[f32], struct_vec: &[f32]) -> anyhow::Result<()> {+ let conn = self.db.conn();+ conn.execute(+ "INSERT OR REPLACE INTO embeddings (iri, text_vec, struct_vec, text_dim, struct_dim, model_fp) \+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)",+ rusqlite::params![+ iri,+ f32_slice_to_bytes(text_vec),+ f32_slice_to_bytes(struct_vec),+ text_vec.len() as i64,+ struct_vec.len() as i64,+ self.embeddings_fp,+ ],+ )?;+ Ok(())+ }++ /// One text vector, from memory or from the row, whichever holds it.+ ///+ /// Prefer this over [`Self::get_text_vec`], which can only answer for a+ /// resident store and returns `None` under eviction.+ pub fn load_text_vec(&self, iri: &str) -> Option<Vec<f32>> {+ match self.entries.get(iri) {+ None => None,+ Some(e) => match &e.text_vec {+ Some(v) => Some(v.clone()),+ None => {+ let conn = self.db.conn();+ conn.query_row(+ "SELECT text_vec FROM embeddings WHERE iri = ?1",+ [iri],+ |row| row.get::<_, Vec<u8>>(0),+ )+ .ok()+ .map(|b| bytes_to_f32_vec(&b))+ }+ },+ }+ }++ /// A named subset of text vectors in one query. This is the hot path under+ /// eviction: the re-score needs the shortlist and nothing else, so it must+ /// not degenerate into one round trip per candidate.+ fn fetch_text_vecs(&self, iris: &[String]) -> HashMap<String, Vec<f32>> {+ if !self.evict_text {+ return iris+ .iter()+ .filter_map(|iri| {+ self.entries+ .get(iri)+ .and_then(|e| e.text_vec.as_ref())+ .map(|v| (iri.clone(), v.clone()))+ })+ .collect();+ }+ if iris.is_empty() {+ return HashMap::new();+ }+ let placeholders = std::iter::repeat_n("?", iris.len())+ .collect::<Vec<_>>()+ .join(",");+ let sql = format!("SELECT iri, text_vec FROM embeddings WHERE iri IN ({placeholders})");+ let conn = self.db.conn();+ let mut out = HashMap::with_capacity(iris.len());+ if let Ok(mut stmt) = conn.prepare(&sql) {+ let params = rusqlite::params_from_iter(iris.iter());+ if let Ok(rows) = stmt.query_map(params, |row| {+ Ok((row.get::<_, String>(0)?, row.get::<_, Vec<u8>>(1)?))+ }) {+ for row in rows.flatten() {+ out.insert(row.0, bytes_to_f32_vec(&row.1));+ }+ }+ }+ out+ }++ /// Every text vector, sorted by IRI so the order is deterministic in both+ /// modes. Used by the paths that genuinely need the whole set: the exact+ /// scan, the product search, index builds, and the fingerprint.+ ///+ /// Borrowed when the vectors are resident. A scan that cloned the entire+ /// corpus per query would cost more than the arithmetic it exists to do,+ /// and would make a resident store slower than an evicted one.+ fn all_text_vecs_cow(&self) -> Vec<(&str, std::borrow::Cow<'_, [f32]>)> {+ if !self.evict_text {+ let mut out: Vec<(&str, std::borrow::Cow<'_, [f32]>)> = self+ .entries+ .iter()+ .filter_map(|(iri, e)| {+ e.text_vec+ .as_ref()+ .map(|v| (iri.as_str(), std::borrow::Cow::Borrowed(v.as_slice())))+ })+ .collect();+ out.sort_by(|a, b| a.0.cmp(b.0));+ return out;+ }+ self.stream_text_vecs()+ .into_iter()+ .map(|(iri, v)| {+ let key = self+ .entries+ .get_key_value(&iri)+ .map(|(k, _)| k.as_str())+ .unwrap_or("");+ (key, std::borrow::Cow::Owned(v))+ })+ .collect()+ }++ /// Owned form, for the index builders that need to hand vectors on.+ fn all_text_vecs(&self) -> Vec<(String, Vec<f32>)> {+ self.all_text_vecs_cow()+ .into_iter()+ .map(|(iri, v)| (iri.to_string(), v.into_owned()))+ .collect()+ }++ /// The evicted arm of [`Self::all_text_vecs_cow`]: read every row back.+ fn stream_text_vecs(&self) -> Vec<(String, Vec<f32>)> {+ let conn = self.db.conn();+ let mut out = Vec::with_capacity(self.entries.len());+ if let Ok(mut stmt) =+ conn.prepare("SELECT iri, text_vec FROM embeddings ORDER BY iri ASC")+ && let Ok(rows) = stmt.query_map([], |row| {+ Ok((row.get::<_, String>(0)?, row.get::<_, Vec<u8>>(1)?))+ })+ {+ {+ for (iri, bytes) in rows.flatten() {+ // The table can outlive an entry that was removed from the+ // set in a mode that did not delete rows; trust `entries`.+ if self.entries.contains_key(&iri) {+ out.push((iri, bytes_to_f32_vec(&bytes)));+ }+ }+ }+ }+ out+ }+pub fn search_cosine(&self, query: &[f32], top_k: usize) -> Vec<(String, f32)> {let query_norm = l2_normalize(query);- let mut scores: Vec<(String, f32)> = self.entries.iter()- .map(|(iri, e)| (iri.clone(), cosine_similarity(&query_norm, &e.text_vec)))+ let mut scores: Vec<(String, f32)> = self+ .all_text_vecs_cow()+ .into_iter()+ .map(|(iri, v)| {+ let sim = cosine_similarity(&query_norm, &v);+ (iri.to_string(), sim)+ }).collect();scores.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));scores.truncate(top_k);@@ -157,11 +354,7 @@ impl VecStore {// 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();+ let points = self.all_text_vecs();self.cosine_index = Some(CosineIndex::build(points));}let query_norm = l2_normalize(query);@@ -210,13 +403,15 @@ impl VecStore {alpha: f32,) -> Vec<(String, f32)> {let text_norm = l2_normalize(text_query);- let mut scores: Vec<(String, f32)> = self.entries.iter()- .map(|(iri, e)| {- let cos = cosine_similarity(&text_norm, &e.text_vec);- let poinc = poincare_distance(struct_query, &e.struct_vec);+ let mut scores: Vec<(String, f32)> = self+ .all_text_vecs_cow()+ .into_iter()+ .filter_map(|(iri, text)| {+ let struct_vec = &self.entries.get(iri)?.struct_vec;+ let cos = cosine_similarity(&text_norm, &text);+ let poinc = poincare_distance(struct_query, struct_vec);let poinc_sim = 1.0 / (1.0 + poinc);- let combined = alpha * cos + (1.0 - alpha) * poinc_sim;- (iri.clone(), combined)+ Some((iri.to_string(), alpha * cos + (1.0 - alpha) * poinc_sim))}).collect();scores.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));@@ -229,17 +424,18 @@ impl VecStore {/// underlying vectors have changed. Includes both keys and text-vec bytes/// in the hash so re-embedding the same IRI with a new vector triggers a/// rebuild.- fn entries_fingerprint(&self) -> Vec<u8> {- let mut keys: Vec<&String> = self.entries.keys().collect();- keys.sort();+ pub fn entries_fingerprint(&self) -> Vec<u8> {+ // `all_text_vecs` returns IRI-sorted pairs in both modes, and SQLite's+ // default BINARY collation orders the same way Rust's `String` does,+ // so an evicted store and a resident one hash the same stream and can+ // share a database and its index caches.let mut hash: u64 = 0xcbf29ce484222325;- for k in keys {- for byte in k.as_bytes() {+ for (iri, vec) in self.all_text_vecs_cow() {+ for byte in iri.as_bytes() {hash ^= *byte as u64;hash = hash.wrapping_mul(0x100000001b3);}- let v = &self.entries[k];- for f in &v.text_vec {+ for f in vec.iter() {for byte in f.to_le_bytes() {hash ^= byte as u64;hash = hash.wrapping_mul(0x100000001b3);@@ -257,11 +453,7 @@ impl VecStore {self.cosine_index = None;return;}- let points: Vec<(String, Vec<f32>)> = self- .entries- .iter()- .map(|(iri, e)| (iri.clone(), e.text_vec.clone()))- .collect();+ let points = self.all_text_vecs();self.cosine_index = Some(crate::hnsw_index::CosineIndex::build_with_params(points, params,));@@ -294,11 +486,7 @@ impl VecStore {return Ok(());}if self.cosine_index.is_none() {- let points: Vec<(String, Vec<f32>)> = self- .entries- .iter()- .map(|(iri, e)| (iri.clone(), e.text_vec.clone()))- .collect();+ let points = self.all_text_vecs();self.cosine_index = Some(CosineIndex::build(points));}let bytes = match self.cosine_index.as_ref() {@@ -378,11 +566,7 @@ impl VecStore {return Ok(tokio::task::spawn(async { Ok::<(), anyhow::Error>(()) }));}if self.cosine_index.is_none() {- let points: Vec<(String, Vec<f32>)> = self- .entries- .iter()- .map(|(iri, e)| (iri.clone(), e.text_vec.clone()))- .collect();+ let points = self.all_text_vecs();self.cosine_index = Some(CosineIndex::build(points));}let bytes = self@@ -546,12 +730,13 @@ impl VecStore {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+ let candidates: Vec<String> = shortlist.into_iter().map(|(iri, _quantised)| iri).collect();+ let vecs = self.fetch_text_vecs(&candidates);+ let mut rescored: Vec<(String, f32)> = candidates.into_iter()- .filter_map(|(iri, _quantised)| {- self.entries- .get(&iri)- .map(|e| (iri.clone(), cosine_similarity(&query_norm, &e.text_vec)))+ .filter_map(|iri| {+ let sim = cosine_similarity(&query_norm, vecs.get(&iri)?);+ Some((iri, sim))}).collect();rescored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));@@ -571,12 +756,7 @@ impl VecStore {#[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)+ crate::turbo_index::TurboCosineIndex::build(self.all_text_vecs())}/// Number of vectors in the live TurboQuant index, or `None` when it has@@ -653,6 +833,12 @@ impl VecStore {}pub fn persist(&self) -> anyhow::Result<()> {+ if self.evict_text {+ // Every upsert already wrote its row. Re-running the bulk path here+ // would DELETE the table and re-insert from memory, which under+ // eviction holds no text vectors at all.+ return Ok(());+ }let conn = self.db.conn();let tx = conn.unchecked_transaction()?;tx.execute("DELETE FROM embeddings", [])?;@@ -661,13 +847,13 @@ impl VecStore {"INSERT INTO embeddings (iri, text_vec, struct_vec, text_dim, struct_dim, model_fp) VALUES (?1, ?2, ?3, ?4, ?5, ?6)")?;for (iri, entry) in &self.entries {- let text_bytes = f32_slice_to_bytes(&entry.text_vec);+ let text_bytes = f32_slice_to_bytes(entry.text_vec.as_deref().unwrap_or(&[]));let struct_bytes = f32_slice_to_bytes(&entry.struct_vec);stmt.execute(rusqlite::params![iri,text_bytes,struct_bytes,- entry.text_vec.len() as i64,+ entry.text_dim as i64,entry.struct_vec.len() as i64,self.embeddings_fp,])?;@@ -708,8 +894,10 @@ impl VecStore {}continue;}+ let text_vec = bytes_to_f32_vec(&text_bytes);self.entries.insert(iri, VecEntry {- text_vec: bytes_to_f32_vec(&text_bytes),+ text_dim: text_vec.len(),+ text_vec: if self.evict_text { None } else { Some(text_vec) },struct_vec: bytes_to_f32_vec(&struct_bytes),});}@@ -752,8 +940,13 @@ impl VecStore {self.entries.is_empty()}+ /// The resident text vector, if there is one.+ ///+ /// Returns `None` under eviction even for an IRI the store holds, because+ /// there is no in-memory vector to borrow. Use [`Self::load_text_vec`] on+ /// any path that must work in both modes.pub fn get_text_vec(&self, iri: &str) -> Option<&[f32]> {- self.entries.get(iri).map(|e| e.text_vec.as_slice())+ self.entries.get(iri).and_then(|e| e.text_vec.as_deref())}pub fn get_struct_vec(&self, iri: &str) -> Option<&[f32]> {diff --git a/tests/turbovec_index_test.rs b/tests/turbovec_index_test.rsindex d9176c42..27d60693 100644--- a/tests/turbovec_index_test.rs+++ b/tests/turbovec_index_test.rs@@ -475,3 +475,165 @@ fn measure_turbo_against_hnsw() {);println!();}++/// Recall of both backends over a *real* embedded corpus.+///+/// `measure_turbo_against_hnsw` runs on 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. This runs the same comparison over real+/// ontology labels embedded with the shipped local ONNX model, which is the+/// only way to know whether that 8 point gap is an artefact of the corpus.+///+/// ```text+/// OO_BENCH_LABELS=/tmp/labels_lso.txt \+/// cargo test --release --features turbovec -- --ignored --nocapture real_corpus+/// ```+///+/// Embeddings are cached next to the labels file, so re-runs skip the model.+#[test]+#[ignore = "measurement; needs OO_BENCH_LABELS and the local ONNX model"]+fn measure_recall_on_a_real_corpus() {+ use open_ontologies::embed::{TextEmbedder, DEFAULT_MODEL_FILENAME};+ use open_ontologies::hnsw_index::CosineIndex;+ use std::io::Write;+ use std::path::PathBuf;++ const TOP_K: usize = 10;+ const WIDE: usize = TOP_K * 4;++ let labels_path = match std::env::var("OO_BENCH_LABELS") {+ Ok(p) => PathBuf::from(p),+ Err(_) => {+ println!("set OO_BENCH_LABELS to a newline-delimited label file");+ return;+ }+ };+ let limit: usize = std::env::var("OO_BENCH_LIMIT")+ .ok()+ .and_then(|v| v.parse().ok())+ .unwrap_or(usize::MAX);++ let labels: Vec<String> = std::fs::read_to_string(&labels_path)+ .expect("labels file")+ .lines()+ .filter(|l| !l.trim().is_empty())+ .take(limit)+ .map(|l| l.to_string())+ .collect();+ let n = labels.len();++ // Embed once, cache to disk. The cache is keyed by the labels file and the+ // count, so a different slice does not silently reuse the wrong vectors.+ let cache_path = labels_path.with_extension(format!("{n}.f32"));+ let flat: Vec<f32> = if cache_path.exists() {+ let raw = std::fs::read(&cache_path).unwrap();+ raw.chunks_exact(4)+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))+ .collect()+ } else {+ let models = PathBuf::from(std::env::var("HOME").unwrap()).join(".open-ontologies/models");+ let embedder = TextEmbedder::load(+ &models.join(DEFAULT_MODEL_FILENAME),+ &models.join("tokenizer.json"),+ )+ .expect("local ONNX model + tokenizer");+ let started = std::time::Instant::now();+ let mut flat = Vec::with_capacity(n * embedder.dim());+ for (i, chunk) in labels.chunks(64).enumerate() {+ let refs: Vec<&str> = chunk.iter().map(|s| s.as_str()).collect();+ for v in embedder.embed_batch(&refs).unwrap() {+ flat.extend_from_slice(&v);+ }+ if i % 20 == 0 {+ println!(" embedded {}/{n} ({:.0?})", (i + 1) * 64, started.elapsed());+ }+ }+ let mut fh = std::fs::File::create(&cache_path).unwrap();+ for v in &flat {+ fh.write_all(&v.to_le_bytes()).unwrap();+ }+ flat+ };++ let dim = flat.len() / n;+ let entries: Vec<(String, Vec<f32>)> = (0..n)+ .map(|i| {+ (+ format!("http://ex.org/L{i}"),+ l2_normalize(&flat[i * dim..(i + 1) * dim]),+ )+ })+ .collect();+ println!("\n{n} real labels x {dim} dims ({})\n", labels_path.display());++ let mut hnsw = CosineIndex::build(entries.clone());+ let turbo = TurboCosineIndex::build(entries.clone()).unwrap();++ // Anisotropy of the corpus, as the one number that says how far it is from+ // the synthetic case: the mean cosine between random distinct pairs. Near+ // zero is isotropic; real embeddings sit well above it.+ let mut acc = 0.0f64;+ let pairs = 20_000;+ for p in 0..pairs {+ let a = &entries[(p * 7919) % n].1;+ let b = &entries[(p * 104729 + 13) % n].1;+ acc += a.iter().zip(b).map(|(x, y)| x * y).sum::<f32>() as f64;+ }+ println!("mean pairwise cosine {:.4} (isotropic random ~= 0)", acc / pairs as f64);++ let queries: Vec<usize> = (0..300).map(|i| (i * 7919) % n).collect();+ let (mut h_hits, mut h_wide_hits, mut t_hits, mut total) = (0usize, 0usize, 0usize, 0usize);+ let mut self_match_failures = 0usize;++ for &qi in &queries {+ let q = &entries[qi].1;+ let mut exact: Vec<(usize, f32)> = entries+ .iter()+ .enumerate()+ .map(|(i, (_, v))| (i, 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, _)| entries[*i].0.clone())+ .collect();++ let h: Vec<String> = hnsw.search(q, TOP_K).into_iter().map(|(i, _)| i).collect();+ let h_wide: Vec<String> = hnsw.search(q, WIDE).into_iter().map(|(i, _)| i).collect();+ let t: Vec<String> = turbo.search(q, WIDE).into_iter().map(|(i, _)| i).collect();++ // Sanity: a query that IS an indexed vector must retrieve itself.+ if t.first().map(|s| s.as_str()) != Some(entries[qi].0.as_str()) {+ self_match_failures += 1;+ }++ for iri in &truth {+ total += 1;+ if h.contains(iri) {+ h_hits += 1;+ }+ if h_wide.contains(iri) {+ h_wide_hits += 1;+ }+ if t.contains(iri) {+ t_hits += 1;+ }+ }+ }++ println!(+ "recall@{TOP_K} hnsw {:>9.1}% (as wired: {TOP_K} returned, {TOP_K} kept)",+ 100.0 * h_hits as f64 / total as f64+ );+ println!(+ " hnsw {:>9.1}% (control: {WIDE} returned, re-scored to {TOP_K})",+ 100.0 * h_wide_hits as f64 / total as f64+ );+ println!(+ " turbo {:>9.1}% (as wired: {WIDE} returned, re-scored to {TOP_K})",+ 100.0 * t_hits as f64 / total as f64+ );+ println!("turbo self-match failures: {self_match_failures}/{}\n", queries.len());+}diff --git a/tests/vecstore_eviction_test.rs b/tests/vecstore_eviction_test.rsnew file mode 100644index 00000000..5e7b3fcb--- /dev/null+++ b/tests/vecstore_eviction_test.rs@@ -0,0 +1,242 @@+#![cfg(feature = "turbovec")]++//! Evicting float32 text vectors from memory.+//!+//! The TurboQuant backend stores 4 bit codes, but until the store stops+//! holding the float32 vectors those codes were made from, the compression is+//! a smaller SQLite blob rather than less RAM. In eviction mode the vectors+//! live only in the `embeddings` table and are loaded on demand: a shortlist+//! of them per query for the exact re-score, all of them for the paths that+//! genuinely need every vector.+//!+//! Every test here asserts against a resident store built from identical+//! data. Eviction is a memory strategy, not a semantic one, so anything an+//! evicted store returns must be what the resident store would have returned.++use open_ontologies::poincare::l2_normalize;+use open_ontologies::state::StateDb;+use open_ontologies::vecstore::VecStore;++fn db_path() -> std::path::PathBuf {+ let tmp = tempfile::NamedTempFile::new().unwrap();+ let path = tmp.path().to_path_buf();+ std::mem::forget(tmp);+ path+}++fn synth(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 resident(entries: &[(String, Vec<f32>)]) -> VecStore {+ let mut s = VecStore::new(StateDb::open(&db_path()).unwrap());+ for (iri, v) in entries {+ s.upsert(iri, v, &[0.1, 0.2]);+ }+ s+}++fn evicted(entries: &[(String, Vec<f32>)]) -> VecStore {+ let mut s = VecStore::new(StateDb::open(&db_path()).unwrap()).with_text_vectors_evicted();+ for (iri, v) in entries {+ s.upsert(iri, v, &[0.1, 0.2]);+ }+ s+}++#[test]+fn an_evicted_store_holds_no_float32_text_vectors() {+ let entries = synth(200, 64);+ let res = resident(&entries);+ let ev = evicted(&entries);++ assert_eq!(res.resident_text_vector_bytes(), 200 * 64 * 4);+ assert_eq!(+ ev.resident_text_vector_bytes(),+ 0,+ "eviction mode must not retain float32 text vectors"+ );+ assert_eq!(ev.len(), 200, "the entry set itself is still known");+}++#[test]+fn turbo_search_is_identical_under_eviction() {+ let entries = synth(400, 64);+ let mut res = resident(&entries);+ let mut ev = evicted(&entries);++ for qi in [0usize, 17, 199, 399] {+ let q = &entries[qi].1;+ assert_eq!(+ ev.search_cosine_turbo(q, 10),+ res.search_cosine_turbo(q, 10),+ "eviction changed the turbo result for query {qi}"+ );+ }+}++#[test]+fn the_exact_scan_is_identical_under_eviction() {+ let entries = synth(300, 64);+ let res = resident(&entries);+ let ev = evicted(&entries);++ let q = &entries[42].1;+ assert_eq!(ev.search_cosine(q, 10), res.search_cosine(q, 10));+}++#[test]+fn the_product_search_is_identical_under_eviction() {+ let entries = synth(200, 64);+ let res = resident(&entries);+ let ev = evicted(&entries);++ let q = &entries[7].1;+ assert_eq!(+ ev.search_product(q, &[0.1, 0.2], 10, 0.5),+ res.search_product(q, &[0.1, 0.2], 10, 0.5)+ );+}++#[test]+fn an_upsert_under_eviction_is_immediately_searchable() {+ let entries = synth(100, 64);+ let mut ev = evicted(&entries);+ let _ = ev.search_cosine_turbo(&entries[0].1, 5);++ let mut newcomer = vec![0.0f32; 64];+ newcomer[0] = 1.0;+ ev.upsert("http://ex.org/Newcomer", &newcomer, &[0.1, 0.2]);++ // Write-through matters: the re-score reads the vector back out of SQLite,+ // so an upsert that only touched memory would score the new entry as+ // missing and drop it from its own top-1.+ assert_eq!(+ ev.search_cosine_turbo(&newcomer, 1)[0].0,+ "http://ex.org/Newcomer"+ );+ assert_eq!(ev.resident_text_vector_bytes(), 0);+}++#[test]+fn a_removal_under_eviction_drops_the_stored_vector() {+ let entries = synth(100, 64);+ let mut ev = evicted(&entries);+ let _ = ev.search_cosine_turbo(&entries[0].1, 5);++ ev.remove("http://ex.org/C5");++ assert_eq!(ev.len(), 99);+ assert!(ev+ .search_cosine_turbo(&entries[5].1, 10)+ .iter()+ .all(|(iri, _)| iri != "http://ex.org/C5"));+ assert!(ev.load_text_vec("http://ex.org/C5").is_none());+}++#[test]+fn the_index_cache_fingerprint_is_the_same_under_eviction() {+ // The fingerprint gates every persisted index. If eviction changed it, an+ // evicted process would reject a cache a resident one wrote, and the two+ // modes could not share a database.+ let entries = synth(150, 64);+ let mut res = resident(&entries);+ let ev = evicted(&entries);++ res.persist().unwrap();+ res.persist_turbo_index().unwrap();++ let reloaded = VecStore::new(StateDb::open(&db_path()).unwrap());+ let _ = reloaded;++ assert_eq!(+ ev.entries_fingerprint(),+ res.entries_fingerprint(),+ "eviction must not change the entry-set fingerprint"+ );+}++#[test]+fn load_text_vec_works_in_both_modes() {+ let entries = synth(50, 64);+ let res = resident(&entries);+ let ev = evicted(&entries);++ assert_eq!(+ ev.load_text_vec("http://ex.org/C9").unwrap(),+ res.load_text_vec("http://ex.org/C9").unwrap()+ );+ assert!(ev.load_text_vec("http://ex.org/Ghost").is_none());+}++/// What eviction costs and what it buys.+/// `cargo test --release --features turbovec -- --ignored --nocapture eviction_cost`+#[test]+#[ignore = "measurement, not an assertion; run explicitly in release"]+fn measure_eviction_cost() {+ use std::time::Instant;++ const N: usize = 20_000;+ const DIM: usize = 384;++ let entries = synth(N, DIM);+ let mut res = resident(&entries);+ let mut ev = evicted(&entries);++ // Warm both indices so the build is not counted in the query timing.+ let _ = res.search_cosine_turbo(&entries[0].1, 10);+ let _ = ev.search_cosine_turbo(&entries[0].1, 10);++ println!("\n{N} vectors x {DIM} dims\n");+ println!(+ "resident float32 {:>8.1} MB evicted {:>8.1} MB",+ res.resident_text_vector_bytes() as f64 / 1e6,+ ev.resident_text_vector_bytes() as f64 / 1e6+ );++ let queries: Vec<&Vec<f32>> = (0..200).map(|i| &entries[i * 97 % N].1).collect();+ let t = Instant::now();+ for q in &queries {+ let _ = res.search_cosine_turbo(q, 10);+ }+ let res_q = t.elapsed() / queries.len() as u32;+ let t = Instant::now();+ for q in &queries {+ let _ = ev.search_cosine_turbo(q, 10);+ }+ let ev_q = t.elapsed() / queries.len() as u32;+ println!(+ "turbo query {res_q:>11.2?} evicted {ev_q:>11.2?} ({:.1}x)",+ ev_q.as_secs_f64() / res_q.as_secs_f64()+ );++ let t = Instant::now();+ for (i, q) in queries.iter().enumerate().take(20) {+ let _ = res.search_cosine(q, 10);+ let _ = i;+ }+ let res_exact = t.elapsed() / 20;+ let t = Instant::now();+ for q in queries.iter().take(20) {+ let _ = ev.search_cosine(q, 10);+ }+ let ev_exact = t.elapsed() / 20;+ println!(+ "exact scan {res_exact:>11.2?} evicted {ev_exact:>11.2?} ({:.1}x)",+ ev_exact.as_secs_f64() / res_exact.as_secs_f64()+ );+ println!();+}