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
fix(registry): preserve active graph on invalid replacement
Rudy Celekli0d0c31687ae6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3d864085..a6873209 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,10 @@ All notable changes to Open Ontologies are documented here.## [Unreleased]+### Fixed++- Keep the last active ontology intact when parsing a replacement source, cache, or refresh fails; publish successful replacements in one graph transaction.+### Added- **A named profile hands a client one job's worth of the tool surface** (#263).diff --git a/src/graph.rs b/src/graph.rsindex 8581bf72..4180a1a5 100644--- a/src/graph.rs+++ b/src/graph.rs@@ -257,34 +257,49 @@ impl GraphStore {}/// Load RDF content with an optional base IRI for resolving relative IRIs.- pub fn load_content_with_base(&self, content: &str, format: RdfFormat, base_iri: Option<&str>) -> anyhow::Result<usize> {- let store = &self.store;+ pub fn load_content_with_base(+ &self,+ content: &str,+ format: RdfFormat,+ base_iri: Option<&str>,+ ) -> anyhow::Result<usize> {+ self.load_content_with_base_mode(content, format, base_iri, false)+ }++ fn load_content_with_base_mode(+ &self,+ content: &str,+ format: RdfFormat,+ base_iri: Option<&str>,+ replace: bool,+ ) -> anyhow::Result<usize> {let reader = Cursor::new(content.as_bytes());let mut parser = RdfParser::from_format(format);if let Some(base) = base_iri {parser = parser.with_base_iri(base)?;}// All or nothing: see load_turtle (issue #93).- let quads: Vec<_> = parser- .for_reader(reader)- .collect::<Result<_, _>>()?;- // Report triples actually added, not parse events. The store is a set, so- // re-inserting a statement it already holds changes nothing and must not be- // counted as a load.- let before = store.len().unwrap_or(0);- // Atomic for the reason given on the first loader above.- let mut txn = store.start_transaction()?;- for quad in &quads {- txn.insert(quad);- }- txn.commit()?;- Ok(store.len().unwrap_or(before).saturating_sub(before))+ let quads: Vec<_> = parser.for_reader(reader).collect::<Result<_, _>>()?;+ self.store_parsed_quads(&quads, replace)}pub fn load_file(&self, path: &str) -> anyhow::Result<usize> {+ self.load_file_mode(path, false)+ }++ /// Replace the active dataset only after the entire source parses.+ pub(crate) fn replace_file(&self, path: &str) -> anyhow::Result<usize> {+ self.load_file_mode(path, true)+ }++ /// Replace from a cache or eviction snapshot without partial publication.+ pub(crate) fn replace_nquads(&self, content: &str) -> anyhow::Result<usize> {+ self.load_content_with_base_mode(content, RdfFormat::NQuads, None, true)+ }++ fn load_file_mode(&self, path: &str, replace: bool) -> anyhow::Result<usize> {let content = std::fs::read_to_string(path)?;let format = Self::detect_format_sniffed(path, &content);- let store = &self.store;let reader = Cursor::new(content.as_bytes());// A document's own location is its default base, per RFC 3986. Without@@ -296,25 +311,34 @@ impl GraphStore {.and_then(|abs| abs.to_str().map(|s| format!("file://{s}")));// All or nothing: see load_turtle (issue #93).let mut parser = RdfParser::from_format(format);- if let Some(p) = base.as_ref().and_then(|b| parser.clone().with_base_iri(b).ok()) {+ if let Some(p) = base+ .as_ref()+ .and_then(|b| parser.clone().with_base_iri(b).ok())+ {parser = p;}- let quads: Vec<_> = parser- .for_reader(reader)- .collect::<Result<_, _>>()?;- // Report triples actually added, not parse events. The store is a set, so- // re-inserting a statement it already holds changes nothing and must not be- // counted as a load.- let before = store.len().unwrap_or(0);- // Atomic for the reason given on the first loader above.- let mut txn = store.start_transaction()?;- for quad in &quads {+ let quads: Vec<_> = parser.for_reader(reader).collect::<Result<_, _>>()?;+ self.store_parsed_quads(&quads, replace)+ }++ fn store_parsed_quads(&self, quads: &[Quad], replace: bool) -> anyhow::Result<usize> {+ let before = if replace {+ 0+ } else {+ self.store.len().unwrap_or(0)+ };+ let mut txn = self.store.start_transaction()?;+ if replace {+ // Clear and insert share one transaction: failed parsing never clears+ // the old graph, and readers cannot observe an empty intermediate graph.+ txn.clear()?;+ }+ for quad in quads {txn.insert(quad);}txn.commit()?;- Ok(store.len().unwrap_or(before).saturating_sub(before))+ Ok(self.store.len().unwrap_or(before).saturating_sub(before))}-pub fn save_file(&self, path: &str, format: &str) -> anyhow::Result<()> {let content = self.serialize(format)?;std::fs::write(path, content)?;diff --git a/src/registry.rs b/src/registry.rsindex 8c0d7fd7..691cd783 100644--- a/src/registry.rs+++ b/src/registry.rs@@ -124,20 +124,17 @@ impl OntologyRegistry {}).unwrap_or(false);- // Always start from a clean store for a fresh load.- self.graph.clear()?;-let (triple_count, origin, cache_path) = if cache_is_fresh {let entry = existing.unwrap();let quads = std::fs::read_to_string(&entry.cache_path).with_context(|| format!("read cache {}", entry.cache_path))?;- let count = self.graph.load_nquads(&quads)?;+ let count = self.graph.replace_nquads(&quads)?;self.cache.touch(&name)?;(count, "cache", PathBuf::from(entry.cache_path))} else {let count = self.graph- .load_file(path)+ .replace_file(path).with_context(|| format!("parse source {}", path))?;let cache_path = if self.config.enabled {let cp = self.cache.cache_path_for(&name, &fp.sha_prefix);@@ -217,8 +214,7 @@ impl OntologyRegistry {let cur = SourceFingerprint::from_path(Path::new(&source_path))?;if cur != stored_fp {// Source changed — re-parse and rewrite cache.- self.graph.clear()?;- let count = self.graph.load_file(&source_path)?;+ let count = self.graph.replace_file(&source_path)?;let new_cache = self.cache.cache_path_for(&name, &cur.sha_prefix);let quads = self.graph.serialize("nquads")?;CacheManager::atomic_write(&new_cache, &quads)?;@@ -247,16 +243,13 @@ impl OntologyRegistry {let evict_path = Self::evict_snapshot_path(&cache_path);if evict_path.exists() {let quads = std::fs::read_to_string(&evict_path)?;- self.graph.clear()?;- self.graph.load_nquads(&quads)?;+ self.graph.replace_nquads(&quads)?;let _ = std::fs::remove_file(&evict_path);} else if cache_path.exists() {let quads = std::fs::read_to_string(&cache_path)?;- self.graph.clear()?;- self.graph.load_nquads(&quads)?;+ self.graph.replace_nquads(&quads)?;} else if Path::new(&source_path).exists() {- self.graph.clear()?;- self.graph.load_file(&source_path)?;+ self.graph.replace_file(&source_path)?;} else {return Err(anyhow!("ontology '{}' was evicted but neither cache file '{}' nor source '{}' exists",diff --git a/tests/registry_replacement_test.rs b/tests/registry_replacement_test.rsnew file mode 100644index 00000000..92efe4e1--- /dev/null+++ b/tests/registry_replacement_test.rs@@ -0,0 +1,153 @@+//! Failed source/cache replacements must preserve the last successful dataset.+use std::sync::Arc;++use open_ontologies::config::CacheConfig;+use open_ontologies::graph::GraphStore;+use open_ontologies::registry::{LoadOptions, OntologyRegistry};+use open_ontologies::state::StateDb;+use oxigraph::io::RdfFormat;++const OLD: &str =+ "<https://example.org/old> <https://example.org/p> \"old\" <https://example.org/g> .\n";+const EXTRA: &str = "<https://example.org/extra> <https://example.org/p> \"mutation\" .\n";+const NEW: &str = "<https://example.org/new> <https://example.org/p> \"new\" .\n";+const BROKEN: &str =+ "<https://example.org/partial> <https://example.org/p> \"partial\" .\nthis is not RDF\n";++struct Harness {+ tmp: tempfile::TempDir,+ graph: Arc<GraphStore>,+ registry: OntologyRegistry,+ source: std::path::PathBuf,+}++impl Harness {+ fn new(ttl: u64) -> Self {+ let tmp = tempfile::tempdir().unwrap();+ let graph = Arc::new(GraphStore::new());+ let db = StateDb::open(&tmp.path().join("state.db")).unwrap();+ let config = CacheConfig {+ enabled: true,+ dir: tmp.path().join("cache").to_string_lossy().into_owned(),+ idle_ttl_secs: ttl,+ ..CacheConfig::default()+ };+ let registry = OntologyRegistry::new(graph.clone(), db, config).unwrap();+ let source = tmp.path().join("old.nq");+ std::fs::write(&source, OLD).unwrap();+ Self {+ tmp,+ graph,+ registry,+ source,+ }+ }++ fn load(&self, refresh: bool) -> open_ontologies::registry::LoadResult {+ self.registry+ .load_file(+ self.source.to_str().unwrap(),+ LoadOptions {+ auto_refresh: refresh,+ ..LoadOptions::default()+ },+ )+ .unwrap()+ }++ fn snapshot(&self) -> String {+ self.graph.serialize("nquads").unwrap()+ }+}++#[test]+fn malformed_replacement_preserves_active_dataset_and_mutations() {+ let h = Harness::new(0);+ h.load(false);+ h.graph.load_nquads(EXTRA).unwrap();+ let before = h.snapshot();+ let broken = h.tmp.path().join("broken.ttl");+ std::fs::write(&broken, BROKEN).unwrap();+ assert!(+ h.registry+ .load_file(broken.to_str().unwrap(), LoadOptions::default())+ .is_err()+ );+ assert_eq!(h.snapshot(), before);+ h.registry.ensure_loaded().unwrap();+ assert_eq!(h.snapshot(), before);+}++#[test]+fn malformed_warm_cache_does_not_clear_or_publish_partial_quads() {+ let h = Harness::new(0);+ let loaded = h.load(false);+ h.graph.load_nquads(EXTRA).unwrap();+ let before = h.snapshot();+ std::fs::write(&loaded.cache_path, BROKEN).unwrap();+ assert!(+ h.registry+ .load_file(h.source.to_str().unwrap(), LoadOptions::default())+ .is_err()+ );+ assert_eq!(h.snapshot(), before);+}++#[test]+fn malformed_auto_refresh_keeps_live_dataset_until_a_valid_refresh() {+ let h = Harness::new(0);+ h.load(true);+ h.graph.load_nquads(EXTRA).unwrap();+ let before = h.snapshot();+ std::fs::write(&h.source, BROKEN).unwrap();+ assert!(h.registry.ensure_loaded().is_err());+ assert_eq!(h.snapshot(), before);+ std::fs::write(&h.source, NEW).unwrap();+ h.registry.ensure_loaded().unwrap();+ assert_eq!(h.snapshot(), NEW);+}++#[test]+fn malformed_eviction_snapshot_does_not_publish_a_partial_restore() {+ let h = Harness::new(1);+ let loaded = h.load(false);+ std::thread::sleep(std::time::Duration::from_millis(1100));+ assert!(h.registry.evictor_tick().unwrap());+ let mut snapshot = std::path::PathBuf::from(loaded.cache_path);+ snapshot.set_extension("nq.evicted");+ assert!(snapshot.exists());+ std::fs::write(&snapshot, BROKEN).unwrap();+ h.graph.load_nquads(EXTRA).unwrap();+ let before = h.snapshot();+ assert!(h.registry.ensure_loaded().is_err());+ assert_eq!(h.snapshot(), before);+ assert!(snapshot.exists(), "a failed restore must keep its snapshot");+}++#[test]+fn successful_replacement_removes_old_quads_but_append_apis_still_append() {+ let h = Harness::new(0);+ h.load(false);+ let new = h.tmp.path().join("new.ttl");+ std::fs::write(&new, format!("{NEW}{NEW}")).unwrap();+ let result = h+ .registry+ .load_file(new.to_str().unwrap(), LoadOptions::default())+ .unwrap();+ assert_eq!(result.triple_count, 1);+ assert_eq!(h.snapshot(), NEW);+ let warm = h+ .registry+ .load_file(new.to_str().unwrap(), LoadOptions::default())+ .unwrap();+ assert_eq!(warm.origin, "cache");+ assert_eq!(warm.triple_count, 1);+ assert_eq!(h.snapshot(), NEW);+ assert_eq!(h.graph.load_file(h.source.to_str().unwrap()).unwrap(), 1);+ assert_eq!(h.graph.load_content(EXTRA, RdfFormat::NQuads).unwrap(), 1);+ let contents = h.snapshot();+ assert!(contents.contains("\"new\""));+ assert!(contents.contains("\"old\" <https://example.org/g>"));+ assert!(contents.contains("\"mutation\""));+ assert_eq!(h.graph.load_content(EXTRA, RdfFormat::NQuads).unwrap(), 0);+}