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.

Unbounded oxrdf RDFC-1.0 made diff/drift factorial on symmetric blank nodes; use the budgeted canon module and report an approximate ground diff (#293)

FABIOTESSdf26423f2ec7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 28a447e6..7eba1f55 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,27 @@ All notable changes to Open Ontologies are documented here.
## [Unreleased]
+### Fixed
+
+- **`diff` and `drift` no longer hang on a symmetric blank-node graph** (#293).
+ Both canonicalised blank nodes through oxrdf's RDFC-1.0, which sets no limit
+ on `hash_n_degree_quads` calls, so the cost was factorial: a 7-node
+ blank-node clique took 17 to 23 seconds to diff against itself and an 8-node
+ clique was still running when killed at 120 seconds. They now use the
+ repository's own `canon` module, the same Recommendation gated on the W3C
+ suite and bounded by its 4000-call budget; Pizza gets the same canonical
+ labels as before. When either snapshot exhausts the budget, both are cut to
+ the triples that mention no blank node and the report says so: `exact:
+ false`, `approximate_reason`, and the omitted counts (`omitted_old`/
+ `omitted_new` for diff, `omitted_v1`/`omitted_v2` for drift). `kgcl_json`
+ carries the flag; the `kgcl` CNL format cannot, so it refuses an
+ approximate drift and names the formats that can. Every report now carries
+ `exact`, true on ordinary input. `canon` itself built all k! neighbour
+ permutations before its first budget check, so two identical 11-leaf
+ blank-node stars cost 10 s and 1.78 GB to refuse; permutations are now
+ generated lazily in the same order, and the same input takes 0.04 s and
+ 17 MB.
+
## [2.1.0] - 2026-10-23
### Fixed
diff --git a/src/canon.rs b/src/canon.rs
index 0c272f1f..783b10a2 100644
--- a/src/canon.rs
+++ b/src/canon.rs
@@ -288,7 +288,7 @@ impl<'a> State<'a> {
nodes.sort();
nodes.dedup_by(|a, b| a == b && false); // keep duplicates: they are distinct positions
- for permutation in permutations(&nodes) {
+ for permutation in Permutations::new(&nodes) {
let mut issuer_copy = issuer.clone();
let mut path = String::new();
let mut recursion: Vec<String> = Vec::new();
@@ -346,22 +346,41 @@ impl<'a> State<'a> {
}
}
-/// Every permutation of `items`, in a deterministic order.
-fn permutations(items: &[String]) -> Vec<Vec<String>> {
- if items.is_empty() {
- return vec![Vec::new()];
+/// Every permutation of `items`, in lexicographic order of position, one at a
+/// time.
+///
+/// Lazy because the budget is checked per `hash_n_degree` call and a list of
+/// all k! permutations is built before the first of them. Built eagerly, two
+/// identical blank-node stars of 11 leaves took 10 s of CPU and 1.78 GB of
+/// resident memory to reach the budget (issue #293), and each further leaf
+/// multiplies that. The order is the one the eager recursion produced, so
+/// which path wins a tie, and therefore every label, is unchanged.
+struct Permutations<'a> {
+ items: &'a [String],
+ indices: Vec<usize>,
+ started: bool,
+}
+
+impl<'a> Permutations<'a> {
+ fn new(items: &'a [String]) -> Self {
+ Self { items, indices: (0..items.len()).collect(), started: false }
}
- let mut out = Vec::new();
- for i in 0..items.len() {
- let mut rest = items.to_vec();
- let head = rest.remove(i);
- for mut tail in permutations(&rest) {
- let mut one = vec![head.clone()];
- one.append(&mut tail);
- out.push(one);
+}
+
+impl Iterator for Permutations<'_> {
+ type Item = Vec<String>;
+
+ fn next(&mut self) -> Option<Vec<String>> {
+ if self.started {
+ // Next index sequence in lexicographic order, or the end.
+ let i = self.indices.windows(2).rposition(|w| w[0] < w[1])?;
+ let j = self.indices.iter().rposition(|&x| x > self.indices[i])?;
+ self.indices.swap(i, j);
+ self.indices[i + 1..].reverse();
}
+ self.started = true;
+ Some(self.indices.iter().map(|&k| self.items[k].clone()).collect())
}
- out
}
/// Canonical blank-node labels for a dataset, as a map from the input label.
@@ -430,6 +449,21 @@ pub fn canonical_labels(
.collect())
}
+/// The dataset with its blank nodes relabelled `c14n0`, `c14n1`, ..., in
+/// input order. The quads themselves are what `GraphStore` loads back into a
+/// store; [`canonical_nquads`] is the same relabelling serialised for hashing.
+pub fn canonical_quads(
+ quads: &[Quad],
+ budget: usize,
+ hash: HashAlgorithm,
+) -> Result<Vec<Quad>, CanonError> {
+ let labels = canonical_labels(quads, budget, hash)?;
+ Ok(quads
+ .iter()
+ .map(|q| relabel(q, &mut |b| labels.get(b).cloned().unwrap_or_else(|| b.to_string())))
+ .collect())
+}
+
/// The dataset in canonical N-Quads: blank nodes relabelled `c14n0`, `c14n1`,
/// ..., every quad serialised, sorted, and concatenated.
///
@@ -440,15 +474,8 @@ pub fn canonical_nquads(
budget: usize,
hash: HashAlgorithm,
) -> Result<String, CanonError> {
- let labels = canonical_labels(quads, budget, hash)?;
- let mut lines: Vec<String> = quads
- .iter()
- .map(|q| {
- nquad(&relabel(q, &mut |b| {
- labels.get(b).cloned().unwrap_or_else(|| b.to_string())
- }))
- })
- .collect();
+ let mut lines: Vec<String> =
+ canonical_quads(quads, budget, hash)?.iter().map(nquad).collect();
lines.sort();
lines.dedup();
Ok(lines.concat())
diff --git a/src/drift.rs b/src/drift.rs
index ee318250..46cfcf69 100644
--- a/src/drift.rs
+++ b/src/drift.rs
@@ -22,13 +22,18 @@ impl DriftDetector {
/// same protection (identical graphs reparse to identical canonical IDs) while
/// keeping anonymous restriction classes / quoted axioms visible in the diff
/// instead of dropping them entirely.
+ ///
+ /// A snapshot that exhausts the RDFC-1.0 budget is not canonicalised; both
+ /// are cut to their ground triples and the report says so with `exact:
+ /// false`, `approximate_reason`, `omitted_v1` and `omitted_v2` (issue #293).
pub fn detect(&self, v1_turtle: &str, v2_turtle: &str) -> anyhow::Result<String> {
let raw1 = GraphStore::new();
let raw2 = GraphStore::new();
raw1.load_turtle(v1_turtle, None)?;
raw2.load_turtle(v2_turtle, None)?;
- let store1 = Arc::new(raw1.canonicalize_blank_nodes()?);
- let store2 = Arc::new(raw2.canonicalize_blank_nodes()?);
+ let (store1, store2, approximation) = GraphStore::canonicalize_pair(&raw1, &raw2)?;
+ let store1 = Arc::new(store1);
+ let store2 = Arc::new(store2);
let v1_vocab = self.extract_vocabulary(&store1);
let v2_vocab = self.extract_vocabulary(&store2);
@@ -74,14 +79,24 @@ impl DriftDetector {
0.0
};
- let result = serde_json::json!({
+ let mut result = serde_json::json!({
"added": added,
"removed": removed,
"likely_renames": likely_renames,
"drift_velocity": drift_velocity,
"v1_count": v1_iris.len(),
"v2_count": v2_iris.len(),
+ "exact": approximation.is_none(),
});
+ if let Some(a) = approximation {
+ result["approximate_reason"] = serde_json::json!(format!(
+ "blank-node triples were not compared, so anonymous classes and the \
+ signals that run through them are missing: {}",
+ a.reason
+ ));
+ result["omitted_v1"] = serde_json::json!(a.omitted_old);
+ result["omitted_v2"] = serde_json::json!(a.omitted_new);
+ }
Ok(result.to_string())
}
diff --git a/src/graph.rs b/src/graph.rs
index b4dce6ae..616f0026 100644
--- a/src/graph.rs
+++ b/src/graph.rs
@@ -182,6 +182,21 @@ pub struct GraphStore {
store: Store,
}
+/// Why [`GraphStore::canonicalize_pair`] compared only ground triples.
+///
+/// Diff and drift attach this to their reports. It is returned alongside the
+/// stores rather than logged so that a caller cannot present the cut as an
+/// exact comparison without dropping a value it was handed.
+#[derive(Debug, Clone)]
+pub struct Approximation {
+ /// The RDFC-1.0 budget error from the snapshot that exhausted it.
+ pub reason: String,
+ /// Quads mentioning a blank node that were left out of the old snapshot.
+ pub omitted_old: usize,
+ /// The same count for the new snapshot.
+ pub omitted_new: usize,
+}
+
impl Default for GraphStore {
fn default() -> Self {
Self::new()
@@ -645,29 +660,77 @@ impl GraphStore {
/// label/domain/range/hierarchy/individual signal ensemble, so the
/// net result is more informative than the previous "filter and forget"
/// approach (PR #14, @rustforrecess) that dropped bnode content entirely.
+ ///
+ /// The work is bounded by [`crate::canon::DEFAULT_CALL_BUDGET`] and a
+ /// poisoned graph is an `Err`, never a hang. oxrdf's `Dataset::canonicalize`
+ /// sets no such bound, and through it a 7-node blank-node clique took 17 to
+ /// 23 seconds to diff against itself and an 8-node clique did not finish in
+ /// three minutes (issue #293). `crate::canon` is the same Recommendation,
+ /// gated on the W3C suite in `tests/w3c-rdfc10/` label map included, so the
+ /// labels an ordinary graph receives do not change.
pub fn canonicalize_blank_nodes(&self) -> anyhow::Result<GraphStore> {
- use oxigraph::model::dataset::{CanonicalizationAlgorithm, CanonicalizationHashAlgorithm};
- use oxigraph::model::Dataset;
-
- let store = &self.store;
- let mut dataset = Dataset::new();
- for quad in store.iter() {
- let q = quad?;
- dataset.insert(&q);
+ let quads = self.store.iter().collect::<Result<Vec<Quad>, _>>()?;
+ let canonical = crate::canon::canonical_quads(
+ &quads,
+ crate::canon::DEFAULT_CALL_BUDGET,
+ crate::canon::HashAlgorithm::Sha256,
+ )?;
+ let new_gs = GraphStore::new();
+ for quad in &canonical {
+ new_gs.store.insert(quad)?;
}
+ Ok(new_gs)
+ }
- dataset.canonicalize(CanonicalizationAlgorithm::Rdfc10 {
- hash_algorithm: CanonicalizationHashAlgorithm::Sha256,
- });
+ /// Canonicalise two snapshots for comparison, or, when either exhausts the
+ /// RDFC-1.0 budget, cut BOTH to the quads that mention no blank node.
+ ///
+ /// This is for commands that compare snapshots (diff, drift) and must
+ /// answer on any input, a poisoned one included. Dropping every quad that
+ /// mentions a blank node is the one cut that is still sound for what
+ /// remains: ground quads need no labels, so a change among them is a real
+ /// change and an absence is a real absence. Both sides are cut, because
+ /// canonical labels on one side against nothing on the other would report
+ /// every blank-node triple of the exact side as a change nobody made. What
+ /// the cut loses is every statement about anonymous structure, and the
+ /// returned [`Approximation`] says so with the reason and the counts.
+ pub fn canonicalize_pair(
+ old: &GraphStore,
+ new: &GraphStore,
+ ) -> anyhow::Result<(GraphStore, GraphStore, Option<Approximation>)> {
+ let budget_error = |e: anyhow::Error| match e.downcast::<crate::canon::CanonError>() {
+ Ok(canon) => Ok(canon.to_string()),
+ Err(other) => Err(other),
+ };
+ let reason = match old.canonicalize_blank_nodes() {
+ Ok(old_canon) => match new.canonicalize_blank_nodes() {
+ Ok(new_canon) => return Ok((old_canon, new_canon, None)),
+ Err(e) => budget_error(e)?,
+ },
+ Err(e) => budget_error(e)?,
+ };
+ let (old_ground, omitted_old) = old.ground_quads()?;
+ let (new_ground, omitted_new) = new.ground_quads()?;
+ Ok((old_ground, new_ground, Some(Approximation { reason, omitted_old, omitted_new })))
+ }
- let new_gs = GraphStore::new();
- {
- let new_store = &new_gs.store;
- for quad in dataset.iter() {
- new_store.insert(quad)?;
+ /// A new store holding only the quads that mention no blank node, and the
+ /// number of quads left out.
+ pub fn ground_quads(&self) -> anyhow::Result<(GraphStore, usize)> {
+ let ground = GraphStore::new();
+ let mut omitted = 0;
+ for quad in self.store.iter() {
+ let quad = quad?;
+ let mentions_blank = quad.subject.is_blank_node()
+ || quad.object.is_blank_node()
+ || quad.graph_name.is_blank_node();
+ if mentions_blank {
+ omitted += 1;
+ } else {
+ ground.store.insert(&quad)?;
}
}
- Ok(new_gs)
+ Ok((ground, omitted))
}
pub fn serialize(&self, format: &str) -> anyhow::Result<String> {
diff --git a/src/kgcl.rs b/src/kgcl.rs
index af75e2d1..af0d7beb 100644
--- a/src/kgcl.rs
+++ b/src/kgcl.rs
@@ -76,10 +76,18 @@ impl KgclChange {
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct KgclReport {
pub changes: Vec<KgclChange>,
+ /// Set when the drift report it came from was approximate (issue #293):
+ /// the changes then cover only the snapshots' ground triples.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub approximate_reason: Option<String>,
}
impl KgclReport {
/// CNL representation, one change per line.
+ ///
+ /// CNL has no place to say a report is approximate, so a caller holding
+ /// one with `approximate_reason` set must not hand this out on its own;
+ /// `onto_drift` refuses the `kgcl` format in that case.
pub fn to_cnl(&self) -> String {
self.changes
.iter()
@@ -90,10 +98,15 @@ impl KgclReport {
/// Structured JSON representation (for machine consumers).
pub fn to_json(&self) -> serde_json::Value {
- serde_json::json!({
+ let mut json = serde_json::json!({
"@context": "http://w3id.org/kgcl/",
"changes": self.changes,
- })
+ "exact": self.approximate_reason.is_none(),
+ });
+ if let Some(reason) = &self.approximate_reason {
+ json["approximate_reason"] = serde_json::json!(reason);
+ }
+ json
}
}
@@ -196,7 +209,8 @@ pub fn drift_to_kgcl(
});
}
- KgclReport { changes }
+ let approximate_reason = drift_json["approximate_reason"].as_str().map(String::from);
+ KgclReport { changes, approximate_reason }
}
#[cfg(test)]
@@ -357,6 +371,7 @@ mod tests {
about_node: "http://example.org/Cat".to_string(),
node_kind: "class".to_string(),
}],
+ approximate_reason: None,
};
let j = report.to_json();
assert_eq!(j["@context"].as_str().unwrap(), "http://w3id.org/kgcl/");
diff --git a/src/ontology.rs b/src/ontology.rs
index 0db5b6f0..55e0b97d 100644
--- a/src/ontology.rs
+++ b/src/ontology.rs
@@ -60,6 +60,12 @@ impl OntologyService {
}
/// Diff two ontologies. Returns added/removed triples.
+ ///
+ /// `exact` is false when either snapshot exhausted the RDFC-1.0 budget
+ /// (issue #293). The diff then covers only the triples that mention no
+ /// blank node, `approximate_reason` says why, and `omitted_old` /
+ /// `omitted_new` count the blank-node triples that were not compared, so an
+ /// empty diff over a poisoned input is never mistaken for "no changes".
pub fn diff(old_content: &str, new_content: &str) -> anyhow::Result<String> {
let old_raw = GraphStore::new();
let new_raw = GraphStore::new();
@@ -69,8 +75,7 @@ impl OntologyService {
// Parse-local blank node IDs are not identity across snapshots.
// Preserve anonymous structure using the same RDFC 1.0 helper as drift.
// Canonical IDs can shift under edits; this is not a minimal edit script.
- let old_store = old_raw.canonicalize_blank_nodes()?;
- let new_store = new_raw.canonicalize_blank_nodes()?;
+ let (old_store, new_store, approximation) = GraphStore::canonicalize_pair(&old_raw, &new_raw)?;
let old_triples: HashSet<String> = old_store
.all_triples()?
.into_iter()
@@ -85,13 +90,20 @@ impl OntologyService {
let added: Vec<&String> = new_triples.difference(&old_triples).collect();
let removed: Vec<&String> = old_triples.difference(&new_triples).collect();
- Ok(serde_json::json!({
+ let mut report = serde_json::json!({
"added": added.len(),
"removed": removed.len(),
"added_triples": added,
"removed_triples": removed,
- })
- .to_string())
+ "exact": approximation.is_none(),
+ });
+ if let Some(a) = approximation {
+ report["approximate_reason"] =
+ serde_json::json!(format!("blank-node triples were not compared: {}", a.reason));
+ report["omitted_old"] = serde_json::json!(a.omitted_old);
+ report["omitted_new"] = serde_json::json!(a.omitted_new);
+ }
+ Ok(report.to_string())
}
/// Collect raw lint issues from a Store.
diff --git a/src/server.rs b/src/server.rs
index 74aa315f..b60c9ded 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -2571,6 +2571,11 @@ impl OpenOntologiesServer {
let threshold = input.rename_threshold.unwrap_or(0.7);
match format {
"kgcl" => match detector.detect_kgcl(&input.version_a, &input.version_b, threshold) {
+ Ok(report) if report.approximate_reason.is_some() => Self::err_json(anyhow::anyhow!(
+ "the drift is approximate and KGCL CNL cannot say so; use format 'json' or \
+ 'kgcl_json', which carry `exact: false` and the reason: {}",
+ report.approximate_reason.unwrap_or_default()
+ )),
Ok(report) => {
self.lineage()
.record(&self.session_id, "D", "drift", "detected:kgcl");
diff --git a/tests/rdfc_budget_diff_test.rs b/tests/rdfc_budget_diff_test.rs
new file mode 100644
index 00000000..e9e05622
--- /dev/null
+++ b/tests/rdfc_budget_diff_test.rs
@@ -0,0 +1,200 @@
+//! **Issue #293: diff and drift on a poisoned blank-node graph.**
+//!
+//! Both commands canonicalise blank nodes with RDFC-1.0 before comparing.
+//! Through oxrdf's unbounded canonicaliser a 7-node blank-node clique took 17
+//! to 23 seconds to diff against itself and an 8-node clique did not finish in
+//! three minutes. The fix runs the budgeted `open_ontologies::canon` and, when
+//! the budget runs out, compares only the ground triples and says so.
+//!
+//! The time bounds below are deliberately generous. On the fixed code the
+//! clique runs in well under a second; on the unfixed code it does not finish
+//! at all, so a bound of a minute separates the two without flaking on a slow
+//! CI runner. The assertions that carry the meaning are the `exact` flags.
+
+use open_ontologies::drift::DriftDetector;
+use open_ontologies::ontology::OntologyService;
+use open_ontologies::state::StateDb;
+use std::collections::BTreeSet;
+use std::time::Duration;
+
+const GENEROUS: Duration = Duration::from_secs(60);
+
+/// `_:bi ex:p _:bj` for every ordered pair i != j: every node has the same
+/// first-degree hash and every permutation of its neighbours looks alike,
+/// which is the RDFC-1.0 section 4.4 poison shape.
+fn clique(n: usize) -> String {
+ let mut ttl = String::from("@prefix ex: <http://example.org/> .\n");
+ for i in 0..n {
+ for j in 0..n {
+ if i != j {
+ ttl.push_str(&format!("_:b{i} ex:p _:b{j} .\n"));
+ }
+ }
+ }
+ ttl
+}
+
+fn pizza() -> String {
+ let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("benchmark/ontoaxiom/data/ontoaxiom/ontologies/pizza.ttl");
+ std::fs::read_to_string(path).unwrap()
+}
+
+/// Run `f` on its own thread and fail, rather than hang, if it overruns.
+fn within<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
+ let (tx, rx) = std::sync::mpsc::channel();
+ std::thread::spawn(move || {
+ let _ = tx.send(f());
+ });
+ rx.recv_timeout(GENEROUS)
+ .unwrap_or_else(|_| panic!("did not finish within {GENEROUS:?}: the RDFC-1.0 work is unbounded"))
+}
+
+fn diff(old: String, new: String) -> serde_json::Value {
+ within(move || serde_json::from_str(&OntologyService::diff(&old, &new).unwrap()).unwrap())
+}
+
+fn drift(v1: String, v2: String) -> serde_json::Value {
+ within(move || {
+ let tmp = tempfile::NamedTempFile::new().unwrap();
+ let detector = DriftDetector::new(StateDb::open(tmp.path()).unwrap());
+ serde_json::from_str(&detector.detect(&v1, &v2).unwrap()).unwrap()
+ })
+}
+
+#[test]
+fn eight_node_clique_diff_is_bounded_and_marked_approximate() {
+ let report = diff(clique(8), clique(8));
+ assert_eq!(report["exact"], false, "{report}");
+ let reason = report["approximate_reason"].as_str().unwrap();
+ assert!(reason.contains("budget"), "{reason}");
+ // All 56 triples mention a blank node, so none was compared, and the
+ // report says that rather than letting `added: 0` read as "no changes".
+ assert_eq!(report["omitted_old"], 56);
+ assert_eq!(report["omitted_new"], 56);
+ assert_eq!(report["added"], 0);
+ assert_eq!(report["removed"], 0);
+}
+
+/// Two identical stars, `_:hub ex:p _:leaf` with 12 leaves each. The hubs
+/// tie, and hashing a hub permutes its 12 interchangeable leaves. Built
+/// eagerly that was 12! (479 million) orderings in memory before the first
+/// budget check; at 11 leaves it already took 10 s and 1.78 GB.
+#[test]
+fn wide_symmetric_star_is_bounded_and_marked_approximate() {
+ let mut ttl = String::from("@prefix ex: <http://example.org/> .\n");
+ for hub in 0..2 {
+ for leaf in 0..12 {
+ ttl.push_str(&format!("_:h{hub} ex:p _:l{hub}_{leaf} .\n"));
+ }
+ }
+ let report = diff(ttl.clone(), ttl);
+ assert_eq!(report["exact"], false, "{report}");
+ assert_eq!(report["omitted_old"], 24);
+}
+
+#[test]
+fn approximate_diff_still_reports_ground_changes() {
+ let old = format!("{}<http://example.org/x> <http://example.org/label> \"old\" .\n", clique(8));
+ let new = format!("{}<http://example.org/x> <http://example.org/label> \"new\" .\n", clique(8));
+ let report = diff(old, new);
+ assert_eq!(report["exact"], false);
+ assert_eq!(report["added"], 1, "{report}");
+ assert_eq!(report["removed"], 1, "{report}");
+ assert!(report["added_triples"][0].as_str().unwrap().ends_with("\"new\""));
+}
+
+/// One poisoned side cuts BOTH sides to ground. Canonical labels on the exact
+/// side against nothing on the other would report the pizza ontology's
+/// anonymous classes as removed, which is a change nobody made.
+#[test]
+fn one_poisoned_side_does_not_invent_churn_on_the_other() {
+ let old = pizza();
+ let new = format!("{old}\n{}", clique(8).lines().skip(1).collect::<Vec<_>>().join("\n"));
+ let new = format!("@prefix ex: <http://example.org/> .\n{new}");
+ let report = diff(old, new);
+ assert_eq!(report["exact"], false);
+ assert_eq!(report["added"], 0, "{report}");
+ assert_eq!(report["removed"], 0, "{report}");
+ let omitted_old = report["omitted_old"].as_u64().unwrap();
+ assert!(omitted_old > 0);
+ assert_eq!(report["omitted_new"].as_u64().unwrap(), omitted_old + 56);
+}
+
+/// pizza.ttl is lists and restrictions throughout, the blank nodes a real
+/// ontology has. It must stay exact, with no churn against itself, and the
+/// budgeted canonicaliser must give it the labels oxrdf's unbounded one gave,
+/// so that switching implementation moves no ordinary diff.
+#[test]
+fn ordinary_blank_node_ontology_stays_exact_with_unchanged_labels() {
+ let report = diff(pizza(), pizza());
+ assert_eq!(report["exact"], true, "{report}");
+ assert!(report.get("approximate_reason").is_none());
+ assert_eq!(report["added"], 0);
+ assert_eq!(report["removed"], 0);
+
+ use oxigraph::io::{RdfFormat, RdfParser};
+ use oxigraph::model::dataset::{CanonicalizationAlgorithm, CanonicalizationHashAlgorithm};
+ use oxigraph::model::{Dataset, Quad};
+ let quads: Vec<Quad> = RdfParser::from_format(RdfFormat::Turtle)
+ .for_reader(pizza().as_bytes())
+ .map(|q| q.unwrap())
+ .collect();
+ let ours: BTreeSet<String> = open_ontologies::canon::canonical_nquads(
+ &quads,
+ open_ontologies::canon::DEFAULT_CALL_BUDGET,
+ open_ontologies::canon::HashAlgorithm::Sha256,
+ )
+ .unwrap()
+ .lines()
+ .map(str::to_string)
+ .collect();
+ assert!(ours.iter().any(|l| l.starts_with("_:c14n")));
+
+ let mut dataset: Dataset = quads.iter().collect();
+ dataset.canonicalize(CanonicalizationAlgorithm::Rdfc10 {
+ hash_algorithm: CanonicalizationHashAlgorithm::Sha256,
+ });
+ let reference: BTreeSet<String> = dataset.iter().map(|q| format!("{q} .")).collect();
+ let only_ours: Vec<_> = ours.difference(&reference).collect();
+ let only_reference: Vec<_> = reference.difference(&ours).collect();
+ assert!(
+ only_ours.is_empty() && only_reference.is_empty(),
+ "labels moved: {} lines only in canon, {} only in oxrdf; first: {:?} / {:?}",
+ only_ours.len(),
+ only_reference.len(),
+ only_ours.first(),
+ only_reference.first()
+ );
+}
+
+#[test]
+fn eight_node_clique_drift_is_bounded_and_marked_approximate() {
+ let report = drift(clique(8), clique(8));
+ assert_eq!(report["exact"], false, "{report}");
+ assert!(report["approximate_reason"].as_str().unwrap().contains("budget"));
+ assert_eq!(report["omitted_v1"], 56);
+ assert_eq!(report["omitted_v2"], 56);
+}
+
+#[test]
+fn ordinary_blank_node_ontology_drift_stays_exact() {
+ let report = drift(pizza(), pizza());
+ assert_eq!(report["exact"], true, "{report}");
+ assert!(report.get("approximate_reason").is_none());
+ assert_eq!(report["added"], serde_json::json!([]));
+ assert_eq!(report["removed"], serde_json::json!([]));
+}
+
+/// KGCL is built from the drift JSON, so it must carry the flag too, or the
+/// `kgcl_json` format would present the cut as an exact change set.
+#[test]
+fn kgcl_report_carries_the_approximation() {
+ let report = within(|| {
+ let tmp = tempfile::NamedTempFile::new().unwrap();
+ let detector = DriftDetector::new(StateDb::open(tmp.path()).unwrap());
+ detector.detect_kgcl(&clique(8), &clique(8), 0.7).unwrap()
+ });
+ assert!(report.approximate_reason.as_deref().unwrap().contains("budget"));
+ assert_eq!(report.to_json()["exact"], false);
+}