Skip to content

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

The embedding model is loaded once per process, not once per HTTP session (#268)

Fabio Rovaidab66383c707
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 850fc1b7..3d864085 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -46,6 +46,38 @@ All notable changes to Open Ontologies are documented here.
### Fixed
+- **The embedding model is loaded once per process rather than once per HTTP
+ session** (#262). The HTTP arm hands the same server constructor to
+ `StreamableHttpService::new` as a per-session factory, so everything that
+ constructor built, every connecting session built again: a tract optimize
+ pass over a 470 MB ONNX graph, a second resident copy of that graph, and a
+ sha256 over the same file for the configuration fingerprint. Session count
+ multiplied both the latency and the resident memory, and nothing about any of
+ it can legitimately differ between two sessions handed the same
+ configuration. The provider is now built once behind a process-level cache
+ and cloned into each session as an `Arc`. Measured on this repository's own
+ debug build with the real multilingual MiniLM model, three sessions went from
+ 43.6 s, 36.5 s and 32.8 s to 46.4 s, 8 ms and 12 ms, and peak resident memory
+ for the three went from 2.84 GiB to 1.26 GiB. Sharing is safe because nothing
+ in the provider is per-session state: `TextEmbedderProvider` takes `&self`
+ down to `SimplePlan::run` and `Tokenizer::encode`, and the OpenAI arm keeps
+ its only interior mutability in an atomic. The fingerprint is cached in the
+ same value and taken at the same instant as the model, because a shared model
+ with a per-session fingerprint would stamp a replaced file's identity onto
+ vectors the old resident model produced, which is the corruption the
+ fingerprint exists to catch. `embed_fingerprint::fingerprint` itself stays
+ uncached, since a direct caller is asking what is on disk now. The cache is
+ keyed by the resolved configuration rather than held in one process-wide
+ cell, so a second server configured for a different model is not handed the
+ first one's. The load stays eager: it is what lets the fingerprint and the
+ model be read at one instant, and the vector store needs the fingerprint
+ before `load_from_db` runs. The vector store itself is deliberately not
+ shared, because `onto_embed` and `onto_hnsw_build` mutate it and one store
+ across all sessions would change what the server does rather than what it
+ costs. Behaviour is otherwise unchanged: the same log line per session, the
+ same `Ok(None)` when the model files are absent, and no effect at all on a
+ build without the `embeddings` feature.
+
- **`onto_temporal_conflicts` no longer files a withdrawn assertion as a live
contradiction partner** (#128). The tool takes no `as_of` and read the
validity map after the lineage pass, so a retracted graph carried its
diff --git a/src/embed.rs b/src/embed.rs
index 4aabea26..4af1fa3a 100644
--- a/src/embed.rs
+++ b/src/embed.rs
@@ -3,6 +3,7 @@
use anyhow::{Context, Result};
use std::path::Path;
+use std::sync::Arc;
use tokenizers::Tokenizer;
use tract_onnx::prelude::*;
@@ -265,6 +266,187 @@ impl TextEmbedderProvider {
}
}
+// ─── One provider per process, not one per session (#262) ───────────────────
+
+/// Everything a server session needs out of the embedding configuration, built
+/// once per process instead of once per session.
+///
+/// # Why this is shared
+///
+/// The HTTP arm hands `OpenOntologiesServer::new_with_repo_options` to
+/// `StreamableHttpService::new` as a per-session factory, so everything that
+/// constructor builds is built again for every MCP session that connects. Two
+/// of those things are expensive and neither can legitimately differ between
+/// sessions handed the same configuration:
+///
+/// * the provider, whose local arm runs the tract optimize pass over a 470 MB
+/// ONNX graph and then holds that graph resident for as long as it lives,
+/// and
+/// * the configuration fingerprint, whose local arm is a sha256 over that
+/// same file plus the tokenizer.
+///
+/// Sharing them turns "N sessions, N copies of the model" into one copy behind
+/// an `Arc`. Nothing in the shared value is mutable: `TextEmbedderProvider`
+/// takes `&self` all the way down to `SimplePlan::run` and `Tokenizer::encode`,
+/// and the `OpenAIEmbedder` arm keeps its only interior mutability in an
+/// `AtomicUsize`. That is what makes one instance servable to every session at
+/// once, and it is worth stating rather than assuming, because a provider
+/// holding per-session state could not be shared at all.
+///
+/// # Why the fingerprint travels with it
+///
+/// `embed_fingerprint` exists to notice that the model behind a set of stored
+/// vectors changed, and it answers by reading the file on disk. If the provider
+/// were shared but the fingerprint recomputed per session, a model file
+/// replaced in place while the process ran would hand a later session the NEW
+/// fingerprint while it embeds with the OLD model still resident in the shared
+/// `Arc`. That stamps one model's identity onto another model's vectors, which
+/// is the exact corruption the fingerprint was added to prevent. Taking both at
+/// the same instant and caching them together keeps the label attached to the
+/// thing it labels.
+///
+/// `embed_fingerprint::fingerprint` itself is deliberately left uncached. A
+/// direct caller is asking what is on disk now, and that module's own tests
+/// replace a model in place and require the answer to change.
+#[derive(Clone)]
+pub struct SharedEmbeddings {
+ /// The provider, or `None` when the configuration produced no usable one,
+ /// which is the ordinary case for a deployment whose local model files were
+ /// never downloaded.
+ pub provider: Option<Arc<TextEmbedderProvider>>,
+ /// The error [`TextEmbedderProvider::from_config`] returned, if it returned
+ /// one. A string because `anyhow::Error` is not `Clone`, and separate from
+ /// `provider: None` because "no model on disk" and "this configuration is
+ /// wrong" are different things to tell an operator.
+ pub init_error: Option<String>,
+ /// [`crate::embed_fingerprint::describe`] over the same configuration, read
+ /// at the same moment as the provider.
+ pub description: String,
+ /// The hash of [`Self::description`], which is what
+ /// [`crate::embed_fingerprint::fingerprint`] returns for this
+ /// configuration.
+ pub fingerprint: String,
+}
+
+type SharedCache = std::sync::Mutex<std::collections::HashMap<String, SharedEmbeddings>>;
+
+static SHARED: std::sync::OnceLock<SharedCache> = std::sync::OnceLock::new();
+
+/// How many times the expensive build has actually run, as opposed to being
+/// served from the cache.
+static BUILD_COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
+/// Identity of a configuration, for cache purposes.
+///
+/// Keyed rather than held in a single process-wide cell because
+/// `new_with_repo_options` takes a configuration per call. One cell would hand
+/// the second, differently configured server the first one's model and report
+/// it as that server's own, and serving vectors from silently the wrong model
+/// is a worse failure than the one being fixed here. The crate's own tests
+/// build differently configured servers inside one process, so this is not a
+/// hypothetical.
+///
+/// Built from RESOLVED values rather than from the struct, because every
+/// resolver consults an environment variable before the config field. All of it
+/// is cheap: environment reads, string work, and the `exists()` calls that
+/// choose between the default and legacy model filenames. Nothing here opens
+/// the model.
+fn cache_key(cfg: &crate::config::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());
+ let timeout = cfg.request_timeout_secs.unwrap_or(30).max(1);
+ // Two deployments differing only by credential do need separate
+ // clients, so the key has to cover the key. It is hashed rather
+ // than stored so that the credential does not sit in a map key
+ // which any future `Debug` over this cache would print.
+ let api_key_hash = {
+ use std::hash::{Hash, Hasher};
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ crate::config::resolve_embeddings_api_key(cfg).hash(&mut h);
+ h.finish()
+ };
+ format!(
+ "openai\u{1f}{api_base}\u{1f}{model}\u{1f}{dimensions}\u{1f}{timeout}\u{1f}{api_key_hash}"
+ )
+ }
+ "local" | "" | "onnx" => {
+ let model = resolve_local_model_path(cfg)
+ .map(|p| p.to_string_lossy().into_owned())
+ .unwrap_or_default();
+ let tokenizer = resolve_local_tokenizer_path(cfg)
+ .map(|p| p.to_string_lossy().into_owned())
+ .unwrap_or_default();
+ format!("local\u{1f}{model}\u{1f}{tokenizer}")
+ }
+ // `from_config` refuses this one. The refusal is cached like any other
+ // outcome so that a misconfigured deployment does not re-derive the
+ // same error for every session that connects.
+ other => format!("unsupported\u{1f}{other}"),
+ }
+}
+
+/// Build the shared embedding state for `cfg`, or return the copy this process
+/// already built for an identical configuration.
+///
+/// This is the whole of the fix for #262. Every session gets a clone of one
+/// `Arc`, so the ONNX optimize pass runs once and one copy of the model is
+/// resident however many sessions are open.
+pub fn shared_embeddings(cfg: &crate::config::EmbeddingsConfig) -> SharedEmbeddings {
+ let key = cache_key(cfg);
+ let cache = SHARED.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
+ // A poisoned lock here means an earlier build panicked. This map is a plain
+ // cache and a panic cannot have left it half written, so take the data back
+ // rather than turning one panic into a server that can never embed again.
+ let mut guard = cache.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some(hit) = guard.get(&key) {
+ return hit.clone();
+ }
+
+ // Built with the lock held, so a second session arriving during the optimize
+ // pass waits for that pass instead of starting a second one. It waits no
+ // longer than it would have spent doing its own load, and it does not end up
+ // holding a second copy of the model.
+ BUILD_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+
+ // Described before the provider is loaded, which is the order this ran in
+ // when it ran per session: the fingerprint was taken before `from_config`.
+ let description = crate::embed_fingerprint::describe(cfg);
+ let fingerprint = crate::cache::sha256_hex(description.as_bytes());
+ let (provider, init_error) = match TextEmbedderProvider::from_config(cfg) {
+ Ok(Some(p)) => (Some(Arc::new(p)), None),
+ Ok(None) => (None, None),
+ Err(e) => (None, Some(e.to_string())),
+ };
+
+ let built = SharedEmbeddings {
+ provider,
+ init_error,
+ description,
+ fingerprint,
+ };
+ guard.insert(key, built.clone());
+ built
+}
+
+/// How many times [`shared_embeddings`] has actually built a provider over the
+/// life of this process, rather than serving one it already had.
+///
+/// This is the test signal for #262, and it is public because the test that
+/// needs it drives whole `OpenOntologiesServer` constructions from outside the
+/// crate. One session cannot distinguish shared from per-session, because the
+/// first session builds under either arrangement. Two sessions over one
+/// configuration must move this counter by exactly one.
+pub fn shared_embeddings_builds() -> u64 {
+ BUILD_COUNT.load(std::sync::atomic::Ordering::Relaxed)
+}
+
/// Download a file from URL to a local path.
pub async fn download_model_file(url: &str, dest: &Path) -> Result<()> {
let client = reqwest::Client::new();
diff --git a/src/server.rs b/src/server.rs
index dca2c83d..94c89147 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -179,34 +179,56 @@ impl OpenOntologiesServer {
#[cfg(feature = "embeddings")]
let (vecstore, text_embedder) = {
+ // The model and the fingerprint over it are built ONCE PER PROCESS
+ // and cloned into every session, not rebuilt here (#262). This
+ // constructor is what the HTTP arm hands `StreamableHttpService` as
+ // a per-session factory, so what it builds, every connecting
+ // session builds again: a tract optimize pass over a 470 MB ONNX
+ // graph, a second resident copy of that graph, and a sha256 over
+ // the same file. None of it can differ between sessions that were
+ // handed the same configuration. See `embed::shared_embeddings` for
+ // why the fingerprint has to be taken at the same instant as the
+ // model rather than recomputed here.
+ //
+ // The vector store is deliberately NOT shared. It is per-session
+ // mutable state: `onto_embed` upserts into it and `onto_hnsw_build`
+ // rebuilds its index, so one store behind one mutex would make one
+ // session's embeddings appear inside another's and let one session's
+ // index parameters govern everybody's searches. That is a change to
+ // what the server does, not an optimisation, and it belongs to its
+ // own issue.
+ let shared = crate::embed::shared_embeddings(&_embed_config);
+
// 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));
+ .with_embeddings_fingerprint(shared.fingerprint.clone());
tracing::debug!(
"embedding configuration fingerprint: {}",
- crate::embed_fingerprint::describe(&_embed_config)
+ shared.description
);
let _ = vs.load_from_db();
- let embedder = match crate::embed::TextEmbedderProvider::from_config(&_embed_config) {
- Ok(Some(e)) => {
+ // One line per session, exactly as before. Only the work behind the
+ // line moved.
+ let embedder = match (&shared.provider, &shared.init_error) {
+ (Some(e), _) => {
tracing::info!(
"embeddings enabled (provider = {})",
e.provider_name()
);
- Some(Arc::new(e))
+ Some(e.clone())
}
- Ok(None) => {
+ (None, None) => {
tracing::info!(
"embeddings configured but no provider available (model files missing or provider disabled)"
);
None
}
- Err(e) => {
- tracing::warn!("failed to initialise embedding provider: {}", e);
+ (None, Some(err)) => {
+ tracing::warn!("failed to initialise embedding provider: {}", err);
None
}
};
@@ -261,6 +283,18 @@ impl OpenOntologiesServer {
self.registry.clone()
}
+ /// The embedding provider this session was given, if it has one.
+ ///
+ /// Exposed so a test can hold two sessions' providers side by side and ask
+ /// whether they are the same allocation. Counting builds says the expensive
+ /// work happened once; `Arc::ptr_eq` over this says the second session is
+ /// actually served by the first session's model rather than by a second
+ /// copy that merely cost nothing to make.
+ #[cfg(feature = "embeddings")]
+ pub fn text_embedder(&self) -> Option<Arc<crate::embed::TextEmbedderProvider>> {
+ self.text_embedder.clone()
+ }
+
fn lineage(&self) -> crate::lineage::LineageLog {
crate::lineage::LineageLog::with_governance_webhook(self.db.clone(), self.governance_webhook.clone())
}
diff --git a/tests/embed_shared_provider_test.rs b/tests/embed_shared_provider_test.rs
new file mode 100644
index 00000000..bfd40d5d
--- /dev/null
+++ b/tests/embed_shared_provider_test.rs
@@ -0,0 +1,222 @@
+#![cfg(feature = "embeddings")]
+//! The embedding provider is built once per process, not once per HTTP session
+//! (#262).
+//!
+//! # Why every assertion here needs two sessions
+//!
+//! `OpenOntologiesServer::new_with_repo_options` is what the HTTP arm hands
+//! `StreamableHttpService::new`, and that is a factory the transport calls again
+//! for every MCP session that connects. Under the defect, session two ran a
+//! fresh tract optimize pass and kept its own copy of a 470 MB model; under the
+//! fix it clones an `Arc`. A test that opens ONE session sees a build either
+//! way, because the first session builds under both arrangements, so it would
+//! have passed before the change and proved nothing. The signal is therefore
+//! always a comparison across two sessions: how far
+//! `shared_embeddings_builds()` moved for the second one, and whether the two
+//! sessions' providers are the same allocation.
+
+use std::sync::Arc;
+
+use open_ontologies::config::{CacheConfig, EmbeddingsConfig};
+use open_ontologies::embed::shared_embeddings_builds;
+use open_ontologies::graph::GraphStore;
+use open_ontologies::server::OpenOntologiesServer;
+use open_ontologies::state::StateDb;
+use open_ontologies::toolfilter::ToolFilter;
+
+/// The build counter is process-wide, so two of these tests running at once
+/// would each see the other's builds inside their own delta and the deltas
+/// would be wrong in whichever direction the scheduler chose. Clearing the
+/// environment is process-wide for the same reason. Every test here takes this
+/// first, which costs nothing: there are four of them and none is slow.
+static ONE_AT_A_TIME: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
+/// Take [`ONE_AT_A_TIME`] and put the embedding environment in a known state.
+///
+/// Every resolver in `config` reads its environment variable before the config
+/// field, so a developer with `OPEN_ONTOLOGIES_EMBEDDINGS_PROVIDER=local`
+/// exported would otherwise get a different provider than the one the case
+/// under test asked for. Removed rather than saved and restored, because this
+/// is a dedicated test binary whose own process nobody else is using.
+fn serialised_with_a_clean_environment() -> std::sync::MutexGuard<'static, ()> {
+ let guard = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
+ for key in [
+ "OPEN_ONTOLOGIES_EMBEDDINGS_PROVIDER",
+ "OPEN_ONTOLOGIES_EMBEDDINGS_API_BASE",
+ "OPEN_ONTOLOGIES_EMBEDDINGS_MODEL",
+ "OPEN_ONTOLOGIES_EMBEDDINGS_API_KEY",
+ "OPENAI_API_KEY",
+ ] {
+ unsafe { std::env::remove_var(key) };
+ }
+ guard
+}
+
+/// A configuration whose provider builds with no model file and no network.
+///
+/// `OpenAIEmbedder::new` builds a `reqwest::Client` and formats a URL. It sends
+/// nothing, so this yields a real `Some(provider)` on a machine with no ONNX
+/// model and no connectivity, which is what lets the identity assertion below
+/// run everywhere rather than only where the 470 MB model happens to be
+/// downloaded. `label` keeps each case on its own cache key.
+fn reachable_without_a_model(label: &str) -> EmbeddingsConfig {
+ EmbeddingsConfig {
+ provider: Some("openai".to_string()),
+ api_base: Some(format!("http://127.0.0.1:9/{label}")),
+ model: Some(format!("oo-262-{label}")),
+ ..Default::default()
+ }
+}
+
+/// One MCP session, built exactly the way the HTTP factory builds one: a fresh
+/// `StateDb` handle over the same file, the shared graph, and the same
+/// configuration values every time.
+fn session(dir: &std::path::Path, cfg: &EmbeddingsConfig, graph: &Arc<GraphStore>) -> OpenOntologiesServer {
+ let db = StateDb::open(&dir.join("state.db")).unwrap();
+ let cache = CacheConfig {
+ enabled: true,
+ dir: dir.join("cache").to_string_lossy().into_owned(),
+ idle_ttl_secs: 0,
+ evictor_interval_secs: 30,
+ auto_refresh: false,
+ hash_prefix_bytes: 64 * 1024,
+ };
+ OpenOntologiesServer::new_with_repo_options(
+ db,
+ graph.clone(),
+ None,
+ cfg.clone(),
+ cache,
+ ToolFilter::default(),
+ Vec::new(),
+ )
+}
+
+/// The claim of #262, stated as a count: two sessions, one build.
+#[test]
+fn a_second_session_does_not_build_a_second_model() {
+ let _serial = serialised_with_a_clean_environment();
+ let tmp = tempfile::tempdir().unwrap();
+ let graph = Arc::new(GraphStore::new());
+ let cfg = reachable_without_a_model("two-sessions");
+
+ let before = shared_embeddings_builds();
+ let first = session(tmp.path(), &cfg, &graph);
+ let after_first = shared_embeddings_builds();
+
+ // Without this the counter could be one that never moves, and the
+ // interesting assertion below would hold for the most boring reason there
+ // is. The first session must pay, under the defect and under the fix.
+ assert_eq!(
+ after_first - before,
+ 1,
+ "the first session did not build a provider at all, so the counter \
+ below proves nothing"
+ );
+
+ let second = session(tmp.path(), &cfg, &graph);
+ let after_second = shared_embeddings_builds();
+
+ assert_eq!(
+ after_second - after_first,
+ 0,
+ "the second session built its own provider: {} builds for 2 sessions, \
+ which is the per-session model load this test exists to forbid",
+ after_second - before
+ );
+
+ // The count says the work happened once. This says the second session is
+ // actually served BY the first session's model rather than by a second copy
+ // that merely happened to be cheap, which is the resident-memory half of
+ // the defect and the half a counter cannot see.
+ let a = first
+ .text_embedder()
+ .expect("first session has a provider for this configuration");
+ let b = second
+ .text_embedder()
+ .expect("second session has a provider for this configuration");
+ assert!(
+ Arc::ptr_eq(&a, &b),
+ "two sessions hold two separate allocations of the model"
+ );
+}
+
+/// Ten sessions is where the defect was severe, so state it at ten as well.
+/// Under the defect this is ten optimize passes and ten resident copies.
+#[test]
+fn ten_sessions_still_build_one_model() {
+ let _serial = serialised_with_a_clean_environment();
+ let tmp = tempfile::tempdir().unwrap();
+ let graph = Arc::new(GraphStore::new());
+ let cfg = reachable_without_a_model("ten-sessions");
+
+ let before = shared_embeddings_builds();
+ let sessions: Vec<_> = (0..10).map(|_| session(tmp.path(), &cfg, &graph)).collect();
+ let builds = shared_embeddings_builds() - before;
+
+ assert_eq!(builds, 1, "10 sessions caused {builds} model builds");
+
+ let first = sessions[0].text_embedder().expect("provider");
+ for (i, s) in sessions.iter().enumerate().skip(1) {
+ let other = s.text_embedder().expect("provider");
+ assert!(
+ Arc::ptr_eq(&first, &other),
+ "session {i} holds its own copy of the model"
+ );
+ }
+}
+
+/// Two different configurations must NOT share, which is the hazard in the
+/// obvious implementation of this fix. A single process-wide cell would hand
+/// the second server the first server's model and report it as that server's
+/// own: vectors from one model served under another model's name, silently.
+#[test]
+fn a_different_configuration_gets_its_own_provider() {
+ let _serial = serialised_with_a_clean_environment();
+ let tmp = tempfile::tempdir().unwrap();
+ let graph = Arc::new(GraphStore::new());
+
+ let before = shared_embeddings_builds();
+ let one = session(tmp.path(), &reachable_without_a_model("config-one"), &graph);
+ let two = session(tmp.path(), &reachable_without_a_model("config-two"), &graph);
+ let builds = shared_embeddings_builds() - before;
+
+ assert_eq!(builds, 2, "two configurations produced {builds} builds");
+ let a = one.text_embedder().expect("provider");
+ let b = two.text_embedder().expect("provider");
+ assert!(
+ !Arc::ptr_eq(&a, &b),
+ "a server configured for one model was handed another server's model"
+ );
+}
+
+/// The absent-model path is unchanged: no provider, no error, and the server
+/// still starts. It is also cached, so a deployment with no model does not
+/// re-probe the filesystem once per session.
+#[test]
+fn an_absent_local_model_still_yields_no_provider() {
+ let _serial = serialised_with_a_clean_environment();
+ let tmp = tempfile::tempdir().unwrap();
+ let graph = Arc::new(GraphStore::new());
+ let cfg = EmbeddingsConfig {
+ provider: Some("local".to_string()),
+ model_path: Some(tmp.path().join("absent.onnx").to_string_lossy().into_owned()),
+ tokenizer_path: Some(tmp.path().join("absent.json").to_string_lossy().into_owned()),
+ ..Default::default()
+ };
+
+ let before = shared_embeddings_builds();
+ let first = session(tmp.path(), &cfg, &graph);
+ let second = session(tmp.path(), &cfg, &graph);
+ let builds = shared_embeddings_builds() - before;
+
+ assert!(
+ first.text_embedder().is_none(),
+ "a missing model file produced a provider"
+ );
+ assert!(
+ second.text_embedder().is_none(),
+ "a missing model file produced a provider on the second session"
+ );
+ assert_eq!(builds, 1, "the absent-model outcome was re-derived per session");
+}