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
Make the reasoner reach its fixpoint, stop it emitting impossible triples, and give cls-hv1 its real name
FABIOTESS160ae7dd18db
diff --git a/lean/OOCert/Rules.lean b/lean/OOCert/Rules.leanindex c11dcbf4..bce2ad3c 100644--- a/lean/OOCert/Rules.lean+++ b/lean/OOCert/Rules.lean@@ -36,7 +36,7 @@ wrong order is rejected, which is a false alarm and never a false pass.| scm-eqp1 | `a owl:equivalentProperty b` | `a sp b` || scm-eqp2 | `a owl:equivalentProperty b` | `b sp a` || cls-svf1 | `r owl:onProperty p`, `r owl:someValuesFrom c`, `x p y`, `y rdf:type c` | `x rdf:type r` |-| cls-hv1 | `r owl:onProperty p`, `r owl:hasValue v`, `k sc r`, `x rdf:type k` | `x p v` |+| cls-hv1 | `r owl:onProperty p`, `r owl:hasValue v`, `x rdf:type r` | `x p v` || cls-hv2 | `r owl:onProperty p`, `r owl:hasValue v`, `x p v` | `x rdf:type r` || cls-int1 | `c owl:intersectionOf l`, the list chain of `l`, `x rdf:type m` for every member `m` | `x rdf:type c` || cls-uni | `c owl:unionOf l`, the list chain of `l`, `x rdf:type m` for one member `m` | `x rdf:type c` |@@ -153,10 +153,9 @@ def checkStep (inG derived : Triple → Bool) (st : Step) : Bool :=t = V.type ∧ c' = c ∧k ⟨r, op, p⟩ ∧ k ⟨r', sv, c⟩ ∧ k ⟨x, p1, y⟩ ∧ k ⟨y', t, c'⟩ ∧st.conclusion = ⟨x, V.type, r⟩- | .clsHv1, [⟨r, op, p⟩, ⟨r', hv, v⟩, ⟨cls, sc, r''⟩, ⟨x, t, cls'⟩] =>- op = V.onProperty ∧ hv = V.hasValue ∧ r' = r ∧ sc = V.subClassOf ∧ r'' = r ∧- t = V.type ∧ cls' = cls ∧- k ⟨r, op, p⟩ ∧ k ⟨r', hv, v⟩ ∧ k ⟨cls, sc, r''⟩ ∧ k ⟨x, t, cls'⟩ ∧+ | .clsHv1, [⟨r, op, p⟩, ⟨r', hv, v⟩, ⟨x, t, r''⟩] =>+ op = V.onProperty ∧ hv = V.hasValue ∧ r' = r ∧ t = V.type ∧ r'' = r ∧+ k ⟨r, op, p⟩ ∧ k ⟨r', hv, v⟩ ∧ k ⟨x, t, r''⟩ ∧st.conclusion = ⟨x, p, v⟩| .clsHv2, [⟨r, op, p⟩, ⟨r', hv, v⟩, ⟨x, p1, v'⟩] =>op = V.onProperty ∧ hv = V.hasValue ∧ r' = r ∧ p1 = p ∧ v' = v ∧diff --git a/lean/OOCert/Soundness.lean b/lean/OOCert/Soundness.leanindex dc1b4f04..eae20a33 100644--- a/lean/OOCert/Soundness.lean+++ b/lean/OOCert/Soundness.lean@@ -214,12 +214,11 @@ theorem checkStep_sound {inG derived : Triple → Bool} {st : Step}exact M.conds.svf _ _ _ (hk _ h1 I M) (hk _ h2 I M) _ _ (hk _ h3 I M) (hk _ h4 I M)case clsHv1 =>rcases premises with- _ | ⟨⟨r, op, p⟩, _ | ⟨⟨r', hv, v⟩, _ | ⟨⟨cls, sc, r''⟩, _ | ⟨⟨x, t, cls'⟩, _ | _⟩⟩⟩⟩ <;>+ _ | ⟨⟨r, op, p⟩, _ | ⟨⟨r', hv, v⟩, _ | ⟨⟨x, t, r''⟩, _ | _⟩⟩⟩ <;>simp only [decide_eq_true_eq, Bool.false_eq_true] at h- obtain ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, h1, h2, h3, h4, rfl⟩ := h+ obtain ⟨rfl, rfl, rfl, rfl, rfl, h1, h2, h3, rfl⟩ := hintro I M- exact (M.conds.hv _ _ _ (hk _ h1 I M) (hk _ h2 I M) _).mp- (M.conds.sc_sub _ _ (hk _ h3 I M) _ (hk _ h4 I M))+ exact (M.conds.hv _ _ _ (hk _ h1 I M) (hk _ h2 I M) _).mp (hk _ h3 I M)case clsHv2 =>rcases premises with_ | ⟨⟨r, op, p⟩, _ | ⟨⟨r', hv, v⟩, _ | ⟨⟨x, p1, v'⟩, _ | _⟩⟩⟩ <;>diff --git a/src/reason.rs b/src/reason.rsindex 30dfdf25..98cc9830 100644--- a/src/reason.rs+++ b/src/reason.rs@@ -180,126 +180,9 @@ impl Reasoner {let rdfs_subclass = interner.intern(RDFS_SUBCLASS);let rdfs_subprop = interner.intern(RDFS_SUBPROP);let owl_sameas = interner.intern(OWL_SAMEAS);-- // Pre-extract static schema relations- let domain_map: Vec<(u32, u32)> = facts.iter()- .filter(|&&(_, p, _)| p == interner.intern(RDFS_DOMAIN))- .map(|&(s, _, o)| (s, o)).collect();- let range_map: Vec<(u32, u32)> = facts.iter()- .filter(|&&(_, p, _)| p == interner.intern(RDFS_RANGE))- .map(|&(s, _, o)| (s, o)).collect();- let transitive_set: HashSet<u32> = facts.iter()- .filter(|&&(_, p, o)| p == rdf_type && o == interner.intern(OWL_TRANSITIVE))- .map(|&(s, _, _)| s).collect();- let symmetric_set: HashSet<u32> = facts.iter()- .filter(|&&(_, p, o)| p == rdf_type && o == interner.intern(OWL_SYMMETRIC))- .map(|&(s, _, _)| s).collect();- let inverse_pairs: Vec<(u32, u32)> = facts.iter()- .filter(|&&(_, p, _)| p == interner.intern(OWL_INVERSE))- .map(|&(s, _, o)| (s, o)).collect();- let equiv_class: Vec<(u32, u32)> = facts.iter()- .filter(|&&(_, p, _)| p == interner.intern(OWL_EQUIV_CLASS))- .map(|&(s, _, o)| (s, o)).collect();- let equiv_prop: Vec<(u32, u32)> = facts.iter()- .filter(|&&(_, p, _)| p == interner.intern(OWL_EQUIV_PROP))- .map(|&(s, _, o)| (s, o)).collect();-- // OWL restriction structures (for owl-rl-ext)- let owl_on_property = interner.intern(OWL_ON_PROPERTY);- let owl_some_values = interner.intern(OWL_SOME_VALUES);- let owl_all_values = interner.intern(OWL_ALL_VALUES);- let owl_has_value = interner.intern(OWL_HAS_VALUE);-- let mut restr_prop: HashMap<u32, u32> = HashMap::new();- let mut restr_svf: HashMap<u32, u32> = HashMap::new();- let mut restr_avf: HashMap<u32, u32> = HashMap::new();- let mut restr_hv: HashMap<u32, u32> = HashMap::new();-- if include_ext {- for &(s, p, o) in &facts {- if p == owl_on_property { restr_prop.insert(s, o); }- if p == owl_some_values { restr_svf.insert(s, o); }- if p == owl_all_values { restr_avf.insert(s, o); }- if p == owl_has_value { restr_hv.insert(s, o); }- }- }-- // svf_rules: (property, filler_class, restriction_node)- let svf_rules: Vec<(u32, u32, u32)> = restr_svf.iter()- .filter_map(|(&r, &filler)| restr_prop.get(&r).map(|&prop| (prop, filler, r)))- .collect();- // hv_rules: (property, value, restriction_node)- let hv_rules: Vec<(u32, u32, u32)> = restr_hv.iter()- .filter_map(|(&r, &val)| restr_prop.get(&r).map(|&prop| (prop, val, r)))- .collect();- // avf_rules: (property, filler_class, restriction_node)- let _avf_rules: Vec<(u32, u32, u32)> = restr_avf.iter()- .filter_map(|(&r, &filler)| restr_prop.get(&r).map(|&prop| (prop, filler, r)))- .collect();-- // Parse RDF lists for intersectionOf/unionOf.- //- // A list is read only when it is well formed: every node carries the- // rdf:first and rdf:rest the certificate checker will look for, and- // the chain reaches rdf:nil. It used to be read leniently (a node- // without rdf:first was skipped, the walk stopped at 100 nodes) and- // the class rules fired on whatever came back. The checker has no- // rule for a list it cannot walk, so the reasoner no longer derives- // from one either; deriving less from malformed input is the sound- // direction. Each entry keeps the head node and the chain triples so- // that a certificate can cite them.- let rdf_first = interner.intern(RDF_FIRST);- let rdf_rest = interner.intern(RDF_REST);- let rdf_nil = interner.intern(RDF_NIL);- let owl_intersection = interner.intern(OWL_INTERSECTION);- let owl_union = interner.intern(OWL_UNION);- let mut intersection_classes: Vec<(u32, u32, Vec<Fact>, Vec<u32>)> = Vec::new();- let mut union_classes: Vec<(u32, u32, Vec<Fact>, Vec<u32>)> = Vec::new();- if include_ext {- let first_map: HashMap<u32, u32> = facts.iter()- .filter(|&&(_, p, _)| p == rdf_first)- .map(|&(s, _, o)| (s, o)).collect();- let rest_map: HashMap<u32, u32> = facts.iter()- .filter(|&&(_, p, _)| p == rdf_rest)- .map(|&(s, _, o)| (s, o)).collect();-- let walk_list = |head: u32| -> Option<(Vec<Fact>, Vec<u32>)> {- let mut chain = Vec::new();- let mut items = Vec::new();- let mut cur = head;- // Bounded so that a cyclic rdf:rest cannot spin.- for _ in 0..100_000 {- if cur == rdf_nil {- return Some((chain, items));- }- let item = *first_map.get(&cur)?;- let next = *rest_map.get(&cur)?;- chain.push((cur, rdf_first, item));- chain.push((cur, rdf_rest, next));- items.push(item);- cur = next;- }- None- };-- for &(s, p, o) in &facts {- if p == owl_intersection- && let Some((chain, items)) = walk_list(o)- && !items.is_empty()- {- intersection_classes.push((s, o, chain, items));- }- if p == owl_union- && let Some((chain, items)) = walk_list(o)- && !items.is_empty()- {- union_classes.push((s, o, chain, items));- }- }- }-- // Ids the certificate cites as premises. Interning a term twice- // returns the same id, so these agree with the filters above.+ // Every well-known id is interned once, before the loop, so the+ // schema indices below can be rebuilt from the closure each iteration+ // without borrowing the interner mutably inside it.let rdfs_domain = interner.intern(RDFS_DOMAIN);let rdfs_range = interner.intern(RDFS_RANGE);let owl_transitive = interner.intern(OWL_TRANSITIVE);@@ -307,6 +190,15 @@ impl Reasoner {let owl_inverse = interner.intern(OWL_INVERSE);let owl_equiv_class = interner.intern(OWL_EQUIV_CLASS);let owl_equiv_prop = interner.intern(OWL_EQUIV_PROP);+ let owl_on_property = interner.intern(OWL_ON_PROPERTY);+ let owl_some_values = interner.intern(OWL_SOME_VALUES);+ let owl_all_values = interner.intern(OWL_ALL_VALUES);+ let owl_has_value = interner.intern(OWL_HAS_VALUE);+ let owl_intersection = interner.intern(OWL_INTERSECTION);+ let owl_union = interner.intern(OWL_UNION);+ let rdf_first = interner.intern(RDF_FIRST);+ let rdf_rest = interner.intern(RDF_REST);+ let rdf_nil = interner.intern(RDF_NIL);// ── Fixpoint iteration ──────────────────────────────────────let mut triple_set: HashSet<Fact> = facts.iter().copied().collect();@@ -327,6 +219,118 @@ impl Reasoner {let before = triple_set.len();let mut new: Vec<Fact> = Vec::new();+ // Schema indices, rebuilt from the closure on every iteration.+ //+ // These used to be filtered ONCE out of the pre-loop snapshot while+ // only the three data indices below were rebuilt, so the run was+ // not a fixpoint of its own rule set: a `rdfs:domain` triple that+ // the reasoner itself derived, by rdfs7 over a subproperty of+ // rdfs:domain or by scm-eqp, was never used, and running `reason` a+ // second time derived more than running it once. The number of runs+ // needed was the length of the longest chain of such rules, not two.+ //+ // For certificates that mattered more than for query answers.+ // Materialising turns run N's conclusions into run N+1's premises,+ // so `asserted.tsv` could list the reasoner's own output as an+ // axiom with nothing marking it as derived, and the soundness+ // theorem is conditional on the assertions. Reaching the fixpoint+ // in one run is what makes a single certificate the whole story.+ //+ // The cost is a constant factor on a scan the loop already does.+ let domain_map: Vec<(u32, u32)> = triple_set.iter()+ .filter(|&&(_, p, _)| p == rdfs_domain)+ .map(|&(s, _, o)| (s, o)).collect();+ let range_map: Vec<(u32, u32)> = triple_set.iter()+ .filter(|&&(_, p, _)| p == rdfs_range)+ .map(|&(s, _, o)| (s, o)).collect();+ let transitive_set: HashSet<u32> = triple_set.iter()+ .filter(|&&(_, p, o)| p == rdf_type && o == owl_transitive)+ .map(|&(s, _, _)| s).collect();+ let symmetric_set: HashSet<u32> = triple_set.iter()+ .filter(|&&(_, p, o)| p == rdf_type && o == owl_symmetric)+ .map(|&(s, _, _)| s).collect();+ let inverse_pairs: Vec<(u32, u32)> = triple_set.iter()+ .filter(|&&(_, p, _)| p == owl_inverse)+ .map(|&(s, _, o)| (s, o)).collect();+ let equiv_class: Vec<(u32, u32)> = triple_set.iter()+ .filter(|&&(_, p, _)| p == owl_equiv_class)+ .map(|&(s, _, o)| (s, o)).collect();+ let equiv_prop: Vec<(u32, u32)> = triple_set.iter()+ .filter(|&&(_, p, _)| p == owl_equiv_prop)+ .map(|&(s, _, o)| (s, o)).collect();++ // OWL restriction structures and RDF lists (owl-rl-ext only).+ let mut restr_prop: HashMap<u32, u32> = HashMap::new();+ let mut restr_svf: HashMap<u32, u32> = HashMap::new();+ let mut restr_hv: HashMap<u32, u32> = HashMap::new();+ let mut intersection_classes: Vec<(u32, u32, Vec<Fact>, Vec<u32>)> = Vec::new();+ let mut union_classes: Vec<(u32, u32, Vec<Fact>, Vec<u32>)> = Vec::new();+ let mut svf_rules: Vec<(u32, u32, u32)> = Vec::new();+ let mut hv_rules: Vec<(u32, u32, u32)> = Vec::new();+ if include_ext {+ let mut restr_avf: HashMap<u32, u32> = HashMap::new();+ for &(s, p, o) in triple_set.iter() {+ if p == owl_on_property { restr_prop.insert(s, o); }+ if p == owl_some_values { restr_svf.insert(s, o); }+ if p == owl_all_values { restr_avf.insert(s, o); }+ if p == owl_has_value { restr_hv.insert(s, o); }+ }+ let _ = restr_avf;+ svf_rules = restr_svf.iter()+ .filter_map(|(&r, &filler)| restr_prop.get(&r).map(|&prop| (prop, filler, r)))+ .collect();+ hv_rules = restr_hv.iter()+ .filter_map(|(&r, &val)| restr_prop.get(&r).map(|&prop| (prop, val, r)))+ .collect();++ // A list is read only when it is well formed: every node carries+ // the rdf:first and rdf:rest the certificate checker will look+ // for, and the chain reaches rdf:nil. It used to be read+ // leniently and the class rules fired on whatever came back. The+ // checker has no rule for a list it cannot walk, so the reasoner+ // no longer derives from one either; deriving less from+ // malformed input is the sound direction. Each entry keeps the+ // head node and the chain triples so a certificate can cite them.+ let first_map: HashMap<u32, u32> = triple_set.iter()+ .filter(|&&(_, p, _)| p == rdf_first)+ .map(|&(s, _, o)| (s, o)).collect();+ let rest_map: HashMap<u32, u32> = triple_set.iter()+ .filter(|&&(_, p, _)| p == rdf_rest)+ .map(|&(s, _, o)| (s, o)).collect();+ let walk_list = |head: u32| -> Option<(Vec<Fact>, Vec<u32>)> {+ let mut chain = Vec::new();+ let mut items = Vec::new();+ let mut cur = head;+ // Bounded so that a cyclic rdf:rest cannot spin.+ for _ in 0..100_000 {+ if cur == rdf_nil {+ return Some((chain, items));+ }+ let item = *first_map.get(&cur)?;+ let next = *rest_map.get(&cur)?;+ chain.push((cur, rdf_first, item));+ chain.push((cur, rdf_rest, next));+ items.push(item);+ cur = next;+ }+ None+ };+ for &(s, p, o) in triple_set.iter() {+ if p == owl_intersection+ && let Some((chain, items)) = walk_list(o)+ && !items.is_empty()+ {+ intersection_classes.push((s, o, chain, items));+ }+ if p == owl_union+ && let Some((chain, items)) = walk_list(o)+ && !items.is_empty()+ {+ union_classes.push((s, o, chain, items));+ }+ }+ }+// Build per-iteration indiceslet type_idx: Vec<(u32, u32)> = triple_set.iter().filter(|&&(_, p, _)| p == rdf_type)@@ -393,7 +397,13 @@ impl Reasoner {// rdfs3: s p o, p range class → o type class (IRI only)for &(prop, cls) in &range_map {for &(s, p, o) in triple_set.iter() {- if p == prop && interner.resolve(o).starts_with('<') {+ // The guard has to exclude LITERALS, which cannot be the+ // subject of the conclusion, and nothing else. Requiring an+ // IRI also dropped every range inference onto a blank node,+ // so a blank-node value never got typed, rdfs9 starved+ // behind it, and a SHACL shape targeting that class found+ // no focus nodes. rdfs2 twelve lines up has no such guard.+ if p == prop && !interner.resolve(o).starts_with('"') {emit((o, rdf_type, cls), "rdfs3", &[(s, p, o), (prop, rdfs_range, cls)]);}}@@ -426,6 +436,17 @@ impl Reasoner {}}+ // Four rules below conclude a triple whose SUBJECT comes from an+ // object position, so a literal object would produce a triple no+ // RDF serialisation can express. The materialiser then failed on+ // the whole batch with "The subject of a triple must be an IRI or a+ // blank node", at a line number that moved between runs because it+ // depends on hash iteration order, and every inference from that+ // run was lost. OWL 2 RL scopes prp-symp, prp-inv1, prp-inv2 and+ // eq-sym to what can legally appear as a subject; this is that+ // scope, made explicit. Pinned by `tests/reason_literal_subject_test.rs`.+ let is_literal = |id: u32| interner.resolve(id).starts_with('"');+// ── OWL-RL rules ────────────────────────────────────────if include_owl {// prp-trp: x P y, y P z → x P z@@ -452,7 +473,7 @@ impl Reasoner {// prp-symp: s P o → o P sfor &sp in &symmetric_set {for &(s, p, o) in triple_set.iter() {- if p == sp {+ if p == sp && !is_literal(o) {emit((o, sp, s), "prp-symp", &[(sp, rdf_type, owl_symmetric), (s, sp, o)]);}}@@ -461,6 +482,9 @@ impl Reasoner {// prp-inv1, prp-inv2: s P o, P inverseOf Q → o Q s (both directions)for &(p, q) in &inverse_pairs {for &(s, pred, o) in triple_set.iter() {+ if is_literal(o) {+ continue;+ }if pred == p {emit((o, q, s), "prp-inv1", &[(p, owl_inverse, q), (s, p, o)]);}@@ -472,7 +496,7 @@ impl Reasoner {// eq-sym: sameAs symmetryfor &(s, p, o) in triple_set.iter() {- if p == owl_sameas {+ if p == owl_sameas && !is_literal(o) {emit((o, owl_sameas, s), "eq-sym", &[(s, owl_sameas, o)]);}}@@ -534,23 +558,28 @@ impl Reasoner {}}- // cls-hv1: x type class, class subClassOf restriction(P, hasValue v) → x P v+ // cls-hv1: x type restriction(P, hasValue v) → x P v// cls-hv2: x P v, restriction(P, hasValue v) → x type restriction+ //+ // The rule emitted under the name `cls-hv1` used to be the+ // composite of `cax-sco` and W3C `cls-hv1`: it demanded an+ // explicit `k rdfs:subClassOf r` hop and fired on `x type k`,+ // so an individual typed with the restriction DIRECTLY derived+ // nothing. The engine reached the restriction class by its own+ // rdfs9 and then refused to use it, and a certificate could+ // carry `rdfs9 <k> rdf:type <R>` right next to a cls-hv1 step+ // that ignored it. Putting a W3C rule name in front of an+ // auditor obliges the rule to be that rule. The W3C form is+ // used here and loses nothing: the composite case is rdfs9+ // followed by this.for &(prop, val, restr) in &hv_rules {- let parent_classes: Vec<u32> = subclass_idx.iter()- .filter(|&&(_, sup)| sup == restr)- .map(|&(sub, _)| sub).collect();-- for &cls in &parent_classes {- for &(x, c) in &type_idx {- if c == cls {- emit((x, prop, val), "cls-hv1", &[- (restr, owl_on_property, prop),- (restr, owl_has_value, val),- (cls, rdfs_subclass, restr),- (x, rdf_type, cls),- ]);- }+ for &(x, c) in &type_idx {+ if c == restr {+ emit((x, prop, val), "cls-hv1", &[+ (restr, owl_on_property, prop),+ (restr, owl_has_value, val),+ (x, rdf_type, restr),+ ]);}}for &(s, p, o) in triple_set.iter() {diff --git a/tests/reason_fixpoint_test.rs b/tests/reason_fixpoint_test.rsnew file mode 100644index 00000000..4318f035--- /dev/null+++ b/tests/reason_fixpoint_test.rs@@ -0,0 +1,167 @@+//! The reasoner must reach a fixpoint of its own rule set in one run.+//!+//! Found by an adversarial audit, 13 Sep 2026. Only the three data indices+//! (`rdf:type`, `rdfs:subClassOf`, `rdfs:subPropertyOf`) were rebuilt each+//! iteration. Every schema index (`rdfs:domain`, `rdfs:range`, the property+//! characteristics, `owl:inverseOf`, the equivalences, the restriction maps and+//! the RDF lists behind `owl:intersectionOf` / `owl:unionOf`) was filtered once+//! out of the pre-loop snapshot. A schema triple the reasoner itself derived+//! was therefore never used as a premise, and running `reason` twice derived+//! more than running it once.+//!+//! For query answers that is incompleteness. For certificates it is worse:+//! materialising turns run N's conclusions into run N+1's premises, so+//! `asserted.tsv` can list the reasoner's own output as an axiom with nothing+//! marking it as derived, and `certificate_sound` is conditional on the+//! assertions. One run reaching the fixpoint is what makes one certificate the+//! whole story.++use open_ontologies::graph::GraphStore;+use open_ontologies::reason::Reasoner;+use std::sync::Arc;++const PREFIXES: &str = r#"+ @prefix : <http://ex.org/> .+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+"#;++fn run(ttl: &str, profile: &str) -> (Arc<GraphStore>, serde_json::Value) {+ let store = Arc::new(GraphStore::new());+ store.load_turtle(&format!("{PREFIXES}{ttl}"), None).unwrap();+ let out = Reasoner::run(&store, profile, true).unwrap();+ let parsed = serde_json::from_str(&out).unwrap();+ (store, parsed)+}++fn holds(store: &Arc<GraphStore>, query: &str) -> bool {+ let json: serde_json::Value =+ serde_json::from_str(&store.sparql_select_union(query).unwrap()).unwrap();+ !json["results"].as_array().unwrap().is_empty()+}++/// `rdfs:domain` reached through a subproperty of `rdfs:domain`: rdfs7 derives+/// the domain axiom, and rdfs2 has to be able to use it in the same run.+const DERIVED_DOMAIN: &str = r#"+ :myDomain rdfs:subPropertyOf rdfs:domain .+ :p :myDomain :C .+ :x :p :y .+"#;++#[test]+fn a_derived_domain_axiom_is_used_in_the_same_run() {+ let (store, r) = run(DERIVED_DOMAIN, "rdfs");+ assert!(+ holds(&store, "SELECT ?s WHERE { <http://ex.org/x> a <http://ex.org/C> }"),+ "rdfs7 derives the domain axiom, so rdfs2 must fire on it in the same run: {r}"+ );+}++#[test]+fn a_second_run_derives_nothing_new() {+ let store = Arc::new(GraphStore::new());+ store.load_turtle(&format!("{PREFIXES}{DERIVED_DOMAIN}"), None).unwrap();+ let first: serde_json::Value =+ serde_json::from_str(&Reasoner::run(&store, "rdfs", true).unwrap()).unwrap();+ let second: serde_json::Value =+ serde_json::from_str(&Reasoner::run(&store, "rdfs", true).unwrap()).unwrap();+ assert!(first["inferred_count"].as_u64().unwrap() > 0, "the first run must do work: {first}");+ assert_eq!(+ second["inferred_count"], 0,+ "the first run must reach the fixpoint, so the second has nothing to add: {second}"+ );+}++#[test]+fn a_derived_equivalence_feeds_the_restriction_rules() {+ // scm-eqc turns the equivalence into subClassOf, rdfs9 carries membership+ // across it, and cls-hv1 then fires on a restriction reached only that way.+ let (store, r) = run(+ r#"+ :G owl:equivalentClass :R .+ :R a owl:Restriction ; owl:onProperty :col ; owl:hasValue :red .+ :b a :G .+ "#,+ "owl-rl-ext",+ );+ assert!(+ holds(&store, "SELECT ?s WHERE { <http://ex.org/b> <http://ex.org/col> <http://ex.org/red> }"),+ "b is a G, G is the restriction, so b has the value: {r}"+ );+}++#[test]+fn cls_hv1_fires_on_an_individual_typed_with_the_restriction_directly() {+ // The engine used to emit a rule named `cls-hv1` that was the composite of+ // cax-sco and W3C cls-hv1: it demanded an explicit subClassOf hop, so this+ // ontology derived nothing at all.+ let (store, r) = run(+ r#"+ :R a owl:Restriction ; owl:onProperty :col ; owl:hasValue :red .+ :k a :R .+ "#,+ "owl-rl-ext",+ );+ assert!(+ holds(&store, "SELECT ?s WHERE { <http://ex.org/k> <http://ex.org/col> <http://ex.org/red> }"),+ "x rdf:type R with R = (col hasValue red) gives x col red: {r}"+ );+}++#[test]+fn the_subclass_route_to_cls_hv1_still_works() {+ // The case the composite rule did handle, which must not regress: it is now+ // rdfs9 followed by cls-hv1 rather than one rule.+ let (store, r) = run(+ r#"+ :R a owl:Restriction ; owl:onProperty :col ; owl:hasValue :red .+ :K rdfs:subClassOf :R .+ :k a :K .+ "#,+ "owl-rl-ext",+ );+ assert!(+ holds(&store, "SELECT ?s WHERE { <http://ex.org/k> <http://ex.org/col> <http://ex.org/red> }"),+ "{r}"+ );+}++#[test]+fn a_range_inference_onto_a_blank_node_is_not_dropped() {+ // The rdfs3 guard required the object to be an IRI when the invariant it+ // needs is "not a literal". Every range inference onto a blank node was+ // dropped, so the blank node never got typed and rdfs9 starved behind it.+ let (store, r) = run(+ r#"+ :addressOf rdfs:range :Address .+ :Address rdfs:subClassOf :Location .+ :person :addressOf [ :street "Main" ] .+ "#,+ "rdfs",+ );+ assert!(+ holds(&store, "SELECT ?b WHERE { ?b a <http://ex.org/Address> . ?b <http://ex.org/street> ?s }"),+ "the blank node must get its range type: {r}"+ );+ assert!(+ holds(&store, "SELECT ?b WHERE { ?b a <http://ex.org/Location> . ?b <http://ex.org/street> ?s }"),+ "and rdfs9 must then carry it up the hierarchy: {r}"+ );+}++#[test]+fn a_literal_object_still_gets_no_range_type() {+ // The other direction: a literal cannot be the subject of the conclusion,+ // so widening the guard must not start emitting one.+ let (store, _) = run(+ r#"+ :name rdfs:range :Name .+ :person :name "Ada" .+ "#,+ "rdfs",+ );+ assert!(+ !holds(&store, "SELECT ?s WHERE { ?s a <http://ex.org/Name> }"),+ "no subject can be a literal"+ );+}diff --git a/tests/reason_literal_subject_test.rs b/tests/reason_literal_subject_test.rsnew file mode 100644index 00000000..6506b004--- /dev/null+++ b/tests/reason_literal_subject_test.rs@@ -0,0 +1,87 @@+//! No rule may conclude a triple whose subject is a literal.+//!+//! Found by an adversarial audit, 13 Sep 2026, on+//! `benchmark/ontoaxiom/data/ontoaxiom/ontologies/nordstream.ttl`. Four rules+//! conclude a triple whose SUBJECT comes from an object position: `prp-symp`,+//! `prp-inv1`, `prp-inv2` and `eq-sym`. Given a literal object, each produced a+//! triple no RDF serialisation can express. Materialisation then failed on the+//! whole batch with "The subject of a triple must be an IRI or a blank node",+//! and every inference from that run was lost, including the sound ones.+//!+//! The reported line number moved between runs (23, 54, 99 on three runs of one+//! file) because it indexes into a serialisation whose order comes from hash+//! iteration. A non-deterministic error message is what made this look like a+//! malformed input rather than a defect.++use open_ontologies::graph::GraphStore;+use open_ontologies::reason::Reasoner;+use std::sync::Arc;++const PREFIXES: &str = r#"+ @prefix : <http://ex.org/> .+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+"#;++fn run(ttl: &str) -> (Arc<GraphStore>, serde_json::Value) {+ let store = Arc::new(GraphStore::new());+ store.load_turtle(&format!("{PREFIXES}{ttl}"), None).unwrap();+ let out = Reasoner::run(&store, "owl-rl-ext", true).unwrap();+ (store, serde_json::from_str(&out).unwrap())+}++/// A symmetric, an inverse and a sameAs, each pointed at a literal.+const LITERAL_OBJECTS: &str = r#"+ :near a owl:SymmetricProperty .+ :a :near "a literal" .+ :parent owl:inverseOf :child .+ :b :parent "another literal" .+ :c owl:sameAs "a third literal" .+ :d :near :e .+"#;++#[test]+fn materialisation_succeeds_where_a_rule_would_have_made_a_literal_subject() {+ let (_store, r) = run(LITERAL_OBJECTS);+ assert!(r["error"].is_null(), "the run must not fail: {r}");+ assert!(+ r["inferred_count"].as_u64().is_some(),+ "a count means materialisation completed: {r}"+ );+}++#[test]+fn the_sound_inferences_on_the_same_input_survive() {+ // The guard must drop only the inexpressible conclusion, not the rule.+ let (store, r) = run(LITERAL_OBJECTS);+ let json: serde_json::Value = serde_json::from_str(+ &store+ .sparql_select_union("SELECT ?s WHERE { <http://ex.org/e> <http://ex.org/near> <http://ex.org/d> }")+ .unwrap(),+ )+ .unwrap();+ assert!(+ !json["results"].as_array().unwrap().is_empty(),+ "the IRI-valued symmetric pair must still be derived: {r}"+ );+}++#[test]+fn no_materialised_triple_has_a_literal_subject() {+ let (store, _) = run(LITERAL_OBJECTS);+ for (s, _, _) in store.all_triples().unwrap() {+ assert!(!s.starts_with('"'), "a literal cannot be a subject: {s}");+ }+}++#[test]+fn the_run_is_deterministic() {+ // The failure surfaced with a line number that changed between runs, so+ // repeat the run and require the same answer every time.+ let counts: Vec<u64> = (0..4)+ .map(|_| run(LITERAL_OBJECTS).1["inferred_count"].as_u64().unwrap())+ .collect();+ assert!(+ counts.windows(2).all(|w| w[0] == w[1]),+ "inference count must not depend on iteration order: {counts:?}"+ );+}