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(embeddings): fingerprint the configuration that produced each vector
Nicolas Geyssea5f424085004
diff --git a/docs/embeddings.md b/docs/embeddings.mdindex f8bf35ce..7ff6bd36 100644--- a/docs/embeddings.md+++ b/docs/embeddings.md@@ -73,8 +73,47 @@ model = "nomic-embed-text"# api_key is unnecessary for local Ollama```+## Changing the model or provider++**Stored vectors are only comparable against queries from the same+configuration.** Two models of the same dimension produce numbers of the same+shape and no shared meaning, so mixing them does not fail — retrieval quality+just quietly drops.++Every stored vector and every cached HNSW index therefore carries `model_fp`, a+composite hash of `(provider, model, revision)`:++| provider | `model` | `revision` |+|---|---|---|+| `local` | model file name | file identity — size, mtime, sha256 of the head |+| `openai`-compatible | resolved model name, plus `api_base` and `dimensions` | none — the API exposes no revision |++The fingerprint describes the **effective** configuration, so an environment+override (`OPEN_ONTOLOGIES_EMBEDDINGS_MODEL`, …) counts as a change. For the+local provider it hashes the file *contents*: replacing the `.onnx` in place+leaves the path and filename identical, and that is the most likely way a local+model gets swapped.++On a mismatch, the affected vectors and index caches are discarded and rebuilt,+with a `warn` naming what happened. What to expect:++- **After changing `[embeddings] model`, `provider`, `api_base` or+ `dimensions`** — everything must be re-embedded. Discarding is not optional:+ the old vectors cannot be compared against new queries.+- **The first start after upgrading** to a build that has this column — vectors+ written earlier carry no fingerprint. Nothing recorded which model produced+ them, and assuming it was the current one is the failure this prevents, so+ they are discarded once. Re-embed and it does not recur.+- **No change** — nothing is discarded and cached indices are reused, exactly as+ before.++`entries_hash` is unchanged and still checked. It catches a changed entry set;+`model_fp` catches an unchanged entry set queried by a different model — which+`entries_hash` structurally cannot see, since the stored bytes are identical.+### Notes- API responses are L2-normalized in-process so cosine scores remain comparable with the local ONNX path.- The local and remote paths share the same downstream `onto_embed` / `onto_search` / `onto_similarity` tools — switching providers requires no code changes.- See `[embeddings]` block in the default config emitted by `open-ontologies init` (`src/main.rs::DEFAULT_CONFIG`) for the full set of fields with comments.+- Changing the *tokenizer* alone (same `.onnx`, different `tokenizer.json`) is **not** covered by the fingerprint today — see the note in `src/embed_fingerprint.rs`.diff --git a/src/cache.rs b/src/cache.rsindex 21b3b2ca..614e0584 100644--- a/src/cache.rs+++ b/src/cache.rs@@ -66,7 +66,7 @@ impl SourceFingerprint {/// implementation over adding a new dependency tree just for the cache key./// If this hash is ever reused for an authenticity-sensitive purpose,/// switch the call sites to `sha2` first.-fn sha256_hex(input: &[u8]) -> String {+pub(crate) fn sha256_hex(input: &[u8]) -> String {let digest = sha256(input);let mut s = String::with_capacity(64);for b in digest.iter() {diff --git a/src/embed.rs b/src/embed.rsindex 5eb85a4f..4aabea26 100644--- a/src/embed.rs+++ b/src/embed.rs@@ -150,6 +150,53 @@ pub enum TextEmbedderProvider {OpenAI(crate::embed_remote::OpenAIEmbedder),}+/// Default directory the local ONNX model and tokenizer are looked up in.+fn default_model_dir() -> Option<std::path::PathBuf> {+ dirs::home_dir().map(|h| h.join(".open-ontologies/models"))+}++/// Resolve the ONNX model file the local provider will load.+///+/// Extracted from `TextEmbedderProvider::from_config` so the embedding+/// fingerprint (`crate::embed_fingerprint`) hashes *the file that is actually+/// loaded*. Two copies of this resolution could drift, and a fingerprint over+/// the wrong file is worse than no fingerprint: it would report "unchanged"+/// while the loader picked up a different model.+///+/// Returns the path whether or not it exists — the caller decides. The legacy+/// fallback only wins when it is the file present on disk.+pub fn resolve_local_model_path(+ cfg: &crate::config::EmbeddingsConfig,+) -> Option<std::path::PathBuf> {+ cfg.model_path+ .clone()+ .map(|p| std::path::PathBuf::from(crate::config::expand_tilde(&p)))+ .or_else(|| {+ default_model_dir().map(|d| {+ // Prefer the multilingual default; fall back to a legacy+ // English model only if it is the one present on disk+ // (older installs).+ let preferred = d.join(DEFAULT_MODEL_FILENAME);+ if preferred.exists() {+ return preferred;+ }+ let legacy = d.join(LEGACY_EN_MODEL_FILENAME);+ if legacy.exists() { legacy } else { preferred }+ })+ })+}++/// Resolve the tokenizer file the local provider will load. Companion to+/// [`resolve_local_model_path`].+pub fn resolve_local_tokenizer_path(+ cfg: &crate::config::EmbeddingsConfig,+) -> Option<std::path::PathBuf> {+ cfg.tokenizer_path+ .clone()+ .map(|p| std::path::PathBuf::from(crate::config::expand_tilde(&p)))+ .or_else(|| default_model_dir().map(|d| d.join("tokenizer.json")))+}+impl TextEmbedderProvider {/// Build a provider from runtime configuration. Returns `Ok(None)` when/// the configured provider cannot be initialised (e.g. local model files@@ -174,36 +221,8 @@ impl TextEmbedderProvider {Ok(Some(Self::OpenAI(embedder)))}"local" | "" | "onnx" => {- let default_model_dir =- dirs::home_dir().map(|h| h.join(".open-ontologies/models"));-- let model_path = cfg- .model_path- .clone()- .map(|p| std::path::PathBuf::from(crate::config::expand_tilde(&p)))- .or_else(|| {- default_model_dir.as_ref().map(|d| {- // Prefer the multilingual default; fall back to a- // legacy English model only if it is the one present- // on disk (older installs).- let preferred = d.join(DEFAULT_MODEL_FILENAME);- if preferred.exists() {- return preferred;- }- let legacy = d.join(LEGACY_EN_MODEL_FILENAME);- if legacy.exists() { legacy } else { preferred }- })- });-- let tokenizer_path = cfg- .tokenizer_path- .clone()- .map(|p| std::path::PathBuf::from(crate::config::expand_tilde(&p)))- .or_else(|| {- default_model_dir- .as_ref()- .map(|d| d.join("tokenizer.json"))- });+ let model_path = resolve_local_model_path(cfg);+ let tokenizer_path = resolve_local_tokenizer_path(cfg);match (model_path, tokenizer_path) {(Some(m), Some(t)) if m.exists() && t.exists() => {diff --git a/src/embed_fingerprint.rs b/src/embed_fingerprint.rsnew file mode 100644index 00000000..e11e8ef1--- /dev/null+++ b/src/embed_fingerprint.rs@@ -0,0 +1,293 @@+//! Fingerprint of the embedding configuration that produced a vector.+//!+//! # Why this exists+//!+//! `embeddings` stores `text_dim`/`struct_dim`, and `hnsw_index_cache` stores+//! `entries_hash` — a fingerprint over the `(iri, text_vec)` set. Neither+//! records *which model produced the numbers*. Change `[embeddings] model`, or+//! swap provider, to something that emits the same dimension — 768 and 1536 are+//! both crowded — and every existing check still passes: the dimensions match,+//! and `entries_hash` is unchanged because the stored bytes are literally the+//! same bytes. The cache is considered valid and the index now spans two+//! semantically unrelated vector spaces.+//!+//! Two distinct failures follow, and only the first is a mix:+//!+//! 1. `VecStore::persist` opens with `DELETE FROM embeddings` and rewrites the+//! whole in-memory map, so `load_from_db` (old-model vectors) + `upsert`+//! (new-model vectors) + `persist` writes out a union that looks internally+//! consistent.+//! 2. With **zero** new entities, every stored vector is old-model and every+//! *query* vector is new-model. The index is perfectly coherent and the+//! comparison is still meaningless. No check over the stored set alone can+//! see this — which is why strengthening `entries_hash` cannot fix it.+//!+//! Hence a fingerprint over the *configuration*, not over the data.+//!+//! # What goes into it+//!+//! A composite hash over `(provider, model, revision)`, per the design agreed in+//! issue #74. `revision` is an `Option` because the local ONNX provider has no+//! such concept — its stand-in is the identity of the model file itself.+//!+//! | provider | `model` | `revision` |+//! |---|---|---|+//! | `local` | model file name | file identity: size, mtime, sha256 of the head |+//! | `openai`-compatible | resolved model name | none — the API exposes no revision |+//!+//! Hashing the model file *path* would not do: the default download URL and the+//! on-disk filename are both stable across a model change made by replacing the+//! file in place. The file identity is computed exactly the way `ontology_cache`+//! fingerprints its sources ([`crate::cache::SourceFingerprint`]).+//!+//! Two inputs are included beyond the agreed triple, for the openai-compatible+//! arm only. Both are one line each and either can be dropped without touching+//! anything else:+//!+//! * **`api_base`** — `provider` is `openai` for every OpenAI-compatible+//! gateway, so without this, moving `nomic-embed-text` from a local Ollama+//! to a hosted endpoint keeps the same fingerprint while changing the vector+//! space. That is the issue's own scenario, one layer down.+//! * **`dimensions`** — the `dimensions` request parameter truncates output+//! dimensionality on models that support it. Same model name, different+//! vectors.+//!+//! # What this deliberately does not cover+//!+//! The **tokenizer**. Swapping `tokenizer.json` while keeping the same `.onnx`+//! changes the vectors and goes undetected here. It is the same class of defect+//! and the fix is one more `SourceFingerprint` — left out only to keep this+//! change to what issue #74 agreed, rather than decided against. Say the word+//! and it is two lines.++use crate::config::EmbeddingsConfig;++/// Marker used when the local model file cannot be inspected. Deliberately not+/// an empty string: "no model on disk" and "a model whose fingerprint happens+/// to be empty" must never collide.+const UNAVAILABLE: &str = "<unavailable>";++/// Human-readable description of the embedding configuration.+///+/// This is the string that gets hashed, and it is also what should be logged on+/// a mismatch — a bare hash tells an operator that something changed, this tells+/// them *what*. Field order is fixed; changing it changes every fingerprint, so+/// treat it as a stored format.+pub fn describe(cfg: &EmbeddingsConfig) -> String {+ let provider = crate::config::resolve_embeddings_provider(cfg);++ match provider.as_str() {+ "openai" | "openai-compatible" | "remote" | "http" => {+ let api_base = crate::config::resolve_embeddings_api_base(cfg);+ let model = crate::config::resolve_embeddings_model(cfg);+ let dimensions = cfg+ .dimensions+ .map(|d| d.to_string())+ .unwrap_or_else(|| "default".to_string());+ // `revision=none`: the OpenAI-compatible API exposes no model+ // revision. The slot is kept so the format does not shift the day+ // one appears.+ format!(+ "provider=openai\napi_base={api_base}\nmodel={model}\ndimensions={dimensions}\nrevision=none"+ )+ }+ _ => {+ // Everything else is the local ONNX arm, including the empty string+ // and "onnx" — mirroring `TextEmbedderProvider::from_config`, which+ // rejects an unknown provider before anything reaches here.+ let path = crate::embed::resolve_local_model_path(cfg);+ let name = path+ .as_ref()+ .and_then(|p| p.file_name())+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_else(|| UNAVAILABLE.to_string());+ let revision = path+ .as_ref()+ .and_then(|p| crate::cache::SourceFingerprint::from_path(p).ok())+ .map(|fp| {+ format!(+ "size={},mtime={},sha={}",+ fp.size, fp.mtime_secs, fp.sha_prefix+ )+ })+ .unwrap_or_else(|| UNAVAILABLE.to_string());+ format!("provider=local\nmodel={name}\nrevision={revision}")+ }+ }+}++/// Composite fingerprint of the embedding configuration, as lowercase hex.+///+/// Stored on `embeddings` (where it detects mixed vector spaces) and on+/// `hnsw_index_cache` (where it detects a stale index). A mismatch invalidates+/// *alongside* `entries_hash`, never instead of it: the two catch different+/// things and both are cheap.+pub fn fingerprint(cfg: &EmbeddingsConfig) -> String {+ crate::cache::sha256_hex(describe(cfg).as_bytes())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn local_cfg(model_path: Option<&str>) -> EmbeddingsConfig {+ EmbeddingsConfig {+ provider: Some("local".into()),+ model_path: model_path.map(|s| s.to_string()),+ ..Default::default()+ }+ }++ fn openai_cfg(model: &str, api_base: Option<&str>) -> EmbeddingsConfig {+ EmbeddingsConfig {+ provider: Some("openai".into()),+ model: Some(model.into()),+ api_base: api_base.map(|s| s.to_string()),+ ..Default::default()+ }+ }++ /// Guard the env-var overrides the resolvers read, so a developer's shell+ /// cannot make these pass or fail for reasons unrelated to the code.+ struct EnvGuard(Vec<(&'static str, Option<String>)>);+ impl EnvGuard {+ fn clear() -> Self {+ let keys = [+ "OPEN_ONTOLOGIES_EMBEDDINGS_PROVIDER",+ "OPEN_ONTOLOGIES_EMBEDDINGS_API_BASE",+ "OPEN_ONTOLOGIES_EMBEDDINGS_MODEL",+ ];+ let saved = keys+ .iter()+ .map(|k| (*k, std::env::var(k).ok()))+ .collect::<Vec<_>>();+ for (k, _) in &saved {+ unsafe { std::env::remove_var(k) };+ }+ Self(saved)+ }+ }+ impl Drop for EnvGuard {+ fn drop(&mut self) {+ for (k, v) in &self.0 {+ match v {+ Some(val) => unsafe { std::env::set_var(k, val) },+ None => unsafe { std::env::remove_var(k) },+ }+ }+ }+ }++ #[test]+ fn the_same_configuration_hashes_the_same_way() {+ let _g = EnvGuard::clear();+ let a = fingerprint(&openai_cfg("text-embedding-3-small", None));+ let b = fingerprint(&openai_cfg("text-embedding-3-small", None));+ assert_eq!(a, b);+ }++ #[test]+ fn swapping_the_model_changes_the_fingerprint() {+ // The issue's headline case: two models of identical dimension.+ let _g = EnvGuard::clear();+ let small = fingerprint(&openai_cfg("text-embedding-3-small", None));+ let other = fingerprint(&openai_cfg("nomic-embed-text", None));+ assert_ne!(small, other);+ }++ #[test]+ fn swapping_the_provider_changes_the_fingerprint() {+ let _g = EnvGuard::clear();+ let remote = fingerprint(&openai_cfg("text-embedding-3-small", None));+ let local = fingerprint(&local_cfg(Some("/nonexistent/model.onnx")));+ assert_ne!(remote, local);+ }++ #[test]+ fn the_same_model_name_on_a_different_gateway_is_a_different_space() {+ // `provider` is "openai" for every OpenAI-compatible gateway, so+ // without api_base this pair collides — and moving a model between a+ // local Ollama and a hosted endpoint silently reuses its vectors.+ let _g = EnvGuard::clear();+ let ollama = fingerprint(&openai_cfg(+ "nomic-embed-text",+ Some("http://localhost:11434/v1"),+ ));+ let hosted = fingerprint(&openai_cfg(+ "nomic-embed-text",+ Some("https://api.example.com/v1"),+ ));+ assert_ne!(ollama, hosted);+ }++ #[test]+ fn truncating_dimensionality_changes_the_fingerprint() {+ let _g = EnvGuard::clear();+ let mut truncated = openai_cfg("text-embedding-3-large", None);+ truncated.dimensions = Some(256);+ assert_ne!(+ fingerprint(&openai_cfg("text-embedding-3-large", None)),+ fingerprint(&truncated)+ );+ }++ #[test]+ fn an_env_override_is_reflected() {+ // The fingerprint has to describe the *effective* configuration. One+ // taken from the config file alone would report "unchanged" for a+ // deployment that overrides the model by environment.+ let _g = EnvGuard::clear();+ let cfg = openai_cfg("text-embedding-3-small", None);+ let from_file = fingerprint(&cfg);+ unsafe { std::env::set_var("OPEN_ONTOLOGIES_EMBEDDINGS_MODEL", "text-embedding-3-large") };+ let overridden = fingerprint(&cfg);+ unsafe { std::env::remove_var("OPEN_ONTOLOGIES_EMBEDDINGS_MODEL") };+ assert_ne!(from_file, overridden);+ }++ #[test]+ fn replacing_the_model_file_in_place_changes_the_fingerprint() {+ // The reason the *path* is not enough: the default download URL and the+ // on-disk filename are both stable across a model swap done by+ // overwriting the file.+ let _g = EnvGuard::clear();+ let dir = std::env::temp_dir().join(format!("oo-fp-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let model = dir.join("model.onnx");++ std::fs::write(&model, b"first model weights").unwrap();+ let cfg = local_cfg(Some(model.to_str().unwrap()));+ let before = fingerprint(&cfg);++ // Same path, same name, different contents.+ std::fs::write(&model, b"second model weights, same length!").unwrap();+ let after = fingerprint(&cfg);++ std::fs::remove_dir_all(&dir).ok();+ assert_ne!(before, after, "a model replaced in place went undetected");+ }++ #[test]+ fn a_missing_model_file_does_not_collide_with_a_real_one() {+ let _g = EnvGuard::clear();+ let absent = fingerprint(&local_cfg(Some("/nonexistent/definitely-not-here.onnx")));+ let dir = std::env::temp_dir().join(format!("oo-fp2-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let model = dir.join("definitely-not-here.onnx");+ std::fs::write(&model, b"weights").unwrap();+ let present = fingerprint(&local_cfg(Some(model.to_str().unwrap())));+ std::fs::remove_dir_all(&dir).ok();+ assert_ne!(absent, present);+ }++ #[test]+ fn describe_is_readable_enough_to_log() {+ // `describe` is what gets logged on a mismatch; a bare hash would tell+ // an operator that something changed but not what.+ let _g = EnvGuard::clear();+ let d = describe(&openai_cfg("text-embedding-3-small", None));+ assert!(d.contains("provider=openai"), "{d}");+ assert!(d.contains("model=text-embedding-3-small"), "{d}");+ assert!(d.contains("revision=none"), "{d}");+ }+}diff --git a/src/lib.rs b/src/lib.rsindex 8c284ec5..27124adf 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -29,6 +29,8 @@ pub mod shape_combinatorics;#[cfg(feature = "embeddings")]pub mod embed;#[cfg(feature = "embeddings")]+pub mod embed_fingerprint;+#[cfg(feature = "embeddings")]pub mod embed_remote;pub mod enforce;pub mod feedback;diff --git a/src/server.rs b/src/server.rsindex 1f14caa8..9b481a63 100644--- a/src/server.rs+++ b/src/server.rs@@ -139,7 +139,16 @@ impl OpenOntologiesServer {#[cfg(feature = "embeddings")]let (vecstore, text_embedder) = {- let mut vs = crate::vecstore::VecStore::new(db.clone());+ // Set the fingerprint BEFORE `load_from_db`: the load path is where+ // a configuration change is detected, and detecting it afterwards+ // would mean the incompatible vectors are already in memory and+ // about to be searched.+ let mut vs = crate::vecstore::VecStore::new(db.clone())+ .with_embeddings_fingerprint(crate::embed_fingerprint::fingerprint(&_embed_config));+ tracing::debug!(+ "embedding configuration fingerprint: {}",+ crate::embed_fingerprint::describe(&_embed_config)+ );let _ = vs.load_from_db();let embedder = match crate::embed::TextEmbedderProvider::from_config(&_embed_config) {diff --git a/src/state.rs b/src/state.rsindex 037a1ac7..9231ce74 100644--- a/src/state.rs+++ b/src/state.rs@@ -96,12 +96,19 @@ CREATE TABLE IF NOT EXISTS tool_feedback ();CREATE INDEX IF NOT EXISTS idx_tool_feedback ON tool_feedback(tool, rule_id, entity);+-- `model_fp` is a composite hash of the embedding configuration that produced+-- the vectors — see src/embed_fingerprint.rs. It is what catches a model or+-- provider swap that keeps the same dimension: `text_dim` still matches and the+-- bytes are unchanged, so nothing else notices. Nullable, because rows written+-- before this column existed have no answer, and unknown must stay+-- distinguishable from known-and-equal.CREATE TABLE IF NOT EXISTS embeddings (iri TEXT PRIMARY KEY,text_vec BLOB NOT NULL,struct_vec BLOB NOT NULL,text_dim INTEGER NOT NULL,struct_dim INTEGER NOT NULL,+ model_fp TEXT,updated_at TEXT NOT NULL DEFAULT (datetime('now')));@@ -110,11 +117,18 @@ CREATE TABLE IF NOT EXISTS embeddings (-- index variants (Poincare, product) can coexist. `entries_hash` is a-- fingerprint of the (iri, text_vec) set the index was built from; if it-- changes we know the cached index is stale and must be rebuilt.+--+-- `model_fp` catches what `entries_hash` structurally cannot. With zero new+-- entities, a model swap leaves every stored vector old-model while every query+-- vector is new-model: the entry set is byte-identical, `entries_hash` is+-- unchanged, and the comparison is meaningless anyway. The two checks are kept+-- side by side because they detect different failures and both are cheap.CREATE TABLE IF NOT EXISTS hnsw_index_cache (kind TEXT PRIMARY KEY,entries_hash BLOB NOT NULL,entry_count INTEGER NOT NULL,serialised BLOB NOT NULL,+ model_fp TEXT,updated_at TEXT NOT NULL DEFAULT (datetime('now')));@@ -180,10 +194,26 @@ const MIGRATIONS: &[Migration] = &[ddl: "ALTER TABLE align_feedback ADD COLUMN signals_json TEXT",}],},+ Migration {+ version: 3,+ description: "embedding model fingerprint on vectors and index cache",+ columns: &[+ ColumnAddition {+ table: "embeddings",+ column: "model_fp",+ ddl: "ALTER TABLE embeddings ADD COLUMN model_fp TEXT",+ },+ ColumnAddition {+ table: "hnsw_index_cache",+ column: "model_fp",+ ddl: "ALTER TABLE hnsw_index_cache ADD COLUMN model_fp TEXT",+ },+ ],+ },];/// Schema version a freshly-opened database is brought up to.-pub const SCHEMA_VERSION: i64 = 2;+pub const SCHEMA_VERSION: i64 = 3;/// Modelling-buffer vault: surrogate to original mappings, per session.///diff --git a/src/vecstore.rs b/src/vecstore.rsindex 4bfc71cc..0c8ada29 100644--- a/src/vecstore.rs+++ b/src/vecstore.rs@@ -26,6 +26,16 @@ pub struct VecStore {/// search. Same invalidation semantics as `cosine_index`. The existing/// brute-force `search_poincare` is unchanged.poincare_index: Option<PoincareIndex>,+ /// Fingerprint of the embedding configuration producing the vectors in this+ /// store — see `crate::embed_fingerprint`. Written alongside every vector+ /// and every cached index, and compared on load.+ ///+ /// `None` means "this store was built without knowing the configuration".+ /// That is the case for unit tests, which construct a `VecStore` with no+ /// `EmbeddingsConfig` in reach; the server always sets it. When it is+ /// `None` the fingerprint checks are skipped entirely, so an unconfigured+ /// store behaves exactly as it did before this column existed.+ embeddings_fp: Option<String>,}impl VecStore {@@ -35,6 +45,40 @@ impl VecStore {entries: HashMap::new(),cosine_index: None,poincare_index: None,+ embeddings_fp: None,+ }+ }++ /// Record which embedding configuration produced (and will produce) the+ /// vectors in this store.+ ///+ /// Set it before `load_from_db`: the load path is where a mismatch is+ /// detected, and detecting it afterwards would mean the stale vectors are+ /// already in memory and about to be searched.+ pub fn with_embeddings_fingerprint(mut self, fp: String) -> Self {+ self.embeddings_fp = Some(fp);+ self+ }++ /// The configuration fingerprint, if this store knows it.+ pub fn embeddings_fingerprint(&self) -> Option<&str> {+ self.embeddings_fp.as_deref()+ }++ /// Whether a fingerprint read back from the database describes the same+ /// configuration this store is running.+ ///+ /// Three-way on purpose, and the stored-`None` case is the interesting one:+ /// a row written before this column existed carries no answer, and treating+ /// unknown as matching would let exactly the corruption this guards against+ /// survive an upgrade. So unknown counts as a mismatch — one loud rebuild+ /// the first time a pre-upgrade database is opened.+ fn fingerprint_matches(&self, stored: Option<&str>) -> bool {+ match (self.embeddings_fp.as_deref(), stored) {+ // Store has no configuration to compare against: behave as before.+ (None, _) => true,+ (Some(current), Some(found)) => current == found,+ (Some(_), None) => false,}}@@ -240,9 +284,9 @@ impl VecStore {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) \- VALUES ('cosine', ?1, ?2, ?3)",- rusqlite::params![fp, count, bytes],+ "INSERT OR REPLACE INTO hnsw_index_cache (kind, entries_hash, entry_count, serialised, model_fp) \+ VALUES ('cosine', ?1, ?2, ?3, ?4)",+ rusqlite::params![fp, count, bytes, self.embeddings_fp],)?;Ok(())}@@ -254,17 +298,35 @@ impl VecStore {/// is a no-op and the next `search_cosine_hnsw` rebuilds normally.pub fn load_cosine_index(&mut self) -> anyhow::Result<bool> {let conn = self.db.conn();- let row: Option<(Vec<u8>, Vec<u8>)> = conn+ let row: Option<(Vec<u8>, Vec<u8>, Option<String>)> = conn.query_row(- "SELECT entries_hash, serialised FROM hnsw_index_cache WHERE kind = 'cosine'",+ "SELECT entries_hash, serialised, model_fp FROM hnsw_index_cache WHERE kind = 'cosine'",[],- |row| Ok((row.get::<_, Vec<u8>>(0)?, row.get::<_, Vec<u8>>(1)?)),+ |row| {+ Ok((+ row.get::<_, Vec<u8>>(0)?,+ row.get::<_, Vec<u8>>(1)?,+ row.get::<_, Option<String>>(2)?,+ ))+ },).ok();- let (stored_hash, bytes) = match row {+ let (stored_hash, bytes, stored_fp) = match row {Some(x) => x,None => return Ok(false),};+ // Two independent checks, neither sufficient alone. `entries_hash`+ // catches a changed entry set; `model_fp` catches an unchanged entry+ // set that a different model now queries against — which+ // `entries_hash` structurally cannot see, the stored bytes being+ // identical.+ if !self.fingerprint_matches(stored_fp.as_deref()) {+ tracing::warn!(+ "cached cosine HNSW index was built under a different embedding configuration \+ — discarding it and rebuilding. One-off cost per configuration change."+ );+ return Ok(false);+ }let current_hash = self.entries_fingerprint();if stored_hash != current_hash {// Stale — let the rebuild path handle it next time.@@ -306,12 +368,13 @@ impl VecStore {let fp = self.entries_fingerprint();let count = self.entries.len() as i64;let db = self.db.clone();+ let model_fp = self.embeddings_fp.clone();let handle = tokio::task::spawn_blocking(move || {let conn = db.conn();conn.execute(- "INSERT OR REPLACE INTO hnsw_index_cache (kind, entries_hash, entry_count, serialised) \- VALUES ('cosine', ?1, ?2, ?3)",- rusqlite::params![fp, count, bytes],+ "INSERT OR REPLACE INTO hnsw_index_cache (kind, entries_hash, entry_count, serialised, model_fp) \+ VALUES ('cosine', ?1, ?2, ?3, ?4)",+ rusqlite::params![fp, count, bytes, model_fp],)?;Ok::<(), anyhow::Error>(())});@@ -342,12 +405,13 @@ impl VecStore {let fp = self.entries_fingerprint();let count = self.entries.len() as i64;let db = self.db.clone();+ let model_fp = self.embeddings_fp.clone();let handle = tokio::task::spawn_blocking(move || {let conn = db.conn();conn.execute(- "INSERT OR REPLACE INTO hnsw_index_cache (kind, entries_hash, entry_count, serialised) \- VALUES ('poincare', ?1, ?2, ?3)",- rusqlite::params![fp, count, bytes],+ "INSERT OR REPLACE INTO hnsw_index_cache (kind, entries_hash, entry_count, serialised, model_fp) \+ VALUES ('poincare', ?1, ?2, ?3, ?4)",+ rusqlite::params![fp, count, bytes, model_fp],)?;Ok::<(), anyhow::Error>(())});@@ -378,9 +442,9 @@ impl VecStore {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) \- VALUES ('poincare', ?1, ?2, ?3)",- rusqlite::params![fp, count, bytes],+ "INSERT OR REPLACE INTO hnsw_index_cache (kind, entries_hash, entry_count, serialised, model_fp) \+ VALUES ('poincare', ?1, ?2, ?3, ?4)",+ rusqlite::params![fp, count, bytes, self.embeddings_fp],)?;Ok(())}@@ -389,17 +453,35 @@ impl VecStore {/// [`Self::load_cosine_index`].pub fn load_poincare_index(&mut self) -> anyhow::Result<bool> {let conn = self.db.conn();- let row: Option<(Vec<u8>, Vec<u8>)> = conn+ let row: Option<(Vec<u8>, Vec<u8>, Option<String>)> = conn.query_row(- "SELECT entries_hash, serialised FROM hnsw_index_cache WHERE kind = 'poincare'",+ "SELECT entries_hash, serialised, model_fp FROM hnsw_index_cache WHERE kind = 'poincare'",[],- |row| Ok((row.get::<_, Vec<u8>>(0)?, row.get::<_, Vec<u8>>(1)?)),+ |row| {+ Ok((+ row.get::<_, Vec<u8>>(0)?,+ row.get::<_, Vec<u8>>(1)?,+ row.get::<_, Option<String>>(2)?,+ ))+ },).ok();- let (stored_hash, bytes) = match row {+ let (stored_hash, bytes, stored_fp) = match row {Some(x) => x,None => return Ok(false),};+ // Two independent checks, neither sufficient alone. `entries_hash`+ // catches a changed entry set; `model_fp` catches an unchanged entry+ // set that a different model now queries against — which+ // `entries_hash` structurally cannot see, the stored bytes being+ // identical.+ if !self.fingerprint_matches(stored_fp.as_deref()) {+ tracing::warn!(+ "cached poincare HNSW index was built under a different embedding configuration \+ — discarding it and rebuilding. One-off cost per configuration change."+ );+ return Ok(false);+ }let current_hash = self.entries_fingerprint();if stored_hash != current_hash {return Ok(false);@@ -414,7 +496,7 @@ impl VecStore {tx.execute("DELETE FROM embeddings", [])?;{let mut stmt = tx.prepare(- "INSERT INTO embeddings (iri, text_vec, struct_vec, text_dim, struct_dim) VALUES (?1, ?2, ?3, ?4, ?5)"+ "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);@@ -425,6 +507,7 @@ impl VecStore {struct_bytes,entry.text_vec.len() as i64,entry.struct_vec.len() as i64,+ self.embeddings_fp,])?;}}@@ -435,24 +518,60 @@ impl VecStore {pub fn load_from_db(&mut self) -> anyhow::Result<()> {// Scope the connection + statement so the conn MutexGuard is dropped// before we call `load_cosine_index` (which re-acquires it).+ let mut rejected_known = 0usize;+ let mut rejected_unknown = 0usize;{let conn = self.db.conn();- let mut stmt = conn.prepare("SELECT iri, text_vec, struct_vec FROM embeddings")?;+ let mut stmt =+ conn.prepare("SELECT iri, text_vec, struct_vec, model_fp FROM embeddings")?;let rows = stmt.query_map([], |row| {let iri: String = row.get(0)?;let text_bytes: Vec<u8> = row.get(1)?;let struct_bytes: Vec<u8> = row.get(2)?;- Ok((iri, text_bytes, struct_bytes))+ let model_fp: Option<String> = row.get(3)?;+ Ok((iri, text_bytes, struct_bytes, model_fp))})?;for row in rows {- let (iri, text_bytes, struct_bytes) = row?;+ let (iri, text_bytes, struct_bytes, model_fp) = row?;+ // Drop rather than load. A vector produced by a different model+ // is not merely stale, it is meaningless against the current+ // query space — keeping it would preserve exactly the silent+ // relevance regression this column exists to end.+ if !self.fingerprint_matches(model_fp.as_deref()) {+ if model_fp.is_none() {+ rejected_unknown += 1;+ } else {+ rejected_known += 1;+ }+ continue;+ }self.entries.insert(iri, VecEntry {text_vec: bytes_to_f32_vec(&text_bytes),struct_vec: bytes_to_f32_vec(&struct_bytes),});}}++ // Loud on purpose. A silent rebuild fixes the correctness problem and+ // leaves the operator wondering why the first query after a restart+ // took 40 seconds.+ if rejected_known > 0 {+ tracing::warn!(+ "discarded {rejected_known} embedding(s) produced by a different embedding \+ configuration — they cannot be compared against queries from the current one. \+ Re-embed to restore them. Current configuration: {}",+ self.embeddings_fp.as_deref().unwrap_or("<unset>")+ );+ }+ if rejected_unknown > 0 {+ tracing::warn!(+ "discarded {rejected_unknown} embedding(s) with no recorded model fingerprint \+ (written before the fingerprint column existed). They may well have come from \+ the current model, but nothing recorded which, and assuming they did is the \+ failure this check exists to prevent. Re-embed once and this will not recur."+ );+ }// Invalidate any previously-built HNSW indices; try to load persisted// ones. If the persisted fingerprint matches the entries we just loaded,// the next `search_cosine_hnsw` / `search_poincare_hnsw` skips rebuild.diff --git a/tests/fixtures/state/v2-pre-model-fp.db b/tests/fixtures/state/v2-pre-model-fp.dbnew file mode 100644index 00000000..744ff9ebBinary files /dev/null and b/tests/fixtures/state/v2-pre-model-fp.db differdiff --git a/tests/state_migration_test.rs b/tests/state_migration_test.rsindex 350072c7..fe47ecef 100644--- a/tests/state_migration_test.rs+++ b/tests/state_migration_test.rs@@ -199,3 +199,56 @@ fn a_genuine_open_failure_is_an_error_not_a_silent_pass() {"opening a non-database must return Err, not succeed silently");}++/// Migration 3: the embedding model fingerprint columns.+///+/// The fixture is a hand-written v2 database — the DDL was copied from the+/// schema as it stood, not generated from the current `SCHEMA` constant, for+/// the reason in this file's header.+#[test]+fn adds_the_model_fingerprint_columns_and_keeps_the_rows() {+ let (_dir, path) = staged("v2-pre-model-fp.db");++ {+ let raw = Connection::open(&path).unwrap();+ let v: i64 = raw.query_row("PRAGMA user_version", [], |r| r.get(0)).unwrap();+ assert_eq!(v, 2, "fixture should start at user_version 2");+ assert!(+ !columns(&raw, "embeddings").contains(&"model_fp".to_string()),+ "fixture should predate the column"+ );+ assert!(!columns(&raw, "hnsw_index_cache").contains(&"model_fp".to_string()));+ }++ let db = StateDb::open(&path).unwrap();+ assert_eq!(db.schema_version().unwrap(), SCHEMA_VERSION);++ let conn = db.conn();+ assert!(columns(&conn, "embeddings").contains(&"model_fp".to_string()));+ assert!(columns(&conn, "hnsw_index_cache").contains(&"model_fp".to_string()));++ // The vectors survive, and their fingerprint is NULL rather than+ // back-filled with a guess. NULL is the honest answer — nothing recorded+ // which model produced them — and it is what makes the load path reject+ // them once instead of trusting them forever.+ let (iri, fp): (String, Option<String>) = conn+ .query_row(+ "SELECT iri, model_fp FROM embeddings WHERE iri = 'http://ex.org/Legacy'",+ [],+ |r| Ok((r.get(0)?, r.get(1)?)),+ )+ .unwrap();+ assert_eq!(iri, "http://ex.org/Legacy");+ assert_eq!(fp, None);++ let (kind, count, fp): (String, i64, Option<String>) = conn+ .query_row(+ "SELECT kind, entry_count, model_fp FROM hnsw_index_cache WHERE kind = 'cosine'",+ [],+ |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),+ )+ .unwrap();+ assert_eq!(kind, "cosine");+ assert_eq!(count, 1);+ assert_eq!(fp, None);+}diff --git a/tests/vecstore_model_fingerprint_test.rs b/tests/vecstore_model_fingerprint_test.rsnew file mode 100644index 00000000..ab765733--- /dev/null+++ b/tests/vecstore_model_fingerprint_test.rs@@ -0,0 +1,240 @@+#![cfg(feature = "embeddings")]++//! The embedding-configuration guard (issue #74).+//!+//! Every test here is written against a database that survives a "process+//! restart", because the failure being guarded against only appears across one:+//! the config changes, the process comes back up, and the vectors on disk are+//! from the previous model.+//!+//! The fingerprints are opaque strings — these tests do not care how one is+//! computed, only that two different configurations produce two different ones.+//! `embed_fingerprint`'s own unit tests cover the computation.++use open_ontologies::state::StateDb;+use open_ontologies::vecstore::VecStore;++const MODEL_A: &str = "fingerprint-of-model-a";+const MODEL_B: &str = "fingerprint-of-model-b";++fn temp_db_path() -> std::path::PathBuf {+ let tmp = tempfile::NamedTempFile::new().unwrap();+ let path = tmp.path().to_path_buf();+ std::mem::forget(tmp);+ path+}++/// Vectors written under one configuration must not be loaded under another.+///+/// This is the mixing path: `load_from_db` pulls old-model vectors in, `upsert`+/// adds new-model ones, and `persist` writes the union back out as a table that+/// looks internally consistent. Refusing them at load is what breaks the chain.+#[test]+fn vectors_from_another_model_are_not_loaded() {+ let path = temp_db_path();++ {+ let db = StateDb::open(&path).unwrap();+ let mut store = VecStore::new(db).with_embeddings_fingerprint(MODEL_A.to_string());+ store.upsert("http://ex.org/Dog", &[0.9, 0.1, 0.0], &[0.1, 0.0]);+ store.upsert("http://ex.org/Cat", &[0.8, 0.2, 0.0], &[0.15, 0.0]);+ store.persist().unwrap();+ }++ // Same database, different embedding configuration.+ let db = StateDb::open(&path).unwrap();+ let mut store = VecStore::new(db).with_embeddings_fingerprint(MODEL_B.to_string());+ store.load_from_db().unwrap();++ assert_eq!(+ store.len(),+ 0,+ "vectors produced by another model were loaded and are about to be \+ compared against queries from this one"+ );+}++/// The same configuration must keep working — the guard has to be inert when+/// nothing changed, or it just means a rebuild on every restart.+#[test]+fn vectors_from_the_same_model_are_loaded() {+ let path = temp_db_path();++ {+ let db = StateDb::open(&path).unwrap();+ let mut store = VecStore::new(db).with_embeddings_fingerprint(MODEL_A.to_string());+ store.upsert("http://ex.org/Dog", &[0.9, 0.1, 0.0], &[0.1, 0.0]);+ store.persist().unwrap();+ }++ let db = StateDb::open(&path).unwrap();+ let mut store = VecStore::new(db).with_embeddings_fingerprint(MODEL_A.to_string());+ store.load_from_db().unwrap();++ assert_eq!(store.len(), 1);+ let hits = store.search_cosine(&[0.9, 0.1, 0.0], 1);+ assert!(hits[0].0.contains("Dog"), "got {hits:?}");+}++/// The case `entries_hash` structurally cannot see.+///+/// **Zero new entities.** Every stored vector is old-model, every query vector+/// is new-model. The entry set is byte-identical, so `entries_hash` is+/// unchanged and the cached index is internally coherent — and the comparison+/// is meaningless anyway. No check over the stored set alone can detect this,+/// which is exactly why the fingerprint had to cover the configuration instead.+#[test]+fn an_unchanged_entry_set_is_still_invalidated_by_a_config_change() {+ let path = temp_db_path();++ {+ let db = StateDb::open(&path).unwrap();+ let mut store = VecStore::new(db).with_embeddings_fingerprint(MODEL_A.to_string());+ for i in 0..12 {+ store.upsert(+ &format!("http://ex.org/E{i}"),+ &[i as f32, 1.0, 0.0],+ &[0.1, 0.0],+ );+ }+ store.persist().unwrap();+ store.persist_cosine_index().unwrap();+ }++ // Nothing is added, removed or re-embedded. Only the configuration moved.+ let db = StateDb::open(&path).unwrap();+ let mut store = VecStore::new(db).with_embeddings_fingerprint(MODEL_B.to_string());+ store.load_from_db().unwrap();++ assert_eq!(+ store.len(),+ 0,+ "the entry set was unchanged, so entries_hash matched — the model \+ fingerprint is the only thing that could have caught this"+ );+ assert!(+ !store.load_cosine_index().unwrap(),+ "the cached HNSW index was accepted despite being built by another model"+ );+}++/// A cached index survives a restart under the same configuration. Guards+/// against "fix it by invalidating always", which would pass the test above+/// while making every restart pay a full rebuild.+#[test]+fn a_cached_index_is_still_reused_when_the_config_is_unchanged() {+ let path = temp_db_path();++ {+ let db = StateDb::open(&path).unwrap();+ let mut store = VecStore::new(db).with_embeddings_fingerprint(MODEL_A.to_string());+ for i in 0..12 {+ store.upsert(+ &format!("http://ex.org/E{i}"),+ &[i as f32, 1.0, 0.0],+ &[0.1, 0.0],+ );+ }+ store.persist().unwrap();+ store.persist_cosine_index().unwrap();+ }++ let db = StateDb::open(&path).unwrap();+ let mut store = VecStore::new(db).with_embeddings_fingerprint(MODEL_A.to_string());+ store.load_from_db().unwrap();+ assert_eq!(store.len(), 12);+ assert!(+ store.load_cosine_index().unwrap(),+ "a valid cached index was rejected — the guard is too eager and every \+ restart now pays a rebuild"+ );+}++/// Rows written before the column existed carry no answer.+///+/// Treating unknown as matching would let the corruption survive precisely the+/// upgrade that adds the check. One loud rebuild is the correct price.+#[test]+fn rows_with_no_recorded_fingerprint_are_rejected_once() {+ let path = temp_db_path();++ {+ // A store with no configuration writes NULL — the pre-upgrade shape.+ let db = StateDb::open(&path).unwrap();+ let mut store = VecStore::new(db);+ store.upsert("http://ex.org/Legacy", &[1.0, 0.0, 0.0], &[0.1, 0.0]);+ store.persist().unwrap();+ }++ {+ let db = StateDb::open(&path).unwrap();+ let mut store = VecStore::new(db).with_embeddings_fingerprint(MODEL_A.to_string());+ store.load_from_db().unwrap();+ assert_eq!(store.len(), 0, "unrecorded vectors were assumed compatible");++ // Re-embedding under a known configuration ends it.+ store.upsert("http://ex.org/Legacy", &[1.0, 0.0, 0.0], &[0.1, 0.0]);+ store.persist().unwrap();+ }++ let db = StateDb::open(&path).unwrap();+ let mut store = VecStore::new(db).with_embeddings_fingerprint(MODEL_A.to_string());+ store.load_from_db().unwrap();+ assert_eq!(+ store.len(),+ 1,+ "the rejection recurred after a clean re-embed"+ );+}++/// A store that was never told its configuration behaves exactly as it did+/// before this column existed. Every pre-existing test constructs one that way,+/// and none of them should have to change.+#[test]+fn a_store_without_a_fingerprint_is_unaffected() {+ let path = temp_db_path();++ {+ let db = StateDb::open(&path).unwrap();+ let mut store = VecStore::new(db).with_embeddings_fingerprint(MODEL_A.to_string());+ store.upsert("http://ex.org/Dog", &[0.9, 0.1, 0.0], &[0.1, 0.0]);+ store.persist().unwrap();+ }++ // No fingerprint set: nothing to compare against, so nothing is refused.+ let db = StateDb::open(&path).unwrap();+ let mut store = VecStore::new(db);+ store.load_from_db().unwrap();+ assert_eq!(store.len(), 1);+ assert!(store.embeddings_fingerprint().is_none());+}++/// The Poincaré index cache carries the fingerprint too. `struct_vec`s come+/// from the structural embedder rather than the text model, but they are+/// persisted by the same store and invalidated by the same swap.+#[test]+fn the_poincare_index_cache_is_also_guarded() {+ let path = temp_db_path();++ {+ let db = StateDb::open(&path).unwrap();+ let mut store = VecStore::new(db).with_embeddings_fingerprint(MODEL_A.to_string());+ for i in 0..12 {+ store.upsert(+ &format!("http://ex.org/E{i}"),+ &[1.0, 0.0, 0.0],+ &[i as f32 * 0.01, 0.02],+ );+ }+ store.persist().unwrap();+ store.persist_poincare_index().unwrap();+ }++ let db = StateDb::open(&path).unwrap();+ let mut store = VecStore::new(db).with_embeddings_fingerprint(MODEL_B.to_string());+ store.load_from_db().unwrap();+ assert!(+ !store.load_poincare_index().unwrap(),+ "the cached Poincaré index was accepted despite a configuration change"+ );+}