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.

feat(reason): keep materialised inferences out of the default graph

FABIOTESS77e60e269601
diff --git a/docs/decisions/0001-an-inference-is-not-an-assertion.md b/docs/decisions/0001-an-inference-is-not-an-assertion.md
new file mode 100644
index 00000000..baeea389
--- /dev/null
+++ b/docs/decisions/0001-an-inference-is-not-an-assertion.md
@@ -0,0 +1,66 @@
+# 0001 · An inference is not an assertion
+
+- **Status**: implemented for the OWL-RL family · `InferenceTarget::Inferred` writes to
+ `https://open-ontologies.org/graph/inferred`, `serialize` withholds that graph from the triple
+ formats, `onto_reason` takes `inference_graph` · **opt-in, default unchanged** · the `owl-dl`
+ tableaux path refuses the target rather than pretending to honour it · not done: `onto_pack`,
+ `onto_shacl` and `onto_query` have not been told which dataset they want
+- **Written**: 2026-09-04
+- **Related**: flaw hunt 30 Aug 2026 defect D2; the temporal named-graph work of issue #95, whose
+ serialiser fix this reuses and narrows
+
+## The problem
+
+`reason` merged materialised triples into the default graph with no marker. After a run,
+`SELECT DISTINCT ?g WHERE { GRAPH ?g { ?s ?p ?o } }` returned empty and an inferred triple was
+byte-identical in form to one a person had written. `save` then wrote them out: a source file of
+8 triples came back as 9, newly asserting `<http://ex.org/ghost> a <http://ex.org/Person>`, which
+nobody ever wrote and which is only true under a range entailment over a dangling reference.
+
+The laundering was therefore not transient. It could be, and would be, published. For a tool whose
+subject is register integrity that is the wrong defect to be carrying.
+
+## Decisions
+
+1. **A separate graph, not a marker triple.** Both make the distinction recordable; they fail in
+ opposite directions. A marker obliges every consumer to filter, and the consumer that forgets
+ publishes an inference as an assertion. A separate graph means the consumer that forgets sees
+ fewer triples and never wrong ones. Choose the defence whose failure mode is silence.
+2. **The triple formats withhold the inference graph; the dataset formats keep it.** This is the
+ part that actually closes the defect, and naming the graph alone would not have. `serialize`
+ deliberately flattens named graphs into the default graph for Turtle, RDF/XML and N-Triples,
+ because that is the only thing a triple format can do (issue #95). Flattening the inference
+ graph is exactly the laundering, so it is dropped instead. TriG, N-Quads and JSON-LD can carry
+ the graph name, so they carry it and lose nothing.
+3. **Opt-in, and the default is untouched.** Existing callers read inferences out of the default
+ graph, `onto_query` among them. Flipping the default is a behaviour change for every downstream
+ pipeline and is a separate decision, taken deliberately, not a side effect of fixing the
+ provenance gap.
+4. **`owl-dl` refuses the target rather than silently ignoring it.** The tableaux path materialises
+ through its own code and has not been taught the graph. Accepting the flag and merging into the
+ default graph anyway would leave a caller believing the inferences had been kept apart. An
+ error naming the two profiles that do support it is the honest answer, and matches the
+ discipline the SHACL layer already keeps for unimplemented constraint components.
+
+## Dead ends
+
+- **A marker triple on each inferred statement.** Rejected on decision 1, and also because
+ a marker on a triple has nowhere to live in RDF without reification, which changes the shape of
+ the data to record a fact about it.
+- **Refusing to `save` at all after a reason run.** Considered because it is the loudest possible
+ signal. Rejected: it punishes the legitimate case, which is saving what you asserted, and the
+ narrower rule already makes the wrong outcome impossible.
+
+## Open questions
+
+- **`onto_shacl` and `onto_query` still read the default graph.** With the flag on, a shape now
+ validates the asserted graph alone. That is arguably the more useful default, since validating
+ the closure is what turns a genuine failure into a pass (defect D3), but it is a choice nobody
+ has made explicitly and it should be made rather than inherited.
+- **`onto_pack` writes sorted N-Triples.** A pack built after a reasoning run therefore now
+ excludes the inferences. That is the safe direction and probably the right one, since a pack is
+ a promotable artefact, but the manifest should say so rather than leaving it to be discovered.
+- **When the default flips**, `all_triples()` reads the whole store including named graphs, so a
+ second reasoning run consumes the first run's output as premises. OWL-RL is monotone, so the
+ closure is unchanged and `inferred_count` correctly reports zero new triples, but the reported
+ `initial_triples` then includes inferences and no longer means "what was asserted".
diff --git a/src/graph.rs b/src/graph.rs
index 545baf49..6e18d48c 100644
--- a/src/graph.rs
+++ b/src/graph.rs
@@ -419,7 +419,15 @@ impl GraphStore {
// 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.
+ //
+ // The inference graph is the one exception to that flattening. Merging
+ // materialised triples into the default graph is what let `save`
+ // publish `<ex:ghost> a <ex:Person>` as though a person had written it
+ // (flaw hunt D2, 30 Aug 2026). A triple format cannot say "this one was
+ // derived", so the only statement it can make honestly is the asserted
+ // one; the dataset formats keep the graph name and lose nothing.
let carries_graph_name = rdf_format.supports_datasets();
+ let inferred_graph = GraphName::NamedNode(NamedNode::new(crate::reason::INFERRED_GRAPH)?);
let mut buf = Vec::new();
let mut serializer = RdfSerializer::from_format(rdf_format).for_writer(&mut buf);
for quad in store.iter() {
@@ -427,6 +435,9 @@ impl GraphStore {
if carries_graph_name {
serializer.serialize_quad(quad.as_ref())?;
} else {
+ if quad.graph_name == inferred_graph {
+ continue;
+ }
serializer.serialize_triple(quad.as_ref())?;
}
}
diff --git a/src/inputs.rs b/src/inputs.rs
index 0334dabc..575a05fb 100644
--- a/src/inputs.rs
+++ b/src/inputs.rs
@@ -256,6 +256,12 @@ pub struct OntoReasonInput {
pub profile: Option<String>,
/// If true (default), add inferred triples to the store. If false, dry-run only.
pub materialize: Option<bool>,
+ /// If true, materialise into the inference graph
+ /// `https://open-ontologies.org/graph/inferred` instead of merging into the
+ /// default graph, so an inference can never be mistaken for an assertion and
+ /// `onto_save` to a triple format cannot publish one. Default false, which
+ /// keeps the historical behaviour. Not available for the `owl-dl` profile.
+ pub inference_graph: Option<bool>,
}
#[derive(Deserialize, JsonSchema)]
diff --git a/src/reason.rs b/src/reason.rs
index 47789984..2e74be40 100644
--- a/src/reason.rs
+++ b/src/reason.rs
@@ -62,6 +62,27 @@ impl Interner {
/// sameAs, equivalentClass/Property)
/// "owl-rl-ext" — All above + someValuesFrom, allValuesFrom, hasValue,
/// intersectionOf, unionOf
+/// The graph materialised inferences are written to when the caller asks for
+/// them to be kept apart from what was asserted.
+pub const INFERRED_GRAPH: &str = "https://open-ontologies.org/graph/inferred";
+
+/// Where `reason` puts the triples it materialises.
+///
+/// The choice is a failure-direction one, not a matter of taste. A marker
+/// triple on statements sitting in the default graph obliges every consumer to
+/// filter, and the one that forgets publishes an inference as an assertion. A
+/// separate graph fails the other way: a consumer that forgets sees fewer
+/// triples, never wrong ones.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum InferenceTarget {
+ /// Merge into the default graph beside the asserted statements. The
+ /// historical behaviour, kept so existing callers keep their contract.
+ DefaultGraph,
+ /// Keep them in [`INFERRED_GRAPH`], where nothing downstream can mistake
+ /// an inference for an assertion.
+ Inferred,
+}
+
pub struct Reasoner;
impl Reasoner {
@@ -69,9 +90,26 @@ impl Reasoner {
graph: &Arc<GraphStore>,
profile: &str,
materialize: bool,
+ ) -> anyhow::Result<String> {
+ Self::run_with_target(graph, profile, materialize, InferenceTarget::DefaultGraph)
+ }
+
+ pub fn run_with_target(
+ graph: &Arc<GraphStore>,
+ profile: &str,
+ materialize: bool,
+ target: InferenceTarget,
) -> anyhow::Result<String> {
// Delegate OWL-DL to tableaux reasoner
if profile == "owl-dl" {
+ if target == InferenceTarget::Inferred {
+ // Say so rather than materialise into the default graph while
+ // the caller believes the inferences were kept apart.
+ anyhow::bail!(
+ "the owl-dl tableaux path does not yet write to {INFERRED_GRAPH}; \
+ run it with the default target, or use owl-rl / owl-rl-ext"
+ );
+ }
return crate::tableaux::DlReasoner::run(graph, materialize);
}
@@ -435,18 +473,26 @@ impl Reasoner {
// Materialize inferred triples
if materialize && inferred_count > 0 {
let original: HashSet<(u32, u32, u32)> = facts.iter().copied().collect();
- let mut ntriples = String::new();
+ let mut lines = String::new();
for &(s, p, o) in &triple_set {
if !original.contains(&(s, p, o)) {
- ntriples.push_str(interner.resolve(s));
- ntriples.push(' ');
- ntriples.push_str(interner.resolve(p));
- ntriples.push(' ');
- ntriples.push_str(interner.resolve(o));
- ntriples.push_str(" .\n");
+ lines.push_str(interner.resolve(s));
+ lines.push(' ');
+ lines.push_str(interner.resolve(p));
+ lines.push(' ');
+ lines.push_str(interner.resolve(o));
+ if target == InferenceTarget::Inferred {
+ lines.push_str(" <");
+ lines.push_str(INFERRED_GRAPH);
+ lines.push('>');
+ }
+ lines.push_str(" .\n");
}
}
- graph.load_ntriples(&ntriples)?;
+ match target {
+ InferenceTarget::DefaultGraph => graph.load_ntriples(&lines)?,
+ InferenceTarget::Inferred => graph.load_nquads(&lines)?,
+ };
}
// Sample
@@ -469,6 +515,11 @@ impl Reasoner {
if !materialize {
result["dry_run"] = serde_json::json!(true);
}
+ if target == InferenceTarget::Inferred {
+ // A caller cannot ask the inferences back unless it is told where
+ // they were put.
+ result["inference_graph"] = serde_json::json!(INFERRED_GRAPH);
+ }
Ok(result.to_string())
}
}
diff --git a/tests/reason_inference_provenance_test.rs b/tests/reason_inference_provenance_test.rs
new file mode 100644
index 00000000..eef17b8b
--- /dev/null
+++ b/tests/reason_inference_provenance_test.rs
@@ -0,0 +1,143 @@
+//! Inferred triples must stay distinguishable from asserted ones.
+//!
+//! The defect this pins (flaw hunt, 30 Aug 2026, D2): `reason` merged
+//! materialised triples into the default graph with no marker, so after
+//! reasoning an inferred statement was byte-identical in form to one a person
+//! wrote, and `save` then published it. Source `laund.ttl` went in at 8 triples
+//! and came out at 9, newly asserting `<http://ex.org/ghost> a
+//! <http://ex.org/Person>`, which nobody ever wrote.
+//!
+//! The fix follows the failure-direction argument: a separate container, not a
+//! marker on the shared one. A reader that forgets about inference sees fewer
+//! triples; a reader that wants them asks for the union. A marker triple would
+//! fail the other way, and the one consumer that forgot to filter would
+//! publish a laundered assertion.
+
+use open_ontologies::graph::GraphStore;
+use open_ontologies::reason::{InferenceTarget, Reasoner, INFERRED_GRAPH};
+use oxigraph::io::RdfFormat;
+use std::sync::Arc;
+
+/// The D2 reproduction: a dangling reference plus a range axiom.
+/// OWL-RL range entailment materialises `ex:ghost a ex:Person`.
+const LAUNDERING_CASE: &str = r#"
+ @prefix ex: <http://ex.org/> .
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+ ex:knows rdfs:range ex:Person .
+ ex:alice ex:knows ex:ghost .
+"#;
+
+const GHOST_IS_A_PERSON: &str = "ASK { <http://ex.org/ghost> a <http://ex.org/Person> }";
+
+fn asks_true(json: &str) -> bool {
+ let parsed: serde_json::Value = serde_json::from_str(json).unwrap();
+ parsed["result"].as_bool().unwrap()
+}
+
+#[test]
+fn inferred_triples_stay_out_of_the_default_graph() {
+ let store = Arc::new(GraphStore::new());
+ store.load_turtle(LAUNDERING_CASE, None).unwrap();
+
+ let result =
+ Reasoner::run_with_target(&store, "owl-rl", true, InferenceTarget::Inferred).unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+ assert!(
+ parsed["inferred_count"].as_u64().unwrap() >= 1,
+ "the range axiom should have entailed at least the ghost's type: {result}"
+ );
+
+ assert!(
+ !asks_true(&store.sparql_select(GHOST_IS_A_PERSON).unwrap()),
+ "an inferred type must not appear in the default graph beside asserted statements"
+ );
+ assert!(
+ asks_true(&store.sparql_select_union(GHOST_IS_A_PERSON).unwrap()),
+ "the inference must still be in the store, reachable through the union dataset"
+ );
+}
+
+#[test]
+fn the_response_names_the_graph_the_inferences_went_to() {
+ let store = Arc::new(GraphStore::new());
+ store.load_turtle(LAUNDERING_CASE, None).unwrap();
+
+ let result =
+ Reasoner::run_with_target(&store, "owl-rl", true, InferenceTarget::Inferred).unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
+
+ assert_eq!(
+ parsed["inference_graph"].as_str(),
+ Some(INFERRED_GRAPH),
+ "a caller cannot ask for the inferences back unless the response says where they went"
+ );
+}
+
+#[test]
+fn a_turtle_save_does_not_bake_in_inferred_triples() {
+ let store = Arc::new(GraphStore::new());
+ store.load_turtle(LAUNDERING_CASE, None).unwrap();
+ Reasoner::run_with_target(&store, "owl-rl", true, InferenceTarget::Inferred).unwrap();
+
+ // Turtle cannot carry a graph name, so the only honest thing it can hold is
+ // what was asserted. Round-trip through a fresh store rather than matching
+ // strings, because the question is what a consumer would read back.
+ let turtle = store.serialize("turtle").unwrap();
+ let reloaded = GraphStore::new();
+ reloaded.load_turtle(&turtle, None).unwrap();
+
+ assert!(
+ !asks_true(&reloaded.sparql_select_union(GHOST_IS_A_PERSON).unwrap()),
+ "saving to a triple format published an inference as an assertion:\n{turtle}"
+ );
+ assert!(
+ asks_true(
+ &reloaded
+ .sparql_select_union("ASK { <http://ex.org/alice> <http://ex.org/knows> <http://ex.org/ghost> }")
+ .unwrap()
+ ),
+ "the asserted statements must survive the save untouched"
+ );
+}
+
+#[test]
+fn a_trig_save_keeps_the_inferences_under_their_own_graph_name() {
+ let store = Arc::new(GraphStore::new());
+ store.load_turtle(LAUNDERING_CASE, None).unwrap();
+ Reasoner::run_with_target(&store, "owl-rl", true, InferenceTarget::Inferred).unwrap();
+
+ // TriG can carry the graph name, so nothing is dropped: the inference is
+ // kept and stays labelled as one.
+ let trig = store.serialize("trig").unwrap();
+ assert!(
+ trig.contains(INFERRED_GRAPH),
+ "a dataset format must name the inference graph it is carrying:\n{trig}"
+ );
+
+ let reloaded = GraphStore::new();
+ reloaded
+ .load_content(&trig, RdfFormat::TriG)
+ .unwrap();
+ assert!(
+ !asks_true(&reloaded.sparql_select(GHOST_IS_A_PERSON).unwrap()),
+ "after a TriG round trip the inference must still be outside the default graph"
+ );
+ assert!(
+ asks_true(&reloaded.sparql_select_union(GHOST_IS_A_PERSON).unwrap()),
+ "after a TriG round trip the inference must still be in the store"
+ );
+}
+
+#[test]
+fn the_default_target_is_unchanged_so_existing_callers_keep_their_contract() {
+ let store = Arc::new(GraphStore::new());
+ store.load_turtle(LAUNDERING_CASE, None).unwrap();
+
+ Reasoner::run(&store, "owl-rl", true).unwrap();
+
+ assert!(
+ asks_true(&store.sparql_select(GHOST_IS_A_PERSON).unwrap()),
+ "Reasoner::run must keep materialising into the default graph until the \
+ default is deliberately flipped"
+ );
+}