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(graph): preserve named graphs when serializing to TriG and N-Quads (#106)
Nicolas217965fc386e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 74d572a1..00ad44a3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,18 @@ All notable changes to Open Ontologies are documented here.## [Unreleased]+### Fixed+- **Named graphs are preserved when exporting to TriG and N-Quads.**+ `GraphStore::serialize` rendered every format with `serialize_triple`, which+ flattens a quad from a named graph into the default graph. Import and the+ persistent store keep graph names, so the loss was export-only — but it meant+ a TriG save/reload round trip dropped the named-graph structure that+ bi-temporal assertions live in (issue #95): every `validFrom`/`validTo`+ binding on `onto_save`/`onto_convert` output was silently gone. The dataset+ formats now serialize quads; the triple formats (Turtle, N-Triples, RDF/XML)+ keep flattening, which is the only thing they can represent. TriG and N-Quads+ round-trip tests in `tests/graph_named_graph_roundtrip_test.rs`.+### Added- **Optional eviction of float32 text vectors from memory**(`VecStore::with_text_vectors_evicted`, `turbovec` feature). Without it thediff --git a/src/graph.rs b/src/graph.rsindex 1d0356cf..84fc689c 100644--- a/src/graph.rs+++ b/src/graph.rs@@ -296,11 +296,26 @@ impl GraphStore {pub fn serialize(&self, format: &str) -> anyhow::Result<String> {let store = self.store.lock().unwrap();let rdf_format = Self::parse_format(format)?;+ // Dataset formats carry the graph name; every other format is a single+ // RDF graph. `serialize_triple` drops the graph name, flattening a quad+ // from a named graph into the default graph. That is the only thing a+ // triple format can do, but for the dataset formats it silently+ // discarded the named-graph structure that temporal assertions live in+ // (issue #95): a TriG save/reload round trip lost every+ // `validFrom`/`validTo` binding. `serialize_quad` keeps the graph name,+ // and for the triple formats we keep flattening. `supports_datasets`+ // owns the list upstream, so a format added later (JSON-LD is already+ // in it) is classified correctly rather than silently flattened.+ let carries_graph_name = rdf_format.supports_datasets();let mut buf = Vec::new();let mut serializer = RdfSerializer::from_format(rdf_format).for_writer(&mut buf);for quad in store.iter() {let quad = quad?;- serializer.serialize_triple(quad.as_ref())?;+ if carries_graph_name {+ serializer.serialize_quad(quad.as_ref())?;+ } else {+ serializer.serialize_triple(quad.as_ref())?;+ }}// `finish()` writes the final terminator (e.g. the trailing `.` on the// last Turtle triple, or `</rdf:RDF>` for RDF/XML). Dropping thediff --git a/tests/graph_named_graph_roundtrip_test.rs b/tests/graph_named_graph_roundtrip_test.rsnew file mode 100644index 00000000..e3e5f051--- /dev/null+++ b/tests/graph_named_graph_roundtrip_test.rs@@ -0,0 +1,139 @@+//! Named graphs survive a dataset round trip (issue #95).+//!+//! Temporal assertions live in named graphs whose validity is described in the+//! default graph. `GraphStore::serialize` used to render every format with+//! `serialize_triple`, which drops the graph name, so a TriG save/reload+//! flattened all assertions into the default graph and lost the+//! `validFrom`/`validTo`/`recordedAt` bindings on export. These tests pin that+//! TriG and N-Quads preserve the graph name, that the triple formats still+//! flatten (the only thing they can do), and that a full round trip keeps a+//! temporal snapshot answerable.++use open_ontologies::graph::GraphStore;+use open_ontologies::temporal::Temporal;+use oxigraph::io::RdfFormat;+use std::sync::Arc;++const DATASET: &str = r#"+@prefix ex: <http://example.org/> .+@prefix t: <https://open-ontologies.org/temporal#> .++ex:g1 { ex:HEK293 a ex:AdherentCellLine . }+ex:g2 { ex:HEK293 a ex:SuspensionCellLine . }++{+ ex:g1 t:validFrom "2024-01-01" ; t:validTo "2026-05-01" .+ ex:g2 t:validFrom "2026-05-01" .+}+"#;++fn named_graphs(store: &GraphStore) -> String {+ store+ .sparql_select("SELECT ?g WHERE { GRAPH ?g { ?s ?p ?o } }")+ .unwrap()+}++#[test]+fn trig_round_trip_preserves_named_graphs() {+ let first = GraphStore::new();+ first.load_content(DATASET, RdfFormat::TriG).unwrap();++ // The named graphs are present before export.+ let before = named_graphs(&first);+ assert!(before.contains("g1") && before.contains("g2"), "{before}");++ // Export to TriG and reload into a fresh store.+ let trig = first.serialize("trig").unwrap();+ assert!(+ trig.contains("g1") && trig.contains("g2"),+ "serialized TriG still names its graphs:\n{trig}"+ );+ let second = GraphStore::new();+ second.load_content(&trig, RdfFormat::TriG).unwrap();++ // The graph names survived the round trip — this is what fails when+ // serialize flattens to triples.+ let after = named_graphs(&second);+ assert!(+ after.contains("g1") && after.contains("g2"),+ "named graphs lost on TriG round trip:\n{after}"+ );++ // And the default-graph validity metadata survived with them.+ let validity = second+ .sparql_select(+ "SELECT ?from WHERE { <http://example.org/g1> \+ <https://open-ontologies.org/temporal#validFrom> ?from }",+ )+ .unwrap();+ assert!(validity.contains("2024-01-01"), "{validity}");+}++#[test]+fn nquads_round_trip_preserves_named_graphs() {+ let first = GraphStore::new();+ first.load_content(DATASET, RdfFormat::TriG).unwrap();++ let nq = first.serialize("nquads").unwrap();+ // Every quad in a named graph carries its graph term at the end of the line.+ assert!(+ nq.contains("<http://example.org/g1>") && nq.contains("<http://example.org/g2>"),+ "serialized N-Quads name their graphs:\n{nq}"+ );++ let second = GraphStore::new();+ second.load_content(&nq, RdfFormat::NQuads).unwrap();+ let after = named_graphs(&second);+ assert!(after.contains("g1") && after.contains("g2"), "{after}");+}++#[test]+fn triple_formats_still_flatten_named_graphs() {+ // A triple format cannot carry graph names; it flattens into one graph.+ // The triples are all still there, but no named graph survives — this is+ // the correct, lossy behaviour for N-Triples, and pinning it guards the+ // dataset-vs-triple branch in `serialize`.+ let store = GraphStore::new();+ store.load_content(DATASET, RdfFormat::TriG).unwrap();++ let nt = store.serialize("ntriples").unwrap();+ assert!(nt.contains("AdherentCellLine"), "the triples survive:\n{nt}");++ let reloaded = GraphStore::new();+ reloaded.load_content(&nt, RdfFormat::NTriples).unwrap();+ let after = named_graphs(&reloaded);+ assert!(+ !after.contains("g1") && !after.contains("g2"),+ "N-Triples has no named graphs to recover:\n{after}"+ );+}++#[test]+fn temporal_snapshot_answerable_after_trig_round_trip() {+ let first = GraphStore::new();+ first.load_content(DATASET, RdfFormat::TriG).unwrap();+ let trig = first.serialize("trig").unwrap();++ let reloaded = Arc::new(GraphStore::new());+ reloaded.load_content(&trig, RdfFormat::TriG).unwrap();++ // Ask what held in mid-2024: only the adherent period, and it must come+ // back by name — impossible if the round trip had flattened the graphs.+ let snap: serde_json::Value =+ serde_json::from_str(&Temporal::new(reloaded).snapshot(Some("2024-06-01"), None).unwrap())+ .unwrap();+ let in_scope: Vec<String> = snap["in_scope"]+ .as_array()+ .unwrap()+ .iter()+ .map(|r| r["graph"].as_str().unwrap().to_string())+ .collect();+ assert!(+ in_scope.iter().any(|g| g.ends_with("g1")),+ "g1 in scope at 2024-06-01: {in_scope:?}"+ );+ assert!(+ !in_scope.iter().any(|g| g.ends_with("g2")),+ "g2 not yet valid at 2024-06-01: {in_scope:?}"+ );+}