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
Certify ten more RL rules, refute inconsistency, check DL models, and stop a target sitting outside the gate
FABIOTESSa96b83c33eb0
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 1e5e4f10..f63fbc02 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -319,6 +319,15 @@ jobs:- uses: Swatinem/rust-cache@v2- name: Certify every shipped ontology through the proved checkerrun: OO_REQUIRE_FIXTURES=1 cargo test --test lean_certificate_test -- --nocapture+ - name: Check the verified SHACL Core evaluator against the W3C suite+ # This job used to run a bare `lake build` while `Shacl` was not a+ # default target, so the SHACL proofs did not compile at the commit+ # that carried them and this gate was green over them. The lakefile now+ # forces every target into the default set and this step measures the+ # verified evaluator, so both halves of that failure are closed.+ run: OO_REQUIRE_FIXTURES=1 cargo test --test shacl_core_verified_test -- --nocapture+ - name: Check the mixed certificate layer+ run: OO_REQUIRE_FIXTURES=1 cargo test --test lean_mixed_certificate_test -- --nocapture- name: Check the generic Horn-rule layer, and that a user rule cannot earn the absolute verdict# The five legs here are not interchangeable. Four of them prove the# checker rejects a specific forgery; the fifth proves that adiff --git a/lean/Dl.lean b/lean/Dl.leannew file mode 100644index 00000000..a9374e2c--- /dev/null+++ b/lean/Dl.lean@@ -0,0 +1,2 @@+import Dl.All+import Dl.Witnessdiff --git a/lean/Dl/All.lean b/lean/Dl/All.leannew file mode 100644index 00000000..a9222274--- /dev/null+++ b/lean/Dl/All.lean@@ -0,0 +1,23 @@+import Dl.Syntax+import Dl.Semantics+import Dl.Count+import Dl.Check+import Dl.Parse+import Dl.Witness++/-!+# `Dl`: a model certificate for the SHIQ tableaux reasoner++The root module. Importing this builds every proof in the directory, including the axiom+pins, so a `sorry` or a changed axiom footprint anywhere fails `lake build`.++* `Dl/Syntax.lean` the fragment, the interpretation, the file format, and a list of what is+ deliberately not covered.+* `Dl/Semantics.lean` satisfaction, well-formedness, and what it means to be a model.+* `Dl/Count.lean` the pigeonhole lemma the number restrictions rest on.+* `Dl/Check.lean` the decision procedure, `Dl.satisfiable_of_checkModel`, and+ `Dl.checkModel_complete`.+* `Dl/Parse.lean` the two file readers, outside the theorem.+* `Dl/Witness.lean` an accepted model, two rejected forgeries, and an unsatisfiable axiom+ set, so that neither the checker nor `Satisfiable` is trivial.+-/diff --git a/lean/Dl/Check.lean b/lean/Dl/Check.leannew file mode 100644index 00000000..eec6de80--- /dev/null+++ b/lean/Dl/Check.lean@@ -0,0 +1,247 @@+import Dl.Count++/-!+# The decision procedure, and the theorem about it++`checkModel I A` decides whether the finite interpretation `I` is a model of the axiom set+`A`. `Dl.satisfiable_of_checkModel` is the result the reasoner buys with it: an accepted+interpretation is an existence proof, so the axiom set really is satisfiable.++`Dl.checkModel_complete` is the other half and is what stops the layer being decoration. The+checker agrees with `Models` in both directions, so it rejects exactly the interpretations+that are not models. A checker that accepted everything would satisfy the soundness theorem+just as well; this one cannot.++Everything here is `Bool`-valued and runs. No `native_decide`, no `Classical` case split on+an undecidable proposition, no Mathlib.+-/+namespace Dl++/-- Does `x` satisfy `c`?++The two counting cases deduplicate the successors that satisfy the filler and compare the+length to the bound. `Dl.atLeast_iff` and `Dl.atMost_iff` are what make that the same+statement as `AtLeast` and `AtMost`; the deduplication is an implementation detail of this+function and appears nowhere in `Dl/Semantics.lean`. -/+def sat (I : Interp) : Concept → Name → Bool+ | .top, _ => true+ | .bot, _ => false+ | .atom a, x => (I.cext a).contains x+ | .neg c, x => !sat I c x+ | .and c d, x => sat I c x && sat I d x+ | .or c d, x => sat I c x || sat I d x+ | .ex r c, x => (I.rext r x).any (fun y => sat I c y)+ | .all r c, x => (I.rext r x).all (fun y => sat I c y)+ | .min n r c, x => n ≤ (nub ((I.rext r x).filter (fun y => sat I c y))).length+ | .max n r c, x => (nub ((I.rext r x).filter (fun y => sat I c y))).length ≤ n++theorem sat_iff (I : Interp) : ∀ (c : Concept) (x : Name), sat I c x = true ↔ Sat I c x+ | .top, x => by simp [sat, Sat]+ | .bot, x => by simp [sat, Sat]+ | .atom a, x => by simp [sat, Sat]+ | .neg c, x => by+ simp only [sat, Sat, Bool.not_eq_true']+ rw [Bool.eq_false_iff, ne_eq, sat_iff I c x]+ | .and c d, x => by+ simp only [sat, Sat, Bool.and_eq_true]+ rw [sat_iff I c x, sat_iff I d x]+ | .or c d, x => by+ simp only [sat, Sat, Bool.or_eq_true]+ rw [sat_iff I c x, sat_iff I d x]+ | .ex r c, x => by+ simp only [sat, Sat, List.any_eq_true]+ exact ⟨fun ⟨y, hy, hs⟩ => ⟨y, hy, (sat_iff I c y).1 hs⟩,+ fun ⟨y, hy, hs⟩ => ⟨y, hy, (sat_iff I c y).2 hs⟩⟩+ | .all r c, x => by+ simp only [sat, Sat, List.all_eq_true]+ exact ⟨fun h y hy => (sat_iff I c y).1 (h y hy),+ fun h y hy => (sat_iff I c y).2 (h y hy)⟩+ | .min n r c, x => by+ have h : ∀ y, (y ∈ I.rext r x ∧ Sat I c y) ↔+ y ∈ (I.rext r x).filter (fun y => sat I c y) := by+ intro y+ rw [List.mem_filter]+ exact and_congr_right (fun _ => (sat_iff I c y).symm)+ simp only [sat, Sat, decide_eq_true_eq]+ exact (atLeast_iff h).symm+ | .max n r c, x => by+ have h : ∀ y, (y ∈ I.rext r x ∧ Sat I c y) ↔+ y ∈ (I.rext r x).filter (fun y => sat I c y) := by+ intro y+ rw [List.mem_filter]+ exact and_congr_right (fun _ => (sat_iff I c y).symm)+ simp only [sat, Sat, decide_eq_true_eq]+ exact (atMost_iff h).symm++/-- Does `I` satisfy the axiom? -/+def holds (I : Interp) : Axiom → Bool+ | .sub c d => I.dom.all (fun x => !sat I c x || sat I d x)+ | .disjoint c d => I.dom.all (fun x => !(sat I c x && sat I d x))+ | .dom r c => I.dom.all (fun x => (I.rext r x).isEmpty || sat I c x)+ | .rng r c => I.dom.all (fun x => (I.rext r x).all (fun y => sat I c y))+ | .subrole r s => I.dom.all (fun x => (I.rext r x).all (fun y => (I.rext s x).contains y))+ | .trans r =>+ I.dom.all (fun x =>+ (I.rext r x).all (fun y => (I.rext r y).all (fun z => (I.rext r x).contains z)))+ | .sym r => I.dom.all (fun x => (I.rext r x).all (fun y => (I.rext r y).contains x))+ | .inv r s =>+ I.dom.all (fun x => (I.rext r x).all (fun y => (I.rext s y).contains x)) &&+ I.dom.all (fun x => (I.rext s x).all (fun y => (I.rext r y).contains x))+ | .invfunc r =>+ I.dom.all (fun y =>+ (nub (I.dom.filter (fun x => (I.rext r x).contains y))).length ≤ 1)+ | .inst a c => sat I c (I.ind a)+ | .rel a r b => (I.rext r (I.ind a)).contains (I.ind b)+ | .indiv a => I.dom.contains (I.ind a)+ | .nonempty c => I.dom.any (fun x => sat I c x)++theorem holds_iff (I : Interp) : ∀ a : Axiom, holds I a = true ↔ Holds I a+ | .sub c d => by+ simp only [holds, Holds, List.all_eq_true, Bool.or_eq_true, Bool.not_eq_true']+ constructor+ · intro h x hx hc+ rcases h x hx with h | h+ · exact absurd ((sat_iff I c x).2 hc) (by simp [h])+ · exact (sat_iff I d x).1 h+ · intro h x hx+ by_cases hc : sat I c x = true+ · exact Or.inr ((sat_iff I d x).2 (h x hx ((sat_iff I c x).1 hc)))+ · exact Or.inl (by simpa using hc)+ | .disjoint c d => by+ simp only [holds, Holds, List.all_eq_true, Bool.not_eq_true', Bool.and_eq_false_iff]+ constructor+ · rintro h x hx ⟨hc, hd⟩+ rcases h x hx with h | h+ · exact absurd ((sat_iff I c x).2 hc) (by simp [h])+ · exact absurd ((sat_iff I d x).2 hd) (by simp [h])+ · intro h x hx+ by_cases hc : sat I c x = true+ · refine Or.inr ?_+ by_cases hd : sat I d x = true+ · exact absurd ⟨(sat_iff I c x).1 hc, (sat_iff I d x).1 hd⟩ (h x hx)+ · simpa using hd+ · exact Or.inl (by simpa using hc)+ | .dom r c => by+ simp only [holds, Holds, List.all_eq_true, Bool.or_eq_true]+ constructor+ · intro h x hx hne+ rcases h x hx with h | h+ · exact absurd (List.isEmpty_iff.1 h) hne+ · exact (sat_iff I c x).1 h+ · intro h x hx+ by_cases hne : I.rext r x = []+ · exact Or.inl (List.isEmpty_iff.2 hne)+ · exact Or.inr ((sat_iff I c x).2 (h x hx hne))+ | .rng r c => by+ simp only [holds, Holds, List.all_eq_true]+ exact ⟨fun h x hx y hy => (sat_iff I c y).1 (h x hx y hy),+ fun h x hx y hy => (sat_iff I c y).2 (h x hx y hy)⟩+ | .subrole r s => by simp [holds, Holds, List.all_eq_true]+ | .trans r => by simp [holds, Holds, List.all_eq_true]+ | .sym r => by simp [holds, Holds, List.all_eq_true]+ | .inv r s => by simp [holds, Holds, List.all_eq_true]+ | .invfunc r => by+ simp only [holds, Holds, List.all_eq_true, decide_eq_true_eq]+ constructor+ · intro h y hy+ refine (atMost_iff (L := I.dom.filter (fun x => (I.rext r x).contains y)) ?_).2 (h y hy)+ intro x; rw [List.mem_filter]; simp+ · intro h y hy+ refine (atMost_iff (L := I.dom.filter (fun x => (I.rext r x).contains y)) ?_).1 (h y hy)+ intro x; rw [List.mem_filter]; simp+ | .inst a c => by simp only [holds, Holds]; exact sat_iff I c (I.ind a)+ | .rel a r b => by simp [holds, Holds]+ | .indiv a => by simp [holds, Holds]+ | .nonempty c => by+ simp only [holds, Holds, List.any_eq_true]+ exact ⟨fun ⟨x, hx, hs⟩ => ⟨x, hx, (sat_iff I c x).1 hs⟩,+ fun ⟨x, hx, hs⟩ => ⟨x, hx, (sat_iff I c x).2 hs⟩⟩++/-- Is `I` a finite interpretation of `A`'s vocabulary at all? -/+def checkWF (I : Interp) (A : List Axiom) : Bool :=+ !I.dom.isEmpty+ && (atomNames A).all (fun a => (I.cext a).all (fun x => I.dom.contains x))+ && (roleNames A).all (fun r =>+ I.dom.all (fun x => (I.rext r x).all (fun y => I.dom.contains y)))+ && (indNames A).all (fun a => I.dom.contains (I.ind a))++theorem checkWF_iff (I : Interp) (A : List Axiom) :+ checkWF I A = true ↔ WellFormed I A := by+ constructor+ · intro h+ simp only [checkWF, Bool.and_eq_true, Bool.not_eq_true', List.all_eq_true] at h+ obtain ⟨⟨⟨h1, h2⟩, h3⟩, h4⟩ := h+ refine ⟨?_, ?_, ?_, ?_⟩+ · intro hd; rw [hd] at h1; simp at h1+ · intro a ha x hx; simpa using h2 a ha x hx+ · intro r hr x hx y hy; simpa using h3 r hr x hx y hy+ · intro a ha; simpa using h4 a ha+ · intro hwf+ simp only [checkWF, Bool.and_eq_true, Bool.not_eq_true', List.all_eq_true]+ refine ⟨⟨⟨?_, ?_⟩, ?_⟩, ?_⟩+ · match hd : I.dom with+ | [] => exact absurd hd hwf.nonempty+ | _ :: _ => simp+ · intro a ha x hx; simpa using hwf.cextInDom a ha x hx+ · intro r hr x hx y hy; simpa using hwf.rextInDom r hr x hx y hy+ · intro a ha; simpa using hwf.indInDom a ha++/-- The whole check: a finite interpretation of the vocabulary, satisfying every axiom. -/+def checkModel (I : Interp) (A : List Axiom) : Bool :=+ checkWF I A && A.all (fun a => holds I a)++theorem checkModel_iff (I : Interp) (A : List Axiom) :+ checkModel I A = true ↔ (I ⊨ A) := by+ simp only [checkModel, Bool.and_eq_true, List.all_eq_true]+ constructor+ · rintro ⟨hwf, ha⟩+ exact ⟨(checkWF_iff I A).1 hwf, fun a h => (holds_iff I a).1 (ha a h)⟩+ · rintro ⟨hwf, ha⟩+ exact ⟨(checkWF_iff I A).2 hwf, fun a h => (holds_iff I a).2 (ha a h)⟩++/-- **What a model certificate buys.** An interpretation the checker accepts is a model, so+the axiom set has one, so it is satisfiable. This is the useful form: the conclusion no+longer mentions the interpretation the reasoner happened to build. -/+theorem satisfiable_of_checkModel {I : Interp} {A : List Axiom}+ (h : checkModel I A = true) : Satisfiable A :=+ ⟨I, (checkModel_iff I A).1 h⟩++/-- **The gate can fail.** The checker rejects nothing that is a model, so a rejection is a+statement about the interpretation, not about the checker's patience. -/+theorem checkModel_complete {I : Interp} {A : List Axiom}+ (h : checkModel I A = false) : ¬ (I ⊨ A) := by+ intro hm+ rw [(checkModel_iff I A).2 hm] at h+ exact Bool.noConfusion h++/-! ## Axioms, pinned++The footprint is the one the rest of this repository carries: propositional extensionality,+choice and quotient soundness, all three from the Lean core. A `sorry` or a `native_decide`+anywhere above changes one of these lines and the build fails. -/++/-- info: 'Dl.sat_iff' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms sat_iff++/-- info: 'Dl.holds_iff' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms holds_iff++/-- info: 'Dl.checkWF_iff' depends on axioms: [propext, Quot.sound] -/+#guard_msgs in+#print axioms checkWF_iff++/-- info: 'Dl.checkModel_iff' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms checkModel_iff++/-- info: 'Dl.satisfiable_of_checkModel' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms satisfiable_of_checkModel++/-- info: 'Dl.checkModel_complete' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms checkModel_complete++end Dldiff --git a/lean/Dl/Count.lean b/lean/Dl/Count.leannew file mode 100644index 00000000..c9cb2bcf--- /dev/null+++ b/lean/Dl/Count.lean@@ -0,0 +1,119 @@+import Dl.Semantics++/-!+# Counting distinct witnesses++`≥n R.C`, `≤n R.C` and inverse functionality all say something about how many DISTINCT+elements satisfy a condition. `Dl/Semantics.lean` states that with `AtLeast` and `AtMost`,+which quantify over duplicate-free lists and mention no computation at all. A checker has+to turn those into a number, and this file is the bridge.++The whole bridge rests on one lemma, `nodup_length_le`: a duplicate-free list whose members+all come from `l` is no longer than `l`. That is pigeonhole, and it is proved here by+induction with `List.erase` rather than assumed, because the entire soundness of the `≤`+direction is that one inequality.++`nub` keeps the last occurrence of each element. Which occurrence survives does not matter;+what matters is `mem_nub` and `nub_nodup`, and both are proved.+-/+namespace Dl++/-- Remove duplicates, keeping the last occurrence. -/+def nub : List Name → List Name+ | [] => []+ | a :: l => if l.contains a then nub l else a :: nub l++theorem mem_nub : ∀ {l : List Name} {x : Name}, x ∈ nub l ↔ x ∈ l+ | [], x => by simp [nub]+ | a :: l, x => by+ by_cases h : l.contains a+ · rw [nub, if_pos h]+ constructor+ · intro hx; exact List.mem_cons_of_mem _ (mem_nub.1 hx)+ · intro hx+ rcases List.mem_cons.1 hx with rfl | hx+ · exact mem_nub.2 (List.elem_iff.1 h)+ · exact mem_nub.2 hx+ · rw [nub, if_neg h]+ constructor+ · intro hx+ rcases List.mem_cons.1 hx with rfl | hx+ · exact List.mem_cons_self ..+ · exact List.mem_cons_of_mem _ (mem_nub.1 hx)+ · intro hx+ rcases List.mem_cons.1 hx with rfl | hx+ · exact List.mem_cons_self ..+ · exact List.mem_cons_of_mem _ (mem_nub.2 hx)++theorem nub_nodup : ∀ l : List Name, (nub l).Nodup+ | [] => by simp [nub]+ | a :: l => by+ by_cases h : l.contains a+ · rw [nub, if_pos h]; exact nub_nodup l+ · rw [nub, if_neg h]+ refine List.nodup_cons.2 ⟨?_, nub_nodup l⟩+ intro hm+ exact h (List.elem_iff.2 (mem_nub.1 hm))++/-- Pigeonhole. A duplicate-free list drawn from `l` is no longer than `l`.++Proved by induction on the duplicate-free list: its head is in `l`, its tail avoids that+head and so is drawn from `l` with one occurrence of the head erased, and erasing an+element that is present shortens the list by exactly one. -/+theorem nodup_length_le :+ ∀ {ys l : List Name}, ys.Nodup → (∀ y ∈ ys, y ∈ l) → ys.length ≤ l.length+ | [], _, _, _ => Nat.zero_le _+ | a :: ys, l, hnd, hsub => by+ rw [List.nodup_cons] at hnd+ have ha : a ∈ l := hsub a (List.mem_cons_self ..)+ have hsub' : ∀ y ∈ ys, y ∈ l.erase a := by+ intro y hy+ have hne : y ≠ a := fun h => hnd.1 (h ▸ hy)+ exact (List.mem_erase_of_ne hne).2 (hsub y (List.mem_cons_of_mem _ hy))+ have ih := nodup_length_le hnd.2 hsub'+ rw [List.length_erase_of_mem ha] at ih+ have hpos : 0 < l.length := List.length_pos_of_mem ha+ simp only [List.length_cons]+ omega++/-- `AtLeast n P` is exactly "the deduplicated list of `P`'s members is at least `n` long",+for any list `L` that enumerates `P`. -/+theorem atLeast_iff {n : Nat} {P : Name → Prop} {L : List Name} (h : ∀ y, P y ↔ y ∈ L) :+ AtLeast n P ↔ n ≤ (nub L).length := by+ constructor+ · rintro ⟨ys, hnd, hlen, hmem⟩+ have : ∀ y ∈ ys, y ∈ nub L := fun y hy => mem_nub.2 ((h y).1 (hmem y hy))+ have := nodup_length_le hnd this+ omega+ · intro hle+ refine ⟨(nub L).take n, ?_, ?_, ?_⟩+ · exact List.Nodup.sublist (List.take_sublist n _) (nub_nodup L)+ · rw [List.length_take]; omega+ · intro y hy+ exact (h y).2 (mem_nub.1 ((List.take_sublist n _).mem hy))++/-- `AtMost n P` is exactly "the deduplicated list of `P`'s members is at most `n` long". -/+theorem atMost_iff {n : Nat} {P : Name → Prop} {L : List Name} (h : ∀ y, P y ↔ y ∈ L) :+ AtMost n P ↔ (nub L).length ≤ n := by+ constructor+ · intro hA+ exact hA (nub L) (nub_nodup L) (fun y hy => (h y).2 (mem_nub.1 hy))+ · intro hle ys hnd hmem+ have : ∀ y ∈ ys, y ∈ nub L := fun y hy => mem_nub.2 ((h y).1 (hmem y hy))+ exact Nat.le_trans (nodup_length_le hnd this) hle++/-! ## Axioms, pinned -/++/-- info: 'Dl.nodup_length_le' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms nodup_length_le++/-- info: 'Dl.atLeast_iff' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms atLeast_iff++/-- info: 'Dl.atMost_iff' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms atMost_iff++end Dldiff --git a/lean/Dl/Parse.lean b/lean/Dl/Parse.leannew file mode 100644index 00000000..1df450f7--- /dev/null+++ b/lean/Dl/Parse.lean@@ -0,0 +1,132 @@+import Dl.Check+import Std.Data.HashMap++/-!+# Reading the two files++`Dl/Syntax.lean` documents the format. This module turns the bytes into the `Axiom` list and+the `Interp` the checker is proved about.++It is NOT part of the theorem. A parse error is exit 2, never an accepted certificate, and+never a rejected one either: "I could not read the file" and "this is not a model" are+different answers and the exit codes keep them apart.++The three extension maps are built as hash tables and handed to `Interp` as closures over+them, so an atomic concept lookup costs one hash rather than a scan of the file. That is a+representation choice inside the parser; `Dl/Semantics.lean` only ever sees the functions.+-/+namespace Dl.Parse++/-- Split on spaces, dropping empties. IRIs keep their `<...>` spelling and contain no+space, so this is exact for the token streams the emitter writes. -/+def tokens (s : String) : List String :=+ (s.splitOn " ").filter (fun t => !t.isEmpty)++/-- Prefix parser for a concept. Every constructor has a fixed arity, so no parentheses are+needed and the grammar is unambiguous. The fuel is the token count, which strictly bounds+the recursion because each step consumes at least one token. -/+def concept? : Nat → List String → Option (Concept × List String)+ | 0, _ => none+ | _ + 1, [] => none+ | fuel + 1, t :: ts =>+ match t with+ | "top" => some (.top, ts)+ | "bot" => some (.bot, ts)+ | "atom" => match ts with+ | a :: ts' => some (.atom a, ts')+ | [] => none+ | "not" => (concept? fuel ts).map (fun p => (.neg p.1, p.2))+ | "and" => do+ let (c, ts1) ← concept? fuel ts+ let (d, ts2) ← concept? fuel ts1+ some (.and c d, ts2)+ | "or" => do+ let (c, ts1) ← concept? fuel ts+ let (d, ts2) ← concept? fuel ts1+ some (.or c d, ts2)+ | "some" => match ts with+ | r :: ts' => (concept? fuel ts').map (fun p => (.ex r p.1, p.2))+ | [] => none+ | "all" => match ts with+ | r :: ts' => (concept? fuel ts').map (fun p => (.all r p.1, p.2))+ | [] => none+ | "min" => match ts with+ | n :: r :: ts' => do+ let k ← n.toNat?+ let (c, ts2) ← concept? fuel ts'+ some (.min k r c, ts2)+ | _ => none+ | "max" => match ts with+ | n :: r :: ts' => do+ let k ← n.toNat?+ let (c, ts2) ← concept? fuel ts'+ some (.max k r c, ts2)+ | _ => none+ | _ => none++/-- A whole field must be exactly one concept, with nothing left over. -/+def parseConcept (s : String) : Option Concept :=+ let ts := tokens s+ match concept? (ts.length + 1) ts with+ | some (c, []) => some c+ | _ => none++def parseAxiomLine (line : String) : Option Axiom :=+ match line.splitOn "\t" with+ | ["sub", c, d] => do some (.sub (← parseConcept c) (← parseConcept d))+ | ["disjoint", c, d] => do some (.disjoint (← parseConcept c) (← parseConcept d))+ | ["domain", r, c] => do some (.dom r (← parseConcept c))+ | ["range", r, c] => do some (.rng r (← parseConcept c))+ | ["subrole", r, s] => some (.subrole r s)+ | ["trans", r] => some (.trans r)+ | ["sym", r] => some (.sym r)+ | ["inv", r, s] => some (.inv r s)+ | ["invfunc", r] => some (.invfunc r)+ | ["inst", a, c] => do some (.inst a (← parseConcept c))+ | ["rel", a, r, b] => some (.rel a r b)+ | ["indiv", a] => some (.indiv a)+ | ["nonempty", c] => do some (.nonempty (← parseConcept c))+ | _ => none++def parseAxioms (content : String) : Except String (List Axiom) := do+ let mut out : Array Axiom := #[]+ let mut n := 0+ for line in (content.replace "\r\n" "\n").splitOn "\n" do+ n := n + 1+ if line.isEmpty then continue+ match parseAxiomLine line with+ | some a => out := out.push a+ | none => throw s!"axioms line {n}: not a well-formed axiom"+ return out.toList++/-- The lookup tables an `Interp` closes over. -/+structure Tables where+ dom : Array Name := #[]+ cmap : Std.HashMap Name (List Name) := ∅+ rmap : Std.HashMap (Name × Name) (List Name) := ∅+ imap : Std.HashMap Name Name := ∅++/-- An individual with no `ind` line denotes the empty name, which is in no domain, so the+`indiv` axiom and the `indInDom` clause of `WellFormed` both fail rather than succeed by+accident. Silence is never taken for agreement. -/+def Tables.toInterp (t : Tables) : Interp where+ dom := t.dom.toList+ cext := fun a => t.cmap.getD a []+ rext := fun r x => t.rmap.getD (r, x) []+ ind := fun a => t.imap.getD a ""++def parseModel (content : String) : Except String Interp := do+ let mut t : Tables := {}+ let mut n := 0+ for line in (content.replace "\r\n" "\n").splitOn "\n" do+ n := n + 1+ if line.isEmpty then continue+ match line.splitOn "\t" with+ | ["domain", e] => t := { t with dom := t.dom.push e }+ | ["class", c, e] => t := { t with cmap := t.cmap.insert c (e :: t.cmap.getD c []) }+ | ["edge", x, r, y] => t := { t with rmap := t.rmap.insert (r, x) (y :: t.rmap.getD (r, x) []) }+ | ["ind", a, e] => t := { t with imap := t.imap.insert a e }+ | _ => throw s!"model line {n}: not a well-formed model fact"+ return t.toInterp++end Dl.Parsediff --git a/lean/Dl/Semantics.lean b/lean/Dl/Semantics.leannew file mode 100644index 00000000..d1bc9b45--- /dev/null+++ b/lean/Dl/Semantics.lean@@ -0,0 +1,101 @@+import Dl.Syntax++/-!+# Satisfaction++The standard set-theoretic semantics of the covered fragment, written against the finite+interpretation of `Dl/Syntax.lean`. Nothing in this file computes; `Dl/Check.lean` carries+the decision procedure and the proof that it agrees with what is written here.++Two points a reader should check rather than take on trust.++**Counting.** `≥n R.C` and `≤n R.C` are stated with `AtLeast` and `AtMost`, which say "there+is a list of `n` DISTINCT witnesses" and "every list of distinct witnesses is at most `n`+long". They are deliberately not phrased through any deduplication function, because that+would make the meaning of a number restriction depend on a piece of the checker. The bridge+from a computed count to these statements is a theorem in `Dl/Check.lean`, proved from a+pigeonhole lemma, not a definition.++**Where satisfaction is evaluated.** A subclass axiom quantifies over `I.dom` and nothing+else. `WellFormed` is what makes that enough: it says every role successor of a domain+element is again a domain element, so the recursion in `Sat` never leaves the domain, and a+subclass axiom that holds at every element of `I.dom` holds at every element the model has.+Without `WellFormed` the statement would be much weaker than it looks, which is why+`Models` carries it and every theorem here does too.+-/+namespace Dl++/-- There are at least `n` distinct elements satisfying `P`. -/+def AtLeast (n : Nat) (P : Name → Prop) : Prop :=+ ∃ ys : List Name, ys.Nodup ∧ ys.length = n ∧ ∀ y ∈ ys, P y++/-- There are at most `n` distinct elements satisfying `P`. -/+def AtMost (n : Nat) (P : Name → Prop) : Prop :=+ ∀ ys : List Name, ys.Nodup → (∀ y ∈ ys, P y) → ys.length ≤ n++/-- `x` is in the extension of `c`. -/+def Sat (I : Interp) : Concept → Name → Prop+ | .top, _ => True+ | .bot, _ => False+ | .atom a, x => x ∈ I.cext a+ | .neg c, x => ¬ Sat I c x+ | .and c d, x => Sat I c x ∧ Sat I d x+ | .or c d, x => Sat I c x ∨ Sat I d x+ | .ex r c, x => ∃ y ∈ I.rext r x, Sat I c y+ | .all r c, x => ∀ y ∈ I.rext r x, Sat I c y+ | .min n r c, x => AtLeast n (fun y => y ∈ I.rext r x ∧ Sat I c y)+ | .max n r c, x => AtMost n (fun y => y ∈ I.rext r x ∧ Sat I c y)++/-- `I` satisfies the axiom.++`invfunc` is the one clause that has no concept-level counterpart. `≤1 R⁻.⊤` cannot be+written as a concept here unless `R` happens to have a named inverse, so inverse+functionality is an axiom in its own right and is stated the way the OWL 2 Direct Semantics+states it: no element has two distinct `R`-predecessors. -/+def Holds (I : Interp) : Axiom → Prop+ | .sub c d => ∀ x ∈ I.dom, Sat I c x → Sat I d x+ | .disjoint c d => ∀ x ∈ I.dom, ¬ (Sat I c x ∧ Sat I d x)+ | .dom r c => ∀ x ∈ I.dom, I.rext r x ≠ [] → Sat I c x+ | .rng r c => ∀ x ∈ I.dom, ∀ y ∈ I.rext r x, Sat I c y+ | .subrole r s => ∀ x ∈ I.dom, ∀ y ∈ I.rext r x, y ∈ I.rext s x+ | .trans r => ∀ x ∈ I.dom, ∀ y ∈ I.rext r x, ∀ z ∈ I.rext r y, z ∈ I.rext r x+ | .sym r => ∀ x ∈ I.dom, ∀ y ∈ I.rext r x, x ∈ I.rext r y+ | .inv r s =>+ (∀ x ∈ I.dom, ∀ y ∈ I.rext r x, x ∈ I.rext s y) ∧+ (∀ x ∈ I.dom, ∀ y ∈ I.rext s x, x ∈ I.rext r y)+ | .invfunc r => ∀ y ∈ I.dom, AtMost 1 (fun x => x ∈ I.dom ∧ y ∈ I.rext r x)+ | .inst a c => Sat I c (I.ind a)+ | .rel a r b => I.ind b ∈ I.rext r (I.ind a)+ | .indiv a => I.ind a ∈ I.dom+ | .nonempty c => ∃ x ∈ I.dom, Sat I c x++/-- The interpretation is a genuine finite interpretation of `A`'s vocabulary.++Without the first clause every subclass axiom holds vacuously in the empty interpretation+and "satisfiable" would mean nothing. Without the others the extension maps could place+elements outside the carrier, and `Sat` could then be evaluated at a point no axiom ever+constrains. -/+structure WellFormed (I : Interp) (A : List Axiom) : Prop where+ /-- The carrier is not empty. -/+ nonempty : I.dom ≠ []+ /-- No atomic concept the axiom set mentions reaches outside the carrier. -/+ cextInDom : ∀ a ∈ atomNames A, ∀ x ∈ I.cext a, x ∈ I.dom+ /-- No role the axiom set mentions leads outside the carrier. -/+ rextInDom : ∀ r ∈ roleNames A, ∀ x ∈ I.dom, ∀ y ∈ I.rext r x, y ∈ I.dom+ /-- Every individual the axiom set mentions denotes a carrier element. -/+ indInDom : ∀ a ∈ indNames A, I.ind a ∈ I.dom++/-- `I` is a model of `A`. -/+structure Models (I : Interp) (A : List Axiom) : Prop where+ wf : WellFormed I A+ holds : ∀ a ∈ A, Holds I a++@[inherit_doc] scoped notation:50 I " ⊨ " A => Models I A++/-- `A` has a finite model. This is the conclusion a certificate buys: not "the tableau ran+without a clash", but the existence of an interpretation, exhibited. -/+def Satisfiable (A : List Axiom) : Prop := ∃ I : Interp, I ⊨ A++theorem Satisfiable.intro {I : Interp} {A : List Axiom} (h : I ⊨ A) : Satisfiable A := ⟨I, h⟩++end Dldiff --git a/lean/Dl/Syntax.lean b/lean/Dl/Syntax.leannew file mode 100644index 00000000..dcf4b83c--- /dev/null+++ b/lean/Dl/Syntax.lean@@ -0,0 +1,204 @@+/-!+# The fragment, the interpretation, and the file format++This development certifies the POSITIVE answers of the SHIQ tableaux reasoner in+`src/tableaux.rs`. When that reasoner says a class is satisfiable, or that an ontology is+consistent, it can hand over the finite interpretation it built. `Dl/Check.lean` decides+whether that interpretation really satisfies the axioms, and `Dl.satisfiable_of_checkModel`+turns an accepted interpretation into `∃ I, I ⊨ A`.++The negative answer is not certified and is not meant to be. "Unsatisfiable" needs a closed+tableau with every branch, every clash and a blocking argument, which is a proof-checking+problem rather than a model-checking one. Nothing here says anything about it, and the+reasoner keeps emitting bare unsatisfiability verdicts.++## What is in the fragment++Atomic concepts, `⊤`, `⊥`, negation, binary conjunction and disjunction, `∃R.C`, `∀R.C`,+and the qualified number restrictions `≥n R.C` and `≤n R.C`. On the axiom side: subclass,+disjointness, `rdfs:domain`, `rdfs:range`, role inclusion, transitive roles, symmetric+roles, inverse roles, inverse-functional roles, class assertions, role assertions, named+individuals, and a non-emptiness claim (`nonempty C`, which is how "the reasoner said C is+satisfiable" becomes something a model can be checked against).++`n`-ary conjunction and disjunction are folded into the binary constructors by the emitter.+Functional roles are emitted as `⊤ ⊑ ≤1 R.⊤` and need no constructor of their own.++## What is NOT in the fragment, and is therefore never emitted++* Nominals (`owl:oneOf`, `owl:hasValue` as `{a}`). `src/tableaux.rs` has no nominal+ constructor either; it approximates `owl:hasValue` by an atomic concept named after the+ individual, and that approximation is emitted as the atom it is, not as a nominal.+* Datatypes, data properties and literal values. The reasoner never puts them on a tableau+ edge and this file has no syntax for them.+* `owl:sameAs`, `owl:differentFrom` and the unique name assumption. A model here is free to+ send two individual IRIs to the same domain element.+* Role chains, reflexive, irreflexive and asymmetric roles, `owl:disjointUnionOf` and+ `owl:AllDisjointClasses` as a single axiom (pairwise disjointness is emitted instead).+* Anything the OWL parser in `src/tableaux.rs` does not recognise. The parser is OUTSIDE+ this theorem, exactly as the N-Triples parser is outside `Shacl.validate_spec`. What is+ certified is that the emitted interpretation satisfies the emitted axioms. Whether the+ emitted axioms are the ontology is a separate question, and a reader must not read the+ exit code as an answer to it.++## The interpretation++A finite interpretation is a domain given as a list of element names, an extension for each+atomic concept, a successor list for each role and each element, and a denotation for each+individual IRI. The extension maps are total functions on `String` because that is what a+lookup table compiles to; `Dl.WellFormed` is what confines them to the domain, and every+theorem here carries that hypothesis.++## The file format++Two tab-separated files, both written by `src/tableaux.rs`.++`axioms.tsv`, one axiom per line. Field 1 is the keyword, the rest are its arguments:++```+sub CONCEPT CONCEPT C ⊑ D+disjoint CONCEPT CONCEPT C ⊓ D ⊑ ⊥+domain ROLE CONCEPT ∃R.⊤ ⊑ C+range ROLE CONCEPT ⊤ ⊑ ∀R.C+subrole ROLE ROLE R ⊑ S+trans ROLE R transitive+sym ROLE R symmetric+inv ROLE ROLE R ≡ S⁻+invfunc ROLE R inverse functional+inst IND CONCEPT C(a)+rel IND ROLE IND R(a, b)+indiv IND a is a named individual+nonempty CONCEPT C^I ≠ ∅, the satisfiability claim+```++A CONCEPT is a SPACE-separated prefix token stream, with no parentheses and no arity+ambiguity, because every constructor has a fixed arity:++```+top | bot | atom IRI | not C | and C C | or C C+| some ROLE C | all ROLE C | min N ROLE C | max N ROLE C+```++IRIs keep their N-Triples spelling `<...>`, which contains no space and no tab, so both+splits are exact. `model.tsv`, one fact per line:++```+domain ELEM ELEM is a domain element+class IRI ELEM ELEM is in the extension of the atomic concept IRI+edge ELEM ROLE ELEM the pair is in the extension of ROLE+ind IRI ELEM the individual IRI denotes ELEM+```++Element names are opaque strings. The emitter uses `n0`, `n1`, ... after the tableau's+node identifiers, but nothing here depends on that.+-/+namespace Dl++/-- An IRI in its N-Triples spelling, or an opaque domain element name. The checker never+looks inside one; two are the same when the strings are the same. -/+abbrev Name := String++/-- A concept of the covered fragment. Conjunction and disjunction are binary: the emitter+folds the `n`-ary OWL constructors, which keeps this type free of the nested `List Concept`+that would otherwise complicate every recursion in `Dl/Check.lean`. -/+inductive Concept where+ | top+ | bot+ | atom (a : Name)+ | neg (c : Concept)+ | and (c d : Concept)+ | or (c d : Concept)+ | ex (r : Name) (c : Concept)+ | all (r : Name) (c : Concept)+ | min (n : Nat) (r : Name) (c : Concept)+ | max (n : Nat) (r : Name) (c : Concept)+deriving DecidableEq, Repr, Inhabited++/-- An axiom of the covered fragment. See the file format table above for the+correspondence with the OWL constructs the reasoner parses. -/+inductive Axiom where+ | sub (c d : Concept)+ | disjoint (c d : Concept)+ | dom (r : Name) (c : Concept)+ | rng (r : Name) (c : Concept)+ | subrole (r s : Name)+ | trans (r : Name)+ | sym (r : Name)+ | inv (r s : Name)+ | invfunc (r : Name)+ | inst (a : Name) (c : Concept)+ | rel (a r b : Name)+ | indiv (a : Name)+ | nonempty (c : Concept)+deriving DecidableEq, Repr, Inhabited++/-- A finite interpretation.++`dom` is the carrier. `cext a` is the extension of the atomic concept `a`, `rext r x` the+list of `r`-successors of `x`, and `ind a` the element the individual IRI `a` denotes. The+three are total functions rather than association lists so that a lookup costs one hash+rather than a scan of every fact in the file; `WellFormed` is what ties them back to+`dom`. -/+structure Interp where+ dom : List Name+ cext : Name → List Name+ rext : Name → Name → List Name+ ind : Name → Name++/-! ## The vocabulary an axiom set mentions++`WellFormed` has to say that the interpretation stays inside its domain. The extension maps+are total on `String`, so that cannot be stated for every name; it is stated for the names+the axiom set actually mentions, which is the only vocabulary any of the semantic clauses+ever looks at. These three functions collect them. -/++/-- The atomic concept names occurring in a concept. -/+def Concept.atoms : Concept → List Name+ | .top | .bot => []+ | .atom a => [a]+ | .neg c => c.atoms+ | .and c d | .or c d => c.atoms ++ d.atoms+ | .ex _ c | .all _ c => c.atoms+ | .min _ _ c | .max _ _ c => c.atoms++/-- The role names occurring in a concept. -/+def Concept.roles : Concept → List Name+ | .top | .bot | .atom _ => []+ | .neg c => c.roles+ | .and c d | .or c d => c.roles ++ d.roles+ | .ex r c | .all r c => r :: c.roles+ | .min _ r c | .max _ r c => r :: c.roles++/-- The atomic concept names an axiom mentions. -/+def Axiom.atoms : Axiom → List Name+ | .sub c d | .disjoint c d => c.atoms ++ d.atoms+ | .dom _ c | .rng _ c => c.atoms+ | .inst _ c | .nonempty c => c.atoms+ | .subrole .. | .trans _ | .sym _ | .inv .. | .invfunc _ | .rel .. | .indiv _ => []++/-- The role names an axiom mentions. -/+def Axiom.roles : Axiom → List Name+ | .sub c d | .disjoint c d => c.roles ++ d.roles+ | .dom r c | .rng r c => r :: c.roles+ | .inst _ c | .nonempty c => c.roles+ | .subrole r s | .inv r s => [r, s]+ | .trans r | .sym r | .invfunc r => [r]+ | .rel _ r _ => [r]+ | .indiv _ => []++/-- The individual IRIs an axiom mentions. -/+def Axiom.inds : Axiom → List Name+ | .inst a _ | .indiv a => [a]+ | .rel a _ b => [a, b]+ | _ => []++/-- Every atomic concept name the axiom set mentions. -/+def atomNames (A : List Axiom) : List Name := A.flatMap Axiom.atoms++/-- Every role name the axiom set mentions. -/+def roleNames (A : List Axiom) : List Name := A.flatMap Axiom.roles++/-- Every individual IRI the axiom set mentions. -/+def indNames (A : List Axiom) : List Name := A.flatMap Axiom.inds++end Dldiff --git a/lean/Dl/Witness.lean b/lean/Dl/Witness.leannew file mode 100644index 00000000..819b7551--- /dev/null+++ b/lean/Dl/Witness.lean@@ -0,0 +1,143 @@+import Dl.Check++/-!+# Witnesses: the checker accepts something, rejects something, and the semantics is not trivial++`satisfiable_of_checkModel` would be worth nothing if `checkModel` accepted everything, and+`checkModel_complete` would be worth nothing if it accepted nothing. This file closes both+by construction rather than by argument, and closes a third gap as well: that `Satisfiable`+is not a predicate that happens to hold of every axiom set.++1. `employment_model_is_accepted` exhibits an axiom set that uses an existential, a+ universal through `rdfs:range`, `rdfs:domain`, disjointness, an inverse role, a maximum+ number restriction and a non-emptiness claim, together with a model of it that the+ checker accepts. `employment_is_satisfiable` is the existence result read off it.++2. `forged_missing_successor_is_rejected` takes that same axiom set and the same+ interpretation with one role edge removed, the shape a hand-edited certificate would+ have, and proves it is NOT a model. The proof goes through `checkModel_complete`, so it+ is the checker's own rejection that is being certified, not an independent argument.++3. `forged_duplicate_successor_is_rejected` is the one that pins the counting. `≥2 r.B`+ needs two DISTINCT successors. The forged interpretation lists the same successor twice,+ which a length comparison that forgot to deduplicate would accept. It is rejected.++4. `bottom_class_is_unsatisfiable` exhibits an axiom set with no model at all, so+ `Satisfiable` is not trivially true and an accepted certificate is saying something.++The names here are bare strings rather than the `<iri>` spellings the emitter writes. The+checker never looks inside a name, so nothing depends on the difference, and short names+keep the kernel's evaluation of these `decide` calls quick.+-/+namespace Dl++/-! ## An ontology about employment -/++/-- `P ⊑ ∃w.C`, `P` and `C` disjoint, `w` has domain `P` and range `C`, `w` is the inverse+of `e`, a `C` employs at most one `P`, and `P` is not empty. -/+def employment : List Axiom :=+ [ .sub (.atom "P") (.ex "w" (.atom "C")),+ .disjoint (.atom "P") (.atom "C"),+ .dom "w" (.atom "P"),+ .rng "w" (.atom "C"),+ .inv "w" "e",+ .sub (.atom "C") (.max 1 "e" (.atom "P")),+ .nonempty (.atom "P") ]++/-- One person, one company, an employment edge and its inverse. -/+def employmentModel : Interp where+ dom := ["p", "c"]+ cext := fun a => if a = "P" then ["p"] else if a = "C" then ["c"] else []+ rext := fun r x =>+ if r = "w" && x = "p" then ["c"]+ else if r = "e" && x = "c" then ["p"]+ else []+ ind := fun _ => "p"++theorem employment_model_is_accepted : checkModel employmentModel employment = true := by decide++/-- The existence result, read off the accepted interpretation. -/+theorem employment_is_satisfiable : Satisfiable employment :=+ satisfiable_of_checkModel employment_model_is_accepted++/-! ## A model with a required successor removed -/++/-- The same interpretation with the `w` edge deleted. Everything else is untouched, so the+only axiom it can break is `P ⊑ ∃w.C`. -/+def employmentForged : Interp where+ dom := ["p", "c"]+ cext := fun a => if a = "P" then ["p"] else if a = "C" then ["c"] else []+ rext := fun r x => if r = "e" && x = "c" then ["p"] else []+ ind := fun _ => "p"++theorem forged_missing_successor_is_rejected : ¬ (employmentForged ⊨ employment) :=+ checkModel_complete (by decide)++/-! ## A model that lists one successor twice where two are required -/++/-- `A ⊑ ≥2 r.B`, and `A` is not empty. -/+def twoSuccessors : List Axiom :=+ [ .sub (.atom "A") (.min 2 "r" (.atom "B")),+ .nonempty (.atom "A") ]++/-- Two genuinely different `B`s. -/+def twoSuccessorsModel : Interp where+ dom := ["x", "y", "z"]+ cext := fun a => if a = "A" then ["x"] else if a = "B" then ["y", "z"] else []+ rext := fun r x => if r = "r" && x = "x" then ["y", "z"] else []+ ind := fun _ => "x"++theorem two_successors_model_is_accepted :+ checkModel twoSuccessorsModel twoSuccessors = true := by decide++theorem two_successors_is_satisfiable : Satisfiable twoSuccessors :=+ satisfiable_of_checkModel two_successors_model_is_accepted++/-- The same element offered twice. A checker that compared `≥2` against the raw length of+the successor list would accept this. -/+def twoSuccessorsForged : Interp where+ dom := ["x", "y", "z"]+ cext := fun a => if a = "A" then ["x"] else if a = "B" then ["y", "z"] else []+ rext := fun r x => if r = "r" && x = "x" then ["y", "y"] else []+ ind := fun _ => "x"++theorem forged_duplicate_successor_is_rejected : ¬ (twoSuccessorsForged ⊨ twoSuccessors) :=+ checkModel_complete (by decide)++/-! ## Satisfiability is not trivial -/++/-- An axiom set with no model: a class is claimed non-empty and contained in `⊥`.++The proof is not a `decide`, because "no interpretation whatsoever" is not a finite check.+It is the one-line argument: the non-emptiness claim produces a domain element in the class,+the subclass axiom sends it to `Sat I .bot`, and that is `False` by definition. -/+def emptyClaim : List Axiom := [.nonempty (.atom "A"), .sub (.atom "A") .bot]++theorem bottom_class_is_unsatisfiable : ¬ Satisfiable emptyClaim := by+ rintro ⟨I, M⟩+ obtain ⟨x, hx, hA⟩ := M.holds (.nonempty (.atom "A")) (by simp [emptyClaim])+ exact M.holds (.sub (.atom "A") .bot) (by simp [emptyClaim]) x hx hA++/-! ## Axioms, pinned -/++/-- info: 'Dl.employment_is_satisfiable' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms employment_is_satisfiable++/-- info: 'Dl.forged_missing_successor_is_rejected' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms forged_missing_successor_is_rejected++/-- info: 'Dl.two_successors_is_satisfiable' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms two_successors_is_satisfiable++/-- info: 'Dl.forged_duplicate_successor_is_rejected' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms forged_duplicate_successor_is_rejected++/-- info: 'Dl.bottom_class_is_unsatisfiable' depends on axioms: [propext] -/+#guard_msgs in+#print axioms bottom_class_is_unsatisfiable++end Dldiff --git a/lean/DlMain.lean b/lean/DlMain.leannew file mode 100644index 00000000..fdf2ba9f--- /dev/null+++ b/lean/DlMain.lean@@ -0,0 +1,162 @@+import Dl.All++/-!+`oo-dlmodel AXIOMS.tsv MODEL.tsv`++Reads an axiom set and a finite interpretation, runs the verified checker, and prints one+JSON object.++Exit codes, matching the convention `oo-cert` uses:++* `0` the interpretation is a model of the axiom set. The axiom set is satisfiable, and the+ statement covering that is `Dl.satisfiable_of_checkModel`.+* `1` the interpretation is NOT a model. By `Dl.checkModel_complete` this is a statement+ about the interpretation, not about the checker giving up: the checker accepts every+ model of the axiom set.+* `2` a file could not be read or parsed. No verdict either way.++What exit 0 does NOT say, and what a reader must not infer from it:++* it says nothing about UNSATISFIABILITY. When `src/tableaux.rs` reports that a class is+ unsatisfiable, or that an ontology is inconsistent, no certificate is produced and none is+ checked here. That answer is still "trust the reasoner". Certifying it needs a closed+ tableau with its blocking argument, which is a different problem and is not solved here;+* it says nothing about whether `AXIOMS.tsv` is the ontology. The OWL parser in+ `src/tableaux.rs` is outside the theorem, exactly as the N-Triples parser is outside+ `Shacl.validate_spec`. What is certified is a relation between the two files;+* it says nothing about the fragment the emitter refused to write. `src/tableaux.rs` emits+ nothing rather than something unchecked when the completion graph cannot be turned into a+ finite interpretation, and "no certificate" is not a verdict.++The diagnostic pass that names the first failing axiom is separate and unverified. It runs+only after the verified checker has already said no.+-/+open Dl++def jsonStr (s : String) : String :=+ let escaped := s.foldl (fun acc c =>+ match c with+ | '"' => acc ++ "\\\""+ | '\\' => acc ++ "\\\\"+ | '\n' => acc ++ "\\n"+ | '\t' => acc ++ "\\t"+ | c => acc.push c) ""+ "\"" ++ escaped ++ "\""++/-- A short name for an axiom, for the diagnostic line only. -/+def axiomKind : Axiom → String+ | .sub .. => "sub"+ | .disjoint .. => "disjoint"+ | .dom .. => "domain"+ | .rng .. => "range"+ | .subrole .. => "subrole"+ | .trans .. => "trans"+ | .sym .. => "sym"+ | .inv .. => "inv"+ | .invfunc .. => "invfunc"+ | .inst .. => "inst"+ | .rel .. => "rel"+ | .indiv .. => "indiv"+ | .nonempty .. => "nonempty"++def showConcept : Concept → String+ | .top => "top"+ | .bot => "bot"+ | .atom a => "atom " ++ a+ | .neg c => "not " ++ showConcept c+ | .and c d => "and " ++ showConcept c ++ " " ++ showConcept d+ | .or c d => "or " ++ showConcept c ++ " " ++ showConcept d+ | .ex r c => "some " ++ r ++ " " ++ showConcept c+ | .all r c => "all " ++ r ++ " " ++ showConcept c+ | .min n r c => "min " ++ toString n ++ " " ++ r ++ " " ++ showConcept c+ | .max n r c => "max " ++ toString n ++ " " ++ r ++ " " ++ showConcept c++def showAxiom : Axiom → String+ | .sub c d => "sub\t" ++ showConcept c ++ "\t" ++ showConcept d+ | .disjoint c d => "disjoint\t" ++ showConcept c ++ "\t" ++ showConcept d+ | .dom r c => "domain\t" ++ r ++ "\t" ++ showConcept c+ | .rng r c => "range\t" ++ r ++ "\t" ++ showConcept c+ | .subrole r s => "subrole\t" ++ r ++ "\t" ++ s+ | .trans r => "trans\t" ++ r+ | .sym r => "sym\t" ++ r+ | .inv r s => "inv\t" ++ r ++ "\t" ++ s+ | .invfunc r => "invfunc\t" ++ r+ | .inst a c => "inst\t" ++ a ++ "\t" ++ showConcept c+ | .rel a r b => "rel\t" ++ a ++ "\t" ++ r ++ "\t" ++ b+ | .indiv a => "indiv\t" ++ a+ | .nonempty c => "nonempty\t" ++ showConcept c++/-- Which well-formedness clause failed, if one did. -/+def wfFailure (I : Interp) (A : List Axiom) : Option String :=+ if I.dom.isEmpty then+ some "the domain is empty"+ else if !((atomNames A).all (fun a => (I.cext a).all (fun x => I.dom.contains x))) then+ some "an atomic concept has a member outside the domain"+ else if !((roleNames A).all (fun r =>+ I.dom.all (fun x => (I.rext r x).all (fun y => I.dom.contains y)))) then+ some "a role edge leaves the domain"+ else if !((indNames A).all (fun a => I.dom.contains (I.ind a))) then+ some "a named individual denotes something outside the domain"+ else+ none++def firstFailure (I : Interp) (A : List Axiom) : Option (Nat × Axiom) := Id.run do+ let mut i := 0+ for a in A do+ if !holds I a then+ return some (i, a)+ i := i + 1+ return none++def readOrFail (path : String) : IO (Except UInt32 String) := do+ try+ return .ok (← IO.FS.readFile path)+ catch e =>+ IO.eprintln s!"cannot read {path}: {e}"+ return .error 2++def run (axPath mPath : String) : IO UInt32 := do+ let axTxt ← match ← readOrFail axPath with+ | .ok s => pure s+ | .error c => return c+ let mTxt ← match ← readOrFail mPath with+ | .ok s => pure s+ | .error c => return c+ match Parse.parseAxioms axTxt, Parse.parseModel mTxt with+ | .ok A, .ok I =>+ if checkModel I A then+ IO.println ("{\"ok\":true,\"axioms\":" ++ toString A.length +++ ",\"domain\":" ++ toString I.dom.length +++ ",\"theorem\":\"Dl.satisfiable_of_checkModel\"}")+ return 0+ else+ match wfFailure I A with+ | some reason =>+ IO.println ("{\"ok\":false,\"axioms\":" ++ toString A.length +++ ",\"domain\":" ++ toString I.dom.length +++ ",\"wellformed\":false,\"reason\":" ++ jsonStr reason ++ "}")+ | none =>+ match firstFailure I A with+ | some (i, a) =>+ IO.println ("{\"ok\":false,\"axioms\":" ++ toString A.length +++ ",\"domain\":" ++ toString I.dom.length +++ ",\"wellformed\":true,\"first_rejected\":" ++ toString i +++ ",\"kind\":" ++ jsonStr (axiomKind a) +++ ",\"axiom\":" ++ jsonStr (showAxiom a) ++ "}")+ | none =>+ IO.println ("{\"ok\":false,\"error\":\"the verified checker rejected the model " +++ "and the diagnostic pass could not name an axiom\"}")+ return 1+ | .error e, _ =>+ IO.eprintln e+ return 2+ | _, .error e =>+ IO.eprintln e+ return 2++def main (args : List String) : IO UInt32 := do+ match args with+ | [a, m] => run a m+ | _ =>+ IO.eprintln "usage: oo-dlmodel AXIOMS.tsv MODEL.tsv"+ return 2diff --git a/lean/OOCert/HornBuiltin.lean b/lean/OOCert/HornBuiltin.leanindex deb764d3..19560697 100644--- a/lean/OOCert/HornBuiltin.lean+++ b/lean/OOCert/HornBuiltin.lean@@ -4,28 +4,38 @@ import OOCert.Horn# The hardcoded arms, as dataThe question this file settles: is the generic Horn theorem a SECOND rule-family bolted on beside the twenty arms, or does it SUBSUME them?+family bolted on beside the per-rule arms, or does it SUBSUME them?-Nineteen of the engine's rules are Horn rules over triple patterns, written out below-as values of `RulePattern`. For each, one lemma says the semantic conditions in-`Semantics.lean` imply the term-level rule. Every one of those lemmas is a-single `exact` against the matching field of `Conditions`, because there is no-premise-list destructuring left to do: the checker did it.+Twenty-five of the engine's twenty-nine rules are Horn rules over triple+patterns, written out below as values of `RulePattern`. Two of them license two+conclusions each, so the table has twenty-seven entries. For each, one lemma+says the semantic conditions in `Semantics.lean` imply the term-level rule.+Every one of those lemmas is a single `exact` against the matching field of+`Conditions`, because there is no premise-list destructuring left to do: the+checker did it.`entails_of_horn` is then the payoff. A certificate that cites only rules withsuch a lemma yields the ORIGINAL `Entails G t`, the same warrant`certificate_sound` gives, with no per-rule arm in the checker and no per-rulelemma about premise lists.-## The two that are not Horn rules, and why--`cls-int1` and `cls-uni` read an RDF list off the graph. Their premise count is-not fixed by the rule: it is the length of the list, which is data. A-`RulePattern` has a finite body, so expressing `cls-int1` needs either one rule-per list length, which is infinitely many rules, or an atom that matches a-chain, which is outside Horn logic over triple patterns. They stay hardcoded.-That is not a defect of the generalisation; it is the exact boundary of the-Horn family, and it is where a user-written rule language will also stop.+## The four that are not Horn rules, and why++`cls-int1`, `cls-int2`, `cls-uni` and `cls-oo` read an RDF list off the graph.+Their premise count is not fixed by the rule: it is the length of the list,+which is data. A `RulePattern` has a finite body, so expressing `cls-int1`+needs either one rule per list length, which is infinitely many rules, or an+atom that matches a chain, which is outside Horn logic over triple patterns.+They stay hardcoded. That is not a defect of the generalisation; it is the+exact boundary of the Horn family, and it is where a user-written rule language+will also stop.++`cls-int2` is the newest of the four and it lands on the same side for the same+reason, even though its premise list is shorter than `cls-int1`'s. What decides+the question is not how many instance premises a rule reads but whether the+LIST is one of them, and `cls-int2` reads the list to know which conclusions it+is allowed to draw. Its condition is therefore a field of `Model`, which sees+the graph, rather than of `Conditions`, which sees only the interpretation.-/namespace OOCertnamespace Builtin@@ -146,9 +156,82 @@ def clsHv2 : RulePattern :=⟨.var "x", .var "p", .var "v"⟩]head := ⟨.var "x", .const V.type, .var "r"⟩ }+/-! ### The restriction-ordering and domain-and-range rules++Eight more, all of them Horn rules over triple patterns and none of them needing+anything the `RulePattern` language does not already have. The first four order+two restrictions on the same property or with the same filler; the last four+move a declared domain or range along the class and the property hierarchy.++`scmAvf2` concludes `?c2 rdfs:subClassOf ?c1`, the reverse of the other three.+That is the W3C table, not a typo here: a universal restriction is antitone in+its property. The `Conditions` field it appeals to is stated the same way round,+so a head written the natural way would fail to typecheck. -/++def scmSvf1 : RulePattern :=+ { name := "scm-svf1"+ body := [⟨.var "c1", .const V.someValuesFrom, .var "y1"⟩,+ ⟨.var "c1", .const V.onProperty, .var "p"⟩,+ ⟨.var "c2", .const V.someValuesFrom, .var "y2"⟩,+ ⟨.var "c2", .const V.onProperty, .var "p"⟩,+ ⟨.var "y1", .const V.subClassOf, .var "y2"⟩]+ head := ⟨.var "c1", .const V.subClassOf, .var "c2"⟩ }++def scmSvf2 : RulePattern :=+ { name := "scm-svf2"+ body := [⟨.var "c1", .const V.someValuesFrom, .var "y"⟩,+ ⟨.var "c1", .const V.onProperty, .var "p1"⟩,+ ⟨.var "c2", .const V.someValuesFrom, .var "y"⟩,+ ⟨.var "c2", .const V.onProperty, .var "p2"⟩,+ ⟨.var "p1", .const V.subPropertyOf, .var "p2"⟩]+ head := ⟨.var "c1", .const V.subClassOf, .var "c2"⟩ }++def scmAvf1 : RulePattern :=+ { name := "scm-avf1"+ body := [⟨.var "c1", .const V.allValuesFrom, .var "y1"⟩,+ ⟨.var "c1", .const V.onProperty, .var "p"⟩,+ ⟨.var "c2", .const V.allValuesFrom, .var "y2"⟩,+ ⟨.var "c2", .const V.onProperty, .var "p"⟩,+ ⟨.var "y1", .const V.subClassOf, .var "y2"⟩]+ head := ⟨.var "c1", .const V.subClassOf, .var "c2"⟩ }++/-- Head REVERSED, `?c2 rdfs:subClassOf ?c1`. See the note above. -/+def scmAvf2 : RulePattern :=+ { name := "scm-avf2"+ body := [⟨.var "c1", .const V.allValuesFrom, .var "y"⟩,+ ⟨.var "c1", .const V.onProperty, .var "p1"⟩,+ ⟨.var "c2", .const V.allValuesFrom, .var "y"⟩,+ ⟨.var "c2", .const V.onProperty, .var "p2"⟩,+ ⟨.var "p1", .const V.subPropertyOf, .var "p2"⟩]+ head := ⟨.var "c2", .const V.subClassOf, .var "c1"⟩ }++def scmDom1 : RulePattern :=+ { name := "scm-dom1"+ body := [⟨.var "p", .const V.domain, .var "c1"⟩,+ ⟨.var "c1", .const V.subClassOf, .var "c2"⟩]+ head := ⟨.var "p", .const V.domain, .var "c2"⟩ }++def scmDom2 : RulePattern :=+ { name := "scm-dom2"+ body := [⟨.var "p2", .const V.domain, .var "c"⟩,+ ⟨.var "p1", .const V.subPropertyOf, .var "p2"⟩]+ head := ⟨.var "p1", .const V.domain, .var "c"⟩ }++def scmRng1 : RulePattern :=+ { name := "scm-rng1"+ body := [⟨.var "p", .const V.range, .var "c1"⟩,+ ⟨.var "c1", .const V.subClassOf, .var "c2"⟩]+ head := ⟨.var "p", .const V.range, .var "c2"⟩ }++def scmRng2 : RulePattern :=+ { name := "scm-rng2"+ body := [⟨.var "p2", .const V.range, .var "c"⟩,+ ⟨.var "p1", .const V.subPropertyOf, .var "p2"⟩]+ head := ⟨.var "p1", .const V.range, .var "c"⟩ }+/-! ## Each is a consequence of the semantic conditions-One `exact` each. Compare `Soundness.lean`, where the same eighteen facts cost+One `exact` each. Compare `Soundness.lean`, where the same facts costa `rcases` over the premise list, a `simp only` to strip the decidabilitywrapper, an `obtain` over the conjunction, and then the `exact`. -/@@ -237,18 +320,77 @@ theorem clsHv2_sound {I : Interp} (C : Conditions I) : SatRule I clsHv2 := fun s(hb ⟨.var "r", .const V.hasValue, .var "v"⟩ (by simp [clsHv2])) _).mpr(hb ⟨.var "x", .var "p", .var "v"⟩ (by simp [clsHv2]))-/-- The built-in rules that are Horn rules, as a rule set. Nineteen of the-engine's rules qualify; `cls-int1` and `cls-uni` do not, for the reason given-at the top of this file. -/+theorem scmSvf1_sound {I : Interp} (C : Conditions I) : SatRule I scmSvf1 := fun s hb =>+ C.svf_sc _ _ _ _ _+ (hb ⟨.var "c1", .const V.someValuesFrom, .var "y1"⟩ (by simp [scmSvf1]))+ (hb ⟨.var "c1", .const V.onProperty, .var "p"⟩ (by simp [scmSvf1]))+ (hb ⟨.var "c2", .const V.someValuesFrom, .var "y2"⟩ (by simp [scmSvf1]))+ (hb ⟨.var "c2", .const V.onProperty, .var "p"⟩ (by simp [scmSvf1]))+ (hb ⟨.var "y1", .const V.subClassOf, .var "y2"⟩ (by simp [scmSvf1]))++theorem scmSvf2_sound {I : Interp} (C : Conditions I) : SatRule I scmSvf2 := fun s hb =>+ C.svf_sp _ _ _ _ _+ (hb ⟨.var "c1", .const V.someValuesFrom, .var "y"⟩ (by simp [scmSvf2]))+ (hb ⟨.var "c1", .const V.onProperty, .var "p1"⟩ (by simp [scmSvf2]))+ (hb ⟨.var "c2", .const V.someValuesFrom, .var "y"⟩ (by simp [scmSvf2]))+ (hb ⟨.var "c2", .const V.onProperty, .var "p2"⟩ (by simp [scmSvf2]))+ (hb ⟨.var "p1", .const V.subPropertyOf, .var "p2"⟩ (by simp [scmSvf2]))++theorem scmAvf1_sound {I : Interp} (C : Conditions I) : SatRule I scmAvf1 := fun s hb =>+ C.avf_sc _ _ _ _ _+ (hb ⟨.var "c1", .const V.allValuesFrom, .var "y1"⟩ (by simp [scmAvf1]))+ (hb ⟨.var "c1", .const V.onProperty, .var "p"⟩ (by simp [scmAvf1]))+ (hb ⟨.var "c2", .const V.allValuesFrom, .var "y2"⟩ (by simp [scmAvf1]))+ (hb ⟨.var "c2", .const V.onProperty, .var "p"⟩ (by simp [scmAvf1]))+ (hb ⟨.var "y1", .const V.subClassOf, .var "y2"⟩ (by simp [scmAvf1]))++/-- The head is `?c2 rdfs:subClassOf ?c1` and `avf_sp` concludes `I.sc c2 c1`.+Swap either one and this `exact` stops typechecking, which is the point of+having the direction in two places rather than one. -/+theorem scmAvf2_sound {I : Interp} (C : Conditions I) : SatRule I scmAvf2 := fun s hb =>+ C.avf_sp _ _ _ _ _+ (hb ⟨.var "c1", .const V.allValuesFrom, .var "y"⟩ (by simp [scmAvf2]))+ (hb ⟨.var "c1", .const V.onProperty, .var "p1"⟩ (by simp [scmAvf2]))+ (hb ⟨.var "c2", .const V.allValuesFrom, .var "y"⟩ (by simp [scmAvf2]))+ (hb ⟨.var "c2", .const V.onProperty, .var "p2"⟩ (by simp [scmAvf2]))+ (hb ⟨.var "p1", .const V.subPropertyOf, .var "p2"⟩ (by simp [scmAvf2]))++theorem scmDom1_sound {I : Interp} (C : Conditions I) : SatRule I scmDom1 := fun s hb =>+ C.dom_sc _ _ _ (hb ⟨.var "p", .const V.domain, .var "c1"⟩ (by simp [scmDom1]))+ (hb ⟨.var "c1", .const V.subClassOf, .var "c2"⟩ (by simp [scmDom1]))++theorem scmDom2_sound {I : Interp} (C : Conditions I) : SatRule I scmDom2 := fun s hb =>+ C.dom_sp _ _ _ (hb ⟨.var "p2", .const V.domain, .var "c"⟩ (by simp [scmDom2]))+ (hb ⟨.var "p1", .const V.subPropertyOf, .var "p2"⟩ (by simp [scmDom2]))++theorem scmRng1_sound {I : Interp} (C : Conditions I) : SatRule I scmRng1 := fun s hb =>+ C.rng_sc _ _ _ (hb ⟨.var "p", .const V.range, .var "c1"⟩ (by simp [scmRng1]))+ (hb ⟨.var "c1", .const V.subClassOf, .var "c2"⟩ (by simp [scmRng1]))++theorem scmRng2_sound {I : Interp} (C : Conditions I) : SatRule I scmRng2 := fun s hb =>+ C.rng_sp _ _ _ (hb ⟨.var "p2", .const V.range, .var "c"⟩ (by simp [scmRng2]))+ (hb ⟨.var "p1", .const V.subPropertyOf, .var "p2"⟩ (by simp [scmRng2]))++/-- The built-in rules that are Horn rules, as a rule set. Twenty-seven of the+twenty-nine rule ids the engine emits qualify; `cls-int1`, `cls-int2`, `cls-uni`+and `cls-oo` do not, for the reason given at the top of this file, and+`scm-eqc1` and `scm-eqp1` each contribute two entries because each licenses two+conclusions.++The ORDER is a contract. A certificate cites a rule by its index into this+list, so the nineteen entries that were here before keep the positions they+had, and anything new is appended. -/def asHorn : List RulePattern :=[rdfs2, rdfs3, rdfs5, rdfs7, rdfs9, rdfs11,prpTrp, prpSymp, prpInv1, prpInv2, eqSym,- scmEqc1, scmEqc1b, scmEqp1, scmEqp1b, clsSvf1, clsAvf, clsHv1, clsHv2]+ scmEqc1, scmEqc1b, scmEqp1, scmEqp1b, clsSvf1, clsAvf, clsHv1, clsHv2,+ scmSvf1, scmSvf2, scmAvf1, scmAvf2, scmDom1, scmDom2, scmRng1, scmRng2]theorem asHorn_sound (I : Interp) (C : Conditions I) : ∀ r ∈ asHorn, SatRule I r := byintro r hrsimp only [asHorn, List.mem_cons, List.not_mem_nil, or_false] at hr- rcases hr with rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl+ rcases hr with rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|+ rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl· exact rdfs2_sound C· exact rdfs3_sound C· exact rdfs5_sound C@@ -268,6 +410,14 @@ theorem asHorn_sound (I : Interp) (C : Conditions I) : ∀ r ∈ asHorn, SatRule· exact clsAvf_sound C· exact clsHv1_sound C· exact clsHv2_sound C+ · exact scmSvf1_sound C+ · exact scmSvf2_sound C+ · exact scmAvf1_sound C+ · exact scmAvf2_sound C+ · exact scmDom1_sound C+ · exact scmDom2_sound C+ · exact scmRng1_sound C+ · exact scmRng2_sound Cend Builtindiff --git a/lean/OOCert/HornWitness.lean b/lean/OOCert/HornWitness.leanindex 3c079025..771b97d4 100644--- a/lean/OOCert/HornWitness.lean+++ b/lean/OOCert/HornWitness.lean@@ -117,14 +117,32 @@ theorem demoH_is_a_model : Model (herbrand demoH) demoG whereabsurd hab (not_mem_pred demoH V.equivalentProperty (by decide) a b)svf := fun r p _ hop => absurd hop (not_mem_pred demoH V.onProperty (by decide) r p)avf := fun r p _ hop => absurd hop (not_mem_pred demoH V.onProperty (by decide) r p)- hv := fun r p _ hop => absurd hop (not_mem_pred demoH V.onProperty (by decide) r p) }+ hv := fun r p _ hop => absurd hop (not_mem_pred demoH V.onProperty (by decide) r p)+ svf_sc := fun c1 _ _ y1 _ hsv =>+ absurd hsv (not_mem_pred demoH V.someValuesFrom (by decide) c1 y1)+ svf_sp := fun c1 _ _ _ y hsv =>+ absurd hsv (not_mem_pred demoH V.someValuesFrom (by decide) c1 y)+ avf_sc := fun c1 _ _ y1 _ hav =>+ absurd hav (not_mem_pred demoH V.allValuesFrom (by decide) c1 y1)+ avf_sp := fun c1 _ _ _ y hav =>+ absurd hav (not_mem_pred demoH V.allValuesFrom (by decide) c1 y)+ dom_sc := fun p c1 _ hd => absurd hd (not_mem_pred demoH V.domain (by decide) p c1)+ dom_sp := fun _ p2 c hd => absurd hd (not_mem_pred demoH V.domain (by decide) p2 c)+ rng_sc := fun p c1 _ hr => absurd hr (not_mem_pred demoH V.range (by decide) p c1)+ rng_sp := fun _ p2 c hr => absurd hr (not_mem_pred demoH V.range (by decide) p2 c) }facts := fun t ht => List.mem_cons_of_mem _ htint := byintro c l _ hcexact absurd hc (not_mem_pred demoG V.intersectionOf (by decide) c l)+ int2 := by+ intro c l _ hc+ exact absurd hc (not_mem_pred demoG V.intersectionOf (by decide) c l)uni := byintro c l _ hcexact absurd hc (not_mem_pred demoG V.unionOf (by decide) c l)+ oneOf := by+ intro c l _ hc+ exact absurd hc (not_mem_pred demoG V.oneOf (by decide) c l)/-- Adding a user rule does not collapse entailment: `a gp b` is still not aconsequence, so the Horn layer derives less than everything. -/diff --git a/lean/OOCert/Mixed.lean b/lean/OOCert/Mixed.leanindex 37d2d78f..14752031 100644--- a/lean/OOCert/Mixed.lean+++ b/lean/OOCert/Mixed.lean@@ -389,6 +389,12 @@ private theorem mixH_int_closed : ∀ t ∈ mixH, ∀ u ∈ mixH,(t.p = V.type ∧ t.o = mVendor ∧ u.p = V.type ∧ u.o = mApproved ∧ u.s = t.s) →(⟨t.s, V.type, mSupplier⟩ : Triple) ∈ mixH := by decide+/-- The other half of what the intersection means, for `Model.int2`: everything+this graph makes a `Supplier` it already makes a `Vendor` and an `Approved`. -/+private theorem mixH_int2_closed : ∀ t ∈ mixH, t.p = V.type → t.o = mSupplier →+ (⟨t.s, V.type, mVendor⟩ : Triple) ∈ mixH ∧ (⟨t.s, V.type, mApproved⟩ : Triple) ∈ mixH := by+ decide+theorem mixH_is_a_model : Model (herbrand mixH) mixG whereconds :={ sc_sub := fun a b hab => absurd hab (not_mem_pred mixH V.subClassOf (by decide) a b)@@ -407,7 +413,19 @@ theorem mixH_is_a_model : Model (herbrand mixH) mixG whereabsurd hab (not_mem_pred mixH V.equivalentProperty (by decide) a b)svf := fun r p _ hop => absurd hop (not_mem_pred mixH V.onProperty (by decide) r p)avf := fun r p _ hop => absurd hop (not_mem_pred mixH V.onProperty (by decide) r p)- hv := fun r p _ hop => absurd hop (not_mem_pred mixH V.onProperty (by decide) r p) }+ hv := fun r p _ hop => absurd hop (not_mem_pred mixH V.onProperty (by decide) r p)+ svf_sc := fun c1 _ _ y1 _ hsv =>+ absurd hsv (not_mem_pred mixH V.someValuesFrom (by decide) c1 y1)+ svf_sp := fun c1 _ _ _ y hsv =>+ absurd hsv (not_mem_pred mixH V.someValuesFrom (by decide) c1 y)+ avf_sc := fun c1 _ _ y1 _ hav =>+ absurd hav (not_mem_pred mixH V.allValuesFrom (by decide) c1 y1)+ avf_sp := fun c1 _ _ _ y hav =>+ absurd hav (not_mem_pred mixH V.allValuesFrom (by decide) c1 y)+ dom_sc := fun p c1 _ hd => absurd hd (not_mem_pred mixH V.domain (by decide) p c1)+ dom_sp := fun _ p2 c hd => absurd hd (not_mem_pred mixH V.domain (by decide) p2 c)+ rng_sc := fun p c1 _ hr => absurd hr (not_mem_pred mixH V.range (by decide) p c1)+ rng_sp := fun _ p2 c hr => absurd hr (not_mem_pred mixH V.range (by decide) p2 c) }facts := fun t ht => List.mem_cons_of_mem _ htint := byintro c l ms hc hchain x hx@@ -416,9 +434,23 @@ theorem mixH_is_a_model : Model (herbrand mixH) mixG wheresubst hmsexact mixH_int_closed _ (hx mVendor (by simp)) _ (hx mApproved (by simp))⟨rfl, rfl, rfl, rfl, rfl⟩+ int2 := by+ intro c l ms hc hchain x hx m hm+ obtain ⟨rfl, rfl⟩ := mix_only_int _ hc rfl+ have hms := mix_chain_l0 ms hchain+ subst hms+ obtain ⟨h1, h2⟩ := mixH_int2_closed ⟨x, V.type, mSupplier⟩ hx rfl rfl+ rcases List.mem_cons.mp hm with rfl | hm+ · exact h1+ · rw [List.mem_singleton] at hm+ subst hm+ exact h2uni := byintro c l _ hcexact absurd hc (not_mem_pred mixG V.unionOf (by decide) c l)+ oneOf := by+ intro c l _ hc+ exact absurd hc (not_mem_pred mixG V.oneOf (by decide) c l)/-- **The distinction, machine-checked.** The certificate above was accepted andits conclusion is entailed under the supplied rule. It is NOT entailed by the@@ -436,6 +468,12 @@ private theorem mixH2_int_closed : ∀ t ∈ mixH2, ∀ u ∈ mixH2,(t.p = V.type ∧ t.o = mVendor ∧ u.p = V.type ∧ u.o = mApproved ∧ u.s = t.s) →(⟨t.s, V.type, mSupplier⟩ : Triple) ∈ mixH2 := by decide+/-- The other half of what the intersection means, for `Model.int2`: everything+this graph makes a `Supplier` it already makes a `Vendor` and an `Approved`. -/+private theorem mixH2_int2_closed : ∀ t ∈ mixH2, t.p = V.type → t.o = mSupplier →+ (⟨t.s, V.type, mVendor⟩ : Triple) ∈ mixH2 ∧ (⟨t.s, V.type, mApproved⟩ : Triple) ∈ mixH2 := by+ decide+private theorem mixH2_rule_closed : ∀ t ∈ mixH2, t.p = V.type → t.o = mSupplier →(⟨t.s, mStatus, mCompliant⟩ : Triple) ∈ mixH2 := by decide@@ -457,7 +495,19 @@ theorem mixH2_is_a_model : Model (herbrand mixH2) mixG whereabsurd hab (not_mem_pred mixH2 V.equivalentProperty (by decide) a b)svf := fun r p _ hop => absurd hop (not_mem_pred mixH2 V.onProperty (by decide) r p)avf := fun r p _ hop => absurd hop (not_mem_pred mixH2 V.onProperty (by decide) r p)- hv := fun r p _ hop => absurd hop (not_mem_pred mixH2 V.onProperty (by decide) r p) }+ hv := fun r p _ hop => absurd hop (not_mem_pred mixH2 V.onProperty (by decide) r p)+ svf_sc := fun c1 _ _ y1 _ hsv =>+ absurd hsv (not_mem_pred mixH2 V.someValuesFrom (by decide) c1 y1)+ svf_sp := fun c1 _ _ _ y hsv =>+ absurd hsv (not_mem_pred mixH2 V.someValuesFrom (by decide) c1 y)+ avf_sc := fun c1 _ _ y1 _ hav =>+ absurd hav (not_mem_pred mixH2 V.allValuesFrom (by decide) c1 y1)+ avf_sp := fun c1 _ _ _ y hav =>+ absurd hav (not_mem_pred mixH2 V.allValuesFrom (by decide) c1 y)+ dom_sc := fun p c1 _ hd => absurd hd (not_mem_pred mixH2 V.domain (by decide) p c1)+ dom_sp := fun _ p2 c hd => absurd hd (not_mem_pred mixH2 V.domain (by decide) p2 c)+ rng_sc := fun p c1 _ hr => absurd hr (not_mem_pred mixH2 V.range (by decide) p c1)+ rng_sp := fun _ p2 c hr => absurd hr (not_mem_pred mixH2 V.range (by decide) p2 c) }facts := fun t ht => List.mem_cons_of_mem _ (List.mem_cons_of_mem _ ht)int := byintro c l ms hc hchain x hx@@ -466,9 +516,23 @@ theorem mixH2_is_a_model : Model (herbrand mixH2) mixG wheresubst hmsexact mixH2_int_closed _ (hx mVendor (by simp)) _ (hx mApproved (by simp))⟨rfl, rfl, rfl, rfl, rfl⟩+ int2 := by+ intro c l ms hc hchain x hx m hm+ obtain ⟨rfl, rfl⟩ := mix_only_int _ hc rfl+ have hms := mix_chain_l0 ms hchain+ subst hms+ obtain ⟨h1, h2⟩ := mixH2_int2_closed ⟨x, V.type, mSupplier⟩ hx rfl rfl+ rcases List.mem_cons.mp hm with rfl | hm+ · exact h1+ · rw [List.mem_singleton] at hm+ subst hm+ exact h2uni := byintro c l _ hcexact absurd hc (not_mem_pred mixG V.unionOf (by decide) c l)+ oneOf := by+ intro c l _ hc+ exact absurd hc (not_mem_pred mixG V.oneOf (by decide) c l)theorem mixH2_sat_rule : SatRule (herbrand mixH2) complianceRule := byintro sigma hbdiff --git a/lean/OOCert/Refute.lean b/lean/OOCert/Refute.leannew file mode 100644index 00000000..0161beee--- /dev/null+++ b/lean/OOCert/Refute.lean@@ -0,0 +1,471 @@+import OOCert.Soundness++/-!+# `oo-refute/1`: certifying that a graph has NO model++Sixteen rules in the OWL 2 RL profile conclude `false` rather than a triple.+`cax-dw` is the first of them and the one with the most axioms waiting for it:+given `c1 owl:disjointWith c2`, `x rdf:type c1` and `x rdf:type c2`, the graph+is contradictory. The certificate format in `Rules.lean` cannot express that,+because `Step.conclusion` is a `Triple` and `certificate_sound` concludes+`Entails`. There is no triple to conclude. This file adds the second format.++## Why the negative conditions live HERE and not in `Semantics.lean`++`lean/OOCert/Witness.lean` proves `saturated_is_a_model`: every graph has a+model, the one in which every property relates everything. That theorem is what+stops `certificate_sound` being vacuously true, and its truth depends on the+fragment having no negation. A disjointness condition is negative: it says+nothing is in both of two disjoint classes, and the saturated interpretation+puts everything in every class. Adding such a condition to `Conditions` would+make `saturated_is_a_model` FALSE, and that theorem cannot be patched because+being unfalsifiable is the whole point of it.++So `RefuteConditions` is a SEPARATE layer. `Conditions` is untouched, every+existing theorem keeps its meaning, and the two model classes are named+differently so that no report can confuse them.++## What `Unsat` means, and what it does not++`Unsat G` says: no interpretation satisfies BOTH `Model I G` AND+`RefuteConditions I`. It is unsatisfiability RELATIVE TO THOSE CONDITIONS, not+absolute unsatisfiability. A reader who takes it for the latter will be wrong in+a specific way: `Model I G` alone is still satisfiable for every graph, refuted+or not, because `saturated` ignores disjointness. `Unsat G` is the statement+that reading `owl:disjointWith` as disjointness leaves no models, which is what+an OWL 2 RL consumer means by "inconsistent" and is not the same sentence.++`RefuteConditions` carries exactly one field, because exactly one rule is+implemented. The other fifteen clash rules (`cax-adc`, `cls-com`,+`cls-nothing2`, `cls-maxc1`, `prp-irp`, `prp-asyp`, `prp-pdw`, `prp-adp`,+`prp-npa1`, `prp-npa2`, `eq-diff1`, `eq-diff2`, `eq-diff3` and the rest) each+need their own condition and their own field, and none of them is here. A+graph that only a missing rule could refute is not refutable by this checker,+and the checker says so by rejecting, never by passing.++## The explosion, and what a consumer must do about it++Once a graph is refutable, every triple is entailed under the disjointness-aware+reading, so an ordinary triple certificate over that graph carries no+information at all. `a_certificate_adds_nothing_when_the_graph_is_refuted`+states this as a theorem rather than as advice: for a refuted `G`, EVERY+conclusion of EVERY list of steps has the disjointness-aware warrant, whether+the checker accepted the certificate or not.++The trap here is subtler than plain explosion, and it is worth being exact.+`certificate_sound`'s verdict, `Entails G t`, is NOT trivialised by a refutation,+because `Entails` quantifies over `Model I G` alone and that class is never+empty. So a triple certificate over a self-contradicting ontology still checks+green, still says something literally true, and still says nothing a consumer+wants. The guarantee the consumer wants is `EntailsIn (RModel G)`, and that one+is empty. A consumer must therefore run the refutation checker FIRST and treat a+successful refutation as invalidating every derivation over the same graph.+`oo-refute guard` does that in one command and refuses the triple certificate.++## The format++```+oo-refute/1+<rule> <s> <p> <o> [<ps> <pp> <po>]* (zero or more, tab separated)+refute cax-dw <c1> <p> <c2> <x> <p> <c1> <x> <p> <c2>+```++The first line is the version marker. The lines between it and the last are+ordinary derivation steps in the `derivations.tsv` spelling, so a refutation may+reach its contradiction through inference: the disjoint types are usually+derived by `rdfs9` off a subclass chain rather than asserted. The last line is+the contradiction step, and there is exactly one. A `derivations.tsv` handed to+this checker is rejected, because it has no `refute` line and no version marker.+-/+namespace OOCert++/-! ## Vocabulary++`V` lives in `Triple.lean` and this round belongs to another file's owner, so+the one term this layer adds is kept here. It is the same N-Triples spelling the+engine's interner produces. -/+namespace RV+/-- `owl:disjointWith`. -/+def disjointWith : Term := "<http://www.w3.org/2002/07/owl#disjointWith>"+end RV++/-! ## The negative conditions -/++/-- The conditions a model must satisfy for a REFUTATION to mean anything.+Minimal by design: one field, for the one rule implemented.++`dw` is the semantic reading of `owl:disjointWith`: if `(a, b)` is in the+extension of `owl:disjointWith` then no domain element is in both class+extensions. It is the *if* direction only, which is all `cax-dw` uses, and it is+a consequence of the OWL 2 condition rather than a strengthening of it. -/+structure RefuteConditions (I : Interp) : Prop where+ /-- cax-dw. -/+ dw : ∀ a b, I.iext (I.ι RV.disjointWith) a b → ∀ x, I.cext a x → I.cext b x → False++/-- A model of `G` that ALSO respects disjointness. Named apart from `Model` so+that no verdict can quietly move between the two classes. -/+def RModel (G : List Triple) (I : Interp) : Prop := Model I G ∧ RefuteConditions I++/-- `G` has no model that respects disjointness.++Relative, not absolute: see the module docstring. `Model I G` on its own is+satisfiable for every graph, by `saturated`. -/+def Unsat (G : List Triple) : Prop := ∀ I : Interp, ¬ RModel G I++theorem RModel.model {G : List Triple} {I : Interp} (h : RModel G I) : Model I G := h.1++/-! ## The refutation step -/++/-- The clash rules, one constructor per rule implemented. One so far. -/+inductive RefuteRule+ | caxDw+deriving DecidableEq, Repr++def RefuteRule.name : RefuteRule → String+ | .caxDw => "cax-dw"++def RefuteRule.all : List RefuteRule := [.caxDw]++def RefuteRule.ofName? (s : String) : Option RefuteRule :=+ RefuteRule.all.find? (fun r => r.name == s)++/-- The final step of a refutation. It has premises and no conclusion, because+what it concludes is contradiction.++`cax-dw` premise order, and the checker matches on it: `c1 owl:disjointWith c2`,+`x rdf:type c1`, `x rdf:type c2`. -/+structure RefuteStep where+ rule : RefuteRule+ premises : List Triple+deriving Repr++/-- A refutation: a derivation prefix in the ordinary format, then one+contradiction step. The prefix is what lets the disjoint types be derived rather+than asserted, which is the normal case in a real ontology. -/+structure Refutation where+ steps : List Step+ final : RefuteStep+deriving Repr++/-! ## The checker++`checkAll` in `Rules.lean` threads its derived set through a `Std.HashSet`,+whose `contains` the Lean kernel cannot evaluate: `String.hash` is `opaque`, so+`decide` cannot run it. `checkAllL` is the same function over a list, which the+kernel can run, so the witness file can settle acceptance and rejection by+`decide` instead of by assertion. Both are proved sound, and the CLI uses the+hashed one because it is the one that scales. -/++/-- `checkAll` with a list for the derived set. Quadratic, and the kernel can+run it. -/+def checkAllL (inG : Triple → Bool) : List Step → List Triple → Bool+ | [], _ => true+ | st :: rest, derived =>+ checkStep inG (fun t => decide (t ∈ derived)) st &&+ checkAllL inG rest (st.conclusion :: derived)++/-- Check the contradiction step. `k` answers "asserted, or concluded by the+prefix". Premise order is part of the contract, as it is for every other rule in+this checker: a refutation with the right triples in the wrong order is+rejected, which is a false alarm and never a false pass. -/+def checkRefuteStep (k : Triple → Bool) (rs : RefuteStep) : Bool :=+ match rs.rule, rs.premises with+ | .caxDw, [⟨c1, dw, c2⟩, ⟨x, t1, c1'⟩, ⟨x', t2, c2'⟩] =>+ dw = RV.disjointWith ∧ t1 = V.type ∧ c1' = c1 ∧+ x' = x ∧ t2 = V.type ∧ c2' = c2 ∧+ k ⟨c1, dw, c2⟩ ∧ k ⟨x, t1, c1'⟩ ∧ k ⟨x', t2, c2'⟩+ | _, _ => false++/-- The conclusions the prefix made available to the contradiction step. A+premise of the final step may be asserted or derived by the prefix; it may not+be assumed. -/+def prefixConclusions (r : Refutation) : List Triple := r.steps.map Step.conclusion++/-- The checker, with the "is asserted" test left abstract so that the list+version and the hashed version are the same function. -/+def checkRefutationWith (inG : Triple → Bool) (r : Refutation) : Bool :=+ checkAllL inG r.steps [] &&+ checkRefuteStep (fun t => inG t || decide (t ∈ prefixConclusions r)) r.final++/-- The kernel-runnable checker. `decide (t ∈ G)` walks the list, so this one is+linear in the size of the asserted graph per premise. The witness file uses it+because the kernel can run it; a caller with a real ontology should not. -/+def checkRefutation (G : List Triple) (r : Refutation) : Bool :=+ checkRefutationWith (fun t => decide (t ∈ G)) r++/-- The checker the CLI runs. Exactly what is hashed, and nothing more: the+ASSERTED graph, which is the part that is large. The derivation prefix is still+scanned as a list, so the check is quadratic in the NUMBER OF STEPS in the+refutation. That is deliberate rather than overlooked. A refutation carries only+the steps needed to reach one contradiction, which is a handful of `rdfs9` hops+down a subclass chain, and buying a hash table for a list of four would cost+more than it saves. A caller who writes thousand-step refutations will notice,+and should say so. -/+def checkRefutationFast (G : List Triple) (r : Refutation) : Bool :=+ let gset := Std.HashSet.ofList G+ checkRefutationWith (fun t => gset.contains t) r++/-! ## Soundness -/++theorem checkAllL_sound {G : List Triple} {P : Interp → Prop} {inG : Triple → Bool}+ (hP : ∀ I, P I → Model I G) (hG : ∀ t, inG t = true → t ∈ G) :+ ∀ (steps : List Step) (derived : List Triple),+ (∀ t ∈ derived, EntailsIn P t) →+ checkAllL inG steps derived = true →+ ∀ st ∈ steps, EntailsIn P st.conclusion := by+ intro steps+ induction steps with+ | nil =>+ intro _ _ _ st hst+ simp at hst+ | cons st rest ih =>+ intro derived hD h st' hst'+ simp only [checkAllL, Bool.and_eq_true] at h+ obtain ⟨h1, h2⟩ := h+ have hD' : ∀ t, decide (t ∈ derived) = true → EntailsIn P t := by+ intro t ht+ exact hD t (of_decide_eq_true ht)+ have hst : EntailsIn P st.conclusion := checkStep_sound hP hG hD' h1+ have hD'' : ∀ t ∈ st.conclusion :: derived, EntailsIn P t := by+ intro t ht+ rcases List.mem_cons.mp ht with rfl | ht+ · exact hst+ · exact hD t ht+ rcases List.mem_cons.mp hst' with rfl | hmem+ · exact hst+ · exact ih _ hD'' h2 st' hmem++/-- The contradiction step, discharged against `RefuteConditions.dw`. -/+theorem checkRefuteStep_sound {G : List Triple} {k : Triple → Bool} {rs : RefuteStep}+ (hk : ∀ t, k t = true → EntailsIn (RModel G) t)+ (h : checkRefuteStep k rs = true) : Unsat G := by+ obtain ⟨rule, premises⟩ := rs+ unfold checkRefuteStep at h+ dsimp only at h+ cases rule+ case caxDw =>+ rcases premises with+ _ | ⟨⟨c1, dw, c2⟩, _ | ⟨⟨x, t1, c1'⟩, _ | ⟨⟨x', t2, c2'⟩, _ | _⟩⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, rfl, rfl, rfl, rfl, h1, h2, h3⟩ := h+ intro I hI+ exact hI.2.dw _ _ (hk _ h1 I hI) _ (hk _ h2 I hI) (hk _ h3 I hI)++/-- **The theorem the refutation checker is trusted for.** An accepted+refutation means no interpretation models `G` and respects disjointness.++Conditional on exactly one thing, and it is named in the statement rather than+in a footnote: the reading of `owl:disjointWith` given by `RefuteConditions`.+Drop that reading and the graph has models again, `saturated` among them. -/+theorem refutation_sound_with {G : List Triple} {inG : Triple → Bool}+ (hG : ∀ t, inG t = true → t ∈ G) (r : Refutation)+ (h : checkRefutationWith inG r = true) : Unsat G := by+ unfold checkRefutationWith at h+ simp only [Bool.and_eq_true] at h+ obtain ⟨h1, h2⟩ := h+ have hsteps : ∀ st ∈ r.steps, EntailsIn (RModel G) st.conclusion :=+ checkAllL_sound (P := RModel G) (fun _ hI => hI.1) hG r.steps [] (by intro t ht; simp at ht) h1+ refine checkRefuteStep_sound (k := fun t => inG t || decide (t ∈ prefixConclusions r)) ?_ h2+ intro t ht+ simp only [Bool.or_eq_true, decide_eq_true_eq] at ht+ rcases ht with hx | hx+ · exact fun I hI => hI.1.facts t (hG t hx)+ · obtain ⟨st, hst, rfl⟩ := List.mem_map.mp hx+ exact hsteps st hst++/-- The kernel-runnable checker is sound. -/+theorem refutation_sound (G : List Triple) (r : Refutation)+ (h : checkRefutation G r = true) : Unsat G :=+ refutation_sound_with (fun _ ht => of_decide_eq_true ht) r h++/-- The hashed checker the CLI runs is sound, by the same theorem. -/+theorem refutation_fast_sound (G : List Triple) (r : Refutation)+ (h : checkRefutationFast G r = true) : Unsat G := by+ refine refutation_sound_with (inG := fun t => (Std.HashSet.ofList G).contains t) ?_ r h+ intro t ht+ rw [Std.HashSet.contains_ofList] at ht+ simpa using ht++/-! ## What a refutation costs the triple certificates over the same graph -/++/-- Once `G` is refuted, every triple has the disjointness-aware warrant. -/+theorem unsat_entails_everything {G : List Triple} (h : Unsat G) (t : Triple) :+ EntailsIn (RModel G) t := fun I hI => absurd hI (h I)++/-- **Why `oo-refute guard` refuses.** Over a refuted graph, EVERY conclusion of+EVERY list of steps already has the disjointness-aware warrant, whether the+checker accepted the certificate or not, whether the steps are derivations or+forgeries. Running the derivation checker on such a graph therefore establishes+nothing that was not already true of an empty file. -/+theorem a_certificate_adds_nothing_when_the_graph_is_refuted {G : List Triple}+ (h : Unsat G) (steps : List Step) :+ ∀ st ∈ steps, EntailsIn (RModel G) st.conclusion :=+ fun st _ => unsat_entails_everything h st.conclusion++/-! ## The replacement for the lost witness, in its general form++`saturated_is_a_model` is not available here, so the non-vacuity of+`refutation_sound` has to be re-earned. If nothing ever satisfied `RModel G`,+`Unsat G` would hold for every graph and the theorem above would say nothing.++`joint_model_of_closure` is the general shape of the answer, and it is stated+without mentioning any particular condition of `Model`, so it does not move when+`Semantics.lean` gains a rule: hand it ANY triple-predicate `D` whose Herbrand+interpretation models `G`, plus the fact that `D` contains no disjointness+violation, and it hands back a joint model. `RefuteWitness.lean` supplies such a+`D` for an arbitrary graph, by induction, and discharges it concretely. -/++/-- Terms denote themselves and a property relates exactly the pairs the+predicate `D` holds of. The list-valued `herbrand` of `Witness.lean` is the+special case `D t := t ∈ H`, and the predicate version is what lets the closure+of an infinite or inductively defined set be used. -/+def herbrandP (D : Triple → Prop) : Interp where+ D := Term+ ι := id+ iext := fun p x y => D ⟨x, p, y⟩++@[simp] theorem herbrandP_iext (D : Triple → Prop) (p x y : Term) :+ (herbrandP D).iext p x y ↔ D ⟨x, p, y⟩ := Iff.rfl++@[simp] theorem herbrandP_sat (D : Triple → Prop) (t : Triple) :+ (herbrandP D).sat t ↔ D t := Iff.rfl++@[simp] theorem herbrandP_cext (D : Triple → Prop) (c x : Term) :+ (herbrandP D).cext c x ↔ D ⟨x, V.type, c⟩ := Iff.rfl++/-- The finite-list special case. This is `Witness.lean`'s `herbrand` with the+membership predicate written through `herbrandP`, definitionally the same+interpretation, and it is spelled again here so that this layer's witnesses+depend on `Semantics.lean` and nothing else. -/+def herbrandL (H : List Triple) : Interp := herbrandP (fun t => t ∈ H)++@[simp] theorem herbrandL_sat (H : List Triple) (t : Triple) :+ (herbrandL H).sat t ↔ t ∈ H := Iff.rfl++@[simp] theorem herbrandL_cext (H : List Triple) (c x : Term) :+ (herbrandL H).cext c x ↔ (⟨x, V.type, c⟩ : Triple) ∈ H := Iff.rfl++/-- **A closure with no disjointness violation is a joint model.** -/+theorem joint_model_of_closure {G : List Triple} {D : Triple → Prop}+ (hD : Model (herbrandP D) G)+ (hdw : ∀ c1 c2 x, D ⟨c1, RV.disjointWith, c2⟩ → D ⟨x, V.type, c1⟩ →+ D ⟨x, V.type, c2⟩ → False) :+ ∃ I : Interp, Model I G ∧ RefuteConditions I :=+ ⟨herbrandP D, hD, ⟨fun a b hab x h1 h2 => hdw a b x hab h1 h2⟩⟩++/-- A graph with a joint model is not refutable, so `refutation_sound` is not a+theorem about an empty model class. -/+theorem not_unsat_of_joint_model {G : List Triple}+ (h : ∃ I : Interp, Model I G ∧ RefuteConditions I) : ¬ Unsat G := by+ obtain ⟨I, hM, hR⟩ := h+ intro hu+ exact hu I ⟨hM, hR⟩++/-! ## Reading a refutation file++Not part of the proof. A parse error is a rejected file, never an accepted+refutation. -/+namespace RefuteParse++def version : String := "oo-refute/1"++/-- The version marker, as it may arrive. A file written on Windows ends its+lines with a carriage return and the marker would then never match. Nothing+else in the format is trimmed: a term's spelling is its identity, and stripping+whitespace from one would be a silent rewrite of the certificate. -/+def isVersionLine (s : String) : Bool := s == version || s == version ++ "\r"++/-- Three tab fields at a time into triples, as `Parse.groupTriples` does for+the derivation format. -/+def groupTriples : List String → Option (List Triple)+ | [] => some []+ | s :: p :: o :: rest => (groupTriples rest).map (⟨s, p, o⟩ :: ·)+ | _ => none++/-- Parse one contradiction line, already split on tabs and with the leading+`refute` removed. An unimplemented clash rule gets its own message: naming it+"bad syntax" would hide the real answer, which is that the checker has no+condition for that rule and cannot judge a refutation citing it. -/+def refuteStepOf (fields : List String) : Except String RefuteStep :=+ match fields with+ | rule :: rest =>+ match RefuteRule.ofName? rule with+ | none =>+ .error s!"unknown or unimplemented clash rule '{rule}'. This checker implements \+ {String.intercalate ", " (RefuteRule.all.map RefuteRule.name)} and nothing else; \+ the other OWL 2 RL clash rules have no semantic condition here, so a refutation \+ citing one cannot be judged and is refused rather than guessed at."+ | some r =>+ match groupTriples rest with+ | some ps => .ok ⟨r, ps⟩+ | none => .error "the premises of the contradiction step are not whole triples"+ | _ => .error "the contradiction step names no rule"++def stepOf? (fields : List String) : Option Step :=+ match fields with+ | rule :: s :: p :: o :: prem =>+ match Rule.ofName? rule, groupTriples prem with+ | some r, some ps => some ⟨r, ps, ⟨s, p, o⟩⟩+ | _, _ => none+ | _ => none++/-- `oo-refute/1`, then derivation steps, then exactly one `refute` line, last. -/+def parseRefutation (content : String) : Except String Refutation := do+ let lines := (content.splitOn "\n").filter (fun l => !l.isEmpty)+ match lines with+ | [] => throw "refutation: the file is empty; expected the line 'oo-refute/1'"+ | header :: body =>+ if !isVersionLine header then+ throw s!"refutation: first line is '{header}', expected '{version}'. \+ A derivations.tsv is not a refutation and is refused here on purpose."+ let mut steps : Array Step := #[]+ let mut final : Option RefuteStep := none+ let mut n := 1+ for line in body do+ n := n + 1+ if final.isSome then+ throw s!"refutation line {n}: the contradiction step must be the last line"+ match line.splitOn "\t" with+ | "refute" :: rest =>+ match refuteStepOf rest with+ | .ok rs => final := some rs+ | .error e => throw s!"refutation line {n}: {e}"+ | fields =>+ match stepOf? fields with+ | some st => steps := steps.push st+ | none => throw s!"refutation line {n}: bad derivation step; expected \+ 'rule TAB s TAB p TAB o' then premises in whole triples"+ match final with+ | some rs => return ⟨steps.toList, rs⟩+ | none => throw "refutation: no 'refute' line. A refutation must reach a \+ contradiction; a file of derivations alone proves nothing here."++end RefuteParse++/-! ## Axioms, pinned++The same tripwire `Soundness.lean` and `Horn.lean` carry. A `sorry` or a+`native_decide` under any of these fails the build here. `joint_model_of_closure`+needs neither choice nor quotients: it is a construction.++The list checker needs no choice. The hashed one does, and only because+`Std.HashSet.contains_ofList` does. A SHORTER footprint than the house one is+the safe direction; a longer one is the alarm. -/++/-- info: 'OOCert.refutation_sound' depends on axioms: [propext, Quot.sound] -/+#guard_msgs in+#print axioms refutation_sound++/-- info: 'OOCert.refutation_fast_sound' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms refutation_fast_sound++/-- info: 'OOCert.a_certificate_adds_nothing_when_the_graph_is_refuted' does not depend on any axioms -/+#guard_msgs in+#print axioms a_certificate_adds_nothing_when_the_graph_is_refuted++/-- info: 'OOCert.joint_model_of_closure' does not depend on any axioms -/+#guard_msgs in+#print axioms joint_model_of_closure++end OOCertdiff --git a/lean/OOCert/RefuteWitness.lean b/lean/OOCert/RefuteWitness.leannew file mode 100644index 00000000..97d193d4--- /dev/null+++ b/lean/OOCert/RefuteWitness.lean@@ -0,0 +1,569 @@+import OOCert.Refute++/-!+# Witnesses for the refutation layer++`refutation_sound` says an accepted refutation means `Unsat G`. That claim is+worth nothing on its own, and it can be hollow in a way the derivation checker's+soundness theorem cannot be.++`Unsat G` means "no interpretation satisfies both `Model I G` and+`RefuteConditions I`". If NOTHING ever satisfied both, `Unsat G` would hold of+every graph, the checker could accept anything, and `refutation_sound` would+still be a theorem. `lean/OOCert/Witness.lean` closes the matching hole for the+derivation checker with `saturated_is_a_model`, which exhibits a model of an+arbitrary graph. That route is closed here by construction: disjointness is a+NEGATIVE condition and the saturated interpretation, which puts everything in+every class, violates it. The witness has to be rebuilt, not reused.++| theorem | says |+|---|---|+| `closure_is_a_model` | the OWL-RL closure of ANY graph, read as a Herbrand interpretation, is a model of it |+| `Der_sound` | that closure contains only entailed triples, so it is the closure and not a junk superset |+| `no_violation_means_a_joint_model` | a graph whose closure has no disjointness violation HAS a model respecting disjointness |+| `unsat_means_a_violation` | and the converse: refutability is exactly a violation in the closure |+| `graze_is_refuted` | a concrete graph is refuted, through a derived type rather than an asserted one |+| `feed_is_not_refuted` | a concrete graph that HAS a disjointness axiom is not refutable, so the checker's rejections are not an accident |+| `the_checker_rejects_the_attempt_on_the_consistent_graph` | and the checker really does reject it |+| six `rejects_*` theorems | six ways to forge a refutation, each caught |+| `an_ordinary_certificate_is_worthless_over_the_refuted_graph` | the explosion, stated for the graph above |+| `and_the_old_verdict_does_not_notice` | and `Entails` does not notice, which is the trap |++## The one hypothesis the general theorem carries, named rather than hidden++`closure_is_a_model` needs `∀ a b, Der G ⟨a, owl:sameAs, b⟩ → a = b`. Every other+semantic condition is a closure rule and becomes a constructor of `Der`, but+`Conditions.same` is not a closure rule: it says the denotations of two terms+coincide, and in a Herbrand interpretation a term denotes itself, so two+different spellings cannot be equal. A graph whose closure asserts an identity+between distinct terms therefore needs a quotient of the term domain, which is a+larger construction and is NOT done here. The hypothesis is an explicit argument+of every theorem that needs it, and both concrete graphs discharge it by+containing no `owl:sameAs` at all.+-/+namespace OOCert++/-! ## The closure of a graph, as an inductive predicate++One constructor per condition of `Model`, `Conditions.same` excepted. Read it as+the definition of "the semantics forces this triple": `Der_sound` proves it+derives nothing that is not entailed, and `closure_is_a_model` proves it derives+everything a model must contain.++The pair matters. Without `Der_sound` the predicate could be everything, which+would make `no_violation_means_a_joint_model` vacuous because no graph would+satisfy its hypothesis. Without `closure_is_a_model` it could be nothing, and the+theorem would be about an interpretation that is not a model. -/+inductive Der (G : List Triple) : Triple → Prop+ | base {t : Triple} : t ∈ G → Der G t+ | sc_sub {a b x : Term} :+ Der G ⟨a, V.subClassOf, b⟩ → Der G ⟨x, V.type, a⟩ → Der G ⟨x, V.type, b⟩+ | sc_trans {a b c : Term} :+ Der G ⟨a, V.subClassOf, b⟩ → Der G ⟨b, V.subClassOf, c⟩ → Der G ⟨a, V.subClassOf, c⟩+ | sp_sub {a b x y : Term} :+ Der G ⟨a, V.subPropertyOf, b⟩ → Der G ⟨x, a, y⟩ → Der G ⟨x, b, y⟩+ | sp_trans {a b c : Term} :+ Der G ⟨a, V.subPropertyOf, b⟩ → Der G ⟨b, V.subPropertyOf, c⟩ →+ Der G ⟨a, V.subPropertyOf, c⟩+ | dom {p c x y : Term} : Der G ⟨p, V.domain, c⟩ → Der G ⟨x, p, y⟩ → Der G ⟨x, V.type, c⟩+ | rng {p c x y : Term} : Der G ⟨p, V.range, c⟩ → Der G ⟨x, p, y⟩ → Der G ⟨y, V.type, c⟩+ | trp {p x y z : Term} :+ Der G ⟨p, V.type, V.transitiveProperty⟩ → Der G ⟨x, p, y⟩ → Der G ⟨y, p, z⟩ →+ Der G ⟨x, p, z⟩+ | symp {p x y : Term} :+ Der G ⟨p, V.type, V.symmetricProperty⟩ → Der G ⟨x, p, y⟩ → Der G ⟨y, p, x⟩+ | inv1 {p q x y : Term} : Der G ⟨p, V.inverseOf, q⟩ → Der G ⟨x, p, y⟩ → Der G ⟨y, q, x⟩+ | inv2 {p q x y : Term} : Der G ⟨p, V.inverseOf, q⟩ → Der G ⟨y, q, x⟩ → Der G ⟨x, p, y⟩+ | eqc1 {a b : Term} : Der G ⟨a, V.equivalentClass, b⟩ → Der G ⟨a, V.subClassOf, b⟩+ | eqc2 {a b : Term} : Der G ⟨a, V.equivalentClass, b⟩ → Der G ⟨b, V.subClassOf, a⟩+ | eqp1 {a b : Term} : Der G ⟨a, V.equivalentProperty, b⟩ → Der G ⟨a, V.subPropertyOf, b⟩+ | eqp2 {a b : Term} : Der G ⟨a, V.equivalentProperty, b⟩ → Der G ⟨b, V.subPropertyOf, a⟩+ | svf {r p c x y : Term} :+ Der G ⟨r, V.onProperty, p⟩ → Der G ⟨r, V.someValuesFrom, c⟩ → Der G ⟨x, p, y⟩ →+ Der G ⟨y, V.type, c⟩ → Der G ⟨x, V.type, r⟩+ | avf {r p c x y : Term} :+ Der G ⟨r, V.onProperty, p⟩ → Der G ⟨r, V.allValuesFrom, c⟩ → Der G ⟨x, V.type, r⟩ →+ Der G ⟨x, p, y⟩ → Der G ⟨y, V.type, c⟩+ | hv1 {r p v x : Term} :+ Der G ⟨r, V.onProperty, p⟩ → Der G ⟨r, V.hasValue, v⟩ → Der G ⟨x, V.type, r⟩ →+ Der G ⟨x, p, v⟩+ | hv2 {r p v x : Term} :+ Der G ⟨r, V.onProperty, p⟩ → Der G ⟨r, V.hasValue, v⟩ → Der G ⟨x, p, v⟩ →+ Der G ⟨x, V.type, r⟩+ | svf_sc {c1 c2 p y1 y2 : Term} :+ Der G ⟨c1, V.someValuesFrom, y1⟩ → Der G ⟨c1, V.onProperty, p⟩ →+ Der G ⟨c2, V.someValuesFrom, y2⟩ → Der G ⟨c2, V.onProperty, p⟩ →+ Der G ⟨y1, V.subClassOf, y2⟩ → Der G ⟨c1, V.subClassOf, c2⟩+ | svf_sp {c1 c2 p1 p2 y : Term} :+ Der G ⟨c1, V.someValuesFrom, y⟩ → Der G ⟨c1, V.onProperty, p1⟩ →+ Der G ⟨c2, V.someValuesFrom, y⟩ → Der G ⟨c2, V.onProperty, p2⟩ →+ Der G ⟨p1, V.subPropertyOf, p2⟩ → Der G ⟨c1, V.subClassOf, c2⟩+ | avf_sc {c1 c2 p y1 y2 : Term} :+ Der G ⟨c1, V.allValuesFrom, y1⟩ → Der G ⟨c1, V.onProperty, p⟩ →+ Der G ⟨c2, V.allValuesFrom, y2⟩ → Der G ⟨c2, V.onProperty, p⟩ →+ Der G ⟨y1, V.subClassOf, y2⟩ → Der G ⟨c1, V.subClassOf, c2⟩+ /-- The reversed one. `scm-avf2` concludes `c2 rdfs:subClassOf c1`. -/+ | avf_sp {c1 c2 p1 p2 y : Term} :+ Der G ⟨c1, V.allValuesFrom, y⟩ → Der G ⟨c1, V.onProperty, p1⟩ →+ Der G ⟨c2, V.allValuesFrom, y⟩ → Der G ⟨c2, V.onProperty, p2⟩ →+ Der G ⟨p1, V.subPropertyOf, p2⟩ → Der G ⟨c2, V.subClassOf, c1⟩+ | dom_sc {p c1 c2 : Term} :+ Der G ⟨p, V.domain, c1⟩ → Der G ⟨c1, V.subClassOf, c2⟩ → Der G ⟨p, V.domain, c2⟩+ | dom_sp {p1 p2 c : Term} :+ Der G ⟨p2, V.domain, c⟩ → Der G ⟨p1, V.subPropertyOf, p2⟩ → Der G ⟨p1, V.domain, c⟩+ | rng_sc {p c1 c2 : Term} :+ Der G ⟨p, V.range, c1⟩ → Der G ⟨c1, V.subClassOf, c2⟩ → Der G ⟨p, V.range, c2⟩+ | rng_sp {p1 p2 c : Term} :+ Der G ⟨p2, V.range, c⟩ → Der G ⟨p1, V.subPropertyOf, p2⟩ → Der G ⟨p1, V.range, c⟩+ | int {c l x : Term} {ms : List Term} :+ (⟨c, V.intersectionOf, l⟩ : Triple) ∈ G → Chain G l ms →+ (∀ m ∈ ms, Der G ⟨x, V.type, m⟩) → Der G ⟨x, V.type, c⟩+ | int2 {c l x m : Term} {ms : List Term} :+ (⟨c, V.intersectionOf, l⟩ : Triple) ∈ G → Chain G l ms →+ Der G ⟨x, V.type, c⟩ → m ∈ ms → Der G ⟨x, V.type, m⟩+ | uni {c l x m : Term} {ms : List Term} :+ (⟨c, V.unionOf, l⟩ : Triple) ∈ G → Chain G l ms →+ m ∈ ms → Der G ⟨x, V.type, m⟩ → Der G ⟨x, V.type, c⟩+ | oneOf {c l m : Term} {ms : List Term} :+ (⟨c, V.oneOf, l⟩ : Triple) ∈ G → Chain G l ms → m ∈ ms → Der G ⟨m, V.type, c⟩++/-- **The closure derives only what the semantics forces.** Every case is a+one-line appeal to the matching field of `Model`, which is what it means for the+constructors to mirror the conditions rather than to invent rules. -/+theorem Der_sound {G : List Triple} {I : Interp} (M : Model I G) :+ ∀ {t : Triple}, Der G t → I.sat t := by+ intro t h+ induction h with+ | @base _ hm => exact M.facts _ hm+ | @sc_sub a b x _ _ ih1 ih2 => exact M.conds.sc_sub _ _ ih1 _ ih2+ | @sc_trans a b c _ _ ih1 ih2 => exact M.conds.sc_trans _ _ _ ih1 ih2+ | @sp_sub a b x y _ _ ih1 ih2 => exact M.conds.sp_sub _ _ ih1 _ _ ih2+ | @sp_trans a b c _ _ ih1 ih2 => exact M.conds.sp_trans _ _ _ ih1 ih2+ | @dom p c x y _ _ ih1 ih2 => exact M.conds.dom _ _ ih1 _ _ ih2+ | @rng p c x y _ _ ih1 ih2 => exact M.conds.rng _ _ ih1 _ _ ih2+ | @trp p x y z _ _ _ ih1 ih2 ih3 => exact M.conds.trp _ ih1 _ _ _ ih2 ih3+ | @symp p x y _ _ ih1 ih2 => exact M.conds.symp _ ih1 _ _ ih2+ | @inv1 p q x y _ _ ih1 ih2 => exact (M.conds.inv _ _ ih1 _ _).mp ih2+ | @inv2 p q x y _ _ ih1 ih2 => exact (M.conds.inv _ _ ih1 _ _).mpr ih2+ | @eqc1 a b _ ih => exact (M.conds.eqc _ _ ih).1+ | @eqc2 a b _ ih => exact (M.conds.eqc _ _ ih).2+ | @eqp1 a b _ ih => exact (M.conds.eqp _ _ ih).1+ | @eqp2 a b _ ih => exact (M.conds.eqp _ _ ih).2+ | @svf r p c x y _ _ _ _ ih1 ih2 ih3 ih4 => exact M.conds.svf _ _ _ ih1 ih2 _ _ ih3 ih4+ | @avf r p c x y _ _ _ _ ih1 ih2 ih3 ih4 => exact M.conds.avf _ _ _ ih1 ih2 _ _ ih3 ih4+ | @hv1 r p v x _ _ _ ih1 ih2 ih3 => exact (M.conds.hv _ _ _ ih1 ih2 _).mp ih3+ | @hv2 r p v x _ _ _ ih1 ih2 ih3 => exact (M.conds.hv _ _ _ ih1 ih2 _).mpr ih3+ | @svf_sc c1 c2 p y1 y2 _ _ _ _ _ ih1 ih2 ih3 ih4 ih5 =>+ exact M.conds.svf_sc _ _ _ _ _ ih1 ih2 ih3 ih4 ih5+ | @svf_sp c1 c2 p1 p2 y _ _ _ _ _ ih1 ih2 ih3 ih4 ih5 =>+ exact M.conds.svf_sp _ _ _ _ _ ih1 ih2 ih3 ih4 ih5+ | @avf_sc c1 c2 p y1 y2 _ _ _ _ _ ih1 ih2 ih3 ih4 ih5 =>+ exact M.conds.avf_sc _ _ _ _ _ ih1 ih2 ih3 ih4 ih5+ | @avf_sp c1 c2 p1 p2 y _ _ _ _ _ ih1 ih2 ih3 ih4 ih5 =>+ exact M.conds.avf_sp _ _ _ _ _ ih1 ih2 ih3 ih4 ih5+ | @dom_sc p c1 c2 _ _ ih1 ih2 => exact M.conds.dom_sc _ _ _ ih1 ih2+ | @dom_sp p1 p2 c _ _ ih1 ih2 => exact M.conds.dom_sp _ _ _ ih1 ih2+ | @rng_sc p c1 c2 _ _ ih1 ih2 => exact M.conds.rng_sc _ _ _ ih1 ih2+ | @rng_sp p1 p2 c _ _ ih1 ih2 => exact M.conds.rng_sp _ _ _ ih1 ih2+ | @int c l x ms hin hch _ ih => exact M.int _ _ _ hin hch _ ih+ | @int2 c l x m ms hin hch _ hm ih => exact M.int2 _ _ _ hin hch _ ih _ hm+ | @uni c l x m ms hin hch hm _ ih => exact M.uni _ _ _ hin hch _ _ hm ih+ | @oneOf c l m ms hin hch hm => exact M.oneOf _ _ _ hin hch _ hm++/-- The closure is contained in every model, in particular in every finite+Herbrand model, which is how the concrete graphs below settle negatives. -/+theorem Der_entails {G : List Triple} {t : Triple} (h : Der G t) : Entails G t :=+ fun _ M => Der_sound M h++/-- **The closure of any graph is a model of it.** Each field is the matching+constructor, because that is how the constructors were chosen. The one+hypothesis is `Conditions.same`, which is not a closure rule: see the module+docstring. -/+theorem closure_is_a_model (G : List Triple)+ (hsame : ∀ a b : Term, Der G ⟨a, V.sameAs, b⟩ → a = b) :+ Model (herbrandP (Der G)) G where+ conds :=+ { sc_sub := fun _ _ h _ hx => Der.sc_sub h hx+ sc_trans := fun _ _ _ h1 h2 => Der.sc_trans h1 h2+ sp_sub := fun _ _ h _ _ hxy => Der.sp_sub h hxy+ sp_trans := fun _ _ _ h1 h2 => Der.sp_trans h1 h2+ dom := fun _ _ h _ _ hxy => Der.dom h hxy+ rng := fun _ _ h _ _ hxy => Der.rng h hxy+ trp := fun _ h _ _ _ h1 h2 => Der.trp h h1 h2+ symp := fun _ h _ _ h1 => Der.symp h h1+ inv := fun _ _ h _ _ => ⟨fun h1 => Der.inv1 h h1, fun h1 => Der.inv2 h h1⟩+ same := hsame+ eqc := fun _ _ h => ⟨Der.eqc1 h, Der.eqc2 h⟩+ eqp := fun _ _ h => ⟨Der.eqp1 h, Der.eqp2 h⟩+ svf := fun _ _ _ h1 h2 _ _ h3 h4 => Der.svf h1 h2 h3 h4+ avf := fun _ _ _ h1 h2 _ _ h3 h4 => Der.avf h1 h2 h3 h4+ hv := fun _ _ _ h1 h2 _ => ⟨fun h3 => Der.hv1 h1 h2 h3, fun h3 => Der.hv2 h1 h2 h3⟩+ svf_sc := fun _ _ _ _ _ h1 h2 h3 h4 h5 => Der.svf_sc h1 h2 h3 h4 h5+ svf_sp := fun _ _ _ _ _ h1 h2 h3 h4 h5 => Der.svf_sp h1 h2 h3 h4 h5+ avf_sc := fun _ _ _ _ _ h1 h2 h3 h4 h5 => Der.avf_sc h1 h2 h3 h4 h5+ avf_sp := fun _ _ _ _ _ h1 h2 h3 h4 h5 => Der.avf_sp h1 h2 h3 h4 h5+ dom_sc := fun _ _ _ h1 h2 => Der.dom_sc h1 h2+ dom_sp := fun _ _ _ h1 h2 => Der.dom_sp h1 h2+ rng_sc := fun _ _ _ h1 h2 => Der.rng_sc h1 h2+ rng_sp := fun _ _ _ h1 h2 => Der.rng_sp h1 h2 }+ facts := fun _ ht => Der.base ht+ int := fun _ _ _ hin hch _ hall => Der.int hin hch hall+ int2 := fun _ _ _ hin hch _ hx _ hm => Der.int2 hin hch hx hm+ uni := fun _ _ _ hin hch _ _ hm hx => Der.uni hin hch hm hx+ oneOf := fun _ _ _ hin hch _ hm => Der.oneOf hin hch hm++/-- **The replacement for `saturated_is_a_model`.** A graph whose closure has no+disjointness violation has a model that satisfies `Model` AND `RefuteConditions`,+so `refutation_sound` is not a theorem about an empty model class.++Conditional on the `owl:sameAs` hypothesis, which is stated and not buried. -/+theorem no_violation_means_a_joint_model (G : List Triple)+ (hsame : ∀ a b : Term, Der G ⟨a, V.sameAs, b⟩ → a = b)+ (hdw : ∀ c1 c2 x : Term, Der G ⟨c1, RV.disjointWith, c2⟩ → Der G ⟨x, V.type, c1⟩ →+ Der G ⟨x, V.type, c2⟩ → False) :+ ∃ I : Interp, Model I G ∧ RefuteConditions I :=+ joint_model_of_closure (closure_is_a_model G hsame) hdw++/-- The converse, and the more useful direction in practice: if a graph IS+refutable then its closure contains a disjointness violation. So `cax-dw` is not+merely sound for this fragment, it is the only way to be unsatisfiable in it, and+a consumer who finds no violation has a positive result rather than a failure to+find one. Same `owl:sameAs` hypothesis. -/+theorem unsat_means_a_violation (G : List Triple)+ (hsame : ∀ a b : Term, Der G ⟨a, V.sameAs, b⟩ → a = b) (h : Unsat G) :+ ∃ c1 c2 x : Term, Der G ⟨c1, RV.disjointWith, c2⟩ ∧ Der G ⟨x, V.type, c1⟩ ∧+ Der G ⟨x, V.type, c2⟩ :=+ Classical.byContradiction fun hno =>+ not_unsat_of_joint_model+ (no_violation_means_a_joint_model G hsame+ (fun c1 c2 x h1 h2 h3 => hno ⟨c1, c2, x, h1, h2, h3⟩)) h++/-! ## A fragment in which a plain Herbrand model is easy to exhibit++Both concrete graphs below use only `rdf:type`, `rdfs:subClassOf` and+`owl:disjointWith`. In that fragment every semantic condition except `sc_sub`+and `sc_trans` has a premise no triple can supply, so a list closed under those+two is a model of everything it contains. `Plain` packages the four side+conditions in a form `decide` can settle over a concrete list. -/++/-- The side conditions, all decidable over a concrete list. `scClosed` and+`scTrans` are written over pairs of triples of `H` rather than over arbitrary+terms for exactly that reason. -/+structure Plain (H : List Triple) : Prop where+ vocab : ∀ t ∈ H, t.p = V.type ∨ t.p = V.subClassOf ∨ t.p = RV.disjointWith+ noMeta : ∀ t ∈ H, ¬(t.p = V.type ∧ (t.o = V.transitiveProperty ∨ t.o = V.symmetricProperty))+ scClosed : ∀ t ∈ H, ∀ u ∈ H, t.p = V.subClassOf → u.p = V.type → u.o = t.s →+ (⟨u.s, V.type, t.o⟩ : Triple) ∈ H+ scTrans : ∀ t ∈ H, ∀ u ∈ H, t.p = V.subClassOf → u.p = V.subClassOf → u.s = t.o →+ (⟨t.s, V.subClassOf, u.o⟩ : Triple) ∈ H++namespace Plain++/-- A predicate outside the fragment has an empty extension in `H`. -/+theorem absent {H : List Triple} (hP : Plain H) (p : Term) (h1 : p ≠ V.type)+ (h2 : p ≠ V.subClassOf) (h3 : p ≠ RV.disjointWith) (s o : Term) :+ (⟨s, p, o⟩ : Triple) ∉ H := by+ intro hm+ rcases hP.vocab _ hm with h | h | h+ · exact h1 h+ · exact h2 h+ · exact h3 h++theorem notTrans {H : List Triple} (hP : Plain H) (p : Term) :+ (⟨p, V.type, V.transitiveProperty⟩ : Triple) ∉ H :=+ fun hm => hP.noMeta _ hm ⟨rfl, Or.inl rfl⟩++theorem notSymm {H : List Triple} (hP : Plain H) (p : Term) :+ (⟨p, V.type, V.symmetricProperty⟩ : Triple) ∉ H :=+ fun hm => hP.noMeta _ hm ⟨rfl, Or.inr rfl⟩++/-- The Herbrand interpretation of a `Plain` list models every graph contained+in it. -/+theorem model {H G : List Triple} (hP : Plain H) (hGH : ∀ t ∈ G, t ∈ H) :+ Model (herbrandL H) G where+ conds :=+ { sc_sub := fun a b hab x hx => hP.scClosed ⟨a, V.subClassOf, b⟩ hab ⟨x, V.type, a⟩ hx rfl rfl rfl+ sc_trans := fun a b c hab hbc =>+ hP.scTrans ⟨a, V.subClassOf, b⟩ hab ⟨b, V.subClassOf, c⟩ hbc rfl rfl rfl+ sp_sub := fun a b hab =>+ absurd hab (hP.absent V.subPropertyOf (by decide) (by decide) (by decide) a b)+ sp_trans := fun a b _ hab =>+ absurd hab (hP.absent V.subPropertyOf (by decide) (by decide) (by decide) a b)+ dom := fun p c h => absurd h (hP.absent V.domain (by decide) (by decide) (by decide) p c)+ rng := fun p c h => absurd h (hP.absent V.range (by decide) (by decide) (by decide) p c)+ trp := fun p h => absurd h (hP.notTrans p)+ symp := fun p h => absurd h (hP.notSymm p)+ inv := fun p q h => absurd h (hP.absent V.inverseOf (by decide) (by decide) (by decide) p q)+ same := fun a b h => absurd h (hP.absent V.sameAs (by decide) (by decide) (by decide) a b)+ eqc := fun a b h =>+ absurd h (hP.absent V.equivalentClass (by decide) (by decide) (by decide) a b)+ eqp := fun a b h =>+ absurd h (hP.absent V.equivalentProperty (by decide) (by decide) (by decide) a b)+ svf := fun r p _ h => absurd h (hP.absent V.onProperty (by decide) (by decide) (by decide) r p)+ avf := fun r p _ h => absurd h (hP.absent V.onProperty (by decide) (by decide) (by decide) r p)+ hv := fun r p _ h => absurd h (hP.absent V.onProperty (by decide) (by decide) (by decide) r p)+ svf_sc := fun c1 _ _ y1 _ h =>+ absurd h (hP.absent V.someValuesFrom (by decide) (by decide) (by decide) c1 y1)+ svf_sp := fun c1 _ _ _ y h =>+ absurd h (hP.absent V.someValuesFrom (by decide) (by decide) (by decide) c1 y)+ avf_sc := fun c1 _ _ y1 _ h =>+ absurd h (hP.absent V.allValuesFrom (by decide) (by decide) (by decide) c1 y1)+ avf_sp := fun c1 _ _ _ y h =>+ absurd h (hP.absent V.allValuesFrom (by decide) (by decide) (by decide) c1 y)+ dom_sc := fun p c1 _ h =>+ absurd h (hP.absent V.domain (by decide) (by decide) (by decide) p c1)+ dom_sp := fun _ p2 c h =>+ absurd h (hP.absent V.domain (by decide) (by decide) (by decide) p2 c)+ rng_sc := fun p c1 _ h =>+ absurd h (hP.absent V.range (by decide) (by decide) (by decide) p c1)+ rng_sp := fun _ p2 c h =>+ absurd h (hP.absent V.range (by decide) (by decide) (by decide) p2 c) }+ facts := fun t ht => hGH t ht+ int := fun c l _ hin =>+ absurd (hGH _ hin) (hP.absent V.intersectionOf (by decide) (by decide) (by decide) c l)+ int2 := fun c l _ hin =>+ absurd (hGH _ hin) (hP.absent V.intersectionOf (by decide) (by decide) (by decide) c l)+ uni := fun c l _ hin =>+ absurd (hGH _ hin) (hP.absent V.unionOf (by decide) (by decide) (by decide) c l)+ oneOf := fun c l _ hin =>+ absurd (hGH _ hin) (hP.absent V.oneOf (by decide) (by decide) (by decide) c l)++/-- The closure of `G` is inside `H`, which is what turns a `decide` over the+list into a fact about the inductive predicate. -/+theorem der_mem {H G : List Triple} (hP : Plain H) (hGH : ∀ t ∈ G, t ∈ H) {t : Triple}+ (h : Der G t) : t ∈ H :=+ Der_sound (hP.model hGH) h++end Plain++/-! ## Two concrete graphs++`graze` is refutable and `feed` is not, and they differ by one triple. Both+carry the same `owl:disjointWith` axiom and the same subclass chain, so the+difference cannot be read off the schema. -/++def rHerbivore : Term := "<http://ex.org/Herbivore>"+def rCarnivore : Term := "<http://ex.org/Carnivore>"+def rLion : Term := "<http://ex.org/Lion>"+def rLeo : Term := "<http://ex.org/leo>"++/-- Herbivore and Carnivore are disjoint, every Lion is a Carnivore, leo is a+Lion, and leo is a Herbivore. Contradictory, and NOT syntactically: the+Carnivore membership has to be derived before the clash is visible. -/+def graze : List Triple :=+ [ ⟨rHerbivore, RV.disjointWith, rCarnivore⟩,+ ⟨rLion, V.subClassOf, rCarnivore⟩,+ ⟨rLeo, V.type, rLion⟩,+ ⟨rLeo, V.type, rHerbivore⟩ ]++/-- The same ontology with the Herbivore assertion removed. Consistent. -/+def feed : List Triple :=+ [ ⟨rHerbivore, RV.disjointWith, rCarnivore⟩,+ ⟨rLion, V.subClassOf, rCarnivore⟩,+ ⟨rLeo, V.type, rLion⟩ ]++/-! ### The refutation of `graze` -/++/-- `rdfs9` premise order is `x rdf:type a`, `a rdfs:subClassOf b`. -/+def grazeStep : Step :=+ { rule := .rdfs9+ premises := [⟨rLeo, V.type, rLion⟩, ⟨rLion, V.subClassOf, rCarnivore⟩]+ conclusion := ⟨rLeo, V.type, rCarnivore⟩ }++/-- `cax-dw` premise order is `c1 owl:disjointWith c2`, `x rdf:type c1`,+`x rdf:type c2`. The third premise is the step above, not an asserted triple. -/+def grazeFinal : RefuteStep :=+ { rule := .caxDw+ premises :=+ [ ⟨rHerbivore, RV.disjointWith, rCarnivore⟩,+ ⟨rLeo, V.type, rHerbivore⟩,+ ⟨rLeo, V.type, rCarnivore⟩ ] }++def grazeRefutation : Refutation := ⟨[grazeStep], grazeFinal⟩++/-- The checker accepts it, by kernel computation rather than by assertion. -/+theorem the_checker_accepts_the_refutation :+ checkRefutation graze grazeRefutation = true := by decide++/-- **A concrete graph is refuted**, with the clash reached through an+inference. -/+theorem graze_is_refuted : Unsat graze :=+ refutation_sound graze grazeRefutation the_checker_accepts_the_refutation++/-! ### Six forgeries, each rejected++A gate that cannot fail is decoration. Each of these is a different way to lie+and each is settled by `decide`, so the rejection is computed and not claimed. -/++/-- The disjointness axiom is invented: `Herbivore owl:disjointWith Lion` is not+in the graph. -/+def forgeUnassertedAxiom : Refutation :=+ ⟨[grazeStep],+ { rule := .caxDw+ premises :=+ [ ⟨rHerbivore, RV.disjointWith, rLion⟩,+ ⟨rLeo, V.type, rHerbivore⟩,+ ⟨rLeo, V.type, rLion⟩ ] }⟩++/-- The first premise is a `rdfs:subClassOf` triple dressed as the axiom. It IS+in the graph, and it still is not a disjointness axiom. -/+def forgeWrongPredicate : Refutation :=+ ⟨[grazeStep],+ { rule := .caxDw+ premises :=+ [ ⟨rLion, V.subClassOf, rCarnivore⟩,+ ⟨rLeo, V.type, rLion⟩,+ ⟨rLeo, V.type, rCarnivore⟩ ] }⟩++/-- The two class memberships are about different individuals, which is the+whole content of `cax-dw` and the easiest thing for a hand-written engine to get+wrong. -/+def forgeTwoIndividuals : Refutation :=+ ⟨[grazeStep],+ { rule := .caxDw+ premises :=+ [ ⟨rHerbivore, RV.disjointWith, rCarnivore⟩,+ ⟨rLeo, V.type, rHerbivore⟩,+ ⟨rLion, V.type, rCarnivore⟩ ] }⟩++/-- The derivation prefix is forged: `rdfs9` does not conclude this. -/+def forgePrefix : Refutation :=+ ⟨[{ grazeStep with conclusion := ⟨rLeo, V.type, rHerbivore⟩ }], grazeFinal⟩++/-- No prefix at all, so the third premise is neither asserted nor derived. This+is the one a careless format would let through, because the triple is true. -/+def forgeMissingPrefix : Refutation := ⟨[], grazeFinal⟩++/-- The right three triples in the wrong order. Premise order is part of the+contract. -/+def forgeWrongOrder : Refutation :=+ ⟨[grazeStep],+ { rule := .caxDw+ premises :=+ [ ⟨rLeo, V.type, rHerbivore⟩,+ ⟨rHerbivore, RV.disjointWith, rCarnivore⟩,+ ⟨rLeo, V.type, rCarnivore⟩ ] }⟩++theorem rejects_an_unasserted_axiom : checkRefutation graze forgeUnassertedAxiom = false := by+ decide+theorem rejects_a_predicate_that_is_not_disjointWith :+ checkRefutation graze forgeWrongPredicate = false := by decide+theorem rejects_two_different_individuals : checkRefutation graze forgeTwoIndividuals = false := by+ decide+theorem rejects_a_forged_derivation_prefix : checkRefutation graze forgePrefix = false := by decide+theorem rejects_a_premise_that_was_never_derived :+ checkRefutation graze forgeMissingPrefix = false := by decide+theorem rejects_premises_in_the_wrong_order : checkRefutation graze forgeWrongOrder = false := by+ decide++/-! ### `feed` is not refutable, and that is proved rather than observed -/++/-- The closure of `feed`, written out. One derived triple: leo is a Carnivore. -/+def feedClosure : List Triple := ⟨rLeo, V.type, rCarnivore⟩ :: feed++theorem feed_closure_is_plain : Plain feedClosure := by+ constructor <;> decide++theorem feed_inside_its_closure : ∀ t ∈ feed, t ∈ feedClosure := by decide++/-- No `owl:sameAs` anywhere in the closure, so the hypothesis of the general+theorem is discharged rather than assumed. -/+theorem feed_has_no_sameAs (a b : Term) (h : Der feed ⟨a, V.sameAs, b⟩) : a = b :=+ absurd (feed_closure_is_plain.der_mem feed_inside_its_closure h)+ (feed_closure_is_plain.absent V.sameAs (by decide) (by decide) (by decide) a b)++/-- No individual is in both halves of the disjointness axiom, checked over the+closure by `decide` rather than by reading the file. -/+private theorem feed_closure_has_no_clash :+ ∀ t ∈ feedClosure, ∀ u ∈ feedClosure, ∀ v ∈ feedClosure,+ ¬(t.p = RV.disjointWith ∧ u.p = V.type ∧ u.o = t.s ∧+ v.p = V.type ∧ v.o = t.o ∧ v.s = u.s) := by decide++/-- **A graph with a disjointness axiom that is NOT refutable.** Without this the+refutation layer would be consistent with a checker that accepts everything. -/+theorem feed_is_not_refuted : ¬ Unsat feed := by+ refine not_unsat_of_joint_model (no_violation_means_a_joint_model feed feed_has_no_sameAs ?_)+ intro c1 c2 x h1 h2 h3+ have m1 := feed_closure_is_plain.der_mem feed_inside_its_closure h1+ have m2 := feed_closure_is_plain.der_mem feed_inside_its_closure h2+ have m3 := feed_closure_is_plain.der_mem feed_inside_its_closure h3+ exact feed_closure_has_no_clash _ m1 _ m2 _ m3 ⟨rfl, rfl, rfl, rfl, rfl, rfl⟩++/-- The attempt to refute the consistent graph, which differs from the accepted+refutation only in that `leo rdf:type Herbivore` is not available. -/+def feedAttempt : Refutation :=+ ⟨[{ rule := .rdfs9+ premises := [⟨rLeo, V.type, rLion⟩, ⟨rLion, V.subClassOf, rCarnivore⟩]+ conclusion := ⟨rLeo, V.type, rCarnivore⟩ }],+ grazeFinal⟩++/-- And the checker rejects it. Taken with `feed_is_not_refuted`, the rejection+is correct and not a limitation. -/+theorem the_checker_rejects_the_attempt_on_the_consistent_graph :+ checkRefutation feed feedAttempt = false := by decide++/-! ## The explosion, and the trap inside it++Over a refuted graph the disjointness-aware warrant is empty, so a derivation+certificate says nothing. The trap is that `certificate_sound`'s own verdict does+NOT collapse, because `Entails` quantifies over `Model I G` alone and that class+is never empty. A consumer reading `"ok":true` from `oo-cert` over a+self-contradicting ontology is reading a true sentence about a model class that+ignores disjointness. -/++def rJunk : Triple := ⟨"<http://ex.org/a>", "<http://ex.org/b>", "<http://ex.org/c>"⟩++/-- Any triple at all has the disjointness-aware warrant over `graze`. -/+theorem an_ordinary_certificate_is_worthless_over_the_refuted_graph :+ EntailsIn (RModel graze) rJunk :=+ unsat_entails_everything graze_is_refuted rJunk++def grazeClosure : List Triple := ⟨rLeo, V.type, rCarnivore⟩ :: graze++theorem graze_closure_is_plain : Plain grazeClosure := by+ constructor <;> decide++theorem graze_inside_its_closure : ∀ t ∈ graze, t ∈ grazeClosure := by decide++/-- **And the old verdict does not notice.** `graze` is refuted, yet `Entails+graze` is still a non-trivial relation: `herbrandL grazeClosure` is a model of+`graze` in which the junk triple is false. So a triple certificate over a+refuted graph checks green and means nothing, and nothing in+`certificate_sound` reports that. This is why `oo-refute guard` exists. -/+theorem the_junk_triple_is_not_in_the_closure : rJunk ∉ grazeClosure := by decide++theorem and_the_old_verdict_does_not_notice : ¬ Entails graze rJunk := fun h =>+ the_junk_triple_is_not_in_the_closure+ (h (herbrandL grazeClosure) (graze_closure_is_plain.model graze_inside_its_closure))++/-! ## Axioms, pinned -/++/-- info: 'OOCert.closure_is_a_model' does not depend on any axioms -/+#guard_msgs in+#print axioms closure_is_a_model++/-- info: 'OOCert.Der_sound' does not depend on any axioms -/+#guard_msgs in+#print axioms Der_sound++/-- info: 'OOCert.no_violation_means_a_joint_model' does not depend on any axioms -/+#guard_msgs in+#print axioms no_violation_means_a_joint_model++/-- info: 'OOCert.unsat_means_a_violation' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms unsat_means_a_violation++/-- info: 'OOCert.graze_is_refuted' depends on axioms: [propext, Quot.sound] -/+#guard_msgs in+#print axioms graze_is_refuted++/-- info: 'OOCert.feed_is_not_refuted' depends on axioms: [propext] -/+#guard_msgs in+#print axioms feed_is_not_refuted++/-- info: 'OOCert.and_the_old_verdict_does_not_notice' depends on axioms: [propext] -/+#guard_msgs in+#print axioms and_the_old_verdict_does_not_notice++end OOCertdiff --git a/lean/OOCert/Rules.lean b/lean/OOCert/Rules.leanindex 8f732517..a00fa4e8 100644--- a/lean/OOCert/Rules.lean+++ b/lean/OOCert/Rules.lean@@ -38,13 +38,34 @@ wrong order is rejected, which is a false alarm and never a false pass.| 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-int2 | `c owl:intersectionOf l`, the list chain of `l`, `x rdf:type c` | `x rdf:type m` for one member `m` || cls-uni | `c owl:unionOf l`, the list chain of `l`, `x rdf:type m` for one member `m` | `x rdf:type c` |+| cls-oo | `c owl:oneOf l`, the list chain of `l` | `m rdf:type c` for one member `m` |+| scm-svf1 | `c1 svf y1`, `c1 onProperty p`, `c2 svf y2`, `c2 onProperty p`, `y1 sc y2` | `c1 sc c2` |+| scm-svf2 | `c1 svf y`, `c1 onProperty p1`, `c2 svf y`, `c2 onProperty p2`, `p1 sp p2` | `c1 sc c2` |+| scm-avf1 | `c1 avf y1`, `c1 onProperty p`, `c2 avf y2`, `c2 onProperty p`, `y1 sc y2` | `c1 sc c2` |+| scm-avf2 | `c1 avf y`, `c1 onProperty p1`, `c2 avf y`, `c2 onProperty p2`, `p1 sp p2` | **`c2 sc c1`** |+| scm-dom1 | `p rdfs:domain c1`, `c1 sc c2` | `p rdfs:domain c2` |+| scm-dom2 | `p2 rdfs:domain c`, `p1 sp p2` | `p1 rdfs:domain c` |+| scm-rng1 | `p rdfs:range c1`, `c1 sc c2` | `p rdfs:range c2` |+| scm-rng2 | `p2 rdfs:range c`, `p1 sp p2` | `p1 rdfs:range c` |++`scm-avf2` is bold because its conclusion is the reverse of the other three+restriction-ordering rules, and a checker that got it the natural way round+would accept an unsound step. The W3C table reads+`T(?c2, rdfs:subClassOf, ?c1)`; see the `avf_sp` condition in+`Semantics.lean` and the refutation in `Witness.lean`.The list chain is the sequence `l rdf:first m₁`, `l rdf:rest l₂`,`l₂ rdf:first m₂`, `l₂ rdf:rest l₃`, … down to a node whose `rdf:rest` is`rdf:nil`. The chain and the constructor triple must be asserted, not derived,because `Model` reads lists off the asserted graph.+`cls-int2` and `cls-oo` license one conclusion per list member, so a+certificate carries one step per member, each repeating the constructor triple+and the chain. `cls-oo` has no premise beyond those two: an enumeration types+its members on schema alone.+`scm-eqc1` and `scm-eqp1` each license TWO conclusions from one premise, so acertificate carries two steps under one rule id and the checker accepts eitherconclusion. They used to emit the second under the ids `scm-eqc2` and `scm-eqp2`,@@ -57,7 +78,9 @@ inductive Rule| rdfs2 | rdfs3 | rdfs5 | rdfs7 | rdfs9 | rdfs11| prpTrp | prpSymp | prpInv1 | prpInv2 | eqSym| scmEqc1 | scmEqp1- | clsSvf1 | clsAvf | clsHv1 | clsHv2 | clsInt1 | clsUni+ | clsSvf1 | clsAvf | clsHv1 | clsHv2 | clsInt1 | clsInt2 | clsUni | clsOo+ | scmSvf1 | scmSvf2 | scmAvf1 | scmAvf2+ | scmDom1 | scmDom2 | scmRng1 | scmRng2deriving DecidableEq, Reprdef Rule.name : Rule → String@@ -68,13 +91,20 @@ def Rule.name : Rule → String| .scmEqc1 => "scm-eqc1" | .scmEqp1 => "scm-eqp1"| .clsSvf1 => "cls-svf1" | .clsAvf => "cls-avf"| .clsHv1 => "cls-hv1" | .clsHv2 => "cls-hv2"- | .clsInt1 => "cls-int1" | .clsUni => "cls-uni"+ | .clsInt1 => "cls-int1" | .clsInt2 => "cls-int2"+ | .clsUni => "cls-uni" | .clsOo => "cls-oo"+ | .scmSvf1 => "scm-svf1" | .scmSvf2 => "scm-svf2"+ | .scmAvf1 => "scm-avf1" | .scmAvf2 => "scm-avf2"+ | .scmDom1 => "scm-dom1" | .scmDom2 => "scm-dom2"+ | .scmRng1 => "scm-rng1" | .scmRng2 => "scm-rng2"def Rule.all : List Rule :=[.rdfs2, .rdfs3, .rdfs5, .rdfs7, .rdfs9, .rdfs11,.prpTrp, .prpSymp, .prpInv1, .prpInv2, .eqSym,.scmEqc1, .scmEqp1,- .clsSvf1, .clsAvf, .clsHv1, .clsHv2, .clsInt1, .clsUni]+ .clsSvf1, .clsAvf, .clsHv1, .clsHv2, .clsInt1, .clsInt2, .clsUni, .clsOo,+ .scmSvf1, .scmSvf2, .scmAvf1, .scmAvf2,+ .scmDom1, .scmDom2, .scmRng1, .scmRng2]def Rule.ofName? (s : String) : Option Rule :=Rule.all.find? (fun r => r.name == s)@@ -176,12 +206,68 @@ def checkStep (inG derived : Triple → Bool) (st : Step) : Bool :=allTyped st.conclusion.s k ms q &&decide (st.conclusion.p = V.type ∧ st.conclusion.o = c)| none => false)+ | .clsInt2, ⟨c, io, l⟩ :: ps =>+ decide (io = V.intersectionOf) && inG ⟨c, io, l⟩ &&+ (match takeChain inG l ps with+ | some (ms, [⟨x, t, c'⟩]) =>+ decide (t = V.type ∧ c' = c ∧ k ⟨x, t, c'⟩ ∧+ st.conclusion.s = x ∧ st.conclusion.p = V.type ∧ st.conclusion.o ∈ ms)+ | _ => false)| .clsUni, ⟨c, uo, l⟩ :: ps =>decide (uo = V.unionOf) && inG ⟨c, uo, l⟩ &&(match takeChain inG l ps with| some (ms, [⟨x, t, m⟩]) =>decide (t = V.type ∧ m ∈ ms ∧ k ⟨x, t, m⟩ ∧ st.conclusion = ⟨x, V.type, c⟩)| _ => false)+ | .clsOo, ⟨c, oo, l⟩ :: ps =>+ decide (oo = V.oneOf) && inG ⟨c, oo, l⟩ &&+ (match takeChain inG l ps with+ | some (ms, []) =>+ decide (st.conclusion.s ∈ ms ∧ st.conclusion.p = V.type ∧ st.conclusion.o = c)+ | _ => false)+ | .scmSvf1, [⟨c1, sv1, y1⟩, ⟨c1a, op1, p⟩, ⟨c2, sv2, y2⟩, ⟨c2a, op2, pa⟩, ⟨y1a, sc, y2a⟩] =>+ sv1 = V.someValuesFrom ∧ op1 = V.onProperty ∧ c1a = c1 ∧+ sv2 = V.someValuesFrom ∧ op2 = V.onProperty ∧ c2a = c2 ∧ pa = p ∧+ sc = V.subClassOf ∧ y1a = y1 ∧ y2a = y2 ∧+ k ⟨c1, sv1, y1⟩ ∧ k ⟨c1a, op1, p⟩ ∧ k ⟨c2, sv2, y2⟩ ∧ k ⟨c2a, op2, pa⟩ ∧+ k ⟨y1a, sc, y2a⟩ ∧+ st.conclusion = ⟨c1, V.subClassOf, c2⟩+ | .scmSvf2, [⟨c1, sv1, y⟩, ⟨c1a, op1, p1⟩, ⟨c2, sv2, ya⟩, ⟨c2a, op2, p2⟩, ⟨p1a, sp, p2a⟩] =>+ sv1 = V.someValuesFrom ∧ op1 = V.onProperty ∧ c1a = c1 ∧+ sv2 = V.someValuesFrom ∧ op2 = V.onProperty ∧ c2a = c2 ∧ ya = y ∧+ sp = V.subPropertyOf ∧ p1a = p1 ∧ p2a = p2 ∧+ k ⟨c1, sv1, y⟩ ∧ k ⟨c1a, op1, p1⟩ ∧ k ⟨c2, sv2, ya⟩ ∧ k ⟨c2a, op2, p2⟩ ∧+ k ⟨p1a, sp, p2a⟩ ∧+ st.conclusion = ⟨c1, V.subClassOf, c2⟩+ | .scmAvf1, [⟨c1, av1, y1⟩, ⟨c1a, op1, p⟩, ⟨c2, av2, y2⟩, ⟨c2a, op2, pa⟩, ⟨y1a, sc, y2a⟩] =>+ av1 = V.allValuesFrom ∧ op1 = V.onProperty ∧ c1a = c1 ∧+ av2 = V.allValuesFrom ∧ op2 = V.onProperty ∧ c2a = c2 ∧ pa = p ∧+ sc = V.subClassOf ∧ y1a = y1 ∧ y2a = y2 ∧+ k ⟨c1, av1, y1⟩ ∧ k ⟨c1a, op1, p⟩ ∧ k ⟨c2, av2, y2⟩ ∧ k ⟨c2a, op2, pa⟩ ∧+ k ⟨y1a, sc, y2a⟩ ∧+ st.conclusion = ⟨c1, V.subClassOf, c2⟩+ -- scm-avf2 concludes `c2 subClassOf c1`. The other three restriction-ordering+ -- arms conclude `c1 subClassOf c2`, and writing this one the same way would+ -- make the checker accept a step no model supports.+ | .scmAvf2, [⟨c1, av1, y⟩, ⟨c1a, op1, p1⟩, ⟨c2, av2, ya⟩, ⟨c2a, op2, p2⟩, ⟨p1a, sp, p2a⟩] =>+ av1 = V.allValuesFrom ∧ op1 = V.onProperty ∧ c1a = c1 ∧+ av2 = V.allValuesFrom ∧ op2 = V.onProperty ∧ c2a = c2 ∧ ya = y ∧+ sp = V.subPropertyOf ∧ p1a = p1 ∧ p2a = p2 ∧+ k ⟨c1, av1, y⟩ ∧ k ⟨c1a, op1, p1⟩ ∧ k ⟨c2, av2, ya⟩ ∧ k ⟨c2a, op2, p2⟩ ∧+ k ⟨p1a, sp, p2a⟩ ∧+ st.conclusion = ⟨c2, V.subClassOf, c1⟩+ | .scmDom1, [⟨p, d, c1⟩, ⟨c1a, sc, c2⟩] =>+ d = V.domain ∧ sc = V.subClassOf ∧ c1a = c1 ∧+ k ⟨p, d, c1⟩ ∧ k ⟨c1a, sc, c2⟩ ∧ st.conclusion = ⟨p, V.domain, c2⟩+ | .scmDom2, [⟨p2, d, c⟩, ⟨p1, sp, p2a⟩] =>+ d = V.domain ∧ sp = V.subPropertyOf ∧ p2a = p2 ∧+ k ⟨p2, d, c⟩ ∧ k ⟨p1, sp, p2a⟩ ∧ st.conclusion = ⟨p1, V.domain, c⟩+ | .scmRng1, [⟨p, r, c1⟩, ⟨c1a, sc, c2⟩] =>+ r = V.range ∧ sc = V.subClassOf ∧ c1a = c1 ∧+ k ⟨p, r, c1⟩ ∧ k ⟨c1a, sc, c2⟩ ∧ st.conclusion = ⟨p, V.range, c2⟩+ | .scmRng2, [⟨p2, r, c⟩, ⟨p1, sp, p2a⟩] =>+ r = V.range ∧ sp = V.subPropertyOf ∧ p2a = p2 ∧+ k ⟨p2, r, c⟩ ∧ k ⟨p1, sp, p2a⟩ ∧ st.conclusion = ⟨p1, V.range, c⟩| _, _ => false/-- Check every step in order, each seeing the conclusions of the ones before. -/diff --git a/lean/OOCert/Semantics.lean b/lean/OOCert/Semantics.leanindex eef5f57b..3206dcbd 100644--- a/lean/OOCert/Semantics.lean+++ b/lean/OOCert/Semantics.lean@@ -32,13 +32,55 @@ rule proved sound here is sound under the W3C semantics and under the OWL 2Direct Semantics translated to triples, since every model of those satisfiesthese conditions.-The two list constructors are the exception to "conditions on the-interpretation alone". `owl:intersectionOf` and `owl:unionOf` point at an RDF+The list constructors are the exception to "conditions on the interpretation+alone". `owl:intersectionOf`, `owl:unionOf` and `owl:oneOf` point at an RDFlist, and a list is a syntactic object: the W3C tables read it off the graphwith the sequence notation. `Model` therefore reads the list off the graphtoo, through `Chain`, and states the class condition relative to the graphbeing interpreted.+## Conditions that let a rule CONCLUDE a schema triple++`sc_sub` says what a `rdfs:subClassOf` triple means for class extensions. It+does not say when such a triple holds, because the interpretation of+`rdfs:subClassOf` is a primitive relation here and only the half the instance+rules use is assumed. A rule whose CONCLUSION is a schema triple therefore+needs its own condition, and `sc_trans` is the first of them: it is what lets+`rdfs11` conclude `a rdfs:subClassOf c`.++Eight more of that kind arrive with the restriction-ordering and the+domain-and-range rules (`scm-svf1`, `scm-svf2`, `scm-avf1`, `scm-avf2`,+`scm-dom1`, `scm-dom2`, `scm-rng1`, `scm-rng2`). Each is stated as exactly the+W3C rule and nothing wider, and each field below carries the verbatim rule from+OWL 2 Profiles Table 9 together with the derivation that makes it a CONSEQUENCE+of the OWL 2 RDF-Based Semantics rather than an independent assumption.++## Why the direction of that argument is the only one that is safe++A field added here SHRINKS the model class, which makes `Entails` easier to+satisfy and therefore weakens `certificate_sound` without any error appearing+anywhere. The protection is that every one of these fields is implied by the+RDF-Based Semantics conditions, so every interpretation that document admits is+still a model here. Soundness proved against this weaker set therefore still+holds under the W3C semantics. Assuming the `iff`s themselves instead would be+strictly stronger, would buy nothing any rule needs, and would put the+non-vacuity witnesses at risk, which is the observable symptom of a condition+that has gone too far.++`scm-dom1` is the one that had to be checked rather than assumed. Under RDF+Semantics `rdfs:domain` carries only the *if* direction and the rule does NOT+follow. The OWL 2 RDF-Based Semantics is stronger: in Table 5.8 the `iff` cell+spans four rows, `rdfs:domain` and `rdfs:range` among them, and it is that+`iff` the rule needs.++`scm-avf2` is the one to read twice. Its conclusion runs the other way,+`?c2 rdfs:subClassOf ?c1` where the other three conclude `?c1 rdfs:subClassOf+?c2`, because a universal restriction is antitone in its property: if `p1` is a+subproperty of `p2` then everything reachable by `p1` is reachable by `p2`, so+`all p2 y` is contained in `all p1 y` and not the other way round. `avf_sp`+below is stated in the direction the W3C table gives, and `Witness.lean` proves+the natural-looking direction is not a consequence.+## What is not hereLiteral values are terms like any other: two spellings of one value are two@@ -49,6 +91,14 @@ used.-/namespace OOCert+namespace V+/-- `owl:oneOf`, the enumeration constructor `cls-oo` reads. The rest of the+vocabulary is in `Triple.lean` and this belongs beside it; it is here because+`cls-oo` is the only rule that mentions it and the condition for that rule is+three lines below. -/+def oneOf : Term := "<http://www.w3.org/2002/07/owl#oneOf>"+end V+structure Interp whereD : Typeι : Term → D@@ -106,6 +156,128 @@ structure Conditions (I : Interp) : Prop where/-- cls-hv1 needs the forward direction, cls-hv2 the backward one. -/hv : ∀ r p v, I.iext (I.ι V.onProperty) r p → I.iext (I.ι V.hasValue) r v →∀ x, (I.cext r x ↔ I.iext p x v)+ /-- **scm-svf1.** Two existential restrictions on the SAME property, ordered+ by their fillers.++ OWL 2 Profiles, Table 9, verbatim: if `T(?c1, owl:someValuesFrom, ?y1)`,+ `T(?c1, owl:onProperty, ?p)`, `T(?c2, owl:someValuesFrom, ?y2)`,+ `T(?c2, owl:onProperty, ?p)`, `T(?y1, rdfs:subClassOf, ?y2)` then+ `T(?c1, rdfs:subClassOf, ?c2)`.++ Derivation, so that this is a consequence of the W3C semantics and not an+ extra assumption. RDF-Based Semantics Table 5.6: "(z, c) ∈ IEXT(I(+ owl:someValuesFrom)), (z, p) ∈ IEXT(I(owl:onProperty))" implies+ "ICEXT(z) = { x | ∃ y : (x, y) ∈ IEXT(p) and y ∈ ICEXT(c) }". Applying it to+ `c1` and to `c2` and Table 5.8's iff "(c1, c2) ∈ IEXT(I(rdfs:subClassOf)) iff+ c1, c2 ∈ IC, ICEXT(c1) ⊆ ICEXT(c2)" to `y1, y2` gives+ ICEXT(c1) ⊆ ICEXT(c2), and the right-to-left half of that same iff turns it+ back into the triple. -/+ svf_sc : ∀ c1 c2 p y1 y2,+ I.iext (I.ι V.someValuesFrom) c1 y1 → I.iext (I.ι V.onProperty) c1 p →+ I.iext (I.ι V.someValuesFrom) c2 y2 → I.iext (I.ι V.onProperty) c2 p →+ I.sc y1 y2 → I.sc c1 c2+ /-- **scm-svf2.** Two existential restrictions with the SAME filler, ordered+ by their properties.++ OWL 2 Profiles, Table 9, verbatim: if `T(?c1, owl:someValuesFrom, ?y)`,+ `T(?c1, owl:onProperty, ?p1)`, `T(?c2, owl:someValuesFrom, ?y)`,+ `T(?c2, owl:onProperty, ?p2)`, `T(?p1, rdfs:subPropertyOf, ?p2)` then+ `T(?c1, rdfs:subClassOf, ?c2)`.++ Derivation: Table 5.6 as above for both classes, and Table 5.8's iff+ "(p1, p2) ∈ IEXT(I(rdfs:subPropertyOf)) iff p1, p2 ∈ IP, IEXT(p1) ⊆+ IEXT(p2)". A witness reached by `p1` is reached by `p2`, so+ ICEXT(c1) ⊆ ICEXT(c2). -/+ svf_sp : ∀ c1 c2 p1 p2 y,+ I.iext (I.ι V.someValuesFrom) c1 y → I.iext (I.ι V.onProperty) c1 p1 →+ I.iext (I.ι V.someValuesFrom) c2 y → I.iext (I.ι V.onProperty) c2 p2 →+ I.sp p1 p2 → I.sc c1 c2+ /-- **scm-avf1.** The mirror of `svf_sc` for universal restrictions, and it+ runs the SAME way round: a wider filler makes a wider class.++ OWL 2 Profiles, Table 9, verbatim: if `T(?c1, owl:allValuesFrom, ?y1)`,+ `T(?c1, owl:onProperty, ?p)`, `T(?c2, owl:allValuesFrom, ?y2)`,+ `T(?c2, owl:onProperty, ?p)`, `T(?y1, rdfs:subClassOf, ?y2)` then+ `T(?c1, rdfs:subClassOf, ?c2)`.++ Derivation: Table 5.6 gives+ "ICEXT(z) = { x | ∀ y : (x, y) ∈ IEXT(p) implies y ∈ ICEXT(c) }" for a+ universal restriction. Widening `ICEXT(c)` weakens the consequent of that+ implication, so it widens `ICEXT(z)`. A universal restriction is MONOTONE in+ its filler and antitone only in its property, which is why this rule and+ `avf_sp` run in opposite directions. -/+ avf_sc : ∀ c1 c2 p y1 y2,+ I.iext (I.ι V.allValuesFrom) c1 y1 → I.iext (I.ι V.onProperty) c1 p →+ I.iext (I.ι V.allValuesFrom) c2 y2 → I.iext (I.ι V.onProperty) c2 p →+ I.sc y1 y2 → I.sc c1 c2+ /-- **scm-avf2, and the conclusion is REVERSED.**++ OWL 2 Profiles, Table 9, verbatim, and this is the quote rather than the+ pattern of its three siblings: if `T(?c1, owl:allValuesFrom, ?y)`,+ `T(?c1, owl:onProperty, ?p1)`, `T(?c2, owl:allValuesFrom, ?y)`,+ `T(?c2, owl:onProperty, ?p2)`, `T(?p1, rdfs:subPropertyOf, ?p2)` then+ **`T(?c2, rdfs:subClassOf, ?c1)`**. The other three conclude+ `T(?c1, rdfs:subClassOf, ?c2)`.++ Derivation, which reaches the same direction independently of the table.+ Table 5.6 gives ICEXT(c1) = { x | ∀ v : (x, v) ∈ IEXT(p1) implies+ v ∈ ICEXT(y) } and the same for `c2` with `p2`; `v` is Table 5.6's bound+ variable renamed, because the table spells it `y` and the rule already uses+ `?y` for the filler. Table 5.8 gives+ IEXT(p1) ⊆ IEXT(p2). Take x ∈ ICEXT(c2) and any v with (x, v) ∈ IEXT(p1);+ then (x, v) ∈ IEXT(p2), so v ∈ ICEXT(y), so x ∈ ICEXT(c1). That is+ ICEXT(c2) ⊆ ICEXT(c1), the reverse inclusion. A universal restriction is+ antitone in its property: the bigger property has more values to constrain,+ so its restriction class is the smaller one.++ Reading the direction off the pattern of the other three is a silent+ unsoundness, and `Witness.lean`'s+ `the_natural_avf2_direction_is_not_entailed` exhibits a model that refutes+ it. -/+ avf_sp : ∀ c1 c2 p1 p2 y,+ I.iext (I.ι V.allValuesFrom) c1 y → I.iext (I.ι V.onProperty) c1 p1 →+ I.iext (I.ι V.allValuesFrom) c2 y → I.iext (I.ι V.onProperty) c2 p2 →+ I.sp p1 p2 → I.sc c2 c1+ /-- **scm-dom1.** A domain may be weakened to a superclass.++ OWL 2 Profiles, Table 9, verbatim: if `T(?p, rdfs:domain, ?c1)`,+ `T(?c1, rdfs:subClassOf, ?c2)` then `T(?p, rdfs:domain, ?c2)`.++ Derivation, and this one is the reason to read Table 5.8 rather than RDF+ Semantics. RDFS alone gives domain only the *if* direction and this rule+ would NOT follow from it. The OWL 2 RDF-Based Semantics makes it an iff: the+ `iff` cell of Table 5.8 carries `rowspan="4"`, so it governs the+ `rdfs:domain` and `rdfs:range` rows as well as the two above them.+ Verbatim: "(p, c) ∈ IEXT(I(rdfs:domain)) iff p ∈ IP, c ∈ IC, ∀ x, y :+ (x, y) ∈ IEXT(p) implies x ∈ ICEXT(c)". Left to right on `c1`, then+ ICEXT(c1) ⊆ ICEXT(c2) from Table 5.8's subClassOf row, then right to left on+ `c2`. -/+ dom_sc : ∀ p c1 c2, I.iext (I.ι V.domain) p c1 → I.sc c1 c2 →+ I.iext (I.ι V.domain) p c2+ /-- **scm-dom2.** A domain is inherited by every subproperty.++ OWL 2 Profiles, Table 9, verbatim: if `T(?p2, rdfs:domain, ?c)`,+ `T(?p1, rdfs:subPropertyOf, ?p2)` then `T(?p1, rdfs:domain, ?c)`.++ Derivation: the same iff of Table 5.8 left to right on `p2`, then+ IEXT(p1) ⊆ IEXT(p2), so every pair of `p1` is a pair of `p2` and its subject+ is already in ICEXT(c), then right to left on `p1`. -/+ dom_sp : ∀ p1 p2 c, I.iext (I.ι V.domain) p2 c → I.sp p1 p2 →+ I.iext (I.ι V.domain) p1 c+ /-- **scm-rng1.** The mirror of `dom_sc`.++ OWL 2 Profiles, Table 9, verbatim: if `T(?p, rdfs:range, ?c1)`,+ `T(?c1, rdfs:subClassOf, ?c2)` then `T(?p, rdfs:range, ?c2)`. Table 5.8's+ range row differs from its domain row only in reading `y ∈ ICEXT(c)` where+ the other reads `x`. -/+ rng_sc : ∀ p c1 c2, I.iext (I.ι V.range) p c1 → I.sc c1 c2 →+ I.iext (I.ι V.range) p c2+ /-- **scm-rng2.** The mirror of `dom_sp`.++ OWL 2 Profiles, Table 9, verbatim: if `T(?p2, rdfs:range, ?c)`,+ `T(?p1, rdfs:subPropertyOf, ?p2)` then `T(?p1, rdfs:range, ?c)`. -/+ rng_sp : ∀ p1 p2 c, I.iext (I.ι V.range) p2 c → I.sp p1 p2 →+ I.iext (I.ι V.range) p1 c/-- `Chain G l ms`: the RDF list whose head node is `l` in graph `G` has themembers `ms`, read through `rdf:first` / `rdf:rest` down to `rdf:nil`. A node@@ -125,9 +297,35 @@ structure Model (I : Interp) (G : List Triple) : Prop where/-- cls-int1. -/int : ∀ c l ms, (⟨c, V.intersectionOf, l⟩ : Triple) ∈ G → Chain G l ms →∀ x, (∀ m ∈ ms, I.cext (I.ι m) x) → I.cext (I.ι c) x+ /-- **cls-int2**, the other half of what an intersection means. `int` says+ membership in every member gives membership in the class; this says+ membership in the class gives membership in each member. Only with both is+ the class extension the intersection, and only `int` was assumed before.++ RDF-Based Semantics Table 5.4, verbatim: "if s sequence of c1, …, cn ∈ IR+ then (z, s) ∈ IEXT(I(owl:intersectionOf)) iff z, c1, …, cn ∈ IC,+ ICEXT(z) = ICEXT(c1) ∩ … ∩ ICEXT(cn)". That equality has two halves. `int`+ is ⊇ and this is ⊆, so each is strictly weaker than the condition and the+ two together are still weaker, because neither asks for+ `z, c1, …, cn ∈ IC`. -/+ int2 : ∀ c l ms, (⟨c, V.intersectionOf, l⟩ : Triple) ∈ G → Chain G l ms →+ ∀ x, I.cext (I.ι c) x → ∀ m ∈ ms, I.cext (I.ι m) x/-- cls-uni. -/uni : ∀ c l ms, (⟨c, V.unionOf, l⟩ : Triple) ∈ G → Chain G l ms →∀ x m, m ∈ ms → I.cext (I.ι m) x → I.cext (I.ι c) x+ /-- **cls-oo.** Every listed member of an `owl:oneOf` enumeration is an+ instance of the enumerated class.++ RDF-Based Semantics Table 5.5, verbatim: "if s sequence of a1, …, an ∈ IR+ then (z, s) ∈ IEXT(I(owl:oneOf)) iff z ∈ IC, ICEXT(z) = { a1, …, an }".+ This field is the ⊇ half of that equality and nothing else: the class holds+ AT LEAST the listed members. The ⊆ half, that it holds no others, is what a+ rule concluding `owl:sameAs` or a clash would need, and no rule here+ concludes either, so assuming it would shrink the model class for nothing.+ `Witness.lean`'s `an_unlisted_individual_is_not_entailed` is the check that+ it really was left out. -/+ oneOf : ∀ c l ms, (⟨c, V.oneOf, l⟩ : Triple) ∈ G → Chain G l ms →+ ∀ m ∈ ms, I.cext (I.ι c) (I.ι m)/-- Entailment relative to an arbitrary class of interpretations. The soundnessproof never needs more than "every interpretation in this class models `G`", sodiff --git a/lean/OOCert/Soundness.lean b/lean/OOCert/Soundness.leanindex 4d150ab6..7d8aa5c6 100644--- a/lean/OOCert/Soundness.lean+++ b/lean/OOCert/Soundness.lean@@ -33,8 +33,8 @@ The parameter is what lets `Mixed.lean` put a built-in step and a step citing auser-supplied Horn rule in one certificate. Such a certificate is relative tothose rules, so its entailment relation quantifies over models of `G` that alsosatisfy them, and that is a smaller class. Every per-rule case below reads its-condition off `Model I G`, which such an interpretation still is, so all twenty-cases are reused with no change to what any of them proves.+condition off `Model I G`, which such an interpretation still is, so all+twenty-nine cases are reused with no change to what any of them proves.The `#guard_msgs` at the end pins the axioms the theorem depends on. If a`sorry` ever enters this file, or a `native_decide`, the build fails there.@@ -284,6 +284,126 @@ theorem checkStep_sound {inG derived : Triple → Bool} {st : Step}show I.iext (I.ι conclusion.p) (I.ι conclusion.s) (I.ι conclusion.o)rw [hp, ho]exact hc+ case clsInt2 =>+ rcases premises with _ | ⟨⟨c, io, l⟩, ps⟩+ · simp at h+ · simp only [Bool.and_eq_true, decide_eq_true_eq] at h+ obtain ⟨⟨rfl, hin⟩, hm⟩ := h+ revert hm+ cases hchain : takeChain inG l ps with+ | none =>+ intro hm+ simp at hm+ | some pr =>+ intro hm+ obtain ⟨ms, q⟩ := pr+ rcases q with _ | ⟨⟨x, t, c'⟩, _ | _⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at hm+ obtain ⟨rfl, hcc, hkx, hs, hp, ho⟩ := hm+ rw [hcc] at hkx+ have hC : Chain G l ms :=+ takeChain_sound hG ps.length ps (Nat.le_refl _) l ms _ hchain+ intro I hPI+ have M : Model I G := hP I hPI+ have hc := M.int2 c l ms (hG _ hin) hC (I.ι x) (hk _ hkx I hPI) conclusion.o ho+ show I.iext (I.ι conclusion.p) (I.ι conclusion.s) (I.ι conclusion.o)+ rw [hs, hp]+ exact hc+ case clsOo =>+ rcases premises with _ | ⟨⟨c, oo, l⟩, ps⟩+ · simp at h+ · simp only [Bool.and_eq_true, decide_eq_true_eq] at h+ obtain ⟨⟨rfl, hin⟩, hm⟩ := h+ revert hm+ cases hchain : takeChain inG l ps with+ | none =>+ intro hm+ simp at hm+ | some pr =>+ intro hm+ obtain ⟨ms, q⟩ := pr+ rcases q with _ | ⟨_, _⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at hm+ obtain ⟨hs, hp, ho⟩ := hm+ have hC : Chain G l ms :=+ takeChain_sound hG ps.length ps (Nat.le_refl _) l ms _ hchain+ intro I hPI+ have M : Model I G := hP I hPI+ have hc := M.oneOf c l ms (hG _ hin) hC conclusion.s hs+ show I.iext (I.ι conclusion.p) (I.ι conclusion.s) (I.ι conclusion.o)+ rw [hp, ho]+ exact hc+ case scmSvf1 =>+ rcases premises with+ _ | ⟨⟨c1, sv1, y1⟩, _ | ⟨⟨c1a, op1, p⟩, _ | ⟨⟨c2, sv2, y2⟩,+ _ | ⟨⟨c2a, op2, pa⟩, _ | ⟨⟨y1a, sc, y2a⟩, _ | _⟩⟩⟩⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, h1, h2, h3, h4, h5, rfl⟩ := h+ intro I hPI+ have M : Model I G := hP I hPI+ exact M.conds.svf_sc _ _ _ _ _ (hk _ h1 I hPI) (hk _ h2 I hPI) (hk _ h3 I hPI)+ (hk _ h4 I hPI) (hk _ h5 I hPI)+ case scmSvf2 =>+ rcases premises with+ _ | ⟨⟨c1, sv1, y⟩, _ | ⟨⟨c1a, op1, p1⟩, _ | ⟨⟨c2, sv2, ya⟩,+ _ | ⟨⟨c2a, op2, p2⟩, _ | ⟨⟨p1a, sp, p2a⟩, _ | _⟩⟩⟩⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, h1, h2, h3, h4, h5, rfl⟩ := h+ intro I hPI+ have M : Model I G := hP I hPI+ exact M.conds.svf_sp _ _ _ _ _ (hk _ h1 I hPI) (hk _ h2 I hPI) (hk _ h3 I hPI)+ (hk _ h4 I hPI) (hk _ h5 I hPI)+ case scmAvf1 =>+ rcases premises with+ _ | ⟨⟨c1, av1, y1⟩, _ | ⟨⟨c1a, op1, p⟩, _ | ⟨⟨c2, av2, y2⟩,+ _ | ⟨⟨c2a, op2, pa⟩, _ | ⟨⟨y1a, sc, y2a⟩, _ | _⟩⟩⟩⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, h1, h2, h3, h4, h5, rfl⟩ := h+ intro I hPI+ have M : Model I G := hP I hPI+ exact M.conds.avf_sc _ _ _ _ _ (hk _ h1 I hPI) (hk _ h2 I hPI) (hk _ h3 I hPI)+ (hk _ h4 I hPI) (hk _ h5 I hPI)+ -- The conclusion here is `c2 subClassOf c1`. `avf_sp` is stated that way round+ -- and the two must agree, so getting either one backwards fails to compile+ -- rather than shipping a rule no model supports.+ case scmAvf2 =>+ rcases premises with+ _ | ⟨⟨c1, av1, y⟩, _ | ⟨⟨c1a, op1, p1⟩, _ | ⟨⟨c2, av2, ya⟩,+ _ | ⟨⟨c2a, op2, p2⟩, _ | ⟨⟨p1a, sp, p2a⟩, _ | _⟩⟩⟩⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, h1, h2, h3, h4, h5, rfl⟩ := h+ intro I hPI+ have M : Model I G := hP I hPI+ exact M.conds.avf_sp _ _ _ _ _ (hk _ h1 I hPI) (hk _ h2 I hPI) (hk _ h3 I hPI)+ (hk _ h4 I hPI) (hk _ h5 I hPI)+ case scmDom1 =>+ rcases premises with _ | ⟨⟨p, d, c1⟩, _ | ⟨⟨c1a, sc, c2⟩, _ | _⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, rfl, h1, h2, rfl⟩ := h+ intro I hPI+ have M : Model I G := hP I hPI+ exact M.conds.dom_sc _ _ _ (hk _ h1 I hPI) (hk _ h2 I hPI)+ case scmDom2 =>+ rcases premises with _ | ⟨⟨p2, d, c⟩, _ | ⟨⟨p1, sp, p2a⟩, _ | _⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, rfl, h1, h2, rfl⟩ := h+ intro I hPI+ have M : Model I G := hP I hPI+ exact M.conds.dom_sp _ _ _ (hk _ h1 I hPI) (hk _ h2 I hPI)+ case scmRng1 =>+ rcases premises with _ | ⟨⟨p, r, c1⟩, _ | ⟨⟨c1a, sc, c2⟩, _ | _⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, rfl, h1, h2, rfl⟩ := h+ intro I hPI+ have M : Model I G := hP I hPI+ exact M.conds.rng_sc _ _ _ (hk _ h1 I hPI) (hk _ h2 I hPI)+ case scmRng2 =>+ rcases premises with _ | ⟨⟨p2, r, c⟩, _ | ⟨⟨p1, sp, p2a⟩, _ | _⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, rfl, h1, h2, rfl⟩ := h+ intro I hPI+ have M : Model I G := hP I hPI+ exact M.conds.rng_sp _ _ _ (hk _ h1 I hPI) (hk _ h2 I hPI)case clsUni =>rcases premises with _ | ⟨⟨c, uo, l⟩, ps⟩· simp at hdiff --git a/lean/OOCert/Witness.lean b/lean/OOCert/Witness.leanindex 0825e752..2d43b2f9 100644--- a/lean/OOCert/Witness.lean+++ b/lean/OOCert/Witness.lean@@ -16,7 +16,26 @@ by argument.2. **If `Entails` held of everything anyway**, soundness would still say nothing.`not_everything_is_entailed` exhibits a triple that is not entailed.-The third theorem is the one worth having. `the_old_svf_derivation_is_not_entailed` proves that the+Three later sections do the same job for the conditions the restriction-ordering and the list rules+added, and each is a PAIR: what the rule draws, proved for an arbitrary model, next to something the+same premises do not give, refuted by a model of them.++| pair | says |+|---|---|+| `the_avf2_direction_the_table_gives_is_entailed` | `scm-avf2` concludes `c2 subClassOf c1` |+| `the_natural_avf2_direction_is_not_entailed` | and `c1 subClassOf c2`, the direction the other three restriction rules run in, is refuted |+| `an_enumerated_member_is_entailed` | `cls-oo` types the members an `owl:oneOf` list names |+| `an_unlisted_individual_is_not_entailed` | and nothing else, because the condition is the "at least" half only |+| `a_member_of_the_intersection_is_entailed` | `cls-int2` takes an intersection apart |+| `membership_in_one_member_does_not_give_the_intersection` | and `cls-int1` still needs every member, so the new condition did not swallow the old one |++The `scm-avf2` pair is the one that earns its place. Three of the four restriction-ordering rules+conclude `c1 subClassOf c2` and that one concludes `c2 subClassOf c1`, so copying the pattern gives+a rule with no model behind it. Nothing downstream would notice: the certificate would check, the+Lean proof would be the only thing that failed, and here it is made to fail on purpose.++The third theorem of the original set is the one worth having.+`the_old_svf_derivation_is_not_entailed` proves that thederivation the reasoner used to make, `x rdf:type C` from `C rdfs:subClassOf (some p D)` togetherwith `x p y` and `y rdf:type D`, is **not** a consequence: there is a model of the premises in which`x` is not a `C`. So that behaviour was unsound in fact, not merely unjustified by the rule set this@@ -56,10 +75,20 @@ theorem saturated_is_a_model (G : List Triple) : Model saturated G whereeqp := fun _ _ _ => ⟨trivial, trivial⟩svf := fun _ _ _ _ _ _ _ _ _ => trivialavf := fun _ _ _ _ _ _ _ _ _ => trivial- hv := fun _ _ _ _ _ _ => Iff.intro (fun _ => trivial) (fun _ => trivial) }+ hv := fun _ _ _ _ _ _ => Iff.intro (fun _ => trivial) (fun _ => trivial)+ svf_sc := by intros; trivial+ svf_sp := by intros; trivial+ avf_sc := by intros; trivial+ avf_sp := by intros; trivial+ dom_sc := by intros; trivial+ dom_sp := by intros; trivial+ rng_sc := by intros; trivial+ rng_sp := by intros; trivial }facts := fun _ _ => trivialint := fun _ _ _ _ _ _ _ => trivial+ int2 := by intros; trivialuni := fun _ _ _ _ _ _ _ _ _ => trivial+ oneOf := by intros; trivial/-! ## Herbrand interpretations -/@@ -114,10 +143,24 @@ theorem empty_herbrand_is_a_model : Model (herbrand []) [] whereeqp := fun a b hab => absurd hab (not_mem_pred [] V.equivalentProperty (by simp) a b)svf := fun r p _ hop => absurd hop (not_mem_pred [] V.onProperty (by simp) r p)avf := fun r p _ hop => absurd hop (not_mem_pred [] V.onProperty (by simp) r p)- hv := fun r p _ hop => absurd hop (not_mem_pred [] V.onProperty (by simp) r p) }+ hv := fun r p _ hop => absurd hop (not_mem_pred [] V.onProperty (by simp) r p)+ svf_sc := fun c1 _ _ y1 _ hsv =>+ absurd hsv (not_mem_pred [] V.someValuesFrom (by simp) c1 y1)+ svf_sp := fun c1 _ _ _ y hsv =>+ absurd hsv (not_mem_pred [] V.someValuesFrom (by simp) c1 y)+ avf_sc := fun c1 _ _ y1 _ hav =>+ absurd hav (not_mem_pred [] V.allValuesFrom (by simp) c1 y1)+ avf_sp := fun c1 _ _ _ y hav =>+ absurd hav (not_mem_pred [] V.allValuesFrom (by simp) c1 y)+ dom_sc := fun p c1 _ hd => absurd hd (not_mem_pred [] V.domain (by simp) p c1)+ dom_sp := fun _ p2 c hd => absurd hd (not_mem_pred [] V.domain (by simp) p2 c)+ rng_sc := fun p c1 _ hr => absurd hr (not_mem_pred [] V.range (by simp) p c1)+ rng_sp := fun _ p2 c hr => absurd hr (not_mem_pred [] V.range (by simp) p2 c) }facts := by intro t ht; simp at htint := by intro c l _ hc; exact absurd hc (not_mem_pred [] V.intersectionOf (by simp) c l)+ int2 := by intro c l _ hc; exact absurd hc (not_mem_pred [] V.intersectionOf (by simp) c l)uni := by intro c l _ hc; exact absurd hc (not_mem_pred [] V.unionOf (by simp) c l)+ oneOf := by intro c l _ hc; exact absurd hc (not_mem_pred [] V.oneOf (by simp) c l)/-- Entailment is not trivial. -/theorem not_everything_is_entailed :@@ -181,6 +224,14 @@ private theorem svf_closed :(⟨v.s, V.type, t.s⟩ : Triple) ∈ svfWitness := bydecide+/-- The one `owl:someValuesFrom` filler in this graph is `D`, and the one class+with a superclass is `C`, so no filler is ever the subject of a+`rdfs:subClassOf` triple. That is what makes `svf_sc` hold vacuously here. -/+private theorem no_svf_filler_is_a_subclass :+ ∀ t ∈ svfWitness, ∀ u ∈ svfWitness,+ ¬(t.p = V.someValuesFrom ∧ u.p = V.subClassOf ∧ u.s = t.o) := by+ decide+theorem svf_witness_is_a_model : Model (herbrand svfWitness) svfPremises whereconds :={ sc_sub := fun a b hab x hx =>@@ -205,10 +256,25 @@ theorem svf_witness_is_a_model : Model (herbrand svfWitness) svfPremises where⟨x, p, y⟩ hxy ⟨y, V.type, c⟩ hy ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl⟩avf := fun r _ c _ hav =>absurd hav (not_mem_pred svfWitness V.allValuesFrom (by decide) r c)- hv := fun r _ v _ hhv => absurd hhv (not_mem_pred svfWitness V.hasValue (by decide) r v) }+ hv := fun r _ v _ hhv => absurd hhv (not_mem_pred svfWitness V.hasValue (by decide) r v)+ svf_sc := fun c1 _ _ y1 y2 hsv _ _ _ hsc =>+ absurd ⟨rfl, rfl, rfl⟩+ (no_svf_filler_is_a_subclass ⟨c1, V.someValuesFrom, y1⟩ hsv ⟨y1, V.subClassOf, y2⟩ hsc)+ svf_sp := fun _ _ p1 p2 _ _ _ _ _ hsp =>+ absurd hsp (not_mem_pred svfWitness V.subPropertyOf (by decide) p1 p2)+ avf_sc := fun c1 _ _ y1 _ hav =>+ absurd hav (not_mem_pred svfWitness V.allValuesFrom (by decide) c1 y1)+ avf_sp := fun c1 _ _ _ y hav =>+ absurd hav (not_mem_pred svfWitness V.allValuesFrom (by decide) c1 y)+ dom_sc := fun p c1 _ hd => absurd hd (not_mem_pred svfWitness V.domain (by decide) p c1)+ dom_sp := fun _ p2 c hd => absurd hd (not_mem_pred svfWitness V.domain (by decide) p2 c)+ rng_sc := fun p c1 _ hr => absurd hr (not_mem_pred svfWitness V.range (by decide) p c1)+ rng_sp := fun _ p2 c hr => absurd hr (not_mem_pred svfWitness V.range (by decide) p2 c) }facts := fun t ht => List.mem_cons_of_mem _ htint := by intro c l _ hc; exact absurd hc (not_mem_pred svfPremises V.intersectionOf (by decide) c l)+ int2 := by intro c l _ hc; exact absurd hc (not_mem_pred svfPremises V.intersectionOf (by decide) c l)uni := by intro c l _ hc; exact absurd hc (not_mem_pred svfPremises V.unionOf (by decide) c l)+ oneOf := by intro c l _ hc; exact absurd hc (not_mem_pred svfPremises V.oneOf (by decide) c l)/-- **The old rule was unsound.** `C ⊑ ∃p.D` together with `x p y` and `y ∈ D` does not entail`x ∈ C`. The reasoner derived exactly this until 13 September 2026. -/@@ -227,6 +293,406 @@ theorem the_sound_half_survives : Entails svfPremises ⟨tx, V.type, tR⟩ := byhave hy := M.facts ⟨ty, V.type, tD⟩ (by simp [svfPremises])exact M.conds.svf _ _ _ hop hsv _ _ hxy hy+/-! ## `scm-avf2` runs one way and not the other++`scm-avf1`, `scm-svf1` and `scm-svf2` conclude `?c1 rdfs:subClassOf ?c2`.+`scm-avf2` concludes `?c2 rdfs:subClassOf ?c1`. Copying the shape of the other+three is the mistake this section is here to make expensive: the wrong+direction has no model behind it, every certificate citing it would check, and+nothing else in the pipeline would notice.++The reason is that a universal restriction is antitone in its property. If+`p1` is a subproperty of `p2` then everything an individual reaches by `p1` it+also reaches by `p2`, so being in `all p2 Y` is the harder condition and+`all p2 Y` is the smaller class.++`avfPremises` is that configuration. `avfWitness` adds the one subsumption the+semantics forces and nothing else. -/++def tY : Term := "<e:Y>"+def tC1 : Term := "<e:C1>"+def tC2 : Term := "<e:C2>"+def tp1 : Term := "<e:p1>"+def tp2 : Term := "<e:p2>"++/-- `C1 = all p1 Y`, `C2 = all p2 Y`, and `p1 rdfs:subPropertyOf p2`. -/+def avfPremises : List Triple :=+ [ ⟨tC1, V.allValuesFrom, tY⟩,+ ⟨tC1, V.onProperty, tp1⟩,+ ⟨tC2, V.allValuesFrom, tY⟩,+ ⟨tC2, V.onProperty, tp2⟩,+ ⟨tp1, V.subPropertyOf, tp2⟩ ]++/-- The premises plus `C2 rdfs:subClassOf C1`, which is what `scm-avf2` draws.+`C1 rdfs:subClassOf C2` is absent, and that absence is the theorem. -/+def avfWitness : List Triple := ⟨tC2, V.subClassOf, tC1⟩ :: avfPremises++/-! The decidable facts the model proof reads off the six-triple list. -/++private theorem avf_only_sp :+ ∀ t ∈ avfWitness, t.p = V.subPropertyOf → t.s = tp1 ∧ t.o = tp2 := by decide+private theorem avf_op_p1 :+ ∀ t ∈ avfWitness, t.p = V.onProperty → t.o = tp1 → t.s = tC1 := by decide+private theorem avf_op_p2 :+ ∀ t ∈ avfWitness, t.p = V.onProperty → t.o = tp2 → t.s = tC2 := by decide+private theorem avf_no_sc_chain :+ ∀ t ∈ avfWitness, ∀ u ∈ avfWitness,+ ¬(t.p = V.subClassOf ∧ u.p = V.subClassOf ∧ u.s = t.o) := by decide+private theorem avf_no_sp_chain :+ ∀ t ∈ avfWitness, ∀ u ∈ avfWitness,+ ¬(t.p = V.subPropertyOf ∧ u.p = V.subPropertyOf ∧ u.s = t.o) := by decide+/-- Nothing in the graph uses `p1` as a predicate, so `sp_sub` is vacuous. -/+private theorem avf_subproperty_unused :+ ∀ t ∈ avfWitness, ∀ u ∈ avfWitness, ¬(t.p = V.subPropertyOf ∧ u.p = t.s) := by decide+/-- The one `owl:allValuesFrom` filler is `Y`, and the one class with a+superclass is `C2`, so no filler is the subject of a `rdfs:subClassOf` triple+and `avf_sc` is vacuous here. -/+private theorem avf_no_filler_is_a_subclass :+ ∀ t ∈ avfWitness, ∀ u ∈ avfWitness,+ ¬(t.p = V.allValuesFrom ∧ u.p = V.subClassOf ∧ u.s = t.o) := by decide++theorem avf_witness_is_a_model : Model (herbrand avfWitness) avfPremises where+ conds :=+ { sc_sub := fun a _ _ x hx => absurd hx (not_mem_pred avfWitness V.type (by decide) x a)+ sc_trans := fun a b c hab hbc =>+ absurd ⟨rfl, rfl, rfl⟩+ (avf_no_sc_chain ⟨a, V.subClassOf, b⟩ hab ⟨b, V.subClassOf, c⟩ hbc)+ sp_sub := fun a b hab x y hxy =>+ absurd ⟨rfl, rfl⟩+ (avf_subproperty_unused ⟨a, V.subPropertyOf, b⟩ hab ⟨x, a, y⟩ hxy)+ sp_trans := fun a b c hab hbc =>+ absurd ⟨rfl, rfl, rfl⟩+ (avf_no_sp_chain ⟨a, V.subPropertyOf, b⟩ hab ⟨b, V.subPropertyOf, c⟩ hbc)+ dom := fun p c hpc => absurd hpc (not_mem_pred avfWitness V.domain (by decide) p c)+ rng := fun p c hpc => absurd hpc (not_mem_pred avfWitness V.range (by decide) p c)+ trp := fun p hp => absurd hp (not_typed avfWitness V.transitiveProperty (by decide) p)+ symp := fun p hp => absurd hp (not_typed avfWitness V.symmetricProperty (by decide) p)+ inv := fun p q hpq => absurd hpq (not_mem_pred avfWitness V.inverseOf (by decide) p q)+ same := fun a b hab => absurd hab (not_mem_pred avfWitness V.sameAs (by decide) a b)+ eqc := fun a b hab => absurd hab (not_mem_pred avfWitness V.equivalentClass (by decide) a b)+ eqp := fun a b hab =>+ absurd hab (not_mem_pred avfWitness V.equivalentProperty (by decide) a b)+ svf := fun r _ c _ hsv =>+ absurd hsv (not_mem_pred avfWitness V.someValuesFrom (by decide) r c)+ avf := fun r _ _ _ _ x _ hx => absurd hx (not_mem_pred avfWitness V.type (by decide) x r)+ hv := fun r _ v _ hhv => absurd hhv (not_mem_pred avfWitness V.hasValue (by decide) r v)+ svf_sc := fun c1 _ _ y1 _ hsv =>+ absurd hsv (not_mem_pred avfWitness V.someValuesFrom (by decide) c1 y1)+ svf_sp := fun c1 _ _ _ y hsv =>+ absurd hsv (not_mem_pred avfWitness V.someValuesFrom (by decide) c1 y)+ avf_sc := fun c1 _ _ y1 y2 hav _ _ _ hsc =>+ absurd ⟨rfl, rfl, rfl⟩+ (avf_no_filler_is_a_subclass ⟨c1, V.allValuesFrom, y1⟩ hav ⟨y1, V.subClassOf, y2⟩ hsc)+ avf_sp := by+ intro c1 c2 q1 q2 _ _ hop1 _ hop2 hsp+ obtain ⟨hs, ho⟩ := avf_only_sp ⟨q1, V.subPropertyOf, q2⟩ hsp rfl+ subst hs+ subst ho+ have h1 : c1 = tC1 := avf_op_p1 ⟨c1, V.onProperty, tp1⟩ hop1 rfl rfl+ have h2 : c2 = tC2 := avf_op_p2 ⟨c2, V.onProperty, tp2⟩ hop2 rfl rfl+ subst h1+ subst h2+ show (⟨tC2, V.subClassOf, tC1⟩ : Triple) ∈ avfWitness+ decide+ dom_sc := fun p c1 _ hd => absurd hd (not_mem_pred avfWitness V.domain (by decide) p c1)+ dom_sp := fun _ p2 c hd => absurd hd (not_mem_pred avfWitness V.domain (by decide) p2 c)+ rng_sc := fun p c1 _ hr => absurd hr (not_mem_pred avfWitness V.range (by decide) p c1)+ rng_sp := fun _ p2 c hr => absurd hr (not_mem_pred avfWitness V.range (by decide) p2 c) }+ facts := fun t ht => List.mem_cons_of_mem _ ht+ int := by+ intro c l _ hc+ exact absurd hc (not_mem_pred avfPremises V.intersectionOf (by decide) c l)+ int2 := by+ intro c l _ hc+ exact absurd hc (not_mem_pred avfPremises V.intersectionOf (by decide) c l)+ uni := by intro c l _ hc; exact absurd hc (not_mem_pred avfPremises V.unionOf (by decide) c l)+ oneOf := by intro c l _ hc; exact absurd hc (not_mem_pred avfPremises V.oneOf (by decide) c l)++/-- **The direction the W3C table gives.** Proved for an arbitrary model, not+just the witness, so it is the rule and not an accident of this graph. -/+theorem the_avf2_direction_the_table_gives_is_entailed :+ Entails avfPremises ⟨tC2, V.subClassOf, tC1⟩ := by+ intro I M+ exact M.conds.avf_sp _ _ _ _ _+ (M.facts ⟨tC1, V.allValuesFrom, tY⟩ (by simp [avfPremises]))+ (M.facts ⟨tC1, V.onProperty, tp1⟩ (by simp [avfPremises]))+ (M.facts ⟨tC2, V.allValuesFrom, tY⟩ (by simp [avfPremises]))+ (M.facts ⟨tC2, V.onProperty, tp2⟩ (by simp [avfPremises]))+ (M.facts ⟨tp1, V.subPropertyOf, tp2⟩ (by simp [avfPremises]))++/-- **And the other direction is unsound.** A rule that concluded+`C1 rdfs:subClassOf C2` here, which is what copying `scm-avf1` gives, would be+making a claim this model refutes. -/+theorem the_natural_avf2_direction_is_not_entailed :+ ¬ Entails avfPremises ⟨tC1, V.subClassOf, tC2⟩ := fun h =>+ absurd (h (herbrand avfWitness) avf_witness_is_a_model)+ (by decide : (⟨tC1, V.subClassOf, tC2⟩ : Triple) ∉ avfWitness)++/-! ## The two list conditions, and what they stop short of++`Chain` has no inversion principle in `Semantics.lean`, because nothing needed+one until a witness graph carried a list. This is it, and it belongs beside the+inductive. -/++theorem chain_inv {G : List Triple} {l : Term} {ms : List Term} (h : Chain G l ms) :+ (l = V.nil ∧ ms = []) ∨+ ∃ m l' ms', ms = m :: ms' ∧ (⟨l, V.first, m⟩ : Triple) ∈ G ∧+ (⟨l, V.rest, l'⟩ : Triple) ∈ G ∧ Chain G l' ms' := by+ cases h with+ | nil => exact Or.inl ⟨rfl, rfl⟩+ | cons h1 h2 hr => exact Or.inr ⟨_, _, _, rfl, h1, h2, hr⟩++/-! ### `cls-oo` types the members it lists, and no one else -/++def tE : Term := "<e:E>"+def tA : Term := "<e:a>"+def tB : Term := "<e:b>"+def tZ : Term := "<e:z>"+def oL0 : Term := "_:o0"+def oL1 : Term := "_:o1"++/-- `E = {a, b}` as an RDF list. `z` is mentioned nowhere. -/+def ooPremises : List Triple :=+ [ ⟨tE, V.oneOf, oL0⟩,+ ⟨oL0, V.first, tA⟩, ⟨oL0, V.rest, oL1⟩,+ ⟨oL1, V.first, tB⟩, ⟨oL1, V.rest, V.nil⟩ ]++/-- The premises plus the two typings `cls-oo` draws, and nothing else. -/+def ooWitness : List Triple := ⟨tA, V.type, tE⟩ :: ⟨tB, V.type, tE⟩ :: ooPremises++private theorem oo_l0_first : ∀ t ∈ ooPremises, t.s = oL0 → t.p = V.first → t.o = tA := by decide+private theorem oo_l0_rest : ∀ t ∈ ooPremises, t.s = oL0 → t.p = V.rest → t.o = oL1 := by decide+private theorem oo_l1_first : ∀ t ∈ ooPremises, t.s = oL1 → t.p = V.first → t.o = tB := by decide+private theorem oo_l1_rest : ∀ t ∈ ooPremises, t.s = oL1 → t.p = V.rest → t.o = V.nil := by decide+private theorem oo_no_nil_subject : ∀ t ∈ ooPremises, t.s ≠ V.nil := by decide+private theorem oo_only_oneOf :+ ∀ t ∈ ooPremises, t.p = V.oneOf → t.s = tE ∧ t.o = oL0 := by decide++private theorem oo_chain_nil : ∀ ms, Chain ooPremises V.nil ms → ms = [] := by+ intro ms h+ rcases chain_inv h with ⟨_, rfl⟩ | ⟨_, _, _, _, h1, _, _⟩+ · rfl+ · exact absurd rfl (oo_no_nil_subject _ h1)++private theorem oo_chain_l1 : ∀ ms, Chain ooPremises oL1 ms → ms = [tB] := by+ intro ms h+ rcases chain_inv h with ⟨hn, _⟩ | ⟨m, l', ms', rfl, h1, h2, hr⟩+ · exact absurd hn (by decide)+ · have hm : m = tB := oo_l1_first _ h1 rfl rfl+ have hl : l' = V.nil := oo_l1_rest _ h2 rfl rfl+ subst hm; subst hl+ rw [oo_chain_nil _ hr]++private theorem oo_chain_l0 : ∀ ms, Chain ooPremises oL0 ms → ms = [tA, tB] := by+ intro ms h+ rcases chain_inv h with ⟨hn, _⟩ | ⟨m, l', ms', rfl, h1, h2, hr⟩+ · exact absurd hn (by decide)+ · have hm : m = tA := oo_l0_first _ h1 rfl rfl+ have hl : l' = oL1 := oo_l0_rest _ h2 rfl rfl+ subst hm; subst hl+ rw [oo_chain_l1 _ hr]++theorem oo_witness_is_a_model : Model (herbrand ooWitness) ooPremises where+ conds :=+ { sc_sub := fun a b hab => absurd hab (not_mem_pred ooWitness V.subClassOf (by decide) a b)+ sc_trans := fun a b _ hab =>+ absurd hab (not_mem_pred ooWitness V.subClassOf (by decide) a b)+ sp_sub := fun a b hab => absurd hab (not_mem_pred ooWitness V.subPropertyOf (by decide) a b)+ sp_trans := fun a b _ hab =>+ absurd hab (not_mem_pred ooWitness V.subPropertyOf (by decide) a b)+ dom := fun p c hpc => absurd hpc (not_mem_pred ooWitness V.domain (by decide) p c)+ rng := fun p c hpc => absurd hpc (not_mem_pred ooWitness V.range (by decide) p c)+ trp := fun p hp => absurd hp (not_typed ooWitness V.transitiveProperty (by decide) p)+ symp := fun p hp => absurd hp (not_typed ooWitness V.symmetricProperty (by decide) p)+ inv := fun p q hpq => absurd hpq (not_mem_pred ooWitness V.inverseOf (by decide) p q)+ same := fun a b hab => absurd hab (not_mem_pred ooWitness V.sameAs (by decide) a b)+ eqc := fun a b hab => absurd hab (not_mem_pred ooWitness V.equivalentClass (by decide) a b)+ eqp := fun a b hab =>+ absurd hab (not_mem_pred ooWitness V.equivalentProperty (by decide) a b)+ svf := fun r p _ hop => absurd hop (not_mem_pred ooWitness V.onProperty (by decide) r p)+ avf := fun r p _ hop => absurd hop (not_mem_pred ooWitness V.onProperty (by decide) r p)+ hv := fun r p _ hop => absurd hop (not_mem_pred ooWitness V.onProperty (by decide) r p)+ svf_sc := fun c1 _ _ y1 _ hsv =>+ absurd hsv (not_mem_pred ooWitness V.someValuesFrom (by decide) c1 y1)+ svf_sp := fun c1 _ _ _ y hsv =>+ absurd hsv (not_mem_pred ooWitness V.someValuesFrom (by decide) c1 y)+ avf_sc := fun c1 _ _ y1 _ hav =>+ absurd hav (not_mem_pred ooWitness V.allValuesFrom (by decide) c1 y1)+ avf_sp := fun c1 _ _ _ y hav =>+ absurd hav (not_mem_pred ooWitness V.allValuesFrom (by decide) c1 y)+ dom_sc := fun p c1 _ hd => absurd hd (not_mem_pred ooWitness V.domain (by decide) p c1)+ dom_sp := fun _ p2 c hd => absurd hd (not_mem_pred ooWitness V.domain (by decide) p2 c)+ rng_sc := fun p c1 _ hr => absurd hr (not_mem_pred ooWitness V.range (by decide) p c1)+ rng_sp := fun _ p2 c hr => absurd hr (not_mem_pred ooWitness V.range (by decide) p2 c) }+ facts := fun t ht => List.mem_cons_of_mem _ (List.mem_cons_of_mem _ ht)+ int := by+ intro c l _ hc+ exact absurd hc (not_mem_pred ooPremises V.intersectionOf (by decide) c l)+ int2 := by+ intro c l _ hc+ exact absurd hc (not_mem_pred ooPremises V.intersectionOf (by decide) c l)+ uni := by intro c l _ hc; exact absurd hc (not_mem_pred ooPremises V.unionOf (by decide) c l)+ oneOf := by+ intro c l ms hc hchain m hm+ obtain ⟨rfl, rfl⟩ := oo_only_oneOf _ hc rfl+ rw [oo_chain_l0 ms hchain] at hm+ show (⟨m, V.type, tE⟩ : Triple) ∈ ooWitness+ rcases List.mem_cons.mp hm with rfl | hm+ · decide+ · rw [List.mem_singleton] at hm+ subst hm+ decide++/-- **`cls-oo` earns its conclusion.** Proved for an arbitrary model. -/+theorem an_enumerated_member_is_entailed : Entails ooPremises ⟨tA, V.type, tE⟩ := by+ intro I M+ have hchain : Chain ooPremises oL0 [tA, tB] := by+ refine Chain.cons (l' := oL1) (by simp [ooPremises]) (by simp [ooPremises]) ?_+ exact Chain.cons (l' := V.nil) (by simp [ooPremises]) (by simp [ooPremises]) Chain.nil+ exact M.oneOf tE oL0 [tA, tB] (by simp [ooPremises]) hchain tA (by simp)++/-- **And it stops at the members.** The condition says the class holds at+least the listed members; it does not say it holds no others, so an individual+the list never mentions is not entailed to be one. -/+theorem an_unlisted_individual_is_not_entailed : ¬ Entails ooPremises ⟨tZ, V.type, tE⟩ :=+ fun h =>+ absurd (h (herbrand ooWitness) oo_witness_is_a_model)+ (by decide : (⟨tZ, V.type, tE⟩ : Triple) ∉ ooWitness)++/-! ### `cls-int2` takes the intersection apart, and `cls-int1` still needs every member -/++def tK : Term := "<e:K>"+def tM1 : Term := "<e:M1>"+def tM2 : Term := "<e:M2>"+def tw : Term := "<e:w>"+def tv : Term := "<e:v>"+def iL0 : Term := "_:i0"+def iL1 : Term := "_:i1"++/-- `K = M1 ⊓ M2`, `w` is a `K`, and `v` is an `M1` and nothing else. -/+def intPremises : List Triple :=+ [ ⟨tK, V.intersectionOf, iL0⟩,+ ⟨iL0, V.first, tM1⟩, ⟨iL0, V.rest, iL1⟩,+ ⟨iL1, V.first, tM2⟩, ⟨iL1, V.rest, V.nil⟩,+ ⟨tw, V.type, tK⟩,+ ⟨tv, V.type, tM1⟩ ]++/-- The premises plus the two typings `cls-int2` draws for `w`. Nothing puts+`v` in `K`, which is the second theorem. -/+def intWitness : List Triple := ⟨tw, V.type, tM1⟩ :: ⟨tw, V.type, tM2⟩ :: intPremises++private theorem i_l0_first : ∀ t ∈ intPremises, t.s = iL0 → t.p = V.first → t.o = tM1 := by decide+private theorem i_l0_rest : ∀ t ∈ intPremises, t.s = iL0 → t.p = V.rest → t.o = iL1 := by decide+private theorem i_l1_first : ∀ t ∈ intPremises, t.s = iL1 → t.p = V.first → t.o = tM2 := by decide+private theorem i_l1_rest : ∀ t ∈ intPremises, t.s = iL1 → t.p = V.rest → t.o = V.nil := by decide+private theorem i_no_nil_subject : ∀ t ∈ intPremises, t.s ≠ V.nil := by decide+private theorem i_only_int :+ ∀ t ∈ intPremises, t.p = V.intersectionOf → t.s = tK ∧ t.o = iL0 := by decide++/-- Anything that is both an `M1` and an `M2` in this graph is already a `K`,+so `int` holds. `v` is an `M1` and not an `M2`, so it does not trigger it. -/+private theorem i_int_closed : ∀ t ∈ intWitness, ∀ u ∈ intWitness,+ (t.p = V.type ∧ t.o = tM1 ∧ u.p = V.type ∧ u.o = tM2 ∧ u.s = t.s) →+ (⟨t.s, V.type, tK⟩ : Triple) ∈ intWitness := by decide++/-- Anything that is a `K` is already both, so `int2` holds. -/+private theorem i_int2_closed : ∀ t ∈ intWitness, t.p = V.type → t.o = tK →+ (⟨t.s, V.type, tM1⟩ : Triple) ∈ intWitness ∧+ (⟨t.s, V.type, tM2⟩ : Triple) ∈ intWitness := by decide++private theorem i_chain_nil : ∀ ms, Chain intPremises V.nil ms → ms = [] := by+ intro ms h+ rcases chain_inv h with ⟨_, rfl⟩ | ⟨_, _, _, _, h1, _, _⟩+ · rfl+ · exact absurd rfl (i_no_nil_subject _ h1)++private theorem i_chain_l1 : ∀ ms, Chain intPremises iL1 ms → ms = [tM2] := by+ intro ms h+ rcases chain_inv h with ⟨hn, _⟩ | ⟨m, l', ms', rfl, h1, h2, hr⟩+ · exact absurd hn (by decide)+ · have hm : m = tM2 := i_l1_first _ h1 rfl rfl+ have hl : l' = V.nil := i_l1_rest _ h2 rfl rfl+ subst hm; subst hl+ rw [i_chain_nil _ hr]++private theorem i_chain_l0 : ∀ ms, Chain intPremises iL0 ms → ms = [tM1, tM2] := by+ intro ms h+ rcases chain_inv h with ⟨hn, _⟩ | ⟨m, l', ms', rfl, h1, h2, hr⟩+ · exact absurd hn (by decide)+ · have hm : m = tM1 := i_l0_first _ h1 rfl rfl+ have hl : l' = iL1 := i_l0_rest _ h2 rfl rfl+ subst hm; subst hl+ rw [i_chain_l1 _ hr]++theorem int_witness_is_a_model : Model (herbrand intWitness) intPremises where+ conds :=+ { sc_sub := fun a b hab => absurd hab (not_mem_pred intWitness V.subClassOf (by decide) a b)+ sc_trans := fun a b _ hab =>+ absurd hab (not_mem_pred intWitness V.subClassOf (by decide) a b)+ sp_sub := fun a b hab => absurd hab (not_mem_pred intWitness V.subPropertyOf (by decide) a b)+ sp_trans := fun a b _ hab =>+ absurd hab (not_mem_pred intWitness V.subPropertyOf (by decide) a b)+ dom := fun p c hpc => absurd hpc (not_mem_pred intWitness V.domain (by decide) p c)+ rng := fun p c hpc => absurd hpc (not_mem_pred intWitness V.range (by decide) p c)+ trp := fun p hp => absurd hp (not_typed intWitness V.transitiveProperty (by decide) p)+ symp := fun p hp => absurd hp (not_typed intWitness V.symmetricProperty (by decide) p)+ inv := fun p q hpq => absurd hpq (not_mem_pred intWitness V.inverseOf (by decide) p q)+ same := fun a b hab => absurd hab (not_mem_pred intWitness V.sameAs (by decide) a b)+ eqc := fun a b hab => absurd hab (not_mem_pred intWitness V.equivalentClass (by decide) a b)+ eqp := fun a b hab =>+ absurd hab (not_mem_pred intWitness V.equivalentProperty (by decide) a b)+ svf := fun r p _ hop => absurd hop (not_mem_pred intWitness V.onProperty (by decide) r p)+ avf := fun r p _ hop => absurd hop (not_mem_pred intWitness V.onProperty (by decide) r p)+ hv := fun r p _ hop => absurd hop (not_mem_pred intWitness V.onProperty (by decide) r p)+ svf_sc := fun c1 _ _ y1 _ hsv =>+ absurd hsv (not_mem_pred intWitness V.someValuesFrom (by decide) c1 y1)+ svf_sp := fun c1 _ _ _ y hsv =>+ absurd hsv (not_mem_pred intWitness V.someValuesFrom (by decide) c1 y)+ avf_sc := fun c1 _ _ y1 _ hav =>+ absurd hav (not_mem_pred intWitness V.allValuesFrom (by decide) c1 y1)+ avf_sp := fun c1 _ _ _ y hav =>+ absurd hav (not_mem_pred intWitness V.allValuesFrom (by decide) c1 y)+ dom_sc := fun p c1 _ hd => absurd hd (not_mem_pred intWitness V.domain (by decide) p c1)+ dom_sp := fun _ p2 c hd => absurd hd (not_mem_pred intWitness V.domain (by decide) p2 c)+ rng_sc := fun p c1 _ hr => absurd hr (not_mem_pred intWitness V.range (by decide) p c1)+ rng_sp := fun _ p2 c hr => absurd hr (not_mem_pred intWitness V.range (by decide) p2 c) }+ facts := fun t ht => List.mem_cons_of_mem _ (List.mem_cons_of_mem _ ht)+ int := by+ intro c l ms hc hchain x hx+ obtain ⟨rfl, rfl⟩ := i_only_int _ hc rfl+ have hms := i_chain_l0 ms hchain+ subst hms+ exact i_int_closed _ (hx tM1 (by simp)) _ (hx tM2 (by simp)) ⟨rfl, rfl, rfl, rfl, rfl⟩+ int2 := by+ intro c l ms hc hchain x hx m hm+ obtain ⟨rfl, rfl⟩ := i_only_int _ hc rfl+ have hms := i_chain_l0 ms hchain+ subst hms+ obtain ⟨h1, h2⟩ := i_int2_closed ⟨x, V.type, tK⟩ hx rfl rfl+ rcases List.mem_cons.mp hm with rfl | hm+ · exact h1+ · rw [List.mem_singleton] at hm+ subst hm+ exact h2+ uni := by intro c l _ hc; exact absurd hc (not_mem_pred intPremises V.unionOf (by decide) c l)+ oneOf := by intro c l _ hc; exact absurd hc (not_mem_pred intPremises V.oneOf (by decide) c l)++/-- **`cls-int2` earns its conclusion.** Being a `K` makes `w` an `M1`. -/+theorem a_member_of_the_intersection_is_entailed : Entails intPremises ⟨tw, V.type, tM1⟩ := by+ intro I M+ have hchain : Chain intPremises iL0 [tM1, tM2] := by+ refine Chain.cons (l' := iL1) (by simp [intPremises]) (by simp [intPremises]) ?_+ exact Chain.cons (l' := V.nil) (by simp [intPremises]) (by simp [intPremises]) Chain.nil+ exact M.int2 tK iL0 [tM1, tM2] (by simp [intPremises]) hchain (I.ι tw)+ (M.facts ⟨tw, V.type, tK⟩ (by simp [intPremises])) tM1 (by simp)++/-- **And the converse still needs every member.** `v` is an `M1` and no model+has to make it a `K`, so `cls-int1` has lost nothing to `cls-int2`. -/+theorem membership_in_one_member_does_not_give_the_intersection :+ ¬ Entails intPremises ⟨tv, V.type, tK⟩ := fun h =>+ absurd (h (herbrand intWitness) int_witness_is_a_model)+ (by decide : (⟨tv, V.type, tK⟩ : Triple) ∉ intWitness)+/-! Axioms, pinned. A `sorry` here would quietly restore the vacuity objection this file exists toclose, which is exactly the kind of silent hole the project refuses elsewhere. These lists areshorter than the one `certificate_sound` carries: the witnesses need no choice, and the two@@ -247,4 +713,30 @@ statements about the removed rule are proved from `propext` alone. -/#guard_msgs in#print axioms the_sound_half_survives+/-- info: 'OOCert.the_avf2_direction_the_table_gives_is_entailed' depends on axioms: [propext] -/+#guard_msgs in+#print axioms the_avf2_direction_the_table_gives_is_entailed++/-- info: 'OOCert.the_natural_avf2_direction_is_not_entailed' depends on axioms: [propext] -/+#guard_msgs in+#print axioms the_natural_avf2_direction_is_not_entailed++/-- info: 'OOCert.an_enumerated_member_is_entailed' depends on axioms: [propext] -/+#guard_msgs in+#print axioms an_enumerated_member_is_entailed++/-- info: 'OOCert.an_unlisted_individual_is_not_entailed' depends on axioms: [propext] -/+#guard_msgs in+#print axioms an_unlisted_individual_is_not_entailed++/-- info: 'OOCert.a_member_of_the_intersection_is_entailed' depends on axioms: [propext] -/+#guard_msgs in+#print axioms a_member_of_the_intersection_is_entailed++/--+info: 'OOCert.membership_in_one_member_does_not_give_the_intersection' depends on axioms: [propext]+-/+#guard_msgs in+#print axioms membership_in_one_member_does_not_give_the_intersection+end OOCertdiff --git a/lean/RefuteMain.lean b/lean/RefuteMain.leannew file mode 100644index 00000000..21d2eb5e--- /dev/null+++ b/lean/RefuteMain.lean@@ -0,0 +1,155 @@+import OOCert.Parse+import OOCert.Refute+import OOCert.RefuteWitness++/-!+`oo-refute check ASSERTED.tsv REFUTATION.tsv`+`oo-refute guard ASSERTED.tsv DERIVATIONS.tsv REFUTATION.tsv`++Exit 0 when the refutation checks, 1 when it does not, 2 when a file cannot be+read or parsed. The house convention is about the CERTIFICATE, not about the+ontology: exit 0 from `check` means "this refutation is valid", which is to say+the ontology is contradictory. It is a good exit code reporting bad news.++# Why `guard` exists++`oo-cert` reports `"ok":true` for a certificate over a self-contradicting+ontology, and what it says is true. Its verdict is `OOCert.Entails`, which+quantifies over `OOCert.Model I G`, and that class of interpretations is never+empty: `OOCert.saturated_is_a_model` exhibits a member for every graph, because+`Conditions` carries no negative condition and therefore cannot notice a+disjointness clash.++The verdict a consumer wants is the one that reads `owl:disjointWith` as+disjointness, and once the graph is refutable that one is empty.+`OOCert.a_certificate_adds_nothing_when_the_graph_is_refuted` states it: over a+refuted graph, every conclusion of every list of steps already carries the+disjointness-aware warrant, checked or forged, so running the derivation checker+establishes nothing.++`guard` therefore runs both and refuses the derivation certificate when the+refutation succeeds. It exits 0 only when the certificate checks AND the+refutation does not.++# What a rejected refutation does NOT mean++It does not mean the graph is consistent. `RefuteConditions` carries one+condition, for `cax-dw`, and fifteen other clash rules of OWL 2 RL have no+condition here at all. A graph that only `prp-irp` or `eq-diff1` could refute is+rejected by this checker and is still contradictory. The checker is a gate, not+an oracle, in that direction as in the other.+-/+open OOCert++def readOrFail (path : String) : IO (Except UInt32 String) := do+ try+ return .ok (← IO.FS.readFile path)+ catch e =>+ IO.eprintln s!"cannot read {path}: {e}"+ return .error 2++def jsonStr (s : String) : String :=+ let escaped := s.foldl (fun acc c =>+ match c with+ | '"' => acc ++ "\\\""+ | '\\' => acc ++ "\\\\"+ | '\n' => acc ++ "\\n"+ | '\t' => acc ++ "\\t"+ | c => acc.push c) ""+ "\"" ++ escaped ++ "\""++def showTriple (t : Triple) : String := s!"{t.s} {t.p} {t.o}"++/-- The diagnostic pass. Unverified, and it runs only after the verified checker+has already said no, exactly as `oo-cert`'s does. -/+def whyRejected (G : List Triple) (r : Refutation) : String := Id.run do+ let gset := Std.HashSet.ofList G+ let inG := fun t => gset.contains t+ let mut derived : Std.HashSet Triple := ∅+ let mut i := 0+ for st in r.steps do+ if !checkStep inG (fun t => derived.contains t) st then+ return s!"derivation step {i} ({st.rule.name}) does not check: it claims \+ {showTriple st.conclusion}"+ derived := derived.insert st.conclusion+ i := i + 1+ let known := fun t => inG t || derived.contains t+ for t in r.final.premises do+ if !known t then+ return s!"the contradiction step cites {showTriple t}, which is neither asserted nor \+ concluded by a step before it"+ return s!"the contradiction step does not have the shape {r.final.rule.name} requires; \+ premise order is part of the contract"++def meansRefuted : String :=+ "no interpretation satisfies both the RDF-based conditions on the asserted graph and the \+ reading of owl:disjointWith as disjointness. This is unsatisfiability RELATIVE TO that \+ reading: drop it and the graph has models again. Every derivation certificate over this \+ graph is now worthless, because under the same reading every triple is entailed."++def runCheck (gPath rPath : String) : IO UInt32 := do+ let gTxt ← match ← readOrFail gPath with | .ok s => pure s | .error c => return c+ let rTxt ← match ← readOrFail rPath with | .ok s => pure s | .error c => return c+ match Parse.parseTriples gTxt, RefuteParse.parseRefutation rTxt with+ | .ok G, .ok r =>+ if checkRefutationFast G r then+ IO.println s!"\{\"ok\":true,\"format\":\"oo-refute/1\",\"asserted\":{G.length},\+ \"prefix\":{r.steps.length},\"rule\":{jsonStr r.final.rule.name},\+ \"verdict\":\"unsatisfiable_under_disjointness\",\+ \"theorem\":\"OOCert.refutation_fast_sound\",\"means\":{jsonStr meansRefuted}}"+ return 0+ else+ IO.println s!"\{\"ok\":false,\"format\":\"oo-refute/1\",\"asserted\":{G.length},\+ \"prefix\":{r.steps.length},\"rule\":{jsonStr r.final.rule.name},\+ \"reason\":{jsonStr (whyRejected G r)},\+ \"means\":\"the refutation was not accepted. That is not a proof of consistency: \+ fifteen other OWL 2 RL clash rules have no condition in this checker.\"}"+ return 1+ | .error e, _ => IO.eprintln e; return 2+ | _, .error e => IO.eprintln e; return 2++def runGuard (gPath dPath rPath : String) : IO UInt32 := do+ let gTxt ← match ← readOrFail gPath with | .ok s => pure s | .error c => return c+ let dTxt ← match ← readOrFail dPath with | .ok s => pure s | .error c => return c+ let rTxt ← match ← readOrFail rPath with | .ok s => pure s | .error c => return c+ match Parse.parseTriples gTxt, Parse.parseSteps dTxt, RefuteParse.parseRefutation rTxt with+ | .ok G, .ok steps, .ok r =>+ let certOk := checkCert G steps+ let refuted := checkRefutationFast G r+ if refuted then+ IO.println s!"\{\"ok\":false,\"certificate_ok\":{certOk},\"refuted\":true,\+ \"asserted\":{G.length},\"derivations\":{steps.length},\+ \"verdict\":\"certificate_refused_graph_is_unsatisfiable\",\+ \"theorem\":\"OOCert.a_certificate_adds_nothing_when_the_graph_is_refuted\",\+ \"means\":\"the graph is refutable, so under the disjointness reading EVERY triple is \+ entailed and this certificate carries no information. oo-cert would still report ok:true \+ for it, and that verdict quantifies over a model class that ignores disjointness.\"}"+ return 1+ else if certOk then+ IO.println s!"\{\"ok\":true,\"certificate_ok\":true,\"refuted\":false,\+ \"asserted\":{G.length},\"derivations\":{steps.length},\+ \"verdict\":\"entailed_and_no_disjointness_clash_found\",\+ \"theorem\":\"OOCert.certificate_sound\",\+ \"means\":\"every conclusion is entailed, and the supplied refutation did NOT check. \+ No clash was found; that is not a proof of consistency, because only cax-dw is \+ implemented.\"}"+ return 0+ else+ IO.println s!"\{\"ok\":false,\"certificate_ok\":false,\"refuted\":false,\+ \"asserted\":{G.length},\"derivations\":{steps.length},\+ \"verdict\":\"certificate_rejected\",\+ \"means\":\"the derivation certificate itself did not check; run oo-cert for the step \+ that failed.\"}"+ return 1+ | .error e, _, _ => IO.eprintln e; return 2+ | _, .error e, _ => IO.eprintln e; return 2+ | _, _, .error e => IO.eprintln e; return 2++def main (args : List String) : IO UInt32 := do+ match args with+ | ["check", gPath, rPath] => runCheck gPath rPath+ | ["guard", gPath, dPath, rPath] => runGuard gPath dPath rPath+ | _ =>+ IO.eprintln "usage: oo-refute check ASSERTED.tsv REFUTATION.tsv"+ IO.eprintln " oo-refute guard ASSERTED.tsv DERIVATIONS.tsv REFUTATION.tsv"+ return 2diff --git a/lean/Shacl/Agreement.lean b/lean/Shacl/Agreement.leanindex c9e2908d..4b07c7a3 100644--- a/lean/Shacl/Agreement.lean+++ b/lean/Shacl/Agreement.lean@@ -86,6 +86,61 @@ theorem leafCase {G : Graph} {b : Bool} {r : Result} {rs : List Result} {s : Shasubst hnilexact absurd hx (by simp)+/-- `leafCase` for a constraint that can produce MORE than one result, where every+result blames the same node for the same constraint. `sh:closed` is the only one:+the Recommendation asks for a result per offending triple. -/+theorem leafCaseMany {G : Graph} {rs : List Result} {s : Shape} {f : Term}+ (hiff : rs = [] ↔ Conf G s f) (hall : ∀ x ∈ rs, x.blamed = s ∧ x.blamedNode = f) :+ (rs = [] ↔ Conf G s f) ∧ (∀ x ∈ rs, ¬ Conf G x.blamed x.blamedNode) := by+ refine ⟨hiff, ?_⟩+ intro x hx+ obtain ⟨h1, h2⟩ := hall x hx+ rw [h1, h2]+ intro hc+ have hnil : rs = [] := hiff.mpr hc+ subst hnil+ exact absurd hx (by simp)++theorem contains_eq_false_iff_not_mem {α : Type} [BEq α] [LawfulBEq α] {l : List α} {a : α} :+ l.contains a = false ↔ a ∉ l := by+ constructor+ · intro h hm+ rw [List.contains_iff_mem.mpr hm] at h+ exact absurd h (by simp)+ · intro h+ by_cases hc : l.contains a = true+ · exact absurd (List.contains_iff_mem.mp hc) h+ · simpa using hc++theorem mem_closedOffenders {G : Graph} {allowed : List Term} {f : Term} {t : Triple} :+ t ∈ closedOffenders G allowed f ↔ (t ∈ G ∧ t.s = f ∧ t.p ∉ allowed) := by+ rw [closedOffenders, List.mem_filter]+ constructor+ · rintro ⟨hG, hb⟩+ simp only [Bool.and_eq_true, beq_iff_eq, Bool.not_eq_true',+ contains_eq_false_iff_not_mem] at hb+ exact ⟨hG, hb.1, hb.2⟩+ · rintro ⟨hG, hs, hp⟩+ refine ⟨hG, ?_⟩+ simp only [Bool.and_eq_true, beq_iff_eq, Bool.not_eq_true', contains_eq_false_iff_not_mem]+ exact ⟨hs, hp⟩++theorem closedResults_nil_iff {G : Graph} {allowed : List Term} {src : Term} {s : Shape}+ {f : Term} :+ closedResults G allowed src s f = [] ↔ ∀ p o, (⟨f, p, o⟩ : Triple) ∈ G → p ∈ allowed := by+ rw [closedResults, List.map_eq_nil_iff, List.eq_nil_iff_forall_not_mem]+ constructor+ · intro h p o hG+ by_cases hp : p ∈ allowed+ · exact hp+ · exact absurd (mem_closedOffenders.mpr ⟨hG, rfl, hp⟩) (h ⟨f, p, o⟩)+ · intro h t ht+ obtain ⟨hG, hs, hp⟩ := mem_closedOffenders.mp ht+ refine hp (h t.p t.o ?_)+ have ht' : (⟨f, t.p, t.o⟩ : Triple) = t := by rw [← hs]+ rw [ht']+ exact hG+theorem liftValue_blamed (f : Term) (pa : Path) (v : Term) (r : Result) :(liftValue f pa v r).blamed = r.blamed := byrw [liftValue]; split <;> rfl@@ -122,32 +177,74 @@ theorem collect_ok {k : Term → Except Refusal (List Result)} :/-! ## The decision procedures, each matched to the proposition it decides -/-theorem nodup_valueNodes {G : Graph} {pa : Path} {f : Term} :- (valueNodes G pa f).Nodup := by- rw [valueNodes]; exact nodup_dedup _+/-- Counting a duplicate-free enumeration of the nodes with some property decides+"there are at least `n` such nodes". The backward direction is the pigeonhole: any+duplicate-free list of such nodes is a subset of the enumeration, so it cannot be+longer. Stated for an arbitrary property because `sh:minCount` and+`sh:qualifiedMinCount` differ only in what the property is. -/+theorem count_ge_iff {L : List Term} {Q : Term → Prop} {n : Nat}+ (hnd : L.Nodup) (hmem : ∀ v, v ∈ L ↔ Q v) :+ n ≤ L.length ↔ ∃ l : List Term, l.Nodup ∧ (∀ v ∈ l, Q v) ∧ n ≤ l.length := by+ constructor+ · intro h+ exact ⟨L, hnd, fun v hv => (hmem v).mp hv, h⟩+ · rintro ⟨l, hl, hm, hlen⟩+ exact Nat.le_trans hlen+ (List.Nodup.length_le_of_subset hl (fun v hv => (hmem v).mpr (hm v hv)))-/-- Counting the deduplicated value nodes decides "there are at least `n` distinct-value nodes". The backward direction is the pigeonhole: any duplicate-free list of-value nodes is a subset of the enumeration, so it cannot be longer. -/-theorem minCount_iff {G : Graph} {pa : Path} {f : Term} {n : Nat} :- n ≤ (valueNodes G pa f).length ↔- ∃ l : List Term, l.Nodup ∧ (∀ v ∈ l, IsValue G pa f v) ∧ n ≤ l.length := by+theorem count_le_iff {L : List Term} {Q : Term → Prop} {n : Nat}+ (hnd : L.Nodup) (hmem : ∀ v, v ∈ L ↔ Q v) :+ L.length ≤ n ↔ ∀ l : List Term, l.Nodup → (∀ v ∈ l, Q v) → l.length ≤ n := byconstructor+ · intro h l hl hm+ exact Nat.le_trans+ (List.Nodup.length_le_of_subset hl (fun v hv => (hmem v).mpr (hm v hv))) h· intro h- exact ⟨valueNodes G pa f, nodup_valueNodes, fun _ hv => mem_valueNodes.mp hv, h⟩- · rintro ⟨l, hnd, hmem, hn⟩- exact Nat.le_trans hn- (List.Nodup.length_le_of_subset hnd (fun _ hv => mem_valueNodes.mpr (hmem _ hv)))+ exact h L hnd (fun v hv => (hmem v).mp hv)++theorem minCount_iff {G : Graph} {pa : Path} {f : Term} {n : Nat} :+ n ≤ (valueNodes G pa f).length ↔+ ∃ l : List Term, l.Nodup ∧ (∀ v ∈ l, IsValue G pa f v) ∧ n ≤ l.length :=+ count_ge_iff nodup_valueNodes (fun _ => mem_valueNodes)theorem maxCount_iff {G : Graph} {pa : Path} {f : Term} {n : Nat} :(valueNodes G pa f).length ≤ n ↔- ∀ l : List Term, l.Nodup → (∀ v ∈ l, IsValue G pa f v) → l.length ≤ n := by+ ∀ l : List Term, l.Nodup → (∀ v ∈ l, IsValue G pa f v) → l.length ≤ n :=+ count_le_iff nodup_valueNodes (fun _ => mem_valueNodes)++/-! ## The qualified value shape++`collect` has already run the inner shape at every value node, so the qualifying+nodes are read off its output rather than recomputed. The two lemmas below are what+turn that output into the set the counting lemmas above need. -/++theorem nodup_qualifyingNodes {out : List (Term × List Result)} {L : List Term}+ (hmap : out.map Prod.fst = L) (hnd : L.Nodup) : (qualifyingNodes out).Nodup := by+ rw [qualifyingNodes]+ refine List.Nodup.sublist ?_ (hmap ▸ hnd)+ exact List.Sublist.map _ List.filter_sublist++theorem mem_qualifyingNodes {G : Graph} {q : Shape} {pa : Path} {f : Term}+ {out : List (Term × List Result)} (hmap : out.map Prod.fst = valueNodes G pa f)+ (hconf : ∀ p ∈ out, (p.2 = [] ↔ Conf G q p.1)) {v : Term} :+ v ∈ qualifyingNodes out ↔ (IsValue G pa f v ∧ Conf G q v) := by+ rw [qualifyingNodes, List.mem_map]constructor- · intro h l hnd hmem- exact Nat.le_trans- (List.Nodup.length_le_of_subset hnd (fun _ hv => mem_valueNodes.mpr (hmem _ hv))) h- · intro h- exact h _ nodup_valueNodes (fun _ hv => mem_valueNodes.mp hv)+ · rintro ⟨p, hp, rfl⟩+ rw [List.mem_filter] at hp+ obtain ⟨hpo, he⟩ := hp+ refine ⟨?_, (hconf p hpo).mp (List.isEmpty_iff.mp he)⟩+ apply mem_valueNodes.mp+ rw [← hmap]+ exact List.mem_map.mpr ⟨p, hpo, rfl⟩+ · rintro ⟨hv, hc⟩+ have hin : v ∈ out.map Prod.fst := by rw [hmap]; exact mem_valueNodes.mpr hv+ obtain ⟨p, hp, hp1⟩ := List.mem_map.mp hin+ refine ⟨p, ?_, hp1⟩+ rw [List.mem_filter]+ refine ⟨hp, ?_⟩+ rw [List.isEmpty_iff]+ exact (hconf p hp).mpr (by rw [hp1]; exact hc)/-- The `sh:class` decision is exactly SHACL instancehood, given a closedsuperclass set. Soundness comes from the iteration, completeness from the closure@@ -203,6 +300,334 @@ theorem evalDatatype_spec {G : Graph} {d src f : Term} {rs : List Result}subst eexact absurd hdt hd+/-- The four value-range constraints at once. The hypothesis `hb` is what ties a+particular constraint to a particular set of accepted orders, and it is discharged+by `Iff.rfl` at each use because `Spec.lean` states those four clauses in exactly+this form. -/+theorem evalCompare_spec {G : Graph} {ok : List Cmp} {comp : Term} {s : Shape}+ {c src f : Term} {rs : List Result}+ (h : evalCompare ok comp s c src f = .ok rs) (hb : Conf G s f ↔ CmpIs ok c f) :+ (rs = [] ↔ Conf G s f) ∧ (∀ x ∈ rs, ¬ Conf G x.blamed x.blamedNode) := by+ rw [evalCompare] at h+ cases hc : cmpTerms c f with+ | none => simp only [hc] at h; exact absurd h (by simp)+ | some k =>+ simp only [hc] at h+ refine leafCase h ?_ rfl rfl+ rw [hb, CmpIs]+ constructor+ · intro hk+ exact ⟨k, hc, List.contains_iff_mem.mp hk⟩+ · rintro ⟨k', hk', hm⟩+ rw [hc] at hk'+ injection hk' with e+ subst e+ exact List.contains_iff_mem.mpr hm++/-- Every constraint that asks a question about the string a value node denotes, at+once: the two lengths and `sh:pattern`. Includes the blank-node rule and the refusal+on an escaped spelling. -/+theorem evalStr_spec {G : Graph} {P : List Char → Bool} {Q : List Char → Prop} {comp : Term}+ {s : Shape} {src f : Term} {rs : List Result}+ (h : evalStr P comp s src f = .ok rs) (hPQ : ∀ cs, P cs = true ↔ Q cs)+ (hb : Conf G s f ↔ StrProp f Q) :+ (rs = [] ↔ Conf G s f) ∧ (∀ x ∈ rs, ¬ Conf G x.blamed x.blamedNode) := by+ rw [evalStr] at h+ cases hs : strRep f with+ | chars cs =>+ simp only [hs] at h+ refine leafCase h ?_ rfl rfl+ rw [hb, StrProp]+ constructor+ · intro hp+ exact ⟨cs, hs, (hPQ _).mp hp⟩+ · rintro ⟨cs', hs', hq⟩+ rw [hs] at hs'+ injection hs' with e+ subst e+ exact (hPQ _).mpr hq+ | noString =>+ simp only [hs] at h+ refine leafCase h ?_ rfl rfl+ rw [hb, StrProp]+ constructor+ · intro hp; exact absurd hp (by simp)+ · rintro ⟨cs, hs', -⟩+ rw [hs] at hs'+ exact absurd hs' (by simp)+ | unknown => simp only [hs] at h; exact absurd h (by simp)++/-- The two length constraints, as the special case where the question is about the+number of characters. -/+theorem evalLength_spec {G : Graph} {P : Nat → Bool} {Q : Nat → Prop} {comp : Term}+ {s : Shape} {src f : Term} {rs : List Result}+ (h : evalLength P comp s src f = .ok rs) (hPQ : ∀ n, P n = true ↔ Q n)+ (hb : Conf G s f ↔ StrLen f Q) :+ (rs = [] ↔ Conf G s f) ∧ (∀ x ∈ rs, ¬ Conf G x.blamed x.blamedNode) :=+ evalStr_spec (by rw [evalLength] at h; exact h) (fun cs => hPQ cs.length) hb++/-! ## The pattern matcher decides the pattern relation++`mem_reRem` is the whole content: the remainders the matcher enumerates are exactly+the remainders the relation admits. Both directions, by induction on the pattern. -/++theorem mem_reRem {fold : Bool} : ∀ (items : List Item) (s r : List Char),+ r ∈ reRem fold items s ↔ ItemsMatch fold items s r+ | [], s, r => by+ rw [reRem.eq_def, ItemsMatch]+ simp [eq_comm]+ | it :: rest, s, r => by+ rw [reRem.eq_def, ItemsMatch]+ cases hq : it.quant with+ | one =>+ simp only [hq]+ cases s with+ | nil => simp+ | cons c s' =>+ by_cases ha : itemAdmits fold it c = true+ · simp only [ha, if_pos]+ rw [mem_reRem rest s' r]+ constructor+ · intro h; exact ⟨c, s', rfl, ha, h⟩+ · rintro ⟨c', s'', he, -, h⟩+ injection he with e1 e2+ subst e1+ subst e2+ exact h+ · simp only [Bool.not_eq_true] at ha+ simp only [ha, Bool.false_eq_true, if_false, List.not_mem_nil, false_iff]+ rintro ⟨c', s'', he, ha', -⟩+ injection he with e1 e2+ subst e1+ rw [ha] at ha'+ exact absurd ha' (by simp)+ | star =>+ simp only [hq]+ rw [List.mem_flatMap]+ constructor+ · rintro ⟨k, hk, hr⟩+ rw [List.mem_filter, List.mem_range] at hk+ obtain ⟨-, hall⟩ := hk+ refine ⟨s.take k, s.drop k, (List.take_append_drop k s).symm, ?_,+ (mem_reRem rest _ r).mp hr⟩+ intro c hc+ exact (List.all_eq_true.mp hall) c hc+ · rintro ⟨pre, s', hcat, hall, hm⟩+ refine ⟨pre.length, ?_, ?_⟩+ · rw [List.mem_filter, List.mem_range]+ constructor+ · subst hcat+ simp+ omega+ · rw [List.all_eq_true]+ intro c hc+ refine hall c ?_+ rw [hcat] at hc+ simpa using hc+ · rw [hcat]+ simpa using (mem_reRem rest s' r).mpr hm++theorem mem_suffixesOf : ∀ {s t : List Char}, t ∈ suffixesOf s ↔ ∃ pre, s = pre ++ t+ | [], t => by+ rw [suffixesOf, List.mem_singleton]+ constructor+ · rintro rfl; exact ⟨[], rfl⟩+ · rintro ⟨pre, h⟩+ exact (List.append_eq_nil_iff.mp h.symm).2+ | c :: s, t => by+ rw [suffixesOf, List.mem_cons, mem_suffixesOf]+ constructor+ · rintro (rfl | ⟨pre, rfl⟩)+ · exact ⟨[], rfl⟩+ · exact ⟨c :: pre, rfl⟩+ · rintro ⟨pre, h⟩+ cases pre with+ | nil => exact Or.inl (by simpa using h.symm)+ | cons a pre' =>+ refine Or.inr ⟨pre', ?_⟩+ injection h with h1 h2++theorem matchFrom_iff {re : Regex} {t : List Char} :+ ((reRem re.fold re.items t).any fun r => !re.anchorEnd || r.isEmpty) = true ↔+ ∃ r, ItemsMatch re.fold re.items t r ∧ (re.anchorEnd = true → r = []) := by+ rw [List.any_eq_true]+ constructor+ · rintro ⟨r, hr, hb⟩+ refine ⟨r, (mem_reRem _ _ _).mp hr, ?_⟩+ intro he+ rw [he] at hb+ exact List.isEmpty_iff.mp (by simpa using hb)+ · rintro ⟨r, hm, he⟩+ refine ⟨r, (mem_reRem _ _ _).mpr hm, ?_⟩+ cases hae : re.anchorEnd with+ | true => simp [he hae]+ | false => simp++/-- **The matcher decides the pattern relation**, anchors and search included. -/+theorem regexMatchB_iff {re : Regex} {s : List Char} :+ regexMatchB re s = true ↔ RegexMatch re s := by+ rw [regexMatchB, List.any_eq_true, RegexMatch]+ constructor+ · rintro ⟨t, ht, hb⟩+ obtain ⟨r, hm, he⟩ := matchFrom_iff.mp hb+ by_cases hs : re.anchorStart = true+ · rw [if_pos hs, List.mem_singleton] at ht+ subst ht+ exact ⟨[], t, r, rfl, fun _ => rfl, hm, he⟩+ · rw [if_neg hs] at ht+ obtain ⟨pre, hpre⟩ := mem_suffixesOf.mp ht+ exact ⟨pre, t, r, hpre, fun h => absurd h hs, hm, he⟩+ · rintro ⟨pre, suf, r, hcat, hps, hm, he⟩+ refine ⟨suf, ?_, matchFrom_iff.mpr ⟨r, hm, he⟩⟩+ by_cases hs : re.anchorStart = true+ · rw [if_pos hs, List.mem_singleton]+ have hp : pre = [] := hps hs+ subst hp+ simpa using hcat.symm+ · rw [if_neg hs]+ exact mem_suffixesOf.mpr ⟨pre, hcat⟩++/-! ## The property-pair constraints -/++theorem cmpPair_ok {ok : List Cmp} {v w : Term} {b : Bool} (h : cmpPair ok v w = .ok b) :+ b = true ↔ CmpIs ok v w := by+ rw [cmpPair] at h+ cases hc : cmpTerms v w with+ | none => simp only [hc] at h; exact absurd h (by simp)+ | some k =>+ simp only [hc] at h+ injection h with h+ subst h+ rw [CmpIs]+ constructor+ · intro hk; exact ⟨k, hc, List.contains_iff_mem.mp hk⟩+ · rintro ⟨k', hk', hm⟩+ rw [hc] at hk'+ injection hk' with e+ subst e+ exact List.contains_iff_mem.mpr hm++theorem cmpRow_ok {ok : List Cmp} {v : Term} :+ ∀ {ws : List Term} {b : Bool}, cmpRow ok v ws = .ok b → (b = true ↔ ∀ w ∈ ws, CmpIs ok v w)+ | [], b, h => by rw [cmpRow] at h; injection h with h; subst h; simp+ | w :: ws, b, h => by+ rw [cmpRow] at h+ cases ha : cmpPair ok v w with+ | error e => rw [bind_error_eq ha] at h; exact absurd h (by simp)+ | ok a =>+ rw [bind_ok_eq ha] at h+ cases hb : cmpRow ok v ws with+ | error e => rw [bind_error_eq hb] at h; exact absurd h (by simp)+ | ok b' =>+ rw [bind_ok_eq hb] at h+ injection h with h+ subst h+ rw [Bool.and_eq_true, cmpPair_ok ha, cmpRow_ok hb]+ constructor+ · rintro ⟨h1, h2⟩ u hu+ rcases List.mem_cons.mp hu with rfl | hu+ · exact h1+ · exact h2 u hu+ · intro hall+ exact ⟨hall w (List.mem_cons_self ..),+ fun u hu => hall u (List.mem_cons_of_mem _ hu)⟩++theorem cmpGrid_ok {ok : List Cmp} :+ ∀ {vs ws : List Term} {b : Bool}, cmpGrid ok vs ws = .ok b →+ (b = true ↔ ∀ v ∈ vs, ∀ w ∈ ws, CmpIs ok v w)+ | [], _, b, h => by rw [cmpGrid] at h; injection h with h; subst h; simp+ | v :: vs, ws, b, h => by+ rw [cmpGrid] at h+ cases ha : cmpRow ok v ws with+ | error e => rw [bind_error_eq ha] at h; exact absurd h (by simp)+ | ok a =>+ rw [bind_ok_eq ha] at h+ cases hb : cmpGrid ok vs ws with+ | error e => rw [bind_error_eq hb] at h; exact absurd h (by simp)+ | ok b' =>+ rw [bind_ok_eq hb] at h+ injection h with h+ subst h+ rw [Bool.and_eq_true, cmpRow_ok ha, cmpGrid_ok hb]+ constructor+ · rintro ⟨h1, h2⟩ u hu+ rcases List.mem_cons.mp hu with rfl | hu+ · exact h1+ · exact h2 u hu+ · intro hall+ exact ⟨hall v (List.mem_cons_self ..),+ fun u hu => hall u (List.mem_cons_of_mem _ hu)⟩++theorem equals_iff {G : Graph} {pa : Option Path} {q f : Term} :+ ((valueNodesOrSelf G pa f).all (fun v => (valueNodes G (.pred q) f).contains v) &&+ (valueNodes G (.pred q) f).all (fun w => (valueNodesOrSelf G pa f).contains w)) = true ↔+ ∀ v, IsValueOrSelf G pa f v ↔ (⟨f, q, v⟩ : Triple) ∈ G := by+ rw [Bool.and_eq_true, List.all_eq_true, List.all_eq_true]+ constructor+ · rintro ⟨h1, h2⟩ v+ constructor+ · intro hv+ exact mem_valueNodes.mp+ (List.contains_iff_mem.mp (h1 v (mem_valueNodesOrSelf.mpr hv)))+ · intro hv+ exact mem_valueNodesOrSelf.mp+ (List.contains_iff_mem.mp (h2 v (mem_valueNodes.mpr hv)))+ · intro h+ refine ⟨?_, ?_⟩+ · intro v hv+ exact List.contains_iff_mem.mpr+ (mem_valueNodes.mpr ((h v).mp (mem_valueNodesOrSelf.mp hv)))+ · intro w hw+ exact List.contains_iff_mem.mpr+ (mem_valueNodesOrSelf.mpr ((h w).mpr (mem_valueNodes.mp hw)))++theorem disjoint_iff {G : Graph} {pa : Option Path} {q f : Term} :+ ((valueNodesOrSelf G pa f).all (fun v => !((valueNodes G (.pred q) f).contains v))) = true ↔+ ∀ v, IsValueOrSelf G pa f v → (⟨f, q, v⟩ : Triple) ∉ G := by+ rw [List.all_eq_true]+ constructor+ · intro h v hv hG+ have hm : v ∈ valueNodes G (Path.pred q) f := mem_valueNodes.mpr hG+ have hc : (valueNodes G (Path.pred q) f).contains v = true := List.contains_iff_mem.mpr hm+ have hb := h v (mem_valueNodesOrSelf.mpr hv)+ rw [hc] at hb+ exact absurd hb (by simp)+ · intro h v hv+ by_cases hc : (valueNodes G (Path.pred q) f).contains v = true+ · have hG : (⟨f, q, v⟩ : Triple) ∈ G := mem_valueNodes.mp (List.contains_iff_mem.mp hc)+ exact absurd hG (h v (mem_valueNodesOrSelf.mp hv))+ · simp only [Bool.not_eq_true] at hc+ rw [hc]+ simp++theorem languageIn_iff {tags : List String} {f : Term} :+ (match langOf f with+ | none => false+ | some t => tags.any (fun r => langMatches r t)) = true ↔+ ∃ t, langOf f = some t ∧ ∃ r ∈ tags, langMatches r t = true := by+ cases h : langOf f with+ | none => simp+ | some t => simp [List.any_eq_true]++theorem uniqueLangB_iff {vs : List Term} :+ uniqueLangB vs = true ↔+ ∀ v ∈ vs, ∀ w ∈ vs, v ≠ w → (langOf v = none ∨ langOf v ≠ langOf w) := by+ rw [uniqueLangB]+ simp only [List.all_eq_true, Bool.or_eq_true, beq_iff_eq, Option.isNone_iff_eq_none,+ Bool.not_eq_true', decide_eq_false_iff_not]+ constructor+ · intro h v hv w hw hne+ rcases h v hv w hw with he | hn | hd+ · exact absurd he hne+ · exact Or.inl hn+ · exact Or.inr hd+ · intro h v hv w hw+ by_cases hvw : v = w+ · exact Or.inl hvw+ · rcases h v hv w hw hvw with hn | hd+ · exact Or.inr (Or.inl hn)+ · exact Or.inr (Or.inr hd)+/-! ## The two theorems -//-- Both halves at once, because the `forAll` case needs the verdict half of the@@ -245,6 +670,135 @@ theorem eval_agrees (G : Graph) (s : Shape) :intro src f rs hrw [eval] at hexact leafCase h List.contains_iff_mem rfl rfl+ | minInclusive c =>+ intro src f rs h+ rw [eval] at h+ exact evalCompare_spec h Iff.rfl+ | maxInclusive c =>+ intro src f rs h+ rw [eval] at h+ exact evalCompare_spec h Iff.rfl+ | minExclusive c =>+ intro src f rs h+ rw [eval] at h+ exact evalCompare_spec h Iff.rfl+ | maxExclusive c =>+ intro src f rs h+ rw [eval] at h+ exact evalCompare_spec h Iff.rfl+ | minLength n =>+ intro src f rs h+ rw [eval] at h+ exact evalLength_spec h (fun _ => decide_eq_true_iff) Iff.rfl+ | maxLength n =>+ intro src f rs h+ rw [eval] at h+ exact evalLength_spec h (fun _ => decide_eq_true_iff) Iff.rfl+ | pattern re =>+ intro src f rs h+ rw [eval] at h+ exact evalStr_spec h (fun _ => regexMatchB_iff) Iff.rfl+ | languageIn tags =>+ intro src f rs h+ rw [eval] at h+ exact leafCase h languageIn_iff rfl rfl+ | equals pa q =>+ intro src f rs h+ rw [eval] at h+ exact leafCase h equals_iff rfl rfl+ | disjoint pa q =>+ intro src f rs h+ rw [eval] at h+ exact leafCase h disjoint_iff rfl rfl+ | lessThan pa q =>+ intro src f rs h+ rw [eval] at h+ cases hg : cmpGrid [Cmp.lt] (valueNodesOrSelf G pa f) (valueNodes G (.pred q) f) with+ | error e => rw [bind_error_eq hg] at h; exact absurd h (by simp)+ | ok b =>+ rw [bind_ok_eq hg] at h+ refine leafCase h ?_ rfl rfl+ rw [cmpGrid_ok hg]+ constructor+ · intro hall v w hv hw+ exact hall v (mem_valueNodesOrSelf.mpr hv) w (mem_valueNodes.mpr hw)+ · intro hall v hv w hw+ exact hall v w (mem_valueNodesOrSelf.mp hv) (mem_valueNodes.mp hw)+ | lessThanOrEq pa q =>+ intro src f rs h+ rw [eval] at h+ cases hg : cmpGrid [Cmp.lt, Cmp.eq] (valueNodesOrSelf G pa f)+ (valueNodes G (.pred q) f) with+ | error e => rw [bind_error_eq hg] at h; exact absurd h (by simp)+ | ok b =>+ rw [bind_ok_eq hg] at h+ refine leafCase h ?_ rfl rfl+ rw [cmpGrid_ok hg]+ constructor+ · intro hall v w hv hw+ exact hall v (mem_valueNodesOrSelf.mpr hv) w (mem_valueNodes.mpr hw)+ · intro hall v hv w hw+ exact hall v w (mem_valueNodesOrSelf.mp hv) (mem_valueNodes.mp hw)+ | qualifiedMin pa q n ihq =>+ intro src f rs h+ rw [eval] at h+ cases hc : collect (fun v => eval G q src v) (valueNodes G pa f) with+ | error e => rw [bind_error_eq hc] at h; exact absurd h (by simp)+ | ok out =>+ rw [bind_ok_eq hc] at h+ obtain ⟨hmap, hall⟩ := collect_ok hc+ have hconf : ∀ p ∈ out, (p.2 = [] ↔ Conf G q p.1) :=+ fun p hp => (ihq src p.1 p.2 (hall p hp)).1+ refine leafCase h ?_ rfl rfl+ exact Iff.trans decide_eq_true_iff+ (count_ge_iff (nodup_qualifyingNodes hmap nodup_valueNodes)+ (fun _ => mem_qualifyingNodes hmap hconf))+ | qualifiedMax pa q n ihq =>+ intro src f rs h+ rw [eval] at h+ cases hc : collect (fun v => eval G q src v) (valueNodes G pa f) with+ | error e => rw [bind_error_eq hc] at h; exact absurd h (by simp)+ | ok out =>+ rw [bind_ok_eq hc] at h+ obtain ⟨hmap, hall⟩ := collect_ok hc+ have hconf : ∀ p ∈ out, (p.2 = [] ↔ Conf G q p.1) :=+ fun p hp => (ihq src p.1 p.2 (hall p hp)).1+ refine leafCase h ?_ rfl rfl+ exact Iff.trans decide_eq_true_iff+ (count_le_iff (nodup_qualifyingNodes hmap nodup_valueNodes)+ (fun _ => mem_qualifyingNodes hmap hconf))+ | closed allowed =>+ intro src f rs h+ rw [eval] at h+ injection h with h+ subst h+ refine leafCaseMany closedResults_nil_iff ?_+ intro x hx+ rw [closedResults, List.mem_map] at hx+ obtain ⟨t, -, hxt⟩ := hx+ rw [← hxt]+ exact ⟨rfl, rfl⟩+ | report comp a iha =>+ intro src f rs h+ rw [eval] at h+ cases ha : eval G a src f with+ | error e => rw [bind_error_eq ha] at h; exact absurd h (by simp)+ | ok ra =>+ rw [bind_ok_eq ha] at h+ obtain ⟨ha1, -⟩ := iha src f ra ha+ refine leafCase h ?_ rfl rfl+ rw [List.isEmpty_iff]+ exact ha1+ | uniqueLang pa =>+ intro src f rs h+ rw [eval] at h+ refine leafCase h ?_ rfl rfl+ rw [uniqueLangB_iff]+ constructor+ · intro hall v w hv hw hne+ exact hall v (mem_valueNodesOrSelf.mpr hv) w (mem_valueNodesOrSelf.mpr hw) hne+ · intro hall v hv w hw hne+ exact hall v w (mem_valueNodesOrSelf.mp hv) (mem_valueNodesOrSelf.mp hw) hne| minCount pa n =>intro src f rs hrw [eval] at hdiff --git a/lean/Shacl/Compile.lean b/lean/Shacl/Compile.leanindex 12009b8d..8288acc5 100644--- a/lean/Shacl/Compile.lean+++ b/lean/Shacl/Compile.lean@@ -74,6 +74,27 @@ def datatype : Term := iri "datatype"def nodeKind : Term := iri "nodeKind"def minCount : Term := iri "minCount"def maxCount : Term := iri "maxCount"+def minInclusive : Term := iri "minInclusive"+def maxInclusive : Term := iri "maxInclusive"+def minExclusive : Term := iri "minExclusive"+def maxExclusive : Term := iri "maxExclusive"+def minLength : Term := iri "minLength"+def maxLength : Term := iri "maxLength"+def languageIn : Term := iri "languageIn"+def pattern : Term := iri "pattern"+def flags : Term := iri "flags"+def equals : Term := iri "equals"+def disjoint : Term := iri "disjoint"+def lessThan : Term := iri "lessThan"+def lessThanOrEquals : Term := iri "lessThanOrEquals"+def uniqueLang : Term := iri "uniqueLang"+def closed : Term := iri "closed"+def ignoredProperties : Term := iri "ignoredProperties"+def xone : Term := iri "xone"+def qualifiedValueShape : Term := iri "qualifiedValueShape"+def qualifiedMinCount : Term := iri "qualifiedMinCount"+def qualifiedMaxCount : Term := iri "qualifiedMaxCount"+def qualifiedValueShapesDisjoint : Term := iri "qualifiedValueShapesDisjoint"def hasValue : Term := iri "hasValue"def inList : Term := iri "in"def notC : Term := iri "not"@@ -111,7 +132,11 @@ def knownParams : List Term :=[ SH.path, SH.klass, SH.datatype, SH.nodeKind, SH.minCount, SH.maxCount,SH.hasValue, SH.inList, SH.notC, SH.andC, SH.orC, SH.nodeC, SH.property,SH.deactivated, SH.targetNode, SH.targetClass, SH.targetSubjectsOf,- SH.targetObjectsOf ]+ SH.targetObjectsOf, SH.minInclusive, SH.maxInclusive, SH.minExclusive,+ SH.maxExclusive, SH.minLength, SH.maxLength, SH.languageIn, SH.equals,+ SH.disjoint, SH.lessThan, SH.lessThanOrEquals, SH.uniqueLang, SH.closed,+ SH.ignoredProperties, SH.xone, SH.qualifiedValueShape, SH.qualifiedMinCount,+ SH.qualifiedMaxCount, SH.qualifiedValueShapesDisjoint, SH.pattern, SH.flags ]/-- Parameters with no effect on the verdict or on the result fields thisvalidator reports. `sh:severity` is the one that is a real gap; see the module@@ -171,8 +196,27 @@ def pathForms (G : Graph) (node : Term) : List String :=(if (objectsOf G node SH.zeroOrOnePath).isEmpty then [] else ["sh:zeroOrOnePath"]) ++(if (objectsOf G node V.first).isEmpty then [] else ["a sequence path"])-/-- A path, or an error naming the path form that was found. Only a predicate path-and `sh:inversePath` of a predicate are covered.+/-- Fold a sequence path's member list to the right. SHACL's sequence path is+n-ary; `Path.seq` is binary, and `a/b/c` means `a/(b/c)` under either bracketing+because the value nodes of a sequence are the same set either way. -/+def foldSeq : List Path → Except String Path+ | [] => .error "a sequence path with no members"+ | [p] => .ok p+ | p :: rest => do+ let t ← foldSeq rest+ .ok (.seq p t)++/-- The same for `sh:alternativePath`, where the folding is associative for the+same reason: alternative is union. -/+def foldAltPath : List Path → Except String Path+ | [] => .error "an sh:alternativePath with no members"+ | [p] => .ok p+ | p :: rest => do+ let t ← foldAltPath rest+ .ok (.alt p t)++/-- A path, or an error naming the path form that was found. `sh:zeroOrMorePath`+and `sh:oneOrMorePath` are the two forms refused; see `Shape.lean` for why.A node carrying TWO path forms is refused rather than read as either. SHACLrequires a well-formed path node to have exactly one form, and the suite's@@ -180,30 +224,150 @@ requires a well-formed path node to have exactly one form, and the suite'san inverse path. Reading it as the first form the code happens to check is how thiscompiler produced its one wrong answer against the suite: it chose the inversereading and blamed the wrong node. Refusing an ill-formed shapes graph and saying-so is the answer that cannot be wrong. -/-def compilePath (G : Graph) (node : Term) : Except String Path :=- if isIriSpelling node then .ok (.pred node)- else- match pathForms G node with- | [] => .error s!"{node} is not a path this development understands"- | ["sh:inversePath"] =>- match objectsOf G node SH.inversePath with- | [inner] =>- if isIriSpelling inner then .ok (.inv inner)- else .error "sh:inversePath of something other than a predicate is not implemented"- | _ => .error "more than one sh:inversePath on a path node"- | [one] => .error s!"{one} is not implemented"- | many =>- .error s!"the path node {node} carries more than one path form \- ({String.intercalate ", " many}); SHACL allows exactly one, so this shapes graph is \- ill formed and no reading of it is chosen"--def isDeactivated (G : Graph) (node : Term) : Bool :=- (objectsOf G node SH.deactivated).any fun o =>+so is the answer that cannot be wrong, and it stays refused now that sequence paths+ARE implemented: the Working Group's expected report reads that node as a sequence,+but the shapes graph does not say so and this compiler will not pick.++`fuel` bounds the nesting of path nodes. One level of nesting consumes at least one+triple of the shapes graph, so a budget of `|G| + 1` exhausts only on a cycle. -/+def compilePath (G : Graph) : Nat → Term → Except String Path+ | 0, node =>+ .error s!"the path at {node} nests deeper than the shapes graph is long, so it is cyclic"+ | fuel + 1, node =>+ if isIriSpelling node then .ok (.pred node)+ else+ match pathForms G node with+ | [] => .error s!"{node} is not a path this development understands"+ | ["sh:inversePath"] =>+ match objectsOf G node SH.inversePath with+ | [inner] =>+ if isIriSpelling inner then .ok (.inv inner)+ else .error "sh:inversePath of something other than a predicate is not implemented"+ | _ => .error "more than one sh:inversePath on a path node"+ | ["sh:alternativePath"] =>+ match objectsOf G node SH.alternativePath with+ | [l] => do+ let members ← readList G (G.length + 1) l+ let mut ps : List Path := []+ for m in members do+ ps := ps ++ [← compilePath G fuel m]+ foldAltPath ps+ | _ => .error "more than one sh:alternativePath on a path node"+ | ["sh:zeroOrOnePath"] =>+ match objectsOf G node SH.zeroOrOnePath with+ | [inner] => do+ let p ← compilePath G fuel inner+ .ok (.zeroOrOne p)+ | _ => .error "more than one sh:zeroOrOnePath on a path node"+ | ["a sequence path"] => do+ let members ← readList G (G.length + 1) node+ let mut ps : List Path := []+ for m in members do+ ps := ps ++ [← compilePath G fuel m]+ foldSeq ps+ | [one] => .error s!"{one} is not implemented"+ | many =>+ .error s!"the path node {node} carries more than one path form \+ ({String.intercalate ", " many}); SHACL allows exactly one, so this shapes graph is \+ ill formed and no reading of it is chosen"++/-- Is this parameter present with the literal value `true`?++Only the lexical form `true` counts. `"1"^^xsd:boolean` denotes the same boolean and+does NOT activate the constraint, which is what `core/property/uniqueLang-002`+requires and what the Recommendation's wording ("if `$uniqueLang` is `true`")+licenses: the parameter value is compared as a term. -/+def hasTrue (G : Graph) (node p : Term) : Bool :=+ (objectsOf G node p).any fun o =>match asLiteral o with| some l => l.lex == "true"| none => false+def isDeactivated (G : Graph) (node : Term) : Bool := hasTrue G node SH.deactivated++/-- The lexical form of a literal, for the string-valued parameters. -/+def readStringLit (o : Term) : Except String String :=+ match asLiteral o with+ | some l => .ok l.lex+ | none => .error s!"{o} is not a literal, so it cannot be a string-valued parameter"++/-! ## Reading a `sh:pattern`++Outside the theorem like everything else in this file, and refusing BY NAME. The+subset the matcher decides is documented in `Shacl/Shape.lean`; every construct+outside it is an error naming the character, so a shapes graph using one is+undetermined rather than answered by a matcher that quietly ignored it. -/++/-- The ranges of a character class, starting after the opening bracket and the+optional negation, ending at the closing bracket. -/+def classRanges : List Char → Option (List (Char × Char) × List Char)+ | [] => none+ | ']' :: rest => some ([], rest)+ | a :: '-' :: b :: rest =>+ if a == '\\' || b == '\\' || b == ']' then none+ else (classRanges rest).map fun p => ((a, b) :: p.1, p.2)+ | c :: rest =>+ if c == '\\' || c == '[' then none+ else (classRanges rest).map fun p => ((c, c) :: p.1, p.2)++/-- The characters that mean something in a regular expression and that this+development does not implement. `-` is absent on purpose: outside a character class+it is an ordinary character. -/+def isPatternMeta (c : Char) : Bool :=+ c == '[' || c == ']' || c == '(' || c == ')' || c == '{' || c == '}' ||+ c == '|' || c == '*' || c == '+' || c == '?' || c == '.' || c == '^' ||+ c == '$' || c == '\\'++def readQuant : List Char → Quant × List Char+ | '*' :: rest => (.star, rest)+ | cs => (.one, cs)++def readItems : Nat → List Char → Except String (List Item)+ | 0, _ =>+ .error "the pattern consumed more elements than it has characters, which cannot happen"+ | _ + 1, [] => .ok []+ | fuel + 1, '[' :: rest =>+ let (neg, r1) := match rest with | '^' :: r => (true, r) | r => (false, r)+ match classRanges r1 with+ | none => .error "the pattern uses a character class this matcher does not parse"+ | some (rs, r2) => do+ let (q, r3) := readQuant r2+ let tl ← readItems fuel r3+ .ok ({ neg := neg, ranges := rs, quant := q } :: tl)+ | fuel + 1, c :: rest =>+ if isPatternMeta c then+ .error s!"the pattern uses the regular-expression construct '{c}', which is not \+ implemented; see the subset in lean/Shacl/Shape.lean"+ else do+ let (q, r3) := readQuant rest+ let tl ← readItems fuel r3+ .ok ({ neg := false, ranges := [(c, c)], quant := q } :: tl)++/-- `sh:flags`, of which only `i` is implemented. -/+def readFlags (G : Graph) (node : Term) : Except String Bool := do+ let mut fold := false+ for o in objectsOf G node SH.flags do+ let f ← readStringLit o+ for c in f.toList do+ if c == 'i' then fold := true+ else throw s!"{node}: sh:flags \"{f}\" uses the flag '{c}', which is not implemented"+ return fold++def readPattern (fold : Bool) (lex : String) : Except String Regex :=+ if hasBackslash lex then+ .error "the pattern carries a backslash, and this development never decodes an escape, so \+ it cannot tell a literal backslash from an escape sequence"+ else+ let cs := lex.toList+ let (anchorStart, c1) := match cs with | '^' :: r => (true, r) | r => (false, r)+ let (anchorEnd, c2) :=+ match c1.getLast? with+ | some '$' => (true, c1.dropLast)+ | _ => (false, c1)+ do+ let items ← readItems (c2.length + 1) c2+ .ok { fold := fold, anchorStart := anchorStart, anchorEnd := anchorEnd, items := items }+/-- Wrap a value-node constraint for the shape it sits on: on a property shape itapplies to every value node, on a node shape to the focus node itself. -/def wrapV : Option Path → Shape → Shape@@ -218,14 +382,49 @@ def foldOr : List Shape → Shape| [] => .bot| s :: rest => .orC s (foldOr rest)+/-- One disjunct per member: that member conforms and none of the others does. -/+def pickOne : List Shape → List Shape → List Shape+ | _, [] => []+ | others, s :: rest =>+ Shape.andC s (foldAnd ((others ++ rest).map Shape.notC)) :: pickOne (others ++ [s]) rest++/-- `sh:xone`: EXACTLY one of the shapes conforms.++Compiled out of `sh:or`, `sh:and` and `sh:not` rather than given a constructor of+its own, so the semantics is the one `Spec.lean` already gives those three and the+agreement proof already covers it. The enclosing `report` is what makes the single+result carry `sh:XoneConstraintComponent`.++The cost is that each member shape is evaluated once per disjunct, so an `sh:xone`+of `n` members does `n` squared shape evaluations. The Working Group's tests use two+and three. A shapes graph with a long `sh:xone` list would be slow here, and that is+a real limit rather than a theoretical one. -/+def exactlyOne (ss : List Shape) : Shape := foldOr (pickOne [] ss)++/-- The sibling shapes of a property shape, for `sh:qualifiedValueShapesDisjoint`:+the `sh:qualifiedValueShape` of every OTHER property shape that the same parent+references through `sh:property`. Comparison is by term, so a parent that lists the+same property shape twice still has it as itself and not as its own sibling. -/+def siblingQualifiedShapes (G : Graph) (parent : Option Term) (self : Term) : List Term :=+ match parent with+ | none => []+ | some p =>+ ((dedup (objectsOf G p SH.property)).filter (fun ps => ps != self)).flatMap+ (fun ps => objectsOf G ps SH.qualifiedValueShape)+/-- Compile one shape node. `fuel` bounds the nesting; one level of nesting alwaysconsumes at least one triple of the shapes graph, so a budget of `|G| + 1`-exhausts only on a cycle. -/-def compileShape (G : Graph) : Nat → Term → Except String Shape- | 0, node =>+exhausts only on a cycle.++`parent` is the shape that reached this one through `sh:property`, and it is+threaded only because `sh:qualifiedValueShapesDisjoint` asks about siblings. A shape+reached any other way, or reached as a top-level target, has no parent for that+purpose and gets `none`. -/+def compileShape (G : Graph) : Nat → Option Term → Term → Except String Shape+ | 0, _, node =>.error s!"shape nesting at {node} exceeds the size of the shapes graph, so the shapes \are recursive; SHACL does not define the semantics of recursive shapes"- | fuel + 1, node => do+ | fuel + 1, parent, node => dofor p in predsOf G node doif isShaclPred p && !(knownParams.contains p) && !(ignoredParams.contains p) thenthrow s!"{node}: the constraint parameter {p} is not implemented"@@ -235,7 +434,7 @@ def compileShape (G : Graph) : Nat → Term → Except String Shapematch objectsOf G node SH.path with| [] => pure none| [po] => do- let pa ← compilePath G po+ let pa ← compilePath G (G.length + 1) popure (some pa)| _ => throw s!"{node}: more than one sh:path")let mut acc : Shape := .top@@ -249,26 +448,106 @@ def compileShape (G : Graph) : Nat → Term → Except String Shapefor o in objectsOf G node SH.inList dolet vs ← readList G (G.length + 1) oacc := .both acc (wrapV pathOpt (.inSet vs))+ for o in objectsOf G node SH.minInclusive do+ acc := .both acc (wrapV pathOpt (.minInclusive o))+ for o in objectsOf G node SH.maxInclusive do+ acc := .both acc (wrapV pathOpt (.maxInclusive o))+ for o in objectsOf G node SH.minExclusive do+ acc := .both acc (wrapV pathOpt (.minExclusive o))+ for o in objectsOf G node SH.maxExclusive do+ acc := .both acc (wrapV pathOpt (.maxExclusive o))+ for o in objectsOf G node SH.minLength do+ let n ← readNat o+ acc := .both acc (wrapV pathOpt (.minLength n))+ for o in objectsOf G node SH.maxLength do+ let n ← readNat o+ acc := .both acc (wrapV pathOpt (.maxLength n))+ let patterns := objectsOf G node SH.pattern+ if !patterns.isEmpty then+ let fold ← readFlags G node+ for o in patterns do+ let lex ← readStringLit o+ let re ← readPattern fold lex+ acc := .both acc (wrapV pathOpt (.pattern re))+ for o in objectsOf G node SH.languageIn do+ let members ← readList G (G.length + 1) o+ let mut tags : List String := []+ for m in members do+ tags := tags ++ [← readStringLit m]+ acc := .both acc (wrapV pathOpt (.languageIn tags))+ for o in objectsOf G node SH.equals do+ acc := .both acc (.equals pathOpt o)+ for o in objectsOf G node SH.disjoint do+ acc := .both acc (.disjoint pathOpt o)+ for o in objectsOf G node SH.lessThan do+ acc := .both acc (.lessThan pathOpt o)+ for o in objectsOf G node SH.lessThanOrEquals do+ acc := .both acc (.lessThanOrEq pathOpt o)+ if hasTrue G node SH.uniqueLang then+ acc := .both acc (.uniqueLang pathOpt)for o in objectsOf G node SH.notC do- let s ← compileShape G fuel o+ let s ← compileShape G fuel none oacc := .both acc (wrapV pathOpt (.notC s))for o in objectsOf G node SH.nodeC do- let s ← compileShape G fuel o+ let s ← compileShape G fuel none oacc := .both acc (wrapV pathOpt (.nodeC s))for o in objectsOf G node SH.andC dolet members ← readList G (G.length + 1) olet mut ss : List Shape := []for m in members do- ss := ss ++ [← compileShape G fuel m]+ ss := ss ++ [← compileShape G fuel none m]acc := .both acc (wrapV pathOpt (foldAnd ss))for o in objectsOf G node SH.orC dolet members ← readList G (G.length + 1) olet mut ss : List Shape := []for m in members do- ss := ss ++ [← compileShape G fuel m]+ ss := ss ++ [← compileShape G fuel none m]acc := .both acc (wrapV pathOpt (foldOr ss))+ for o in objectsOf G node SH.xone do+ let members ← readList G (G.length + 1) o+ let mut ss : List Shape := []+ for m in members do+ ss := ss ++ [← compileShape G fuel none m]+ acc := .both acc (wrapV pathOpt (.report C.xone (exactlyOne ss)))+ if hasTrue G node SH.closed then+ -- The allowed predicates: the `sh:path` of every property shape this shape+ -- references, when that path is an IRI, plus `sh:ignoredProperties`. A path+ -- that is not an IRI contributes nothing, which is what the Recommendation+ -- says ("all values of sh:path ... assuming these are IRIs").+ let mut allowed : List Term := []+ for ps in objectsOf G node SH.property do+ for p in objectsOf G ps SH.path do+ if isIriSpelling p then allowed := allowed ++ [p]+ for o in objectsOf G node SH.ignoredProperties do+ allowed := allowed ++ (← readList G (G.length + 1) o)+ acc := .both acc (wrapV pathOpt (.closed allowed))+ -- `sh:qualifiedValueShape` is the parameter that ACTIVATES the qualified+ -- components. Without it the count parameters carry no constraint at all, and+ -- `core/node/qualified-001` is the Working Group's test that they are then+ -- ignored rather than misread.+ match objectsOf G node SH.qualifiedValueShape with+ | [] => pure ()+ | [qv] =>+ match pathOpt with+ | none =>+ throw s!"{node}: sh:qualifiedValueShape on a shape with no sh:path; SHACL defines \+ the qualified components for property shapes only"+ | some pa => do+ let inner ← compileShape G fuel none qv+ let mut q : Shape := inner+ if hasTrue G node SH.qualifiedValueShapesDisjoint then+ for sv in siblingQualifiedShapes G parent node do+ let sibShape ← compileShape G fuel none sv+ q := .both q (.notC sibShape)+ for o in objectsOf G node SH.qualifiedMinCount do+ let n ← readNat o+ acc := .both acc (.qualifiedMin pa q n)+ for o in objectsOf G node SH.qualifiedMaxCount do+ let n ← readNat o+ acc := .both acc (.qualifiedMax pa q n)+ | _ => throw s!"{node}: more than one sh:qualifiedValueShape"for o in objectsOf G node SH.property do- let s ← compileShape G fuel o+ let s ← compileShape G fuel (some node) oacc := .both acc (wrapV pathOpt s)for o in objectsOf G node SH.hasValue domatch pathOpt with@@ -336,7 +615,7 @@ def compileShapes (G : Graph) : Except String (List ShapeDecl) := dofor node in targetedNodes G doif isDeactivated G node thencontinue- let s ← compileShape G (G.length + 1) node+ let s ← compileShape G (G.length + 1) none nodeout := out.push { id := node, targets := targetsOf G node, shape := s }return out.toListdiff --git a/lean/Shacl/Eval.lean b/lean/Shacl/Eval.leanindex 57c55bf3..b080b0a7 100644--- a/lean/Shacl/Eval.lean+++ b/lean/Shacl/Eval.lean@@ -84,40 +84,91 @@ theorem nodup_dedup [DecidableEq α] : ∀ (l : List α), (dedup l).Nodup/-! ## Reading the graph -/-/-- The value nodes of `f` along `pa`, without duplicates. -/-def valueNodes (G : Graph) (pa : Path) (f : Term) : List Term :=- dedup ((G.filter (pa.sel f)).map pa.val)+/-- The value nodes of `f` along `pa`, without duplicates.++The recursion is on the PATH, not on the graph, so it terminates for the same+reason a path is finite. That is the whole reason `sh:zeroOrMorePath` is not a+constructor: it would need a fixpoint over the graph instead. -/+def valueNodes (G : Graph) : Path → Term → List Term+ | .pred p, f => dedup ((G.filter (fun t => t.s == f && t.p == p)).map Triple.o)+ | .inv p, f => dedup ((G.filter (fun t => t.p == p && t.o == f)).map Triple.s)+ | .seq a b, f => dedup ((valueNodes G a f).flatMap (fun m => valueNodes G b m))+ | .alt a b, f => dedup (valueNodes G a f ++ valueNodes G b f)+ | .zeroOrOne a, f => dedup (f :: valueNodes G a f)++theorem mem_valueNodes {G : Graph} : ∀ {pa : Path} {f v : Term},+ v ∈ valueNodes G pa f ↔ IsValue G pa f v+ | .pred p, f, v => by+ rw [valueNodes, mem_dedup, List.mem_map]+ constructor+ · rintro ⟨t, ht, hv⟩+ rw [List.mem_filter] at ht+ obtain ⟨hG, hsel⟩ := ht+ simp only [Bool.and_eq_true, beq_iff_eq] at hsel+ cases t+ simp_all [IsValue]+ · intro h+ refine ⟨⟨f, p, v⟩, ?_, rfl⟩+ rw [List.mem_filter]+ exact ⟨h, by simp⟩+ | .inv p, f, v => by+ rw [valueNodes, mem_dedup, List.mem_map]+ constructor+ · rintro ⟨t, ht, hv⟩+ rw [List.mem_filter] at ht+ obtain ⟨hG, hsel⟩ := ht+ simp only [Bool.and_eq_true, beq_iff_eq] at hsel+ cases t+ simp_all [IsValue]+ · intro h+ refine ⟨⟨v, p, f⟩, ?_, rfl⟩+ rw [List.mem_filter]+ exact ⟨h, by simp⟩+ | .seq a b, f, v => by+ rw [valueNodes, mem_dedup, List.mem_flatMap]+ constructor+ · rintro ⟨m, hm, hv⟩+ exact ⟨m, mem_valueNodes.mp hm, mem_valueNodes.mp hv⟩+ · rintro ⟨m, hm, hv⟩+ exact ⟨m, mem_valueNodes.mpr hm, mem_valueNodes.mpr hv⟩+ | .alt a b, f, v => by+ rw [valueNodes, mem_dedup, List.mem_append]+ constructor+ · rintro (h | h)+ · exact Or.inl (mem_valueNodes.mp h)+ · exact Or.inr (mem_valueNodes.mp h)+ · rintro (h | h)+ · exact Or.inl (mem_valueNodes.mpr h)+ · exact Or.inr (mem_valueNodes.mpr h)+ | .zeroOrOne a, f, v => by+ rw [valueNodes, mem_dedup, List.mem_cons]+ constructor+ · rintro (rfl | h)+ · exact Or.inl rfl+ · exact Or.inr (mem_valueNodes.mp h)+ · rintro (rfl | h)+ · exact Or.inl rfl+ · exact Or.inr (mem_valueNodes.mpr h)++theorem nodup_valueNodes {G : Graph} {pa : Path} {f : Term} : (valueNodes G pa f).Nodup := by+ cases pa <;> (rw [valueNodes]; exact nodup_dedup _)++/-- The value nodes of a shape that may or may not carry a path. -/+def valueNodesOrSelf (G : Graph) : Option Path → Term → List Term+ | none, f => [f]+ | some pa, f => valueNodes G pa f++theorem mem_valueNodesOrSelf {G : Graph} {pa : Option Path} {f v : Term} :+ v ∈ valueNodesOrSelf G pa f ↔ IsValueOrSelf G pa f v := by+ cases pa with+ | none => simp [valueNodesOrSelf, IsValueOrSelf]+ | some p => exact mem_valueNodes-theorem mem_valueNodes {G : Graph} {pa : Path} {f v : Term} :- v ∈ valueNodes G pa f ↔ IsValue G pa f v := by- rw [valueNodes, mem_dedup, List.mem_map]+theorem nodup_valueNodesOrSelf {G : Graph} {pa : Option Path} {f : Term} :+ (valueNodesOrSelf G pa f).Nodup := bycases pa with- | pred p =>- constructor- · rintro ⟨t, ht, hv⟩- rw [List.mem_filter] at ht- obtain ⟨hG, hsel⟩ := ht- simp only [Path.sel, Bool.and_eq_true, beq_iff_eq] at hsel- simp only [Path.val] at hv- cases t- simp_all [IsValue]- · intro h- refine ⟨⟨f, p, v⟩, ?_, rfl⟩- rw [List.mem_filter]- exact ⟨h, by simp [Path.sel]⟩- | inv p =>- constructor- · rintro ⟨t, ht, hv⟩- rw [List.mem_filter] at ht- obtain ⟨hG, hsel⟩ := ht- simp only [Path.sel, Bool.and_eq_true, beq_iff_eq] at hsel- simp only [Path.val] at hv- cases t- simp_all [IsValue]- · intro h- refine ⟨⟨v, p, f⟩, ?_, rfl⟩- rw [List.mem_filter]- exact ⟨h, by simp [Path.sel]⟩+ | none => simp [valueNodesOrSelf]+ | some p => rw [valueNodesOrSelf]; exact nodup_valueNodes/-- Every `rdf:type` value of `x`. Duplicates are harmless here: only membership isever asked. -/@@ -299,6 +350,13 @@ inductive Refusal where| unknownLexicalSpace (dt : Term) (lex : String)/-- The `rdfs:subClassOf` iteration did not reach a closed set in budget. -/| subclassClosureNotReached (c : Term)+ /-- A value-range or property-pair constraint had to compare two terms by value+ and `cmpTerms` declined. Note that this is NOT the case where SPARQL raises a+ type error: that one is comparable-by-refusal, reported as a violation. -/+ | unknownComparison (a b : Term)+ /-- A length constraint had to count the characters of the string a spelling+ denotes, and the spelling carries a backslash escape that nothing here decodes. -/+ | escapedLexicalForm (t : Term)deriving Reprdef Refusal.describe : Refusal → String@@ -306,6 +364,12 @@ def Refusal.describe : Refusal → Strings!"sh:datatype: the lexical space of {dt} is not implemented, so \"{lex}\" cannot be judged well formed"| .subclassClosureNotReached c =>s!"sh:class: the rdfs:subClassOf closure of {c} did not settle within the iteration budget"+ | .unknownComparison a b =>+ s!"value comparison: no rule this development implements orders {a} against {b}, and \+ SPARQL's type-error case is not known to apply either, so no order is claimed"+ | .escapedLexicalForm t =>+ s!"string length: {t} carries a backslash escape and escapes are never decoded here, so \+ the length of the string it denotes is unknown"/-- A result blaming the focus node itself. -/def violation (src comp : Term) (s : Shape) (f : Term) : Result :=@@ -319,6 +383,21 @@ def violationOn (src comp : Term) (s : Shape) (f : Term) (pa : Path) : Result :={ focus := f, path := some pa, value := none, source := src, component := comp,blamed := s, blamedNode := f }+/-- A result blaming the value-node SET of a shape that may or may not carry a+path. The property-pair constraints and `sh:uniqueLang` are about the set, so they+name the path when there is one and carry no `sh:value`.++**One result per focus node, not one per offending value.** The Recommendation asks+for a separate result for each value node that breaks `sh:equals`, `sh:disjoint`,+`sh:lessThan` or `sh:lessThanOrEquals`, each carrying that value in `sh:value`.+This validator reports one. The verdict is unaffected and the result it does+produce is licensed by `eval_results_licensed`, but a consumer counting results+will count fewer than a fully conforming validator would. Named here rather than+discovered. -/+def violationPair (src comp : Term) (s : Shape) (f : Term) (pa : Option Path) : Result :=+ { focus := f, path := pa, value := none, source := src, component := comp,+ blamed := s, blamedNode := f }+/-- Decide a leaf constraint: no results when it holds, exactly one when it does not. -/def check (b : Bool) (r : Result) : Except Refusal (List Result) :=if b then .ok [] else .ok [r]@@ -330,7 +409,7 @@ Only results that do not already carry a path are re-aimed. A result that has oncame from a property shape nested inside this one and already names its own focusnode, which is the value node here; SHACL reports it unchanged. -/def liftValue (f : Term) (pa : Path) (v : Term) (r : Result) : Result :=- { r with focus := f, path := some pa, value := some v }+ if r.path.isNone then { r with focus := f, path := some pa, value := some v } else r/-- Evaluate a shape at each of a list of nodes, keeping the pairing so the callercan say which node produced which results. Any refusal aborts. -/@@ -371,6 +450,114 @@ def evalDatatype (d src f : Term) : Except Refusal (List Result) :=| some b => check b (violation src C.datatype (.datatype d) f)else check false (violation src C.datatype (.datatype d) f)+/-- The four value-range constraints, which differ only in which orders they+accept. A comparison the term model declines to make is a refusal; a comparison it+reports as a SPARQL type error is a violation, because the Recommendation asks+whether the SPARQL expression returns true and a type error does not. -/+def evalCompare (ok : List Cmp) (comp : Term) (s : Shape) (c src f : Term) :+ Except Refusal (List Result) :=+ match cmpTerms c f with+ | none => .error (.unknownComparison c f)+ | some k => check (ok.contains k) (violation src comp s f)++/-- Any constraint that asks a question about the string a value node denotes. A+blank node fails all of them, which is what the Recommendation says in as many+words for `sh:minLength` and `sh:maxLength` and what the approved tests+`core/node/minLength-001` and `core/node/pattern-001` both require. -/+def evalStr (P : List Char → Bool) (comp : Term) (s : Shape) (src f : Term) :+ Except Refusal (List Result) :=+ match strRep f with+ | .chars cs => check (P cs) (violation src comp s f)+ | .noString => check false (violation src comp s f)+ | .unknown => .error (.escapedLexicalForm f)++/-- The two length constraints. -/+def evalLength (P : Nat → Bool) (comp : Term) (s : Shape) (src f : Term) :+ Except Refusal (List Result) :=+ evalStr (fun cs => P cs.length) comp s src f++/-! ## Deciding a pattern++`reRem items s` is the set of REMAINDERS the items can leave after consuming a+prefix of `s`. Reading the answer as a set of remainders rather than as a boolean is+what makes the anchored and unanchored cases one function: `$` asks whether the+empty remainder is among them, and its absence asks whether there is any remainder+at all. -/++def reRem (fold : Bool) : (items : List Item) → (s : List Char) → List (List Char)+ | [], s => [s]+ | it :: rest, s =>+ match it.quant with+ | .one =>+ match s with+ | [] => []+ | c :: s' => if itemAdmits fold it c then reRem fold rest s' else []+ | .star =>+ ((List.range (s.length + 1)).filter+ (fun k => (s.take k).all (fun c => itemAdmits fold it c))).flatMap+ (fun k => reRem fold rest (s.drop k))+ termination_by items => items.length+ decreasing_by all_goals simp++/-- Every suffix of a string, longest first, including the empty one. These are the+positions an unanchored search may start at. -/+def suffixesOf : List Char → List (List Char)+ | [] => [[]]+ | c :: s => (c :: s) :: suffixesOf s++def regexMatchB (re : Regex) (s : List Char) : Bool :=+ (if re.anchorStart then [s] else suffixesOf s).any fun t =>+ (reRem re.fold re.items t).any fun r => !re.anchorEnd || r.isEmpty++/-! ## The two property-pair comparisons++`sh:lessThan` and `sh:lessThanOrEquals` compare every value node against every+value of the other property, so a single unknown comparison anywhere in that grid+makes the whole constraint undetermined. The traversal below binds BOTH halves+before combining them, so a refusal in any cell propagates whatever the other cells+decided: the answer cannot depend on which cell was reached first. -/++def cmpPair (ok : List Cmp) (v w : Term) : Except Refusal Bool :=+ match cmpTerms v w with+ | none => .error (.unknownComparison v w)+ | some k => .ok (ok.contains k)++def cmpRow (ok : List Cmp) (v : Term) : List Term → Except Refusal Bool+ | [] => .ok true+ | w :: ws => do+ let a ← cmpPair ok v w+ let b ← cmpRow ok v ws+ .ok (a && b)++def cmpGrid (ok : List Cmp) : List Term → List Term → Except Refusal Bool+ | [], _ => .ok true+ | v :: vs, ws => do+ let a ← cmpRow ok v ws+ let b ← cmpGrid ok vs ws+ .ok (a && b)++/-- The triples at a value node whose predicate the closed shape does not allow. -/+def closedOffenders (G : Graph) (allowed : List Term) (f : Term) : List Triple :=+ G.filter (fun t => t.s == f && !(allowed.contains t.p))++/-- One result per offending triple, each naming the predicate that was not allowed+and the object that was reached through it, which is what the Recommendation asks+for. All of them blame the same node and the same constraint. -/+def closedResults (G : Graph) (allowed : List Term) (src : Term) (s : Shape) (f : Term) :+ List Result :=+ (closedOffenders G allowed f).map fun t =>+ { focus := f, path := some (.pred t.p), value := some t.o, source := src,+ component := C.closed, blamed := s, blamedNode := f }++/-- The value nodes that conformed, out of what `collect` returned. -/+def qualifyingNodes (out : List (Term × List Result)) : List Term :=+ (out.filter (fun p => p.2.isEmpty)).map Prod.fst++/-- No two distinct value nodes carry the same language tag. -/+def uniqueLangB (vs : List Term) : Bool :=+ vs.all (fun v => vs.all (fun w =>+ (v == w) || ((langOf v).isNone || !(decide (langOf v = langOf w)))))+/-! ## The evaluator -/def eval (G : Graph) : Shape → Term → Term → Except Refusal (List Result)@@ -381,6 +568,47 @@ def eval (G : Graph) : Shape → Term → Term → Except Refusal (List Result)| .nodeKind k, src, f => check (nodeKindOK k f) (violation src C.nodeKind (.nodeKind k) f)| .hasValue v, src, f => check (f == v) (violation src C.hasValue (.hasValue v) f)| .inSet vs, src, f => check (vs.contains f) (violation src C.inSet (.inSet vs) f)+ | .minInclusive c, src, f => evalCompare [.lt, .eq] C.minInclusive (.minInclusive c) c src f+ | .maxInclusive c, src, f => evalCompare [.gt, .eq] C.maxInclusive (.maxInclusive c) c src f+ | .minExclusive c, src, f => evalCompare [.lt] C.minExclusive (.minExclusive c) c src f+ | .maxExclusive c, src, f => evalCompare [.gt] C.maxExclusive (.maxExclusive c) c src f+ | .minLength n, src, f =>+ evalLength (fun len => decide (n ≤ len)) C.minLength (.minLength n) src f+ | .maxLength n, src, f =>+ evalLength (fun len => decide (len ≤ n)) C.maxLength (.maxLength n) src f+ | .pattern re, src, f =>+ evalStr (fun cs => regexMatchB re cs) C.pattern (.pattern re) src f+ | .languageIn tags, src, f =>+ check (match langOf f with+ | none => false+ | some t => tags.any (fun r => langMatches r t))+ (violation src C.languageIn (.languageIn tags) f)+ | .equals pa q, src, f =>+ check ((valueNodesOrSelf G pa f).all (fun v => (valueNodes G (.pred q) f).contains v) &&+ (valueNodes G (.pred q) f).all (fun w => (valueNodesOrSelf G pa f).contains w))+ (violationPair src C.equals (.equals pa q) f pa)+ | .disjoint pa q, src, f =>+ check ((valueNodesOrSelf G pa f).all+ (fun v => !((valueNodes G (.pred q) f).contains v)))+ (violationPair src C.disjoint (.disjoint pa q) f pa)+ | .lessThan pa q, src, f => do+ let b ← cmpGrid [.lt] (valueNodesOrSelf G pa f) (valueNodes G (.pred q) f)+ check b (violationPair src C.lessThan (.lessThan pa q) f pa)+ | .lessThanOrEq pa q, src, f => do+ let b ← cmpGrid [.lt, .eq] (valueNodesOrSelf G pa f) (valueNodes G (.pred q) f)+ check b (violationPair src C.lessThanOrEq (.lessThanOrEq pa q) f pa)+ | .uniqueLang pa, src, f =>+ check (uniqueLangB (valueNodesOrSelf G pa f))+ (violationPair src C.uniqueLang (.uniqueLang pa) f pa)+ | .closed allowed, src, f => .ok (closedResults G allowed src (.closed allowed) f)+ | .qualifiedMin pa q n, src, f => do+ let out ← collect (fun v => eval G q src v) (valueNodes G pa f)+ check (decide (n ≤ (qualifyingNodes out).length))+ (violationOn src C.qualifiedMin (.qualifiedMin pa q n) f pa)+ | .qualifiedMax pa q n, src, f => do+ let out ← collect (fun v => eval G q src v) (valueNodes G pa f)+ check (decide ((qualifyingNodes out).length ≤ n))+ (violationOn src C.qualifiedMax (.qualifiedMax pa q n) f pa)| .minCount pa n, src, f =>check (decide (n ≤ (valueNodes G pa f).length))(violationOn src C.minCount (.minCount pa n) f pa)@@ -409,6 +637,9 @@ def eval (G : Graph) : Shape → Term → Term → Except Refusal (List Result)| .nodeC a, src, f => dolet ra ← eval G a src fcheck ra.isEmpty (violation src C.nodeC (.nodeC a) f)+ | .report comp a, src, f => do+ let ra ← eval G a src f+ check ra.isEmpty (violation src comp (.report comp a) f)| .forAll pa a, src, f => dolet out ← collect (fun v => eval G a src v) (valueNodes G pa f).ok (out.flatMap (fun q => q.2.map (liftValue f pa q.1)))diff --git a/lean/Shacl/Shape.lean b/lean/Shacl/Shape.leanindex 818560b0..a1b5aa1a 100644--- a/lean/Shacl/Shape.lean+++ b/lean/Shacl/Shape.lean@@ -45,27 +45,92 @@ the report and must not be able to change a verdict.-/namespace Shacl-/-- The two path forms this development covers.+/-- The path forms this development covers.-`sh:path` in SHACL Core also has sequence, alternative, zero-or-more, one-or-more-and zero-or-one forms. They are not here. The compiler refuses a shapes graph that-uses one, so a test that needs them is undetermined rather than wrong. -/+`sh:zeroOrMorePath` and `sh:oneOrMorePath` are NOT here, and they are the only+SHACL Core path forms that are not. Every form below is decided by a recursion that+follows the shape of the PATH and terminates because a path is a finite tree; those+two are transitive closures over the DATA GRAPH, so deciding them needs an+iteration whose bound has to be argued rather than read off the syntax. The+compiler refuses a shapes graph that uses one, so a test that needs them is+undetermined rather than wrong.++`inv` takes a predicate rather than a path. `sh:inversePath` of a compound path is+legal SHACL and the compiler refuses it, for a related reason: the value nodes of+an inverse path cannot be computed forwards from the focus node. -/inductive Path where+ /-- A predicate path. -/| pred (p : Term)+ /-- `sh:inversePath` of a predicate. -/| inv (p : Term)-deriving DecidableEq, Repr+ /-- A sequence path, written as an RDF list in the shapes graph. Binary here; the+ compiler folds a longer list to the right. -/+ | seq (a b : Path)+ /-- `sh:alternativePath`. Binary here, folded the same way. -/+ | alt (a b : Path)+ /-- `sh:zeroOrOnePath` -/+ | zeroOrOne (a : Path)+deriving DecidableEq, Repr, Inhabited++/-! ## The regular-expression subset `sh:pattern` is decided over++`sh:pattern` is defined by the SPARQL `REGEX` function, which is XPath's regular+expression language, which is XML Schema's plus a few additions. Core Lean has no+regular expression engine, and writing a general one with a proof that it decides+the XPath language is a project of its own.++So this development implements a SUBSET and refuses everything outside it BY NAME,+in `Shacl/Compile.lean`. The subset is: a literal character, a character class with+ranges and an optional leading negation, the `*` quantifier, the `^` and `$`+anchors, and the `i` flag. Anything else, `+`, `?`, `{n}`, `.`, `|`, grouping, a+backreference, an escape of any kind, is a compile error naming the construct, so a+shapes graph that uses one is undetermined rather than answered wrongly.++**Every element of the subset matches exactly one character.** That is what makes+the matcher below a structural recursion over the pattern with no backtracking+budget and no fuel: `star` is decided by trying each split point of the remaining+string, and the recursion moves to a shorter list of items each time.++A pattern is matched against the string a term denotes, by SEARCH rather than by+full match, which is what SPARQL `REGEX` does: an unanchored pattern matches when+SOME substring matches. -/-/-- Does this triple contribute a value node for focus node `f` along this path? -/-def Path.sel (pa : Path) (f : Term) (t : Triple) : Bool :=- match pa with- | .pred p => t.s == f && t.p == p- | .inv p => t.p == p && t.o == f+/-- How many times one element may repeat. -/+inductive Quant where+ | one+ | star+deriving DecidableEq, Repr, Inhabited-/-- The value node a selected triple contributes. -/-def Path.val (pa : Path) (t : Triple) : Term :=- match pa with- | .pred _ => t.o- | .inv _ => t.s+/-- One element of a pattern: a character class and a quantifier. A literal+character is the class holding the one range from it to itself. -/+structure Item where+ neg : Bool+ ranges : List (Char × Char)+ quant : Quant+deriving DecidableEq, Repr, Inhabited++def inRanges (rs : List (Char × Char)) (c : Char) : Bool :=+ rs.any (fun r => r.1.toNat ≤ c.toNat && c.toNat ≤ r.2.toNat)++/-- Does this element admit this character?++The `i` flag is applied to the INPUT character: the class is tried against both its+lower and its upper case. For a class of ASCII letters and ASCII letter ranges that+is exactly what XPath's `i` flag does. For a class whose range straddles a case+boundary it is not, and this matcher does not pretend otherwise; the suite's only+uses of the flag are the literal patterns `Aldi` and `joh`. -/+def itemAdmits (fold : Bool) (it : Item) (c : Char) : Bool :=+ let hit :=+ if fold then inRanges it.ranges c.toLower || inRanges it.ranges c.toUpper+ else inRanges it.ranges c+ if it.neg then !hit else hit++structure Regex where+ fold : Bool+ anchorStart : Bool+ anchorEnd : Bool+ items : List Item+deriving DecidableEq, Repr, Inhabited/-- The constraint components covered, plus the two units.@@ -88,6 +153,62 @@ inductive Shape where| hasValue (v : Term)/-- `sh:in` -/| inSet (vs : List Term)+ /-- `sh:minInclusive`. The parameter's value is carried as a term and compared+ by VALUE with `cmpTerms`, not by spelling. -/+ | minInclusive (c : Term)+ /-- `sh:maxInclusive` -/+ | maxInclusive (c : Term)+ /-- `sh:minExclusive` -/+ | minExclusive (c : Term)+ /-- `sh:maxExclusive` -/+ | maxExclusive (c : Term)+ /-- `sh:minLength` -/+ | minLength (n : Nat)+ /-- `sh:maxLength` -/+ | maxLength (n : Nat)+ /-- `sh:languageIn` -/+ | languageIn (tags : List String)+ /-- `sh:pattern`, with `sh:flags` folded into the `Regex`. -/+ | pattern (re : Regex)+ /-- `sh:equals`. The `Option Path` is `none` on a node shape, where the set of+ value nodes is the focus node on its own, and `some pa` on a property shape. The+ four property-pair constraints and `sh:uniqueLang` all take that shape, which is+ why they carry an `Option Path` rather than a `Path`: the suite puts `sh:equals`+ and `sh:disjoint` on node shapes and a `Path` could not express that. -/+ | equals (pa : Option Path) (q : Term)+ /-- `sh:disjoint` -/+ | disjoint (pa : Option Path) (q : Term)+ /-- `sh:lessThan` -/+ | lessThan (pa : Option Path) (q : Term)+ /-- `sh:lessThanOrEquals` -/+ | lessThanOrEq (pa : Option Path) (q : Term)+ /-- `sh:uniqueLang` -/+ | uniqueLang (pa : Option Path)+ /-- `sh:qualifiedMinCount`: at least `n` value nodes along `pa` conform to `q`.++ `q` is not only the `sh:qualifiedValueShape`. When+ `sh:qualifiedValueShapesDisjoint` is true the compiler conjoins the negation of+ every SIBLING shape into `q`, so the disjointness is expressed with `sh:and` and+ `sh:not`, whose semantics `Spec.lean` already gives, rather than with a clause of+ its own. The sibling lookup needs the parent shape and is therefore a compile-time+ question, which is where it belongs: the evaluator never re-reads the shapes+ graph. -/+ | qualifiedMin (pa : Path) (q : Shape) (n : Nat)+ /-- `sh:qualifiedMaxCount`, with `q` built the same way. -/+ | qualifiedMax (pa : Path) (q : Shape) (n : Nat)+ /-- `sh:closed`. The allowed predicates are computed by the compiler from the+ `sh:path` of every property shape the closed shape references plus+ `sh:ignoredProperties`, so the evaluator receives a list and never re-reads the+ shapes graph. -/+ | closed (allowed : List Term)+ /-- Evaluate the inner shape and report ONE result carrying this constraint+ component when it fails, discarding the inner results.++ `nodeC` is the same idea with `sh:NodeConstraintComponent` fixed. This one+ carries its own component, which is what lets `sh:xone` be COMPILED into the+ constructors already here, with `sh:or`, `sh:and` and `sh:not` doing the work,+ and still report `sh:XoneConstraintComponent` as the Recommendation requires. -/+ | report (comp : Term) (a : Shape)/-- The implicit conjunction of one shape's constraints. Transparent: theresults of both sides are reported. -/| both (a b : Shape)@@ -129,6 +250,23 @@ def notC : Term := "<http://www.w3.org/ns/shacl#NotConstraintComponent>"def nodeC : Term := "<http://www.w3.org/ns/shacl#NodeConstraintComponent>"def minCount : Term := "<http://www.w3.org/ns/shacl#MinCountConstraintComponent>"def maxCount : Term := "<http://www.w3.org/ns/shacl#MaxCountConstraintComponent>"+def minInclusive : Term := "<http://www.w3.org/ns/shacl#MinInclusiveConstraintComponent>"+def maxInclusive : Term := "<http://www.w3.org/ns/shacl#MaxInclusiveConstraintComponent>"+def minExclusive : Term := "<http://www.w3.org/ns/shacl#MinExclusiveConstraintComponent>"+def maxExclusive : Term := "<http://www.w3.org/ns/shacl#MaxExclusiveConstraintComponent>"+def minLength : Term := "<http://www.w3.org/ns/shacl#MinLengthConstraintComponent>"+def maxLength : Term := "<http://www.w3.org/ns/shacl#MaxLengthConstraintComponent>"+def languageIn : Term := "<http://www.w3.org/ns/shacl#LanguageInConstraintComponent>"+def pattern : Term := "<http://www.w3.org/ns/shacl#PatternConstraintComponent>"+def equals : Term := "<http://www.w3.org/ns/shacl#EqualsConstraintComponent>"+def disjoint : Term := "<http://www.w3.org/ns/shacl#DisjointConstraintComponent>"+def lessThan : Term := "<http://www.w3.org/ns/shacl#LessThanConstraintComponent>"+def lessThanOrEq : Term := "<http://www.w3.org/ns/shacl#LessThanOrEqualsConstraintComponent>"+def uniqueLang : Term := "<http://www.w3.org/ns/shacl#UniqueLangConstraintComponent>"+def closed : Term := "<http://www.w3.org/ns/shacl#ClosedConstraintComponent>"+def xone : Term := "<http://www.w3.org/ns/shacl#XoneConstraintComponent>"+def qualifiedMin : Term := "<http://www.w3.org/ns/shacl#QualifiedMinCountConstraintComponent>"+def qualifiedMax : Term := "<http://www.w3.org/ns/shacl#QualifiedMaxCountConstraintComponent>"/-- Not a SHACL IRI. `bot` has no counterpart in the Recommendation because it hasno counterpart in a shapes graph; it exists as the unit of `orC` and its result isdiff --git a/lean/Shacl/Spec.lean b/lean/Shacl/Spec.leanindex 796c9b58..bbf5f016 100644--- a/lean/Shacl/Spec.lean+++ b/lean/Shacl/Spec.lean@@ -27,6 +27,10 @@ called out where they occur, and there are two of them:specification would license, which is the more conservative of the two.* `klass` reads `rdfs:subClassOf*` off the data graph only. The Recommendation saysthe same, and an engine that reasons first will disagree with both.+* The four value-range clauses and the two length clauses read `cmpTerms` and+ `strRep` from `Shacl/Term.lean`, and both of those have a third answer. Where they+ decline, these clauses say the node does NOT conform and the evaluator refuses to+ answer instead, which is again the more conservative of the two.## Why `Conf` ignores `named`@@ -38,10 +42,27 @@ pass-through. That is a property worth stating rather than assuming, andnamespace Shacl/-- `v` is a value node of `f` along `pa`. The whole of the path semantics covered,-in two lines. -/+by recursion on the path.++A sequence path holds when some intermediate node joins the two halves, which is+the SPARQL property-path semantics and is NOT the same as "there is a triple".+`zeroOrOne` admits the focus node itself, so a focus node with no outgoing triple+still has exactly one value node, and `core/path/path-zeroOrOne-001` is the+Working Group's test that a validator does not forget that. -/def IsValue (G : Graph) : Path → Term → Term → Prop| .pred p, f, v => (⟨f, p, v⟩ : Triple) ∈ G| .inv p, f, v => (⟨v, p, f⟩ : Triple) ∈ G+ | .seq a b, f, v => ∃ m, IsValue G a f m ∧ IsValue G b m v+ | .alt a b, f, v => IsValue G a f v ∨ IsValue G b f v+ | .zeroOrOne a, f, v => v = f ∨ IsValue G a f v++/-- The value nodes of a shape that may or may not carry a path. On a property+shape they are the nodes reached along the path; on a node shape the single value+node is the focus node itself, which is what the Recommendation says and what makes+`sh:equals` on a node shape mean anything at all. -/+def IsValueOrSelf (G : Graph) : Option Path → Term → Term → Prop+ | none, f, v => v = f+ | some pa, f, v => IsValue G pa f v/-- `rdfs:subClassOf*`, read off the data graph and nothing else. Reflexive andtransitive by construction. -/@@ -55,6 +76,80 @@ subclass, reflexively and transitively, of the class. -/def IsInstance (G : Graph) (c x : Term) : Prop :=∃ t, (⟨x, V.type, t⟩ : Triple) ∈ G ∧ SubClassStar G t c+/-- `cmpTerms a b` is known, and the order it reports is one of `ok`.++The Recommendation phrases the four value-range constraints as SPARQL expressions+that must RETURN TRUE, so a pair SPARQL cannot compare is a violation rather than a+pass. `cmpTerms` reports such a pair as `some .incomparable`, which is never in any+`ok` list below, so this definition inherits that reading. A pair `cmpTerms`+declines to classify is `none`, which is also not in `ok`, so the specification+calls it a violation; the evaluator refuses instead. -/+def CmpIs (ok : List Cmp) (a b : Term) : Prop := ∃ k, cmpTerms a b = some k ∧ k ∈ ok++theorem CmpIs.of_eq {ok : List Cmp} {a b : Term} {k : Cmp} (h : cmpTerms a b = some k)+ (hm : k ∈ ok) : CmpIs ok a b := ⟨k, h, hm⟩++theorem CmpIs.not_of_eq {ok : List Cmp} {a b : Term} {k : Cmp} (h : cmpTerms a b = some k)+ (hm : k ∉ ok) : ¬ CmpIs ok a b := by+ rintro ⟨k', hk', hm'⟩+ rw [h] at hk'+ injection hk' with e+ subst e+ exact hm hm'++/-- Something holds of the string a term denotes. False for a blank node, which has+no string representation, and false for a spelling whose characters are not the+denoted string's, where the evaluator refuses instead. -/+def StrProp (t : Term) (Q : List Char → Prop) : Prop := ∃ cs, strRep t = .chars cs ∧ Q cs++/-- The string a term denotes has this many characters. False for a blank node,+which SHACL says violates both length constraints, and false for a spelling whose+characters are not the denoted string's, where the evaluator refuses. -/+def StrLen (t : Term) (P : Nat → Prop) : Prop := StrProp t (fun cs => P cs.length)++/-! ## What it is for a pattern to match++A recursive definition rather than an inductive relation, so that inverting it is+unfolding rather than a case analysis on indices. `ItemsMatch fold items s r` says+the items consume a prefix of `s` and leave `r`. -/++def ItemsMatch (fold : Bool) : List Item → List Char → List Char → Prop+ | [], s, r => r = s+ | it :: rest, s, r =>+ match it.quant with+ | .one =>+ ∃ c s', s = c :: s' ∧ itemAdmits fold it c = true ∧ ItemsMatch fold rest s' r+ | .star =>+ ∃ pre s', s = pre ++ s' ∧ (∀ c ∈ pre, itemAdmits fold it c = true) ∧+ ItemsMatch fold rest s' r++/-- SPARQL `REGEX` is a SEARCH: an unanchored pattern matches when some substring+matches. `^` pins the start of that substring to the start of the string and `$`+pins its end to the end. -/+def RegexMatch (re : Regex) (s : List Char) : Prop :=+ ∃ pre suf r, s = pre ++ suf ∧ (re.anchorStart = true → pre = []) ∧+ ItemsMatch re.fold re.items suf r ∧ (re.anchorEnd = true → r = [])++theorem StrLen.of_chars {t : Term} {cs : List Char} {P : Nat → Prop}+ (h : strRep t = .chars cs) (hp : P cs.length) : StrLen t P := ⟨cs, h, hp⟩++theorem StrLen.not_of_chars {t : Term} {cs : List Char} {P : Nat → Prop}+ (h : strRep t = .chars cs) (hp : ¬ P cs.length) : ¬ StrLen t P := by+ rintro ⟨cs', hc, hp'⟩+ rw [h] at hc+ injection hc with e+ subst e+ exact hp hp'++/-- A blank node has no string representation at all, so no length constraint holds+of it. This is the clause the Recommendation states separately for `sh:minLength`+and `sh:maxLength`, and it is why a blank node violates BOTH of them at once. -/+theorem StrLen.not_of_blank {t : Term} {P : Nat → Prop} (h : strRep t = .noString) :+ ¬ StrLen t P := by+ rintro ⟨cs, hc, -⟩+ rw [h] at hc+ exact absurd hc (by simp)+/-- **Conformance.** `Conf G s f` says focus node `f` conforms to shape `s` ingraph `G`.@@ -71,6 +166,32 @@ def Conf (G : Graph) : Shape → Term → Prop| .nodeKind k, f => ∃ κ, kindOf f = some κ ∧ k.admits κ = true| .hasValue v, f => f = v| .inSet vs, f => f ∈ vs+ | .minInclusive c, f => CmpIs [.lt, .eq] c f+ | .maxInclusive c, f => CmpIs [.gt, .eq] c f+ | .minExclusive c, f => CmpIs [.lt] c f+ | .maxExclusive c, f => CmpIs [.gt] c f+ | .minLength n, f => StrLen f (fun len => n ≤ len)+ | .maxLength n, f => StrLen f (fun len => len ≤ n)+ | .languageIn tags, f =>+ ∃ t, langOf f = some t ∧ ∃ r ∈ tags, langMatches r t = true+ | .pattern re, f => StrProp f (fun cs => RegexMatch re cs)+ | .equals pa q, f =>+ ∀ v, IsValueOrSelf G pa f v ↔ (⟨f, q, v⟩ : Triple) ∈ G+ | .disjoint pa q, f =>+ ∀ v, IsValueOrSelf G pa f v → (⟨f, q, v⟩ : Triple) ∉ G+ | .lessThan pa q, f =>+ ∀ v w, IsValueOrSelf G pa f v → (⟨f, q, w⟩ : Triple) ∈ G → CmpIs [.lt] v w+ | .lessThanOrEq pa q, f =>+ ∀ v w, IsValueOrSelf G pa f v → (⟨f, q, w⟩ : Triple) ∈ G → CmpIs [.lt, .eq] v w+ | .uniqueLang pa, f =>+ ∀ v w, IsValueOrSelf G pa f v → IsValueOrSelf G pa f w → v ≠ w →+ langOf v = none ∨ langOf v ≠ langOf w+ | .qualifiedMin pa q n, f =>+ ∃ l : List Term, l.Nodup ∧ (∀ v ∈ l, IsValue G pa f v ∧ Conf G q v) ∧ n ≤ l.length+ | .qualifiedMax pa q n, f =>+ ∀ l : List Term, l.Nodup → (∀ v ∈ l, IsValue G pa f v ∧ Conf G q v) → l.length ≤ n+ | .closed allowed, f => ∀ p o, (⟨f, p, o⟩ : Triple) ∈ G → p ∈ allowed+ | .report _ a, f => Conf G a f| .both a b, f => Conf G a f ∧ Conf G b f| .andC a b, f => Conf G a f ∧ Conf G b f| .orC a b, f => Conf G a f ∨ Conf G b fdiff --git a/lean/Shacl/Term.lean b/lean/Shacl/Term.leanindex 768c9178..211367bb 100644--- a/lean/Shacl/Term.lean+++ b/lean/Shacl/Term.lean@@ -26,9 +26,10 @@ the W3C suite and it is better to name them than to discover them.* **Two spellings of one value are two terms.** `"1"^^xsd:integer` and`"01"^^xsd:integer` denote the same integer and are distinct terms here, so`sh:hasValue`, `sh:in` and `sh:maxCount` count them separately. RDF itself is on- this side of the line for term equality, but SHACL's comparison constraints- (`sh:lessThan`, `sh:minInclusive`) are value-based and are therefore not- implemented at all rather than implemented wrongly.+ this side of the line for term equality. SHACL's comparison constraints+ (`sh:lessThan`, `sh:minInclusive`) are value-based, so they do NOT go through+ term equality: they go through `cmpTerms` below, which reads a value out of the+ spelling for the datatypes it knows and declines for the rest.* **Escapes are not normalised.** `"aAb"` and `"aAb"` are one value and twoterms. Nothing here unescapes a lexical form.* **IRIs are not normalised.** No percent-decoding, no case folding of the scheme,@@ -39,15 +40,18 @@ the W3C suite and it is better to name them than to discover them.different labels are different graphs here. SHACL conformance is not affected byblank node identity in the fragment covered, but a validation RESULT naming ablank node is only meaningful relative to the file it was read from.-* **Language tags are compared as written.** BCP 47 says `EN` and `en` are the same- tag. Here they are two tags. Nothing in the covered fragment compares tags, so- this costs nothing today; `sh:languageIn` is not implemented.+* **Language tags are compared as written, apart from ASCII case.** BCP 47 says+ `EN` and `en` are the same tag, and `langMatches` below folds ASCII case for+ exactly that reason. It does not do anything else BCP 47 asks for: no canonical+ form, no extlang collapsing, no validity check on the subtag grammar.* **A lexical form's LENGTH is not the value's length.** `"a\\nb"` is a three-character- value written with four characters, because nothing here decodes an escape. That is- why `sh:minLength` and `sh:maxLength` are not implemented rather than implemented- over the spelling: they would be right for every literal without an escape and- silently wrong for the rest, which is the worst of the three options.-* **Lexical spaces are known for five datatypes and no more.** See `lexOK`.+ value written with four characters, because nothing here decodes an escape. So+ `strRep` below hands back the characters of a spelling only when that spelling+ carries NO backslash, and answers `unknown` when it does. `sh:minLength` and+ `sh:maxLength` are then right for every literal without an escape and refuse on+ the rest, rather than being silently wrong on the rest.+* **Lexical spaces are known for nine datatypes and no more.** See `lexOK`.+* **Value comparison is known for four families and no more.** See `cmpTerms`.-/namespace Shacl@@ -79,6 +83,10 @@ def xsdString : Term := "<http://www.w3.org/2001/XMLSchema#string>"def xsdBoolean : Term := "<http://www.w3.org/2001/XMLSchema#boolean>"def xsdInteger : Term := "<http://www.w3.org/2001/XMLSchema#integer>"def xsdByte : Term := "<http://www.w3.org/2001/XMLSchema#byte>"+def xsdDecimal : Term := "<http://www.w3.org/2001/XMLSchema#decimal>"+def xsdDate : Term := "<http://www.w3.org/2001/XMLSchema#date>"+def xsdDateTime : Term := "<http://www.w3.org/2001/XMLSchema#dateTime>"+def rdfHTML : Term := "<http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML>"end V@@ -204,6 +212,211 @@ def intValue (s : String) : Option Int :=| '+' :: rest => if isDigits rest then some (Int.ofNat (natOfDigits rest)) else none| cs => if isDigits cs then some (Int.ofNat (natOfDigits cs)) else none+/-- An exact decimal value: `mant` divided by ten to the `scale`. No floating+point anywhere, so two spellings of one number compare equal and nothing rounds. -/+structure Dec where+ mant : Int+ scale : Nat+deriving DecidableEq, Repr++def takeDigits : List Char → List Char × List Char+ | [] => ([], [])+ | c :: rest =>+ if c.isDigit then+ let (a, b) := takeDigits rest+ (c :: a, b)+ else ([], c :: rest)++/-- The lexical space of `xsd:decimal` without its sign: digits with an optional+fractional part, or a bare fractional part. `4.`, `.5` and `4.0` are all in it. -/+def decUnsigned (cs : List Char) : Option Dec :=+ let (ip, r) := takeDigits cs+ match r with+ | [] => if ip.isEmpty then none else some ⟨Int.ofNat (natOfDigits ip), 0⟩+ | '.' :: fr =>+ let (fp, r2) := takeDigits fr+ if !r2.isEmpty then none+ else if ip.isEmpty && fp.isEmpty then none+ else some ⟨Int.ofNat (natOfDigits (ip ++ fp)), fp.length⟩+ | _ => none++def decOfLex (s : String) : Option Dec :=+ match s.toList with+ | '-' :: rest => (decUnsigned rest).map (fun d => ⟨-d.mant, d.scale⟩)+ | '+' :: rest => decUnsigned rest+ | cs => decUnsigned cs++/-! ## The Gregorian calendar, for `xsd:date` and `xsd:dateTime`++Written in `Nat` throughout. `Int` division in Lean rounds toward zero, the usual+day-number algorithms rely on that in one direction and on flooring in the other,+and the difference is exactly the kind of off-by-one that would be invisible in+this suite and wrong in a real graph. Restricting to years from 1 CE keeps every+division on a non-negative number, where all the conventions agree.++The price is stated rather than hidden: a lexical form with a NEGATIVE year, or the+year `0000`, is not judged at all. It is well formed XSD (`0000` in XSD 1.1, not in+1.0, which is itself a reason not to answer), and this module says `none` rather+than guessing either way. -/++def isLeapYear (y : Nat) : Bool := (y % 4 == 0 && y % 100 != 0) || y % 400 == 0++def daysInMonth (y m : Nat) : Nat :=+ if m == 2 then (if isLeapYear y then 29 else 28)+ else if m == 4 || m == 6 || m == 9 || m == 11 then 30+ else if 1 ≤ m && m ≤ 12 then 31+ else 0++/-- Days from 0001-01-01, which is day zero, on the proleptic Gregorian calendar. -/+def dayNumber (y m d : Nat) : Nat :=+ let n := y - 1+ let yearDays := n * 365 + n / 4 - n / 100 + n / 400+ let monthDays := (List.range (m - 1)).foldl (fun acc i => acc + daysInMonth y (i + 1)) 0+ yearDays + monthDays + (d - 1)++/-- Exactly `n` characters, or nothing. -/+def takeExactly : Nat → List Char → Option (List Char × List Char)+ | 0, cs => some ([], cs)+ | _ + 1, [] => none+ | n + 1, c :: cs => (takeExactly n cs).map fun p => (c :: p.1, p.2)++/-- Exactly `n` digits, as a number. -/+def digitsN (n : Nat) (cs : List Char) : Option (Nat × List Char) :=+ match takeExactly n cs with+ | none => none+ | some (ds, rest) => if ds.all Char.isDigit then some (natOfDigits ds, rest) else none++/-- A timezone offset in minutes east of UTC. XSD caps it at fourteen hours. -/+def parseOffset (cs : List Char) : Option Int :=+ match digitsN 2 cs with+ | none => none+ | some (h, r1) =>+ match r1 with+ | ':' :: r2 =>+ match digitsN 2 r2 with+ | none => none+ | some (mi, r3) =>+ if !r3.isEmpty then none+ else if h > 14 || mi > 59 then none+ else if h == 14 && mi != 0 then none+ else some (Int.ofNat (h * 60 + mi))+ | _ => none++/-- The timezone at the END of a lexical form: absent, `Z`, or a signed offset.+Anything else, including trailing junk, is not a timezone. -/+def parseTzEnd : List Char → Option (Option Int)+ | [] => some none+ | ['Z'] => some (some 0)+ | '+' :: rest => (parseOffset rest).map some+ | '-' :: rest => (parseOffset rest).map (fun m => some (-m))+ | _ => none++/-- `yyyy-mm-dd`, with the day checked against the month and the year. -/+def parseDateBody (cs : List Char) : Option (Nat × Nat × Nat × List Char) :=+ let (ds, r0) := takeDigits cs+ if ds.length < 4 then none+ else if ds.length > 4 && ds.head? == some '0' then none+ else+ let y := natOfDigits ds+ match r0 with+ | '-' :: r1 =>+ match digitsN 2 r1 with+ | none => none+ | some (mo, r2) =>+ match r2 with+ | '-' :: r3 =>+ match digitsN 2 r3 with+ | none => none+ | some (d, r4) =>+ if mo < 1 || mo > 12 then none+ else if d < 1 || d > daysInMonth y mo then none+ else some (y, mo, d, r4)+ | _ => none+ | _ => none++/-- `hh:mm:ss` with optional fractional seconds. Returns the seconds since+midnight as an exact scaled decimal, plus a carry of one day for the `24:00:00`+form, which XSD allows and which denotes midnight starting the next day. -/+def parseTimeBody (cs : List Char) : Option (Dec × Nat × List Char) :=+ match digitsN 2 cs with+ | none => none+ | some (h, r1) =>+ match r1 with+ | ':' :: r2 =>+ match digitsN 2 r2 with+ | none => none+ | some (mi, r3) =>+ match r3 with+ | ':' :: r4 =>+ match digitsN 2 r4 with+ | none => none+ | some (sec, r5) =>+ let (fd, r6) :=+ match r5 with+ | '.' :: fr => let (a, b) := takeDigits fr; (a, b)+ | _ => ([], r5)+ if (match r5 with | '.' :: _ => fd.isEmpty | _ => false) then none+ else if h > 24 || mi > 59 || sec > 59 then none+ else if h == 24 && (mi != 0 || sec != 0 || !(fd.all (· == '0'))) then none+ else+ let carry := if h == 24 then 1 else 0+ let base := (if h == 24 then 0 else h) * 3600 + mi * 60 + sec+ let scale := fd.length+ some (⟨Int.ofNat (base * 10 ^ scale + natOfDigits fd), scale⟩, carry, r6)+ | _ => none+ | _ => none++/-- What reading a date or dateTime lexical form can produce. `illFormed` is a+verdict about the lexical space; `notJudged` is this module declining. -/+inductive DtRead where+ /-- The seconds from 0001-01-01T00:00:00 in the form's OWN timezone, and that+ timezone's offset in minutes when the form carried one. -/+ | ok (local_ : Dec) (tz : Option Int)+ | illFormed+ | notJudged+deriving Repr++/-- Is this lexical form a year this module is willing to read? -/+def yearJudgeable (cs : List Char) : Bool :=+ match cs with+ | '-' :: _ => false+ | _ => let (ds, _) := takeDigits cs; !(ds.length ≥ 4 && ds.all (· == '0'))++def readDate (s : String) : DtRead :=+ let cs := s.toList+ if !yearJudgeable cs then .notJudged+ else+ match parseDateBody cs with+ | none => .illFormed+ | some (y, m, d, rest) =>+ match parseTzEnd rest with+ | none => .illFormed+ | some tz => .ok ⟨Int.ofNat (dayNumber y m d * 86400), 0⟩ tz++def readDateTime (s : String) : DtRead :=+ let cs := s.toList+ if !yearJudgeable cs then .notJudged+ else+ match parseDateBody cs with+ | none => .illFormed+ | some (y, m, d, r0) =>+ match r0 with+ | 'T' :: r1 =>+ match parseTimeBody r1 with+ | none => .illFormed+ | some (tod, carry, r2) =>+ match parseTzEnd r2 with+ | none => .illFormed+ | some tz =>+ let days := Int.ofNat ((dayNumber y m d + carry) * 86400)+ .ok ⟨days * Int.ofNat (10 ^ tod.scale) + tod.mant, tod.scale⟩ tz+ | _ => .illFormed++def dtLexOK : DtRead → Option Bool+ | .ok _ _ => some true+ | .illFormed => some false+ | .notJudged => none+/-- **Is this literal well formed for its datatype?**`some true` yes, `some false` no, `none` this module does not know the datatype's@@ -216,14 +429,19 @@ evaluator turns a `none` into a refusal to answer rather than into a verdict. This the whole difference between a validator that is quiet about what it does notknow and one that says `conforms` because it did not look.-The five it does know are `xsd:string` (every lexical form), `rdf:langString`-(every lexical form, given a tag), `xsd:boolean`, `xsd:integer` and `xsd:byte`.-Those are the datatypes the W3C core suite names in a `sh:datatype` constraint,-apart from `xsd:date` and `rdf:HTML`, which land in `none`.--The lexical form is still N-Triples-escaped when it gets here. For the five-datatypes above no well-formed value contains a character that needs escaping, so-the check is exact for them; it would not be for a datatype whose lexical space+The nine it does know are `xsd:string` (every lexical form), `rdf:langString`+(every lexical form, given a tag), `rdf:HTML` (every lexical form: RDF 1.1+Concepts says "the lexical space is the set of Unicode strings", so HTML parsing+never fails and there is nothing to reject), `xsd:boolean`, `xsd:integer`,+`xsd:byte`, `xsd:decimal`, `xsd:date` and `xsd:dateTime`. The last two are judged+by a real calendar, leap years included, and decline rather than answer on a+negative year or on `0000`; see the calendar section above.++The lexical form is still N-Triples-escaped when it gets here. For every datatype+above except `rdf:HTML` no well-formed value contains a character that needs+escaping, so the check is exact for them; `rdf:HTML` accepts every string, so the+escaping cannot change the answer there either. It would not be exact for a+datatype whose lexical spaceincludes quotes or newlines, which is one more reason the list is short. -/def lexOK (l : Lit) : Option Bool :=if l.dt = V.xsdString then some true@@ -231,10 +449,266 @@ def lexOK (l : Lit) : Option Bool :=else if l.dt = V.xsdBoolean thensome (l.lex = "true" || l.lex = "false" || l.lex = "1" || l.lex = "0")else if l.dt = V.xsdInteger then some (isIntLex l.lex)+ else if l.dt = V.rdfHTML then some trueelse if l.dt = V.xsdByte thensome (match intValue l.lex with| some v => -128 ≤ v && v ≤ 127| none => false)+ else if l.dt = V.xsdDecimal then some (decOfLex l.lex).isSome+ else if l.dt = V.xsdDate then dtLexOK (readDate l.lex)+ else if l.dt = V.xsdDateTime then dtLexOK (readDateTime l.lex)+ else none++/-! ## The string a term denotes, for the two length constraints++`sh:minLength` and `sh:maxLength` are defined over the SPARQL `STRLEN(str(v))` of+the value node, with the extra rule that a blank node always violates them. So the+question a length constraint asks is not "how long is this spelling" but "how long+is the string this spelling denotes", and those differ exactly when the spelling+carries a backslash escape, which nothing in this development decodes. -/++/-- The characters of the string a term denotes.++* `chars cs` the term denotes the string `cs`, exactly.+* `noString` the term is a blank node. SHACL says a blank node violates+ `sh:minLength` and `sh:maxLength` whatever the bound is, so this is a verdict and+ not a refusal.+* `unknown` the spelling carries a backslash, so its characters are not the+ denoted string's characters and this module will not guess how many there are. -/+inductive StrRep where+ | chars (cs : List Char)+ | noString+ | unknown+deriving DecidableEq, Repr++def hasBackslash (s : String) : Bool := s.toList.any (fun c => c == '\\')++/-- The body of an IRI spelling, without the angle brackets. -/+def iriBody (t : Term) : List Char :=+ match t.toList with+ | '<' :: rest => rest.dropLast+ | cs => cs++/-- `str(v)` as a character list, or a reason there is not one. For an IRI this is+the IRI itself; for a literal it is the lexical form, tag and datatype dropped. -/+def strRep (t : Term) : StrRep :=+ if isBlankSpelling t then .noString+ else if isIriSpelling t then+ (let body := iriBody t+ if body.any (fun c => c == '\\') then .unknown else .chars body)+ else+ match asLiteral t with+ | some l => if hasBackslash l.lex then .unknown else .chars l.lex.toList+ | none => .unknown++/-! ## Language tags, for `sh:languageIn` and `sh:uniqueLang` -/++def toLowerAscii (cs : List Char) : List Char := cs.map Char.toLower++/-- BCP 47 basic filtering, section 3.3.1: a basic language range matches a+language tag when the tag is the range, or the tag continues the range at a subtag+boundary. Comparison is ASCII case-insensitive, which is what BCP 47 requires;+nothing else BCP 47 says is implemented, and `*` is NOT treated as the wildcard+range because `sh:languageIn` takes tags rather than ranges in every test this is+measured against. -/+def langMatches (range tag : String) : Bool :=+ let r := toLowerAscii range.toList+ let t := toLowerAscii tag.toList+ if r.isPrefixOf t then (t.length == r.length) || (t.drop r.length).head? == some '-'+ else false++/-- The language tag of a term, when it has one. -/+def langOf (t : Term) : Option String :=+ match asLiteral t with+ | some l => l.lang+ | none => none++/-! ## Comparing two terms by VALUE++The Recommendation defines `sh:minExclusive`, `sh:maxExclusive`, `sh:minInclusive`,+`sh:maxInclusive`, `sh:lessThan` and `sh:lessThanOrEquals` through a SPARQL+expression: for `sh:minExclusive` the condition is that `$minExclusive < $value`+RETURNS TRUE. That phrasing carries the whole of SPARQL's three-valued behaviour.+`<` is defined only for two numerics, two simple literals or `xsd:string`s, two+`xsd:boolean`s and two `xsd:dateTime`s; every other pair of operands is a TYPE+ERROR, and a type error does not return true, so it is a violation.++This module therefore answers with three possibilities rather than two, and the+distinction between the second and the third is the point of the whole file.++* `some k` for `k` one of `lt`, `eq`, `gt`: the two are comparable and this is the+ order.+* `some incomparable`: SPARQL's `<` RAISES A TYPE ERROR here, and that is a+ verdict. An IRI or a blank node on either side, a language-tagged literal, or two+ literals from different families are all in this case.+* `some unordered`: the two have the same type and the order relation still does+ not put them in an order. Only `xsd:dateTime` does this, and only when one form+ carries a timezone and the other does not; see below. Also a verdict.+* `none`: this development does not know. A literal of a datatype outside the four+ families implemented, or a lexical form carrying an escape. The evaluator turns+ this into a refusal to answer, never into a verdict.++## What is and is not implemented++Implemented: `xsd:integer` and `xsd:decimal` (as exact scaled integers, so+`"4"^^xsd:integer` and `"4.0"^^xsd:decimal` compare EQUAL and no rounding happens+anywhere), `xsd:string` and plain literals, `xsd:boolean`, and `xsd:dateTime`.++NOT implemented, and therefore `none`: `xsd:float` and `xsd:double`, which are+binary floating point with `NaN` and two zeros; every derived integer type+(`xsd:byte`, `xsd:int`, `xsd:unsignedLong` and the rest), which SPARQL treats as+numeric and which this module declines rather than half-handles; `xsd:date`, whose+lexical space IS judged above but which the suite never compares. Declining costs a+refusal. Guessing would cost a wrong answer, and the second is worse.++## The timezone rule for `xsd:dateTime`, which is where the care is++Two forms that both carry a timezone are compared as instants. Two that both lack+one are compared as written. A MIXED pair is the interesting case, and XSD 1.0's+order relation for `dateTime` settles it: the form without a timezone stands for+any instant within fourteen hours either side, so the pair is ordered only when the+timezoned instant falls entirely outside that window, and is UNORDERED otherwise.++That is not an implementation convenience. `core/node/minInclusive-002` and+`core/node/minInclusive-003` are the Working Group's approved tests for exactly this+pair of cases, and both require the mixed comparisons to come out as violations:+`$minInclusive <= $value` does not return true when the two are unordered. An+implementation that instead gave the untimezoned form an implicit timezone, as+XPath's `op:dateTime-less-than` does, would answer `conforms` for at least one of+the value nodes in `minInclusive-003` and would fail that test. -/++/-- The result of SPARQL's `<` family on two RDF terms, as far as this development+is willing to commit. `incomparable` is a verdict, not an absence of one. -/+inductive Cmp where+ | lt+ | eq+ | gt+ /-- SPARQL's `<` is a type error on this pair of operands. -/+ | incomparable+ /-- Same type, and the order relation still does not order them. Only a+ timezoned `xsd:dateTime` against an untimezoned one, within fourteen hours. -/+ | unordered+deriving DecidableEq, Repr++/-- The families SPARQL's `<` is defined within. -/+inductive Fam where+ | num+ | str+ | boolean+ | dateTime+deriving DecidableEq, Repr++/-- Where a term sits: in a family, definitely in none, or not classified. -/+inductive Classified where+ | inFam (φ : Fam)+ /-- Definitely outside every family SPARQL's `<` is defined on, so `<` is a type+ error on this term whatever the other operand is. -/+ | noFam+ | unknown+deriving DecidableEq, Repr++def famOf (t : Term) : Classified :=+ if isIriSpelling t then .noFam+ else if isBlankSpelling t then .noFam+ else+ match asLiteral t with+ | none => .unknown+ | some l =>+ if l.lang.isSome then .noFam+ else if l.dt = V.xsdString then .inFam .str+ else if l.dt = V.xsdBoolean then .inFam .boolean+ else if l.dt = V.xsdInteger then .inFam .num+ else if l.dt = V.xsdDecimal then .inFam .num+ else if l.dt = V.xsdDateTime then .inFam .dateTime+ else .unknown++/-- The number a literal denotes, for the two numeric datatypes implemented.+`none` means the literal is ILL TYPED for its datatype, which SPARQL treats as+having no value at all. -/+def numValue (l : Lit) : Option Dec :=+ if l.dt = V.xsdInteger then (intValue l.lex).map (fun v => ⟨v, 0⟩)+ else if l.dt = V.xsdDecimal then decOfLex l.lexelse none+def cmpDec (a b : Dec) : Cmp :=+ let x := a.mant * Int.ofNat (10 ^ b.scale)+ let y := b.mant * Int.ofNat (10 ^ a.scale)+ if x < y then .lt else if x = y then .eq else .gt++/-- Codepoint order, which is the collation SPARQL's `<` uses on strings. -/+def cmpChars : List Char → List Char → Cmp+ | [], [] => .eq+ | [], _ :: _ => .lt+ | _ :: _, [] => .gt+ | a :: as, b :: bs =>+ if a.toNat < b.toNat then .lt+ else if b.toNat < a.toNat then .gt+ else cmpChars as bs++def boolValue (lex : String) : Option Bool :=+ if lex = "true" || lex = "1" then some true+ else if lex = "false" || lex = "0" then some false+ else none++/-- Fourteen hours in seconds, the width of XSD's timezone window. -/+def tzWindowSeconds : Int := 14 * 3600++/-- Shift an exact number of seconds by a whole number of seconds, keeping the+scale so nothing rounds. -/+def decShift (d : Dec) (secs : Int) : Dec :=+ ⟨d.mant + secs * Int.ofNat (10 ^ d.scale), d.scale⟩++/-- Compare two `xsd:dateTime` readings. See the section header for the timezone+rule; `unordered` is a verdict and `none` is a refusal. -/+def cmpDateTime : DtRead → DtRead → Option Cmp+ | .notJudged, _ => none+ | _, .notJudged => none+ | .illFormed, _ => some .incomparable+ | _, .illFormed => some .incomparable+ | .ok a ta, .ok b tb =>+ match ta, tb with+ | some oa, some ob =>+ some (cmpDec (decShift a (-(oa * 60))) (decShift b (-(ob * 60))))+ | none, none => some (cmpDec a b)+ | some oa, none =>+ -- `a` is an instant; `b` stands for the window around its local value.+ let ai := decShift a (-(oa * 60))+ if cmpDec ai (decShift b (-tzWindowSeconds)) == .lt then some .lt+ else if cmpDec ai (decShift b tzWindowSeconds) == .gt then some .gt+ else some .unordered+ | none, some ob =>+ let bi := decShift b (-(ob * 60))+ if cmpDec (decShift a tzWindowSeconds) bi == .lt then some .lt+ else if cmpDec (decShift a (-tzWindowSeconds)) bi == .gt then some .gt+ else some .unordered++/-- Compare two literals known to be in the same family. -/+def cmpSameFam : Fam → Lit → Lit → Option Cmp+ | .num, a, b =>+ match numValue a, numValue b with+ | some x, some y => some (cmpDec x y)+ | _, _ => some .incomparable+ | .str, a, b =>+ if hasBackslash a.lex || hasBackslash b.lex then none+ else some (cmpChars a.lex.toList b.lex.toList)+ | .boolean, a, b =>+ match boolValue a.lex, boolValue b.lex with+ | some x, some y => some (if x = y then .eq else if x then .gt else .lt)+ | _, _ => some .incomparable+ | .dateTime, a, b => cmpDateTime (readDateTime a.lex) (readDateTime b.lex)++/-- **The comparison.** See the section header for what each answer means. -/+def cmpTerms (a b : Term) : Option Cmp :=+ match famOf a, famOf b with+ | .noFam, _ => some .incomparable+ | _, .noFam => some .incomparable+ | .unknown, _ => none+ | _, .unknown => none+ | .inFam φ, .inFam ψ =>+ if φ = ψ then+ match asLiteral a, asLiteral b with+ | some la, some lb => cmpSameFam φ la lb+ | _, _ => none+ else some .incomparable+end Shacldiff --git a/lean/Shacl/Witness.lean b/lean/Shacl/Witness.leanindex c28236b9..96ba2c68 100644--- a/lean/Shacl/Witness.lean+++ b/lean/Shacl/Witness.lean@@ -19,6 +19,16 @@ derivation checker.| `duplicate_triples_are_counted_once` | `sh:maxCount` counts the SET of value nodes || `two_distinct_values_break_maxCount_one` | and it really does count them || `the_evaluator_refuses_rather_than_guessing` | the third answer is reachable, not decoration |+| `four_point_zero_is_at_most_four` | the value-range constraints compare VALUES, not spellings |+| `four_point_one_is_not_at_most_four` | and they still reject something |+| `a_string_is_not_greater_than_a_number` | a SPARQL type error is a violation, not a refusal |+| `mixed_timezones_are_unordered` | a dateTime with a timezone and one without can be UNORDERED |+| `a_day_earlier_is_ordered_even_across_the_window` | and that is not a blanket refusal |+| `a_blank_node_has_no_length` | a blank node fails every length constraint |+| `an_iri_is_as_long_as_it_is_written` | and an IRI does not |+| `a_sequence_path_reaches_two_steps` | a sequence path is a join, not a union |+| `a_sequence_path_does_not_stop_halfway` | and the intermediate node is not a value node |+| `zero_or_one_admits_the_focus_node` | `sh:zeroOrOnePath` gives a bare focus node one value node |The two counting theorems are the ones worth reading. SHACL counts distinct valuenodes, so a triple asserted twice must not make a `sh:maxCount 1` fail. An engine@@ -181,35 +191,146 @@ theorem two_distinct_values_break_maxCount_one :/-! ## The third answer is reachable-A refusal that never fires is decoration. This one fires on the first `xsd:date`-literal it meets, and `tests/shacl_core_verified_test.rs` counts how often that-happens across the W3C suite. -/+A refusal that never fires is decoration. This one fires on the first+`rdf:XMLLiteral` it meets: RDF 1.1 says that datatype's lexical space is the set of+strings that are well-balanced, self-contained XML content, and deciding that needs+an XML parser this development does not have and will not pretend to have.+`tests/shacl_core_verified_test.rs` counts how often a refusal happens across the+W3C suite. -/-def xsdDate : Term := "<http://www.w3.org/2001/XMLSchema#date>"-def litDate : Term := "\"2026-09-14\"^^<http://www.w3.org/2001/XMLSchema#date>"+def xmlLiteral : Term := "<http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral>"+def litXml : Term :=+ "\"<b>hi</b>\"^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral>"/-- The literal has the right datatype IRI, so the constraint turns on whether it is-a well-formed `xsd:date`, and `lexOK` does not know. The evaluator says so by name-instead of choosing an answer. -/+well formed, and `lexOK` does not know. The evaluator says so by name instead of+choosing an answer. -/theorem the_evaluator_refuses_rather_than_guessing :- eval [] (.datatype xsdDate) exShape litDate- = .error (.unknownLexicalSpace xsdDate "2026-09-14") := by rfl+ eval [] (.datatype xmlLiteral) exShape litXml+ = .error (.unknownLexicalSpace xmlLiteral "<b>hi</b>") := by rfl/-- The specification, meanwhile, treats an unjudgeable literal as non-conforming.So the two possible behaviours at this point were "report a violation" and "report arefusal", and the evaluator takes the weaker one. Neither is a false pass, which isthe property that matters. -/theorem the_refused_literal_does_not_conform :- ¬ Conf [] (.datatype xsdDate) litDate := by+ ¬ Conf [] (.datatype xmlLiteral) litXml := byrintro ⟨l, hl, -, hok⟩- have : l = ⟨"2026-09-14", xsdDate, none⟩ := by- have : asLiteral litDate = some ⟨"2026-09-14", xsdDate, none⟩ := by decide+ have : l = ⟨"<b>hi</b>", xmlLiteral, none⟩ := by+ have : asLiteral litXml = some ⟨"<b>hi</b>", xmlLiteral, none⟩ := by deciderw [this] at hlexact (Option.some.inj hl).symmsubst thisexact absurd hok (by decide)-/-! ## Axioms, pinned -/+/-! ## The parameters added after the first eleven++Each one below exhibits a model and something the semantics does NOT entail, the+same discipline the two counting theorems follow. A one-sided witness would leave+open that the new clause is trivially true or trivially false. Every one is settled+by kernel computation, so a change to the decision procedure breaks it rather than+passing quietly. -/++def lit4int : Term := "\"4\"^^<http://www.w3.org/2001/XMLSchema#integer>"+def lit40dec : Term := "\"4.0\"^^<http://www.w3.org/2001/XMLSchema#decimal>"+def lit41dec : Term := "\"4.1\"^^<http://www.w3.org/2001/XMLSchema#decimal>"++/-- **Comparison is by value, not by spelling.** `"4"^^xsd:integer` and+`"4.0"^^xsd:decimal` are two different TERMS, and `sh:maxInclusive 4` admits the+second. A validator comparing spellings would report a violation here. -/+theorem four_point_zero_is_at_most_four :+ Conf [] (.maxInclusive lit4int) lit40dec :=+ CmpIs.of_eq (k := .eq) (by decide) (by decide)++/-- And it is not vacuous: the same constraint rejects a larger value. -/+theorem four_point_one_is_not_at_most_four :+ ¬ Conf [] (.maxInclusive lit4int) lit41dec :=+ CmpIs.not_of_eq (k := .lt) (by decide) (by decide)++/-- **A pair SPARQL cannot compare is a violation, not a refusal.** `sh:minExclusive`+is defined as a SPARQL expression that must return TRUE, and `4 < "Hello"` is a type+error, which is not true. -/+theorem a_string_is_not_greater_than_a_number :+ ¬ Conf [] (.minExclusive lit4int) "\"Hello\"" :=+ CmpIs.not_of_eq (k := .incomparable) (by decide) (by decide)++def dtWithZone : Term :=+ "\"2002-10-10T12:00:00-05:00\"^^<http://www.w3.org/2001/XMLSchema#dateTime>"+def dtNoZone : Term :=+ "\"2002-10-10T12:00:00\"^^<http://www.w3.org/2001/XMLSchema#dateTime>"+def dtDayBefore : Term :=+ "\"2002-10-09T12:00:00-05:00\"^^<http://www.w3.org/2001/XMLSchema#dateTime>"++/-- **A timezoned dateTime and an untimezoned one within fourteen hours are+UNORDERED, and that is a verdict rather than a refusal.** The comparison answers,+and what it answers is that neither is first. -/+theorem mixed_timezones_are_unordered :+ cmpTerms dtWithZone dtNoZone = some .unordered := by decide++/-- So `sh:minInclusive` rejects it, which is what+`core/node/minInclusive-002` requires. -/+theorem an_unordered_value_does_not_conform :+ ¬ Conf [] (.minInclusive dtWithZone) dtNoZone :=+ CmpIs.not_of_eq (k := .unordered) (by decide) (by decide)++/-- Outside the fourteen-hour window the order IS settled, so the rule above is not+a blanket refusal to compare across timezones. -/+theorem a_day_earlier_is_ordered_even_across_the_window :+ cmpTerms dtNoZone dtDayBefore = some .gt := by decide++/-- **A blank node fails both length constraints**, whatever the bound, which is the+rule `core/node/minLength-001` and `core/node/maxLength-001` both turn on. -/+theorem a_blank_node_has_no_length :+ ¬ Conf [] (.minLength 0) "_:b" := StrLen.not_of_blank (by decide)++/-- An IRI, meanwhile, has the length of the IRI itself, so the same constraint at a+bound of three admits `<a:b>` and a bound of four does not. Two directions, one+term, so neither answer can be the constant one. -/+theorem an_iri_is_as_long_as_it_is_written :+ Conf [] (.maxLength 3) "<a:b>" ∧ ¬ Conf [] (.minLength 4) "<a:b>" :=+ ⟨StrLen.of_chars (cs := ['a', ':', 'b']) (by decide) (by decide),+ StrLen.not_of_chars (cs := ['a', ':', 'b']) (by decide) (by decide)⟩++/-! ### A sequence path reaches through an intermediate node -/++def exP1 : Term := "<http://ex.org/p1>"+def exP2 : Term := "<http://ex.org/p2>"+def exMid : Term := "<http://ex.org/mid>"+def exEnd : Term := "<http://ex.org/end>"++def gSeq : Graph := [⟨exAlice, exP1, exMid⟩, ⟨exMid, exP2, exEnd⟩]++/-- The value node of `p1/p2` at Alice is the node two steps away, NOT the node one+step away. A validator that read a sequence path as "either predicate" would put+`exMid` here. -/+theorem a_sequence_path_reaches_two_steps :+ IsValue gSeq (.seq (.pred exP1) (.pred exP2)) exAlice exEnd := by+ refine ⟨exMid, ?_, ?_⟩+ · show (⟨exAlice, exP1, exMid⟩ : Triple) ∈ gSeq+ simp [gSeq]+ · show (⟨exMid, exP2, exEnd⟩ : Triple) ∈ gSeq+ simp [gSeq]++/-- Proved through `mem_valueNodes`, which is the lemma that makes the enumeration+and the specification the same question. -/+theorem a_sequence_path_does_not_stop_halfway :+ ¬ IsValue gSeq (.seq (.pred exP1) (.pred exP2)) exAlice exMid := by+ rw [← mem_valueNodes]+ decide++/-- `sh:zeroOrOnePath` admits the focus node itself, so a focus node with no+outgoing triple at all still has exactly one value node and `sh:minCount 2` fails.+That is the whole content of `core/path/path-zeroOrOne-001`. -/+theorem zero_or_one_admits_the_focus_node :+ valueNodes [] (.zeroOrOne (.pred exP1)) exBob = [exBob] := by decide++/-! ## Axioms, pinned++Every pin below is the footprint `#print axioms` actually reports, not the one the+rest of this repository standardises on. Two of these theorems come out at+`[propext]` alone, a strict subset: they are settled by kernel computation and never+reach `Classical.choice`. Pinning what is true rather than what is expected is the+point of the exercise, and a proof that grew a dependency would break the pin. -//-- info: 'Shacl.alice_conforms' depends on axioms: [propext, Classical.choice, Quot.sound] -/#guard_msgs in@@ -235,4 +356,48 @@ theorem the_refused_literal_does_not_conform :#guard_msgs in#print axioms the_evaluator_refuses_rather_than_guessing+/-- info: 'Shacl.four_point_zero_is_at_most_four' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms four_point_zero_is_at_most_four++/-- info: 'Shacl.four_point_one_is_not_at_most_four' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms four_point_one_is_not_at_most_four++/-- info: 'Shacl.a_string_is_not_greater_than_a_number' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms a_string_is_not_greater_than_a_number++/-- info: 'Shacl.mixed_timezones_are_unordered' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms mixed_timezones_are_unordered++/-- info: 'Shacl.an_unordered_value_does_not_conform' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms an_unordered_value_does_not_conform++/-- info: 'Shacl.a_day_earlier_is_ordered_even_across_the_window' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms a_day_earlier_is_ordered_even_across_the_window++/-- info: 'Shacl.a_blank_node_has_no_length' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms a_blank_node_has_no_length++/-- info: 'Shacl.an_iri_is_as_long_as_it_is_written' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms an_iri_is_as_long_as_it_is_written++/-- info: 'Shacl.a_sequence_path_reaches_two_steps' depends on axioms: [propext] -/+#guard_msgs in+#print axioms a_sequence_path_reaches_two_steps++/-- info: 'Shacl.a_sequence_path_does_not_stop_halfway' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms a_sequence_path_does_not_stop_halfway++/-- info: 'Shacl.zero_or_one_admits_the_focus_node' depends on axioms: [propext] -/+#guard_msgs in+#print axioms zero_or_one_admits_the_focus_node+end Shacldiff --git a/lean/ShaclMain.lean b/lean/ShaclMain.leanindex 5f9eeb0f..8cd898e0 100644--- a/lean/ShaclMain.lean+++ b/lean/ShaclMain.lean@@ -45,6 +45,9 @@ def jsonStr (s : String) : String :=def showPath : Path → String| .pred p => p| .inv p => "^" ++ p+ | .seq a b => "(" ++ showPath a ++ "/" ++ showPath b ++ ")"+ | .alt a b => "(" ++ showPath a ++ "|" ++ showPath b ++ ")"+ | .zeroOrOne a => "(" ++ showPath a ++ ")?"def jsonOpt (o : Option String) : String :=match o withdiff --git a/lean/lakefile.toml b/lean/lakefile.tomlindex b201b56a..f0e8a54e 100644--- a/lean/lakefile.toml+++ b/lean/lakefile.toml@@ -1,7 +1,14 @@name = "oocert"version = "0.1.0"-defaultTargets = ["OOCert", "oo-cert", "oo-horn"]+defaultTargets = ["OOCert", "oo-cert", "oo-horn", "Shacl", "oo-shacl", "oo-refute", "Dl", "oo-dlmodel"]+# Every library and executable here is in defaultTargets on purpose. A target+# left out of the default set is not built by a bare `lake build`, which is what+# the CI job runs, so its proofs can fail to compile while the gate reports+# success. That happened once, on 14 September 2026: the SHACL layer did not+# compile at the commit that carried it and CI was green over it, because+# `Shacl` was not a default target. Anything added here must be added there.+## Core Lean only. No Mathlib, no external packages: the checker's trust surface# is the Lean kernel plus what is written in this directory, and it should stay# small enough to read in an afternoon.@@ -28,3 +35,18 @@ globs = ["Shacl.+"][[lean_exe]]name = "oo-shacl"root = "ShaclMain"++# The refutation checker. `oo-refute/1` is a second certificate format: a+# derivation prefix plus one step that concludes contradiction rather than a+# triple. Its own executable because its verdict is a different sentence from+# `oo-cert`'s, and the two must never be confused for one another.+[[lean_exe]]+name = "oo-refute"+root = "RefuteMain"++[[lean_lib]]+name = "Dl"++[[lean_exe]]+name = "oo-dlmodel"+root = "DlMain"diff --git a/src/reason.rs b/src/reason.rsindex 57f5cfc8..42009d16 100644--- a/src/reason.rs+++ b/src/reason.rs@@ -21,6 +21,7 @@ const OWL_HAS_VALUE: &str = "<http://www.w3.org/2002/07/owl#hasValue>";const OWL_ON_PROPERTY: &str = "<http://www.w3.org/2002/07/owl#onProperty>";const OWL_INTERSECTION: &str = "<http://www.w3.org/2002/07/owl#intersectionOf>";const OWL_UNION: &str = "<http://www.w3.org/2002/07/owl#unionOf>";+const OWL_ONEOF: &str = "<http://www.w3.org/2002/07/owl#oneOf>";const RDF_FIRST: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#first>";const RDF_REST: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#rest>";const RDF_NIL: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#nil>";@@ -70,9 +71,45 @@ impl Interner {/// Profiles:/// "rdfs" — RDFS rules (subclass, domain/range, subproperty)/// "owl-rl" — RDFS + core OWL-RL (transitive, symmetric, inverse,-/// sameAs, equivalentClass/Property)+/// sameAs, equivalentClass/Property) + the schema rules that+/// move a domain or a range along the class and property+/// hierarchies (scm-dom1, scm-dom2, scm-rng1, scm-rng2)/// "owl-rl-ext" — All above + someValuesFrom, allValuesFrom, hasValue,-/// intersectionOf, unionOf+/// intersectionOf (both directions), unionOf, oneOf, and the+/// four rules that order two restrictions by their filler or+/// by their property (scm-svf1, scm-svf2, scm-avf1, scm-avf2)+///+/// Twenty-nine rule ids in all, every one of them with an arm in+/// `lean/OOCert/Rules.lean` and a lemma in `lean/OOCert/Soundness.lean`. A rule+/// the checker cannot prove sound is a rule this file does not run: that is the+/// contract, and `tests/lean_certificate_test.rs` walks the whole corpus to+/// enforce it.+///+/// What is deliberately NOT here, with the reason, because "not implemented" and+/// "not sound" are different statements and a reader is owed which one applies:+///+/// * `eq-ref` is sound and useless. It asserts `owl:sameAs` reflexivity for+/// every term in every position. Measured on the largest file this+/// repository ships, `benchmark/oaei/data/anatomy/human.owl`, that is+/// 17,194 triples of no consequence added to a graph of 35,354. It would+/// also put a derivation into the empty-graph case that+/// `OOCert.not_everything_is_entailed` depends on staying empty.+/// * The `eq-rep-s`, `eq-rep-p`, `eq-rep-o` family is sound and quadratic in+/// the size of a `owl:sameAs` clique. Counted by SPARQL over every RDF file+/// this repository tracks that parses and is under the size cap, the corpus+/// contains ZERO `owl:sameAs` triples, so the cost is certain and the+/// benefit here is nothing at all. Three files mention `sameAs` inside an+/// `rdfs:comment` and none of them asserts one.+/// * `scm-cls`, `scm-op` and `scm-dp` are sound and emit reflexive trivia+/// (`c rdfs:subClassOf c`, `c owl:equivalentClass c`) of exactly the kind+/// the `a != b` guards elsewhere in this file exist to suppress.+/// * The `dt-*` family needs a datatype VALUE space. `OOCert.Semantics`+/// reads a literal as its N-Triples spelling and says so, so there is no+/// condition here for those rules to be sound against.+/// * Nothing concludes `false`. The profile's inconsistency rules need a+/// certificate format that can carry a refutation, which this format+/// cannot.+////// 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";@@ -196,6 +233,7 @@ impl Reasoner {let owl_has_value = interner.intern(OWL_HAS_VALUE);let owl_intersection = interner.intern(OWL_INTERSECTION);let owl_union = interner.intern(OWL_UNION);+ let owl_oneof = interner.intern(OWL_ONEOF);let rdf_first = interner.intern(RDF_FIRST);let rdf_rest = interner.intern(RDF_REST);let rdf_nil = interner.intern(RDF_NIL);@@ -265,6 +303,7 @@ impl Reasoner {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 oneof_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();let mut avf_rules: Vec<(u32, u32, u32)> = Vec::new();@@ -331,6 +370,12 @@ impl Reasoner {{union_classes.push((s, o, chain, items));}+ if p == owl_oneof+ && let Some((chain, items)) = walk_list(o)+ && !items.is_empty()+ {+ oneof_classes.push((s, o, chain, items));+ }}}@@ -524,6 +569,76 @@ impl Reasoner {emit((a, rdfs_subprop, b), "scm-eqp1", &[(a, owl_equiv_prop, b)]);emit((b, rdfs_subprop, a), "scm-eqp1", &[(a, owl_equiv_prop, b)]);}++ // scm-dom1, scm-dom2, scm-rng1, scm-rng2: a declared domain or+ // range moved along the class and the property hierarchy.+ //+ // These four add no ANSWERS. Everything they license at the+ // instance level is already reachable: rdfs2 over the original+ // domain gives `s rdf:type c1` and rdfs9 carries it up to `c2`,+ // which is what scm-dom1 followed by rdfs2 gives, and scm-dom2+ // is rdfs7 up to the superproperty followed by rdfs2. What they+ // add is the SCHEMA those answers are consequences of. A+ // consumer reading the materialised graph for "what is the+ // domain of this property" saw the declaration and not its+ // consequences, and a second reasoner run over the output+ // derived them, so the output was not a fixpoint of the+ // profile.+ //+ // They also fire on schema alone, so unlike almost everything+ // else in the extended profile they fire on a schema-only file+ // with no instances at all, which is most of this repository's+ // corpus.++ // scm-dom1: p rdfs:domain c1, c1 subClassOf c2 → p rdfs:domain c2+ for &(p, c1) in &domain_map {+ if let Some(supers) = sub_to_super.get(&c1) {+ for &c2 in supers {+ if c1 != c2 {+ emit((p, rdfs_domain, c2), "scm-dom1",+ &[(p, rdfs_domain, c1), (c1, rdfs_subclass, c2)]);+ }+ }+ }+ }++ // scm-dom2: p2 rdfs:domain c, p1 subPropertyOf p2 → p1 rdfs:domain c+ for &(p1, p2) in &subprop_idx {+ if p1 == p2 {+ continue;+ }+ for &(pd, c) in &domain_map {+ if pd == p2 {+ emit((p1, rdfs_domain, c), "scm-dom2",+ &[(p2, rdfs_domain, c), (p1, rdfs_subprop, p2)]);+ }+ }+ }++ // scm-rng1: p rdfs:range c1, c1 subClassOf c2 → p rdfs:range c2+ for &(p, c1) in &range_map {+ if let Some(supers) = sub_to_super.get(&c1) {+ for &c2 in supers {+ if c1 != c2 {+ emit((p, rdfs_range, c2), "scm-rng1",+ &[(p, rdfs_range, c1), (c1, rdfs_subclass, c2)]);+ }+ }+ }+ }++ // scm-rng2: p2 rdfs:range c, p1 subPropertyOf p2 → p1 rdfs:range c+ for &(p1, p2) in &subprop_idx {+ if p1 == p2 {+ continue;+ }+ for &(pr, c) in &range_map {+ if pr == p2 {+ emit((p1, rdfs_range, c), "scm-rng2",+ &[(p2, rdfs_range, c), (p1, rdfs_subprop, p2)]);+ }+ }+ }}// ── OWL-RL extended (someValuesFrom, hasValue, intersection, union)@@ -633,6 +748,127 @@ impl Reasoner {}}+ // scm-svf1, scm-svf2, scm-avf1, scm-avf2: two restrictions+ // ordered by their fillers or by their properties.+ //+ // These are the rules that reach subsumptions no instance-level+ // rule can. `cls-svf1` needs an individual with a witness before+ // it says anything, and a schema-only ontology has none, so a+ // pizza-style file full of restrictions licensed nothing at all+ // from them. These four run on the schema.+ //+ // Two indices per restriction kind: (property, filler) → the+ // restrictions with both, and property → its (filler,+ // restriction) pairs. The first is the lookup and the second is+ // the scan, which keeps each rule linear in the hierarchy it+ // walks rather than quadratic in the restriction count.+ let mut svf_by_pf: HashMap<(u32, u32), Vec<u32>> = HashMap::new();+ let mut svf_by_filler: HashMap<u32, Vec<(u32, u32)>> = HashMap::new();+ let mut svf_by_prop: HashMap<u32, Vec<(u32, u32)>> = HashMap::new();+ for &(prop, filler, restr) in &svf_rules {+ svf_by_pf.entry((prop, filler)).or_default().push(restr);+ svf_by_filler.entry(filler).or_default().push((prop, restr));+ svf_by_prop.entry(prop).or_default().push((filler, restr));+ }+ let mut avf_by_pf: HashMap<(u32, u32), Vec<u32>> = HashMap::new();+ let mut avf_by_filler: HashMap<u32, Vec<(u32, u32)>> = HashMap::new();+ let mut avf_by_prop: HashMap<u32, Vec<(u32, u32)>> = HashMap::new();+ for &(prop, filler, restr) in &avf_rules {+ avf_by_pf.entry((prop, filler)).or_default().push(restr);+ avf_by_filler.entry(filler).or_default().push((prop, restr));+ avf_by_prop.entry(prop).or_default().push((filler, restr));+ }++ // scm-svf1: c1 svf y1, c1 onProperty p, c2 svf y2,+ // c2 onProperty p, y1 subClassOf y2 → c1 subClassOf c2+ for &(y1, y2) in &subclass_idx {+ let Some(ones) = svf_by_filler.get(&y1) else { continue };+ for &(p, r1) in ones {+ let Some(twos) = svf_by_pf.get(&(p, y2)) else { continue };+ for &r2 in twos {+ if r1 != r2 {+ emit((r1, rdfs_subclass, r2), "scm-svf1", &[+ (r1, owl_some_values, y1),+ (r1, owl_on_property, p),+ (r2, owl_some_values, y2),+ (r2, owl_on_property, p),+ (y1, rdfs_subclass, y2),+ ]);+ }+ }+ }+ }++ // scm-svf2: c1 svf y, c1 onProperty p1, c2 svf y,+ // c2 onProperty p2, p1 subPropertyOf p2 → c1 subClassOf c2+ for &(p1, p2) in &subprop_idx {+ let Some(ones) = svf_by_prop.get(&p1) else { continue };+ for &(y, r1) in ones {+ let Some(twos) = svf_by_pf.get(&(p2, y)) else { continue };+ for &r2 in twos {+ if r1 != r2 {+ emit((r1, rdfs_subclass, r2), "scm-svf2", &[+ (r1, owl_some_values, y),+ (r1, owl_on_property, p1),+ (r2, owl_some_values, y),+ (r2, owl_on_property, p2),+ (p1, rdfs_subprop, p2),+ ]);+ }+ }+ }+ }++ // scm-avf1: the same shape with owl:allValuesFrom, and the same+ // direction: a wider filler makes a wider class.+ for &(y1, y2) in &subclass_idx {+ let Some(ones) = avf_by_filler.get(&y1) else { continue };+ for &(p, r1) in ones {+ let Some(twos) = avf_by_pf.get(&(p, y2)) else { continue };+ for &r2 in twos {+ if r1 != r2 {+ emit((r1, rdfs_subclass, r2), "scm-avf1", &[+ (r1, owl_all_values, y1),+ (r1, owl_on_property, p),+ (r2, owl_all_values, y2),+ (r2, owl_on_property, p),+ (y1, rdfs_subclass, y2),+ ]);+ }+ }+ }+ }++ // scm-avf2: c1 avf y, c1 onProperty p1, c2 avf y,+ // c2 onProperty p2, p1 subPropertyOf p2+ // → c2 subClassOf c1+ //+ // THE CONCLUSION IS THE OTHER WAY ROUND. The W3C table reads+ // `T(?c2, rdfs:subClassOf, ?c1)` where scm-svf2 reads+ // `T(?c1, rdfs:subClassOf, ?c2)`, because a universal+ // restriction is antitone in its property: `all p2 y` has more+ // values to constrain than `all p1 y`, so it is the smaller+ // class. Writing it the way scm-svf2 is written gives a step no+ // model supports, and `OOCert.the_natural_avf2_direction_is_not_entailed`+ // is the refutation.+ for &(p1, p2) in &subprop_idx {+ let Some(ones) = avf_by_prop.get(&p1) else { continue };+ for &(y, r1) in ones {+ let Some(twos) = avf_by_pf.get(&(p2, y)) else { continue };+ for &r2 in twos {+ if r1 != r2 {+ emit((r2, rdfs_subclass, r1), "scm-avf2", &[+ (r1, owl_all_values, y),+ (r1, owl_on_property, p1),+ (r2, owl_all_values, y),+ (r2, owl_on_property, p2),+ (p1, rdfs_subprop, p2),+ ]);+ }+ }+ }+ }+// cls-int1: x type ALL members → x type intersection classfor (cls, head, chain, members) in &intersection_classes {for (&x, x_types) in &inst_types {@@ -650,6 +886,53 @@ impl Reasoner {}}+ // cls-int2: x type intersection class → x type EVERY member+ //+ // The mirror of cls-int1, and the only high-count rule in the+ // measured gap that produces genuinely new instance typings+ // rather than schema. One step per member, each repeating the+ // constructor triple and the chain, because a certificate step+ // carries one conclusion.+ for (cls, head, chain, members) in &intersection_classes {+ for &(x, c) in &type_idx {+ if c != *cls {+ continue;+ }+ let premises: Vec<Fact> = if certify {+ let mut v = vec![(*cls, owl_intersection, *head)];+ v.extend(chain.iter().copied());+ v.push((x, rdf_type, *cls));+ v+ } else {+ Vec::new()+ };+ for &m in members {+ emit((x, rdf_type, m), "cls-int2", &premises);+ }+ }+ }++ // cls-oo: every member of an owl:oneOf list is an instance of+ // the enumerated class. The only rule here with no instance+ // premise at all: an enumeration types its members on schema+ // alone. A literal member is skipped for the same reason the+ // four rules above skip one, since it would be the subject of+ // the conclusion.+ for (cls, head, chain, members) in &oneof_classes {+ let premises: Vec<Fact> = if certify {+ let mut v = vec![(*cls, owl_oneof, *head)];+ v.extend(chain.iter().copied());+ v+ } else {+ Vec::new()+ };+ for &m in members {+ if !is_literal(m) {+ emit((m, rdf_type, *cls), "cls-oo", &premises);+ }+ }+ }+// cls-uni: x type ANY member → x type union classfor (cls, head, chain, members) in &union_classes {for &(x, c) in &type_idx {diff --git a/src/tableaux.rs b/src/tableaux.rsindex cc823bb5..67291bce 100644--- a/src/tableaux.rs+++ b/src/tableaux.rs@@ -1208,6 +1208,15 @@ struct Tableau {tbox: Arc<ProcessedTBox>,trace: ExplanationTrace,budget: Budget,+ /// Keep the completion graph of the branch that succeeded.+ ///+ /// The ⊔-rule explores a disjunct in a CLONE and returns `true` from the+ /// clone's expansion without copying it back, so after a successful run+ /// `self.nodes` is the state as it was BEFORE the last disjunction, not the+ /// model that was found. Every existing caller reads only the boolean, so+ /// this stays off by default and nothing changes; the model emitter turns it+ /// on because it has to hand over the graph, not the verdict.+ capture: bool,}impl Tableau {@@ -1218,6 +1227,7 @@ impl Tableau {tbox,trace: ExplanationTrace::new(false),budget: Budget::default(),+ capture: false,}}@@ -1234,6 +1244,7 @@ impl Tableau {tbox,trace: ExplanationTrace::new(true),budget: Budget::default(),+ capture: false,}}@@ -1713,6 +1724,11 @@ impl Tableau {let mut branch = self.clone();branch.add_label(nid, disjunct.clone());if branch.expand(depth + 1) {+ // Only the model emitter asks for the graph back. See+ // `Tableau::capture`.+ if self.capture {+ *self = branch;+ }return true;}// Same here: an exhausted disjunct is not a refuted one.@@ -1844,17 +1860,19 @@ impl Tableau {/// "anywhere" blocking. Anywhere blocking yields smaller models but is a/// further optimisation on top of a correct base; get the base right first.fn is_pairwise_blocked(&self, s: u32) -> bool {+ self.blocker_of(s).is_some()+ }++ /// The ancestor that blocks `s`, under the condition `is_pairwise_blocked`+ /// documents. Split out so that the model emitter can fold a blocked node+ /// into the node that blocks it, which is the only way a completion graph+ /// with blocking becomes a finite interpretation. One condition, one place.+ fn blocker_of(&self, s: u32) -> Option<u32> {// Only blockable successors can be blocked. A node with no parent is// a root and is never blocked.- let Some(s_parent) = self.nodes.get(&s).and_then(|n| n.parent) else {- return false;- };- let Some(s_node) = self.nodes.get(&s) else {- return false;- };- let Some(s_parent_node) = self.nodes.get(&s_parent) else {- return false;- };+ let s_parent = self.nodes.get(&s).and_then(|n| n.parent)?;+ let s_node = self.nodes.get(&s)?;+ let s_parent_node = self.nodes.get(&s_parent)?;let s_labels = &s_node.labels;let s_parent_labels = &s_parent_node.labels;@@ -1880,12 +1898,12 @@ impl Tableau {&& self.roles_between(t_parent, t) == s_down&& self.roles_between(t, t_parent) == s_up{- return true;+ return Some(t);}}cur = t_node.parent;}- false+ None}}@@ -1907,6 +1925,31 @@ pub struct DlReasoner {/// Wall-clock cut-off applied to each individual satisfiability test./// `None` means no time limit (the node/depth budgets still apply).deadline: Option<Instant>,+ /// The axioms as the OWL parser read them, before `ProcessedTBox` absorbed,+ /// rewrote and folded them. A model certificate is written against these, so+ /// that what the checker verifies is the ontology's own axioms rather than+ /// the reasoner's internal encoding of them.+ source: Arc<AxiomSource>,+}++/// The parsed axioms, kept whole for the model emitter.+///+/// `ProcessedTBox` is a compilation target: it absorbs atomic left-hand sides+/// into `concept_defs`, turns the rest into `¬C ⊔ D`, splits disjunctive+/// left-hand sides and lifts domain and range out of the axiom list entirely.+/// Certifying a model against THAT would certify the reasoner's encoding+/// against itself. This is the input to that compilation, kept so the checker+/// can be pointed at the axioms instead.+struct AxiomSource {+ axioms: Vec<(Concept, Concept)>,+ disjoint_pairs: Vec<(Concept, Concept)>,+ role_domains: Vec<(u32, Concept)>,+ role_ranges: Vec<(u32, Concept)>,+ sub_to_super: HashMap<u32, HashSet<u32>>,+ transitive_roles: HashSet<u32>,+ inverse_roles: HashMap<u32, u32>,+ functional_roles: HashSet<u32>,+ inv_functional_roles: HashSet<u32>,}impl DlReasoner {@@ -1941,6 +1984,18 @@ impl DlReasoner {closure.insert(sub, seen);}+ let source = Arc::new(AxiomSource {+ axioms: result.axioms.clone(),+ disjoint_pairs: result.disjoint_pairs.clone(),+ role_domains: result.role_domains.clone(),+ role_ranges: result.role_ranges.clone(),+ sub_to_super: result.sub_to_super.clone(),+ transitive_roles: result.transitive_roles.clone(),+ inverse_roles: result.inverse_roles.clone(),+ functional_roles: result.functional_roles.clone(),+ inv_functional_roles: result.inv_functional_roles.clone(),+ });+let tbox = Arc::new(ProcessedTBox::new(&result.axioms,&result.disjoint_pairs,@@ -1969,6 +2024,7 @@ impl DlReasoner {subclass_closure: closure,deadline: crate::runtime::tableaux_test_timeout_ms().map(|ms| Instant::now() + std::time::Duration::from_millis(ms)),+ source,})}@@ -2348,16 +2404,18 @@ impl DlReasoner {.is_some_and(|subs| subs.contains(&asserted))}- pub fn check_abox(&self) -> ABoxResult {- if self.individual_types.is_empty() && self.individual_anon_types.is_empty() {- return ABoxResult {- consistent: true,- undecided: false,- individuals_checked: 0,- inferred_types: HashMap::new(),- };- }-+ /// Build the single tableau the ABox check runs on, with one node per named+ /// individual and the asserted role assertions as edges.+ ///+ /// Extracted verbatim out of `check_abox` so the model emitter runs on the+ /// SAME graph the consistency answer came from. Two copies of this setup+ /// would let the certificate drift away from the verdict it is supposed to+ /// certify, which is precisely the failure this whole layer exists to catch.+ ///+ /// Returns the tableau, the individual-to-node map, and the number of+ /// individuals that carry a type (which is what `check_abox` reports, and+ /// excludes nodes created only because a role assertion pointed at them).+ fn build_abox_tableau(&self) -> (Tableau, HashMap<u32, u32>, usize) {// The ABox check builds ONE tableau containing every named individual,// so it is the largest single expansion the reasoner ever performs. It// must carry the same deadline as every other test, otherwise it is an@@ -2452,6 +2510,22 @@ impl DlReasoner {}}++ (tableau, ind_to_node, individuals_checked)+ }++ pub fn check_abox(&self) -> ABoxResult {+ if self.individual_types.is_empty() && self.individual_anon_types.is_empty() {+ return ABoxResult {+ consistent: true,+ undecided: false,+ individuals_checked: 0,+ inferred_types: HashMap::new(),+ };+ }++ let (mut tableau, ind_to_node, individuals_checked) = self.build_abox_tableau();+// Same three-valued discipline as everywhere else: exhausting the// budget is not a proof of inconsistency. Declaring an ABox// inconsistent is a strong, user-visible claim and must never be the@@ -2638,6 +2712,27 @@ impl DlReasoner {},});+ // Opt-in model certificates. Off unless `OO_DL_MODEL_DIR` names a+ // directory, so the default behaviour of `owl-dl` is exactly what it+ // was. Only the POSITIVE answers are certified: an inconsistent TBox or+ // an unsatisfiable class produces `Refuted` here, which means "no+ // certificate", not "certified unsatisfiable".+ if let Ok(root) = std::env::var("OO_DL_MODEL_DIR") {+ let root = std::path::PathBuf::from(root);+ let describe = |r: anyhow::Result<ModelOutcome>| match r {+ Ok(o) => o.describe(),+ Err(e) => format!("no certificate: {e}"),+ };+ output["model_certificate"] = serde_json::json!({+ "dir": root.display().to_string(),+ "tbox": describe(reasoner.certify_tbox_consistent(&root.join("tbox"))),+ "abox": describe(reasoner.certify_abox_consistent(&root.join("abox"))),+ "checker": "oo-dlmodel",+ "theorem": "Dl.satisfiable_of_checkModel",+ "not_covered": "unsatisfiability and inconsistency carry no certificate",+ });+ }+if !explanations.is_empty() {output["explanations"] = serde_json::json!(explanations);}@@ -2760,3 +2855,926 @@ pub struct ClassificationResult {pub equivalences: Vec<(u32, u32)>,pub inferred_subsumptions: usize,}++// ── Model certificates ──────────────────────────────────────────────────+//+// Every verdict above is a bare verdict. A consumer who wants to know whether+// the reasoner was right has to trust the reasoner. This section closes half of+// that gap, and only half, deliberately.+//+// A tableaux run gives two kinds of answer and they are not equally hard to+// certify. SATISFIABLE is easy: the procedure builds a completion graph, and a+// completion graph either is a finite model or folds into one. A finite model is+// a finite object, and checking that a finite interpretation satisfies a set of+// axioms is decidable and provable. UNSATISFIABLE is hard: it needs the closed+// tableau, every branch, every clash and the blocking argument, which is a+// proof-checking problem and is not attempted here.+//+// So the positive answers carry a certificate and the negative ones do not. When+// the reasoner reports a class unsatisfiable or an ontology inconsistent, it+// still just says so, and the report says that plainly rather than blurring the+// two.+//+// The certificate is two tab-separated files, `axioms.tsv` and `model.tsv`, read+// by `oo-dlmodel` (`lean/DlMain.lean`). `lean/Dl/Syntax.lean` documents the+// format and is the normative description of it. `Dl.satisfiable_of_checkModel`+// is the machine-checked statement the exit code stands for: an interpretation+// the checker accepts is a model, so the axiom set is satisfiable.+//+// Three things this does NOT do, stated here so no reader has to discover them:+//+// 1. The OWL parser is outside the theorem. The axioms written out are the+// axioms `OwlParser` read, not the ontology. A triple the parser ignores is+// absent from the certificate and the checker never sees it.+// 2. Nothing is emitted for an answer that is not positive, and nothing is+// emitted when the completion graph cannot be turned into a finite+// interpretation. `ModelOutcome::Refused` says which, and no file is+// written. Emitting something that will not check would be worse than+// emitting nothing.+// 3. The self-check below decides whether to emit. It is the same semantics+// `lean/Dl/Check.lean` implements, written twice on purpose: the Rust copy+// is a gate on the emitter, and the Lean copy is the one with the proof. A+// disagreement between them shows up as `oo-dlmodel` rejecting a certificate+// this side thought was fine, which is a failure, not a shrug.++use std::path::Path;++/// An axiom in the fragment `lean/Dl/` covers, over interned identifiers.+#[derive(Clone, Debug)]+enum DlAxiom {+ Sub(Concept, Concept),+ Disjoint(Concept, Concept),+ Domain(u32, Concept),+ Range(u32, Concept),+ SubRole(u32, u32),+ Trans(u32),+ Sym(u32),+ Inv(u32, u32),+ InvFunc(u32),+ Inst(u32, Concept),+ Rel(u32, u32, u32),+ Indiv(u32),+ NonEmpty(Concept),+}++/// A folded completion graph: the node identifiers that survived, and the edges+/// between them, each written `(source, role, target)`.+type FoldedGraph = (Vec<u32>, Vec<(u32, u32, u32)>);++/// A finite interpretation whose domain elements are tableau node identifiers.+#[derive(Default)]+struct FiniteModel {+ dom: Vec<u32>,+ domset: HashSet<u32>,+ /// Atomic concept identifier → the nodes in its extension. Closed world on+ /// atoms: a node is in `A` exactly when `Atom(A)` is in its label. That is+ /// the canonical reading of a completion graph, and it is what makes the+ /// negated atoms in the labels mean anything.+ cext: HashMap<u32, HashSet<u32>>,+ /// (role, source) → deduplicated targets.+ rext: HashMap<(u32, u32), Vec<u32>>,+ /// Individual identifier → the node that denotes it.+ ind: HashMap<u32, u32>,+}++/// What `DlReasoner::certify_*` did.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum ModelOutcome {+ /// `axioms.tsv` and `model.tsv` were written and pass the emitter's own+ /// check. `oo-dlmodel` is what turns that into a verified statement.+ Certified {+ axioms: usize,+ domain: usize,+ edges: usize,+ },+ /// The reasoner PROVED the negative answer. There is no model to hand over,+ /// and this layer says nothing about whether the proof is right.+ Refuted,+ /// A resource budget was hit. Nothing was proven either way.+ Undetermined,+ /// A positive answer was reached but the completion graph could not be+ /// turned into a finite interpretation that satisfies the axioms. No file+ /// was written. The string says why.+ Refused(String),+}++impl ModelOutcome {+ /// True only when files were written.+ pub fn is_certified(&self) -> bool {+ matches!(self, ModelOutcome::Certified { .. })+ }++ /// A one-line description, for logs and for the `owl-dl` JSON output.+ pub fn describe(&self) -> String {+ match self {+ ModelOutcome::Certified {+ axioms,+ domain,+ edges,+ } => format!("certified: {axioms} axioms, {domain} elements, {edges} edges"),+ ModelOutcome::Refuted => "no certificate: the answer was negative".to_string(),+ ModelOutcome::Undetermined => "no certificate: the run was undetermined".to_string(),+ ModelOutcome::Refused(why) => format!("no certificate: {why}"),+ }+ }+}++/// A name that survives the round trip through the two files.+///+/// The concept grammar is space-separated and the files are tab-separated, so a+/// term carrying either would be read back as a different term. N-Triples IRIs+/// and blank node labels never do. A literal can, and `owl:hasValue` is+/// approximated here by an atomic concept named after the individual, which may+/// be a literal. Refusing is the only honest answer for one of those.+fn name_is_safe(s: &str) -> bool {+ !s.is_empty() && !s.contains([' ', '\t', '\n', '\r'])+}++// ── Serialisation ───────────────────────────────────────────────────────++fn write_concept(out: &mut String, interner: &Interner, c: &Concept) {+ match c {+ Concept::Top => out.push_str("top"),+ Concept::Bottom => out.push_str("bot"),+ Concept::Atom(a) => {+ out.push_str("atom ");+ out.push_str(interner.resolve(*a));+ }+ Concept::NegAtom(a) => {+ out.push_str("not atom ");+ out.push_str(interner.resolve(*a));+ }+ // `lean/Dl` has binary conjunction and disjunction, so the n-ary OWL+ // constructors are folded right-associatively here. An empty list is the+ // unit of the connective, which is how `RawConcept::to_nnf` already+ // reads it.+ Concept::And(cs) => write_nary(out, interner, cs, "and", &Concept::Top),+ Concept::Or(cs) => write_nary(out, interner, cs, "or", &Concept::Bottom),+ Concept::Exists(r, f) => {+ out.push_str("some ");+ out.push_str(interner.resolve(*r));+ out.push(' ');+ write_concept(out, interner, f);+ }+ Concept::ForAll(r, f) => {+ out.push_str("all ");+ out.push_str(interner.resolve(*r));+ out.push(' ');+ write_concept(out, interner, f);+ }+ Concept::MinCard(r, n, f) => {+ out.push_str("min ");+ out.push_str(&n.to_string());+ out.push(' ');+ out.push_str(interner.resolve(*r));+ out.push(' ');+ write_concept(out, interner, f);+ }+ Concept::MaxCard(r, n, f) => {+ out.push_str("max ");+ out.push_str(&n.to_string());+ out.push(' ');+ out.push_str(interner.resolve(*r));+ out.push(' ');+ write_concept(out, interner, f);+ }+ }+}++fn write_nary(out: &mut String, interner: &Interner, cs: &[Concept], op: &str, unit: &Concept) {+ match cs.split_first() {+ None => write_concept(out, interner, unit),+ Some((head, [])) => write_concept(out, interner, head),+ Some((head, rest)) => {+ out.push_str(op);+ out.push(' ');+ write_concept(out, interner, head);+ out.push(' ');+ write_nary(out, interner, rest, op, unit);+ }+ }+}++fn concept_string(interner: &Interner, c: &Concept) -> String {+ let mut s = String::new();+ write_concept(&mut s, interner, c);+ s+}++fn axiom_line(interner: &Interner, a: &DlAxiom) -> String {+ let cs = |c: &Concept| concept_string(interner, c);+ let r = |id: &u32| interner.resolve(*id).to_string();+ match a {+ DlAxiom::Sub(c, d) => format!("sub\t{}\t{}", cs(c), cs(d)),+ DlAxiom::Disjoint(c, d) => format!("disjoint\t{}\t{}", cs(c), cs(d)),+ DlAxiom::Domain(role, c) => format!("domain\t{}\t{}", r(role), cs(c)),+ DlAxiom::Range(role, c) => format!("range\t{}\t{}", r(role), cs(c)),+ DlAxiom::SubRole(a1, b1) => format!("subrole\t{}\t{}", r(a1), r(b1)),+ DlAxiom::Trans(role) => format!("trans\t{}", r(role)),+ DlAxiom::Sym(role) => format!("sym\t{}", r(role)),+ DlAxiom::Inv(a1, b1) => format!("inv\t{}\t{}", r(a1), r(b1)),+ DlAxiom::InvFunc(role) => format!("invfunc\t{}", r(role)),+ DlAxiom::Inst(i, c) => format!("inst\t{}\t{}", r(i), cs(c)),+ DlAxiom::Rel(a1, role, b1) => format!("rel\t{}\t{}\t{}", r(a1), r(role), r(b1)),+ DlAxiom::Indiv(i) => format!("indiv\t{}", r(i)),+ DlAxiom::NonEmpty(c) => format!("nonempty\t{}", cs(c)),+ }+}++/// Every name a concept mentions, for the safety check.+fn concept_names(interner: &Interner, c: &Concept, out: &mut Vec<String>) {+ match c {+ Concept::Top | Concept::Bottom => {}+ Concept::Atom(a) | Concept::NegAtom(a) => out.push(interner.resolve(*a).to_string()),+ Concept::And(cs) | Concept::Or(cs) => {+ for c in cs {+ concept_names(interner, c, out);+ }+ }+ Concept::Exists(r, f) | Concept::ForAll(r, f) => {+ out.push(interner.resolve(*r).to_string());+ concept_names(interner, f, out);+ }+ Concept::MinCard(r, _, f) | Concept::MaxCard(r, _, f) => {+ out.push(interner.resolve(*r).to_string());+ concept_names(interner, f, out);+ }+ }+}++// ── The finite interpretation, and the check on it ──────────────────────++impl FiniteModel {+ fn successors(&self, role: u32, x: u32) -> &[u32] {+ self.rext+ .get(&(role, x))+ .map(|v| v.as_slice())+ .unwrap_or(&[])+ }++ fn in_class(&self, class: u32, x: u32) -> bool {+ self.cext.get(&class).is_some_and(|s| s.contains(&x))+ }++ /// The same clauses as `Dl.sat` in `lean/Dl/Check.lean`. `rext` entries are+ /// deduplicated when the model is built, so the counting cases compare+ /// against a count of DISTINCT successors, which is what `Dl.AtLeast` and+ /// `Dl.AtMost` mean.+ fn sat(&self, c: &Concept, x: u32) -> bool {+ match c {+ Concept::Top => true,+ Concept::Bottom => false,+ Concept::Atom(a) => self.in_class(*a, x),+ Concept::NegAtom(a) => !self.in_class(*a, x),+ Concept::And(cs) => cs.iter().all(|d| self.sat(d, x)),+ Concept::Or(cs) => cs.iter().any(|d| self.sat(d, x)),+ Concept::Exists(r, f) => self.successors(*r, x).iter().any(|&y| self.sat(f, y)),+ Concept::ForAll(r, f) => self.successors(*r, x).iter().all(|&y| self.sat(f, y)),+ Concept::MinCard(r, n, f) => {+ self.successors(*r, x).iter().filter(|&&y| self.sat(f, y)).count() >= *n as usize+ }+ Concept::MaxCard(r, n, f) => {+ self.successors(*r, x).iter().filter(|&&y| self.sat(f, y)).count() <= *n as usize+ }+ }+ }++ /// The same clauses as `Dl.holds`.+ fn holds(&self, a: &DlAxiom) -> bool {+ match a {+ DlAxiom::Sub(c, d) => self.dom.iter().all(|&x| !self.sat(c, x) || self.sat(d, x)),+ DlAxiom::Disjoint(c, d) => {+ self.dom.iter().all(|&x| !(self.sat(c, x) && self.sat(d, x)))+ }+ DlAxiom::Domain(r, c) => self+ .dom+ .iter()+ .all(|&x| self.successors(*r, x).is_empty() || self.sat(c, x)),+ DlAxiom::Range(r, c) => self+ .dom+ .iter()+ .all(|&x| self.successors(*r, x).iter().all(|&y| self.sat(c, y))),+ DlAxiom::SubRole(r, s) => self.dom.iter().all(|&x| {+ self.successors(*r, x)+ .iter()+ .all(|y| self.successors(*s, x).contains(y))+ }),+ DlAxiom::Trans(r) => self.dom.iter().all(|&x| {+ self.successors(*r, x).iter().all(|&y| {+ self.successors(*r, y)+ .iter()+ .all(|z| self.successors(*r, x).contains(z))+ })+ }),+ DlAxiom::Sym(r) => self.dom.iter().all(|&x| {+ self.successors(*r, x)+ .iter()+ .all(|&y| self.successors(*r, y).contains(&x))+ }),+ DlAxiom::Inv(r, s) => {+ self.dom.iter().all(|&x| {+ self.successors(*r, x)+ .iter()+ .all(|&y| self.successors(*s, y).contains(&x))+ }) && self.dom.iter().all(|&x| {+ self.successors(*s, x)+ .iter()+ .all(|&y| self.successors(*r, y).contains(&x))+ })+ }+ DlAxiom::InvFunc(r) => self.dom.iter().all(|&y| {+ self.dom+ .iter()+ .filter(|&&x| self.successors(*r, x).contains(&y))+ .count()+ <= 1+ }),+ DlAxiom::Inst(i, c) => self.ind.get(i).is_some_and(|&x| self.sat(c, x)),+ DlAxiom::Rel(a1, r, b1) => match (self.ind.get(a1), self.ind.get(b1)) {+ (Some(&x), Some(&y)) => self.successors(*r, x).contains(&y),+ _ => false,+ },+ DlAxiom::Indiv(i) => self.ind.get(i).is_some_and(|x| self.domset.contains(x)),+ DlAxiom::NonEmpty(c) => self.dom.iter().any(|&x| self.sat(c, x)),+ }+ }++ /// The same clauses as `Dl.checkWF`. Returns the first failure.+ fn well_formed(&self, axioms: &[DlAxiom]) -> Result<(), String> {+ if self.dom.is_empty() {+ return Err("the domain is empty".to_string());+ }+ for (class, members) in &self.cext {+ if let Some(bad) = members.iter().find(|m| !self.domset.contains(m)) {+ return Err(format!(+ "class {class} has member n{bad} outside the domain"+ ));+ }+ }+ for (&(role, from), targets) in &self.rext {+ if !self.domset.contains(&from) {+ return Err(format!("role {role} has an edge from n{from}, outside the domain"));+ }+ if let Some(bad) = targets.iter().find(|t| !self.domset.contains(t)) {+ return Err(format!("role {role} has an edge to n{bad}, outside the domain"));+ }+ }+ for a in axioms {+ let inds: Vec<u32> = match a {+ DlAxiom::Inst(i, _) | DlAxiom::Indiv(i) => vec![*i],+ DlAxiom::Rel(x, _, y) => vec![*x, *y],+ _ => vec![],+ };+ for i in inds {+ match self.ind.get(&i) {+ Some(x) if self.domset.contains(x) => {}+ _ => {+ return Err(format!(+ "individual {i} has no denotation inside the domain"+ ));+ }+ }+ }+ }+ Ok(())+ }+}++// ── Reading a completion graph off a finished tableau ────────────────────++impl Tableau {+ /// Fold blocked nodes into the nodes that block them, and return the+ /// surviving nodes with their labels and edges.+ ///+ /// A blocked node is never expanded, so its label can carry an `∃R.C` with+ /// no `R`-successor: the completion graph as it stands is NOT an+ /// interpretation. The standard repair is to send the edge that reaches the+ /// blocked node to its blocker instead. Pairwise blocking requires the two+ /// labels to be EQUAL, not merely included, so the redirect moves the edge+ /// to a node carrying exactly the same constraints.+ ///+ /// That argument is why the fold is worth doing at all. It is not why the+ /// result is trusted: the caller checks the folded interpretation against+ /// the axioms and refuses to emit if it does not hold. SHIQ has no finite+ /// model property, so for some inputs no fold can work, and refusing is the+ /// correct outcome there rather than a bug.+ fn folded_graph(&self) -> Result<FoldedGraph, String> {+ let resolve = |mut n: u32| -> Result<u32, String> {+ let mut steps = 0usize;+ while let Some(b) = self.blocker_of(n) {+ n = b;+ steps += 1;+ if steps > self.nodes.len() + 1 {+ return Err("a blocking chain did not terminate".to_string());+ }+ }+ Ok(n)+ };++ let mut roots: Vec<u32> = self+ .nodes+ .iter()+ .filter(|(_, n)| n.parent.is_none())+ .map(|(&id, _)| id)+ .collect();+ roots.sort_unstable();+ if roots.is_empty() {+ return Err("the completion graph has no root node".to_string());+ }++ let mut kept: Vec<u32> = Vec::new();+ let mut seen: HashSet<u32> = HashSet::new();+ let mut edges: Vec<(u32, u32, u32)> = Vec::new();+ let mut queue: Vec<u32> = Vec::new();+ for r in roots {+ let r = resolve(r)?;+ if seen.insert(r) {+ kept.push(r);+ queue.push(r);+ }+ }+ while let Some(x) = queue.pop() {+ let Some(node) = self.nodes.get(&x) else {+ return Err(format!("node {x} is referenced but absent"));+ };+ let mut roles: Vec<u32> = node.edges.keys().copied().collect();+ roles.sort_unstable();+ for role in roles {+ let mut targets: Vec<u32> = node.edges[&role].iter().copied().collect();+ targets.sort_unstable();+ for t in targets {+ let t = resolve(t)?;+ edges.push((x, role, t));+ if seen.insert(t) {+ kept.push(t);+ queue.push(t);+ }+ }+ }+ }+ kept.sort_unstable();+ edges.sort_unstable();+ edges.dedup();+ Ok((kept, edges))+ }+}++// ── Closing the role extensions ─────────────────────────────────────────++/// Add every edge the role axioms force: super-roles, inverses (a symmetric role+/// is its own inverse here) and transitive closure.+///+/// The completion graph carries only the edges the tableau rules created, and+/// `Tableau::successors` reads the rest off the role hierarchy and the parent+/// back-link as it goes. A finite interpretation has to carry them, because+/// `subrole`, `inv`, `sym` and `trans` are axioms the checker will evaluate.+///+/// The cap is not a nicety. Closing a transitive role over a completion graph+/// can square the edge count, and a certificate nobody can read is no better+/// than none.+fn close_roles(+ src: &AxiomSource,+ raw: &[(u32, u32, u32)],+ cap: usize,+) -> Result<HashSet<(u32, u32, u32)>, String> {+ let mut super_of: HashMap<u32, HashSet<u32>> = HashMap::new();+ for (&sub, sups) in &src.sub_to_super {+ let mut seen: HashSet<u32> = HashSet::new();+ let mut stack: Vec<u32> = sups.iter().copied().collect();+ while let Some(x) = stack.pop() {+ if seen.insert(x)+ && let Some(next) = src.sub_to_super.get(&x)+ {+ stack.extend(next.iter().copied());+ }+ }+ seen.remove(&sub);+ super_of.insert(sub, seen);+ }++ let mut all: HashSet<(u32, u32, u32)> = raw.iter().copied().collect();+ let mut work: Vec<(u32, u32, u32)> = all.iter().copied().collect();+ while let Some((x, r, y)) = work.pop() {+ if all.len() > cap {+ return Err(format!(+ "closing the role extensions passed {cap} edges; no finite interpretation \+ small enough to certify was produced"+ ));+ }+ let mut add: Vec<(u32, u32, u32)> = Vec::new();+ if let Some(sups) = super_of.get(&r) {+ for &s in sups {+ add.push((x, s, y));+ }+ }+ if let Some(&inv) = src.inverse_roles.get(&r) {+ add.push((y, inv, x));+ }+ if src.transitive_roles.contains(&r) {+ for &(a, rr, b) in all.iter() {+ if rr != r {+ continue;+ }+ if b == x {+ add.push((a, r, y));+ }+ if a == y {+ add.push((x, r, b));+ }+ }+ }+ for e in add {+ if all.insert(e) {+ work.push(e);+ }+ }+ }+ Ok(all)+}++// ── The public entry points ─────────────────────────────────────────────++impl DlReasoner {+ /// The TBox axioms, as the OWL parser read them, in the `lean/Dl` fragment.+ fn tbox_axioms(&self) -> Vec<DlAxiom> {+ let s = &self.source;+ let mut out: Vec<DlAxiom> = Vec::new();+ for (sub, sup) in &s.axioms {+ out.push(DlAxiom::Sub(sub.clone(), sup.clone()));+ }+ for (a, b) in &s.disjoint_pairs {+ out.push(DlAxiom::Disjoint(a.clone(), b.clone()));+ }+ for (r, c) in &s.role_domains {+ out.push(DlAxiom::Domain(*r, c.clone()));+ }+ for (r, c) in &s.role_ranges {+ out.push(DlAxiom::Range(*r, c.clone()));+ }+ let mut subrole: Vec<(u32, u32)> = Vec::new();+ for (&sub, sups) in &s.sub_to_super {+ for &sup in sups {+ if sub != sup {+ subrole.push((sub, sup));+ }+ }+ }+ subrole.sort_unstable();+ for (sub, sup) in subrole {+ out.push(DlAxiom::SubRole(sub, sup));+ }+ let mut trans: Vec<u32> = s.transitive_roles.iter().copied().collect();+ trans.sort_unstable();+ for r in trans {+ out.push(DlAxiom::Trans(r));+ }+ // `inverse_roles` holds both directions, and a symmetric role appears as+ // its own inverse. Emit each pair once, and a symmetric role as `sym`,+ // which is the same condition stated in the form a reader expects.+ let mut invs: Vec<(u32, u32)> = s.inverse_roles.iter().map(|(&a, &b)| (a, b)).collect();+ invs.sort_unstable();+ for (a, b) in invs {+ if a == b {+ out.push(DlAxiom::Sym(a));+ } else if a < b {+ out.push(DlAxiom::Inv(a, b));+ }+ }+ // A functional role is exactly `⊤ ⊑ ≤1 R.⊤`, so it needs no constructor+ // of its own. Inverse functionality does: `≤1 R⁻.⊤` is not expressible+ // as a concept unless `R` happens to have a named inverse.+ let mut func: Vec<u32> = s.functional_roles.iter().copied().collect();+ func.sort_unstable();+ for r in func {+ out.push(DlAxiom::Sub(+ Concept::Top,+ Concept::MaxCard(r, 1, Box::new(Concept::Top)),+ ));+ }+ let mut invfunc: Vec<u32> = s.inv_functional_roles.iter().copied().collect();+ invfunc.sort_unstable();+ for r in invfunc {+ out.push(DlAxiom::InvFunc(r));+ }+ out+ }++ /// The TBox axioms plus the ABox: class assertions, role assertions, and one+ /// `indiv` line per named individual so that a model is forced to contain it.+ fn abox_axioms(&self) -> Vec<DlAxiom> {+ let mut out = self.tbox_axioms();+ let mut inds: Vec<u32> = self.individual_types.keys().copied().collect();+ for &i in self.individual_anon_types.keys() {+ inds.push(i);+ }+ for &(a, _, b) in &self.role_assertions {+ inds.push(a);+ inds.push(b);+ }+ inds.sort_unstable();+ inds.dedup();+ for i in inds {+ out.push(DlAxiom::Indiv(i));+ }+ let mut typed: Vec<(u32, Vec<u32>)> = self+ .individual_types+ .iter()+ .map(|(&i, ts)| {+ let mut v: Vec<u32> = ts.iter().copied().collect();+ v.sort_unstable();+ (i, v)+ })+ .collect();+ typed.sort_unstable();+ for (i, ts) in typed {+ for t in ts {+ out.push(DlAxiom::Inst(i, Concept::Atom(t)));+ }+ }+ let mut anon: Vec<(u32, Vec<Concept>)> = self+ .individual_anon_types+ .iter()+ .map(|(&i, cs)| (i, cs.clone()))+ .collect();+ anon.sort_unstable_by_key(|(i, _)| *i);+ for (i, cs) in anon {+ for c in cs {+ out.push(DlAxiom::Inst(i, c));+ }+ }+ let mut rels: Vec<(u32, u32, u32)> = self.role_assertions.clone();+ rels.sort_unstable();+ rels.dedup();+ for (a, r, b) in rels {+ out.push(DlAxiom::Rel(a, r, b));+ }+ out+ }++ /// Build the finite interpretation, check it here, and write the two files.+ /// Nothing is written unless the check passes.+ fn emit(+ &self,+ tableau: &Tableau,+ ind_to_node: &HashMap<u32, u32>,+ axioms: Vec<DlAxiom>,+ dir: &Path,+ ) -> anyhow::Result<ModelOutcome> {+ let (kept, raw_edges) = match tableau.folded_graph() {+ Ok(v) => v,+ Err(e) => return Ok(ModelOutcome::Refused(e)),+ };+ if kept.is_empty() {+ return Ok(ModelOutcome::Refused(+ "the completion graph is empty, so there is no interpretation to hand over"+ .to_string(),+ ));+ }++ let domset: HashSet<u32> = kept.iter().copied().collect();+ let closed = match close_roles(&self.source, &raw_edges, 200_000) {+ Ok(v) => v,+ Err(e) => return Ok(ModelOutcome::Refused(e)),+ };++ let mut rext: HashMap<(u32, u32), Vec<u32>> = HashMap::new();+ for (x, r, y) in closed {+ if !domset.contains(&x) || !domset.contains(&y) {+ return Ok(ModelOutcome::Refused(format!(+ "closing the role extensions produced an edge outside the folded domain \+ (n{x} to n{y}); the completion graph does not fold into a finite model"+ )));+ }+ rext.entry((r, x)).or_default().push(y);+ }+ for v in rext.values_mut() {+ v.sort_unstable();+ v.dedup();+ }++ let mut cext: HashMap<u32, HashSet<u32>> = HashMap::new();+ for &n in &kept {+ let Some(node) = tableau.nodes.get(&n) else {+ return Ok(ModelOutcome::Refused(format!("node {n} vanished")));+ };+ for label in &node.labels {+ if let Concept::Atom(a) = label {+ cext.entry(*a).or_default().insert(n);+ }+ }+ }++ let mut ind: HashMap<u32, u32> = HashMap::new();+ for (&i, &n) in ind_to_node {+ // An individual whose node was folded away denotes the node it was+ // folded into. Roots are never blocked, and every individual is a+ // root, so in practice this is the identity; it is written out+ // rather than assumed.+ let mut cur = n;+ let mut steps = 0usize;+ while let Some(b) = tableau.blocker_of(cur) {+ cur = b;+ steps += 1;+ if steps > tableau.nodes.len() + 1 {+ return Ok(ModelOutcome::Refused(+ "a blocking chain under a named individual did not terminate".to_string(),+ ));+ }+ }+ if !domset.contains(&cur) {+ return Ok(ModelOutcome::Refused(format!(+ "individual {} has no node in the folded domain",+ self.interner.resolve(i)+ )));+ }+ ind.insert(i, cur);+ }++ let model = FiniteModel {+ dom: kept.clone(),+ domset,+ cext,+ rext,+ ind,+ };++ // Every name that will appear in either file has to survive the round+ // trip. `owl:hasValue` is approximated by an atom named after the+ // individual, and that individual can be a literal with a space in it.+ let mut names: Vec<String> = Vec::new();+ for a in &axioms {+ match a {+ DlAxiom::Sub(c, d) | DlAxiom::Disjoint(c, d) => {+ concept_names(&self.interner, c, &mut names);+ concept_names(&self.interner, d, &mut names);+ }+ DlAxiom::Domain(r, c) | DlAxiom::Range(r, c) => {+ names.push(self.interner.resolve(*r).to_string());+ concept_names(&self.interner, c, &mut names);+ }+ DlAxiom::Inst(i, c) => {+ names.push(self.interner.resolve(*i).to_string());+ concept_names(&self.interner, c, &mut names);+ }+ DlAxiom::NonEmpty(c) => concept_names(&self.interner, c, &mut names),+ DlAxiom::SubRole(x, y) | DlAxiom::Inv(x, y) => {+ names.push(self.interner.resolve(*x).to_string());+ names.push(self.interner.resolve(*y).to_string());+ }+ DlAxiom::Trans(r) | DlAxiom::Sym(r) | DlAxiom::InvFunc(r) => {+ names.push(self.interner.resolve(*r).to_string())+ }+ DlAxiom::Rel(x, r, y) => {+ names.push(self.interner.resolve(*x).to_string());+ names.push(self.interner.resolve(*r).to_string());+ names.push(self.interner.resolve(*y).to_string());+ }+ DlAxiom::Indiv(i) => names.push(self.interner.resolve(*i).to_string()),+ }+ }+ for &(role, _) in model.rext.keys() {+ names.push(self.interner.resolve(role).to_string());+ }+ for &class in model.cext.keys() {+ names.push(self.interner.resolve(class).to_string());+ }+ if let Some(bad) = names.iter().find(|n| !name_is_safe(n)) {+ return Ok(ModelOutcome::Refused(format!(+ "the name {bad:?} carries whitespace, so it would not survive the \+ tab-and-space separated format; nothing was written"+ )));+ }++ // The gate. A certificate that will not check is worse than no+ // certificate, so the emitter runs the same semantics the checker does+ // and refuses when it does not hold.+ if let Err(why) = model.well_formed(&axioms) {+ return Ok(ModelOutcome::Refused(format!(+ "the folded completion graph is not a finite interpretation: {why}"+ )));+ }+ if let Some(bad) = axioms.iter().find(|a| !model.holds(a)) {+ return Ok(ModelOutcome::Refused(format!(+ "the folded completion graph does not satisfy the axiom `{}`",+ axiom_line(&self.interner, bad).replace('\t', " ")+ )));+ }++ let mut axiom_text = String::new();+ for a in &axioms {+ axiom_text.push_str(&axiom_line(&self.interner, a));+ axiom_text.push('\n');+ }++ let mut model_text = String::new();+ for &n in &model.dom {+ model_text.push_str(&format!("domain\tn{n}\n"));+ }+ let mut classes: Vec<(u32, Vec<u32>)> = model+ .cext+ .iter()+ .map(|(&c, ms)| {+ let mut v: Vec<u32> = ms.iter().copied().collect();+ v.sort_unstable();+ (c, v)+ })+ .collect();+ classes.sort_unstable();+ for (c, ms) in classes {+ for m in ms {+ model_text.push_str(&format!("class\t{}\tn{m}\n", self.interner.resolve(c)));+ }+ }+ let mut edge_lines: Vec<(u32, u32, u32)> = Vec::new();+ for (&(r, x), ys) in &model.rext {+ for &y in ys {+ edge_lines.push((x, r, y));+ }+ }+ edge_lines.sort_unstable();+ let edge_count = edge_lines.len();+ for (x, r, y) in edge_lines {+ model_text.push_str(&format!("edge\tn{x}\t{}\tn{y}\n", self.interner.resolve(r)));+ }+ let mut ind_lines: Vec<(u32, u32)> = model.ind.iter().map(|(&i, &n)| (i, n)).collect();+ ind_lines.sort_unstable();+ for (i, n) in ind_lines {+ model_text.push_str(&format!("ind\t{}\tn{n}\n", self.interner.resolve(i)));+ }++ std::fs::create_dir_all(dir)?;+ std::fs::write(dir.join("axioms.tsv"), axiom_text)?;+ std::fs::write(dir.join("model.tsv"), model_text)?;++ Ok(ModelOutcome::Certified {+ axioms: axioms.len(),+ domain: model.dom.len(),+ edges: edge_count,+ })+ }++ /// Certify that `class_iri` is satisfiable with respect to the TBox.+ ///+ /// The claim is written into the axiom set as `nonempty`, so a checker that+ /// accepts the certificate has verified the reasoner's actual answer and not+ /// merely that the TBox has some model. The ABox is NOT part of this+ /// certificate: classification in this reasoner is a TBox question, the+ /// completion graph has no named individuals in it, and pretending otherwise+ /// would produce a certificate that cannot check.+ pub fn certify_class_satisfiable(+ &self,+ class_iri: &str,+ dir: &Path,+ ) -> anyhow::Result<ModelOutcome> {+ let Some(&cid) = self.interner.to_id.get(class_iri) else {+ anyhow::bail!("no class named {class_iri} in this ontology");+ };+ let concept = Concept::Atom(cid);+ let mut tableau = Tableau::with_deadline(Arc::clone(&self.tbox), self.deadline);+ tableau.capture = true;+ match tableau.decide(&concept) {+ Verdict::Unsatisfiable => return Ok(ModelOutcome::Refuted),+ Verdict::Unknown => return Ok(ModelOutcome::Undetermined),+ Verdict::Satisfiable => {}+ }+ let mut axioms = self.tbox_axioms();+ axioms.push(DlAxiom::NonEmpty(concept));+ self.emit(&tableau, &HashMap::new(), axioms, dir)+ }++ /// Certify that the TBox is consistent.+ ///+ /// No `nonempty` line is needed: `Dl.WellFormed` already requires the domain+ /// to be non-empty, so a model of the axiom set alone is exactly what TBox+ /// consistency asserts.+ pub fn certify_tbox_consistent(&self, dir: &Path) -> anyhow::Result<ModelOutcome> {+ let mut tableau = Tableau::with_deadline(Arc::clone(&self.tbox), self.deadline);+ tableau.capture = true;+ match tableau.decide(&Concept::Top) {+ Verdict::Unsatisfiable => return Ok(ModelOutcome::Refuted),+ Verdict::Unknown => return Ok(ModelOutcome::Undetermined),+ Verdict::Satisfiable => {}+ }+ self.emit(&tableau, &HashMap::new(), self.tbox_axioms(), dir)+ }++ /// Certify that the ABox is consistent with the TBox.+ pub fn certify_abox_consistent(&self, dir: &Path) -> anyhow::Result<ModelOutcome> {+ if self.individual_types.is_empty() && self.individual_anon_types.is_empty() {+ return Ok(ModelOutcome::Refused(+ "this ontology has no ABox, so there is nothing to certify beyond the TBox"+ .to_string(),+ ));+ }+ let (mut tableau, ind_to_node, _) = self.build_abox_tableau();+ tableau.capture = true;+ if !tableau.expand(0) {+ return Ok(if tableau.budget.exhausted {+ ModelOutcome::Undetermined+ } else {+ ModelOutcome::Refuted+ });+ }+ self.emit(&tableau, &ind_to_node, self.abox_axioms(), dir)+ }+}diff --git a/tests/dl_model_certificate_test.rs b/tests/dl_model_certificate_test.rsnew file mode 100644index 00000000..7d2e50c6--- /dev/null+++ b/tests/dl_model_certificate_test.rs@@ -0,0 +1,608 @@+//! Model certificates for the SHIQ tableaux reasoner, end to end.+//!+//! `src/tableaux.rs` answers satisfiability, classification and ABox+//! consistency, and until now every answer was a bare verdict. The positive+//! answers now carry a finite model, and `lean/Dl/` holds a checker for it whose+//! soundness is a machine-checked theorem: `Dl.satisfiable_of_checkModel` says+//! that an interpretation the checker accepts is a model, so the axiom set it+//! was checked against really is satisfiable. These tests close that loop.+//!+//! 1. The reasoner emits and the checker accepts. A class the reasoner says is+//! satisfiable comes with a model of the TBox in which that class is not+//! empty, and an ABox the reasoner says is consistent comes with a model of+//! the TBox and the ABox together.+//! 2. The checker can say no, and each way it can say no is exercised on its+//! own. A model with a required successor removed, a model that violates a+//! disjointness, a model whose domain omits a named individual, and a model+//! that satisfies every TBox axiom while leaving empty the very class the+//! reasoner called satisfiable. Four separate forgeries, four separate+//! runs, four separate rejections. A gate that cannot fail is decoration.+//! 3. The negative answers carry NOTHING, and the emitter says so rather than+//! inventing a certificate. An unsatisfiable class produces `Refuted` and+//! writes no file.+//! 4. The emitter refuses instead of emitting something that will not check.+//! One case where it refuses is not a limitation of the certificate layer+//! but a defect in the reasoner, and that case is pinned here.+//!+//! The checker needs a Lean toolchain (`lake`) AND the `oo-dlmodel` target in+//! `lean/lakefile.toml`. Without either these tests skip loudly through+//! `common::skip_unless`; the CI job that installs Lean runs them with+//! `OO_REQUIRE_FIXTURES=1`, which turns that skip into a failure.++mod common;++use open_ontologies::graph::GraphStore;+use open_ontologies::tableaux::{DlReasoner, ModelOutcome};+use std::path::{Path, PathBuf};+use std::process::Command;+use std::sync::{Arc, OnceLock};++fn repo() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+}++/// The Lean package to build the checker from. `OO_LEAN_DIR` exists so the+/// suite can be pointed at a copy of `lean/` while the `oo-dlmodel` target is+/// being landed in the real `lakefile.toml`; unset, which is the normal case,+/// it is the repository's own `lean/`.+fn lean_dir() -> PathBuf {+ std::env::var("OO_LEAN_DIR")+ .map(PathBuf::from)+ .unwrap_or_else(|_| repo().join("lean"))+}++fn lake_available() -> bool {+ // `.current_dir(lean_dir())` is not cosmetic: elan resolves the toolchain+ // from the working directory's `lean-toolchain`, and the crate root has none+ // in its ancestry. See the same probe in `tests/lean_certificate_test.rs`.+ Command::new("lake")+ .arg("--version")+ .current_dir(lean_dir())+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+}++/// The build outcome, computed once per test binary. `Err` carries the reason,+/// so a missing toolchain and a missing lakefile target are distinguishable.+fn build() -> &'static Result<PathBuf, String> {+ static BUILT: OnceLock<Result<PathBuf, String>> = OnceLock::new();+ BUILT.get_or_init(|| {+ if !lake_available() {+ return Err(+ "lake (the Lean 4 build tool); install elan from \+ https://github.com/leanprover/elan, and lean/lean-toolchain pins the version"+ .to_string(),+ );+ }+ let out = Command::new("lake")+ .arg("build")+ .arg("oo-dlmodel")+ .current_dir(lean_dir())+ .output()+ .expect("run lake build oo-dlmodel");+ let text = format!(+ "{}{}",+ String::from_utf8_lossy(&out.stdout),+ String::from_utf8_lossy(&out.stderr)+ );+ if !out.status.success() {+ // A missing target is a lakefile that has not been updated yet, not+ // a broken proof. The two must not be reported as the same thing.+ if text.contains("unknown target") || text.contains("no such target") {+ return Err(format!(+ "the `oo-dlmodel` target in lean/lakefile.toml. Add:\n\+ \n\+ [[lean_lib]]\nname = \"Dl\"\nroots = [\"Dl.All\"]\nglobs = [\"Dl.+\"]\n\+ \n\+ [[lean_exe]]\nname = \"oo-dlmodel\"\nroot = \"DlMain\"\n\+ \n\+ lake said: {text}"+ ));+ }+ panic!("lake build oo-dlmodel failed:\n{text}");+ }+ let exe = lean_dir()+ .join(".lake")+ .join("build")+ .join("bin")+ .join("oo-dlmodel");+ if !exe.exists() {+ panic!("checker binary missing at {}", exe.display());+ }+ Ok(exe)+ })+}++fn skip() -> bool {+ match build() {+ Ok(_) => false,+ Err(why) => common::skip_unless(+ false,+ why,+ "the model-certificate tests need both, and check nothing without them",+ ),+ }+}++fn checker() -> &'static Path {+ build().as_ref().expect("checked by skip()").as_path()+}++/// Run `oo-dlmodel` over a directory. Returns (exit code, stdout + stderr).+fn check_dir(dir: &Path) -> (i32, String) {+ check_files(&dir.join("axioms.tsv"), &dir.join("model.tsv"))+}++fn check_files(axioms: &Path, model: &Path) -> (i32, String) {+ let out = Command::new(checker())+ .arg(axioms)+ .arg(model)+ .output()+ .expect("run oo-dlmodel");+ let text = format!(+ "{}{}",+ String::from_utf8_lossy(&out.stdout),+ String::from_utf8_lossy(&out.stderr)+ );+ (out.status.code().unwrap_or(-1), text)+}++fn scratch(name: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("oo-dlmodel-{}-{}", name, std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+}++fn reasoner_for(ttl: &str) -> DlReasoner {+ let store = Arc::new(GraphStore::new());+ store.load_turtle(ttl, None).unwrap();+ DlReasoner::from_graph(&store).unwrap()+}++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#> .+ @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .+"#;++/// A TBox with an existential, a disjointness and a range. Small enough that the+/// expected model can be written out by hand, which is the point: a test whose+/// expected output nobody can predict is not a test.+const EMPLOYMENT_TBOX: &str = r#"+ :Person a owl:Class .+ :Company a owl:Class .+ :Person owl:disjointWith :Company .+ :worksFor a owl:ObjectProperty ; rdfs:range :Company .+ :Employed a owl:Class ;+ rdfs:subClassOf :Person ,+ [ a owl:Restriction ; owl:onProperty :worksFor ; owl:someValuesFrom :Company ] .+"#;++fn employment_certificate(name: &str) -> PathBuf {+ let dir = scratch(name);+ let reasoner = reasoner_for(&format!("{PREFIXES}{EMPLOYMENT_TBOX}"));+ let outcome = reasoner+ .certify_class_satisfiable("<http://ex.org/Employed>", &dir)+ .unwrap();+ assert!(+ outcome.is_certified(),+ "the emitter refused a class it reports satisfiable: {}",+ outcome.describe()+ );+ dir+}++/// Read `model.tsv`, apply an edit, write it back under a new name, and return+/// the path to the forged file. The axiom file is untouched, so the only thing+/// that can change the verdict is the interpretation.+fn forge(dir: &Path, name: &str, edit: impl Fn(Vec<String>) -> Vec<String>) -> PathBuf {+ let text = std::fs::read_to_string(dir.join("model.tsv")).unwrap();+ let lines: Vec<String> = text.lines().map(|l| l.to_string()).collect();+ let out = edit(lines);+ let path = dir.join(format!("model.{name}.tsv"));+ std::fs::write(&path, out.join("\n") + "\n").unwrap();+ path+}++// ── 1. The reasoner emits and the checker accepts ───────────────────────++#[test]+fn a_satisfiable_class_carries_a_model_the_checker_accepts() {+ if skip() {+ return;+ }+ let dir = employment_certificate("sat-class");++ let axioms = std::fs::read_to_string(dir.join("axioms.tsv")).unwrap();+ let model = std::fs::read_to_string(dir.join("model.tsv")).unwrap();++ // The claim the reasoner actually made has to be IN the axiom set, or the+ // certificate would only say "this ontology has some model", which is not+ // what was asked.+ assert!(+ axioms.contains("nonempty\tatom <http://ex.org/Employed>"),+ "the satisfiability claim is missing from the axiom file:\n{axioms}"+ );+ assert!(+ model.lines().any(|l| l.starts_with("domain\t")),+ "the model has no domain:\n{model}"+ );++ let (code, out) = check_dir(&dir);+ assert_eq!(code, 0, "oo-dlmodel rejected a genuine certificate: {out}");+ assert!(+ out.contains("\"theorem\":\"Dl.satisfiable_of_checkModel\""),+ "the accepted verdict does not name the theorem it stands for: {out}"+ );+}++#[test]+fn a_consistent_abox_carries_a_model_the_checker_accepts() {+ if skip() {+ return;+ }+ let dir = scratch("abox");+ let reasoner = reasoner_for(&format!(+ r#"{PREFIXES}{EMPLOYMENT_TBOX}+ :alice a owl:NamedIndividual, :Person, :Employed .+ :acme a owl:NamedIndividual, :Company .+ :alice :worksFor :acme .+ "#+ ));+ let outcome = reasoner.certify_abox_consistent(&dir).unwrap();+ assert!(+ outcome.is_certified(),+ "the emitter refused an ABox it reports consistent: {}",+ outcome.describe()+ );++ let axioms = std::fs::read_to_string(dir.join("axioms.tsv")).unwrap();+ assert!(+ axioms.contains("indiv\t<http://ex.org/alice>"),+ "a named individual is missing from the axiom file:\n{axioms}"+ );+ assert!(+ axioms.contains("rel\t<http://ex.org/alice>\t<http://ex.org/worksFor>\t<http://ex.org/acme>"),+ "the role assertion is missing from the axiom file:\n{axioms}"+ );++ let (code, out) = check_dir(&dir);+ assert_eq!(code, 0, "oo-dlmodel rejected a genuine ABox certificate: {out}");+}++// ── 2. Four forgeries, each rejected on its own ─────────────────────────++#[test]+fn forged_missing_successor_is_rejected() {+ if skip() {+ return;+ }+ let dir = employment_certificate("forge-successor");+ let forged = forge(&dir, "no-successor", |lines| {+ lines+ .into_iter()+ .filter(|l| !l.starts_with("edge\t"))+ .collect()+ });+ let (code, out) = check_files(&dir.join("axioms.tsv"), &forged);+ assert_eq!(code, 1, "a model with no successor at all was accepted: {out}");+ assert!(+ out.contains("\"kind\":\"sub\""),+ "the rejection does not blame the subclass axiom that needs the successor: {out}"+ );+}++#[test]+fn forged_disjointness_violation_is_rejected() {+ if skip() {+ return;+ }+ let dir = employment_certificate("forge-disjoint");+ // Put the person element into Company as well. Person and Company are+ // declared disjoint, so exactly one axiom can now fail.+ let forged = forge(&dir, "disjoint", |mut lines| {+ let person_elem = lines+ .iter()+ .find(|l| l.starts_with("class\t<http://ex.org/Person>\t"))+ .and_then(|l| l.split('\t').nth(2).map(|s| s.to_string()))+ .expect("the model puts something in Person");+ lines.push(format!("class\t<http://ex.org/Company>\t{person_elem}"));+ lines+ });+ let (code, out) = check_files(&dir.join("axioms.tsv"), &forged);+ assert_eq!(code, 1, "a model violating a disjointness was accepted: {out}");+ assert!(+ out.contains("\"kind\":\"disjoint\""),+ "the rejection does not blame the disjointness: {out}"+ );+}++#[test]+fn forged_domain_omitting_a_named_individual_is_rejected() {+ if skip() {+ return;+ }+ let dir = scratch("forge-individual");+ let reasoner = reasoner_for(&format!(+ r#"{PREFIXES}{EMPLOYMENT_TBOX}+ :alice a owl:NamedIndividual, :Person, :Employed .+ :acme a owl:NamedIndividual, :Company .+ :alice :worksFor :acme .+ "#+ ));+ assert!(reasoner.certify_abox_consistent(&dir).unwrap().is_certified());++ // Drop alice's element from the domain and leave everything else. The+ // individual now denotes something that is not in the interpretation at all.+ let forged = forge(&dir, "no-alice", |lines| {+ let alice_elem = lines+ .iter()+ .find(|l| l.starts_with("ind\t<http://ex.org/alice>\t"))+ .and_then(|l| l.split('\t').nth(2).map(|s| s.to_string()))+ .expect("alice has a denotation");+ lines+ .into_iter()+ .filter(|l| l.as_str() != format!("domain\t{alice_elem}"))+ .collect()+ });+ let (code, out) = check_files(&dir.join("axioms.tsv"), &forged);+ assert_eq!(code, 1, "a model whose domain omits a named individual was accepted: {out}");+ assert!(+ out.contains("\"wellformed\":false"),+ "the rejection does not blame well-formedness: {out}"+ );+}++#[test]+fn a_model_of_the_axioms_that_drops_the_claim_is_rejected() {+ if skip() {+ return;+ }+ let dir = employment_certificate("forge-claim");+ // This is the sharp one. Take the class the reasoner called satisfiable and+ // empty its extension. Every TBox axiom about it becomes vacuously true, so+ // the result IS a model of the ontology. It is not a model of the ANSWER,+ // and the `nonempty` line is what makes the difference visible.+ let forged = forge(&dir, "empty-claim", |lines| {+ lines+ .into_iter()+ .filter(|l| !l.starts_with("class\t<http://ex.org/Employed>\t"))+ .collect()+ });+ let (code, out) = check_files(&dir.join("axioms.tsv"), &forged);+ assert_eq!(+ code, 1,+ "a model of the ontology in which the class is empty was accepted as a certificate \+ that the class is satisfiable: {out}"+ );+ assert!(+ out.contains("\"kind\":\"nonempty\""),+ "the rejection does not blame the satisfiability claim, so the certificate is not \+ certifying the answer: {out}"+ );+}++// ── 3. The negative answers carry nothing ───────────────────────────────++/// No `skip()`: this checks only that the emitter writes nothing, which needs no+/// Lean toolchain. A suite that checks nothing at all without `lake` would let+/// the "we emit nothing for a negative answer" promise go untested everywhere+/// the toolchain is absent, and that is the promise most worth keeping.+#[test]+fn an_unsatisfiable_class_gets_no_certificate() {+ let dir = scratch("unsat");+ let reasoner = reasoner_for(&format!(+ r#"{PREFIXES}+ :A a owl:Class . :B a owl:Class .+ :A owl:disjointWith :B .+ :Impossible a owl:Class ; rdfs:subClassOf :A, :B .+ "#+ ));+ let outcome = reasoner+ .certify_class_satisfiable("<http://ex.org/Impossible>", &dir)+ .unwrap();+ assert_eq!(+ outcome,+ ModelOutcome::Refuted,+ "an unsatisfiable class should get no certificate, not a bad one"+ );+ assert!(+ !dir.join("axioms.tsv").exists() && !dir.join("model.tsv").exists(),+ "the emitter wrote files for an answer it cannot certify"+ );+}++// ── 4. The emitter refuses rather than emitting something that will not check ──++/// The first thing this layer caught, pinned.+///+/// `check_abox` inserts an asserted role assertion straight into the edge map+/// rather than through `create_successor`, and `create_successor` is the ONLY+/// place `rdfs:domain` and `rdfs:range` are applied. So on an asserted edge+/// neither constraint ever reaches the individuals.+///+/// The ontology below is inconsistent and it takes three axioms to see why:+/// `worksFor` has range `Company`, `alice worksFor carol` forces carol into+/// `Company`, carol is asserted a `Person`, and `Person` and `Company` are+/// disjoint. `check_abox` reports it CONSISTENT, and reports `undecided: false`,+/// so the claim is not hedged. That is a wrong positive answer, which is the+/// direction that matters: an ontology with a contradiction in it passes.+///+/// The certificate layer cannot fix that and does not try. What it does is+/// refuse to certify: the completion graph is not a model of the range axiom, so+/// no file is written and the refusal names the axiom. The assertion below is on+/// the CURRENT behaviour of both. When the reasoner is fixed, `abox_consistent`+/// becomes false and this test has to be rewritten, which is the correct moment+/// to notice.+#[test]+fn an_asserted_edge_skips_its_range_and_the_emitter_refuses_to_certify() {+ let dir = scratch("range-gap");+ let reasoner = reasoner_for(&format!(+ r#"{PREFIXES}+ :Person a owl:Class .+ :Company a owl:Class .+ :Person owl:disjointWith :Company .+ :worksFor a owl:ObjectProperty ; rdfs:range :Company .+ :alice a owl:NamedIndividual, :Person .+ :carol a owl:NamedIndividual, :Person .+ :alice :worksFor :carol .+ "#+ ));++ // The reasoner's own answer, and it is wrong.+ let abox = reasoner.check_abox();+ assert!(+ abox.consistent && !abox.undecided,+ "this test exists because the reasoner reports this inconsistent ABox as consistent; \+ if that has been fixed, rewrite the test rather than deleting it"+ );++ let outcome = reasoner.certify_abox_consistent(&dir).unwrap();+ match &outcome {+ ModelOutcome::Refused(why) => assert!(+ why.contains("range"),+ "the refusal should name the axiom that fails: {why}"+ ),+ other => panic!(+ "expected a refusal because the asserted edge never had its range applied, got {}",+ other.describe()+ ),+ }+ assert!(+ !dir.join("axioms.tsv").exists(),+ "a refusal must write nothing"+ );+}++// ── 5. Qualified number restrictions count DISTINCT successors ──────────++fn fixture(name: &str) -> PathBuf {+ repo().join("tests").join("fixtures").join("dlmodel").join(name)+}++/// `≥2 R.C` needs two different successors, and a hand-written certificate that+/// lists one successor twice must not pass. `lean/Dl/Count.lean` is where that+/// is proved, through a pigeonhole lemma; this runs it through the executable.+///+/// The fixtures are written by hand rather than emitted, because the reasoner's+/// own completion graphs never produce a duplicated edge and so could not+/// exercise the case at all.+#[test]+fn qualified_number_restrictions_count_distinct_successors() {+ if skip() {+ return;+ }+ let axioms = fixture("qnr_axioms.tsv");++ let (code, out) = check_files(&axioms, &fixture("qnr_model.tsv"));+ assert_eq!(code, 0, "a genuine two-member committee was rejected: {out}");++ let (code, out) = check_files(&axioms, &fixture("qnr_model_duplicate.tsv"));+ assert_eq!(+ code, 1,+ "one member listed twice was accepted as two members: {out}"+ );+ assert!(+ out.contains("min 2"),+ "the rejection does not blame the minimum cardinality: {out}"+ );+}++/// A file the parser cannot read is exit 2, which is neither "this is a model"+/// nor "this is not a model". A harness that collapsed the three would report an+/// unreadable certificate as a refuted one.+#[test]+fn an_unreadable_file_is_neither_verdict() {+ if skip() {+ return;+ }+ let (code, _) = check_files(&fixture("malformed_axioms.tsv"), &fixture("qnr_model.tsv"));+ assert_eq!(code, 2, "a malformed axiom file should be exit 2");++ let (code, _) = check_files(&fixture("qnr_axioms.tsv"), Path::new("/nonexistent/model.tsv"));+ assert_eq!(code, 2, "a missing model file should be exit 2");+}++// ── 6. A real ontology, class by class ──────────────────────────────────++/// The hand-written fixtures above prove the machinery works. This proves it+/// works on something nobody wrote for it.+///+/// Every named class of a shipped ontology is put through the reasoner, and+/// every class it reports satisfiable has its model checked by `oo-dlmodel`. The+/// interesting number is the disagreements, which must be zero: the emitter's+/// own gate and the verified checker have to agree on every single one, or one+/// of the two is wrong.+#[test]+fn a_shipped_ontology_certifies_class_by_class() {+ if skip() {+ return;+ }+ let onto = repo().join("benchmark/generated/boro-building-ai.ttl");+ if common::skip_unless(+ onto.exists(),+ "benchmark/generated/boro-building-ai.ttl",+ "it ships with the repository; a checkout without benchmark/ cannot run this",+ ) {+ return;+ }++ let store = Arc::new(GraphStore::new());+ store.load_file(onto.to_str().unwrap()).unwrap();+ let reasoner = DlReasoner::from_graph(&store).unwrap();++ let mut classes: Vec<String> = store+ .all_triples()+ .unwrap()+ .into_iter()+ .filter(|(_, p, o)| {+ (p == "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>"+ && (o == "<http://www.w3.org/2002/07/owl#Class>"+ || o == "<http://www.w3.org/2000/01/rdf-schema#Class>"))+ || p == "<http://www.w3.org/2000/01/rdf-schema#subClassOf>"+ })+ .map(|(s, _, _)| s)+ .filter(|s| s.starts_with('<'))+ .collect();+ classes.sort();+ classes.dedup();+ assert!(+ !classes.is_empty(),+ "no named classes found, so this test would pass without checking anything"+ );++ let dir = scratch("shipped");+ let mut certified = 0usize;+ let mut accepted = 0usize;+ let mut disagreements: Vec<String> = Vec::new();+ for (i, class) in classes.iter().enumerate() {+ let d = dir.join(i.to_string());+ if let ModelOutcome::Certified { .. } = reasoner+ .certify_class_satisfiable(class, &d)+ .unwrap_or_else(|e| panic!("certifying {class}: {e}"))+ {+ certified += 1;+ let (code, out) = check_dir(&d);+ if code == 0 {+ accepted += 1;+ } else {+ disagreements.push(format!("{class}: {out}"));+ }+ }+ }++ assert!(+ disagreements.is_empty(),+ "the emitter and the verified checker disagreed on {} of {certified} certificates:\n{}",+ disagreements.len(),+ disagreements.join("\n")+ );+ assert!(+ certified > 0,+ "no class of a consistent ontology was certified, so nothing was checked"+ );+ assert_eq!(certified, accepted);+}diff --git a/tests/fixtures/dlmodel/malformed_axioms.tsv b/tests/fixtures/dlmodel/malformed_axioms.tsvnew file mode 100644index 00000000..26890d80--- /dev/null+++ b/tests/fixtures/dlmodel/malformed_axioms.tsv@@ -0,0 +1 @@+sub atom <http://ex.org/A> some <http://ex.org/r>diff --git a/tests/fixtures/dlmodel/qnr_axioms.tsv b/tests/fixtures/dlmodel/qnr_axioms.tsvnew file mode 100644index 00000000..43f57bec--- /dev/null+++ b/tests/fixtures/dlmodel/qnr_axioms.tsv@@ -0,0 +1,7 @@+sub atom <http://ex.org/Committee> min 2 <http://ex.org/hasMember> atom <http://ex.org/Person>+sub atom <http://ex.org/Committee> max 3 <http://ex.org/hasMember> atom <http://ex.org/Person>+range <http://ex.org/hasMember> atom <http://ex.org/Person>+inv <http://ex.org/hasMember> <http://ex.org/memberOf>+invfunc <http://ex.org/chairedBy>+disjoint atom <http://ex.org/Committee> atom <http://ex.org/Person>+nonempty atom <http://ex.org/Committee>diff --git a/tests/fixtures/dlmodel/qnr_model.tsv b/tests/fixtures/dlmodel/qnr_model.tsvnew file mode 100644index 00000000..9b0bb442--- /dev/null+++ b/tests/fixtures/dlmodel/qnr_model.tsv@@ -0,0 +1,10 @@+domain c+domain p1+domain p2+class <http://ex.org/Committee> c+class <http://ex.org/Person> p1+class <http://ex.org/Person> p2+edge c <http://ex.org/hasMember> p1+edge c <http://ex.org/hasMember> p2+edge p1 <http://ex.org/memberOf> c+edge p2 <http://ex.org/memberOf> cdiff --git a/tests/fixtures/dlmodel/qnr_model_duplicate.tsv b/tests/fixtures/dlmodel/qnr_model_duplicate.tsvnew file mode 100644index 00000000..e4ac2e70--- /dev/null+++ b/tests/fixtures/dlmodel/qnr_model_duplicate.tsv@@ -0,0 +1,9 @@+domain c+domain p1+domain p2+class <http://ex.org/Committee> c+class <http://ex.org/Person> p1+class <http://ex.org/Person> p2+edge c <http://ex.org/hasMember> p1+edge c <http://ex.org/hasMember> p1+edge p1 <http://ex.org/memberOf> cdiff --git a/tests/fixtures/horn/builtin_rules.tsv b/tests/fixtures/horn/builtin_rules.tsvindex 69233461..19ffe87e 100644--- a/tests/fixtures/horn/builtin_rules.tsv+++ b/tests/fixtures/horn/builtin_rules.tsv@@ -17,3 +17,11 @@ cls-svf1 4 ?r <http://www.w3.org/2002/07/owl#onProperty> ?p ?r <http://www.w3.orcls-avf 4 ?r <http://www.w3.org/2002/07/owl#onProperty> ?p ?r <http://www.w3.org/2002/07/owl#allValuesFrom> ?c ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?r ?x ?p ?y ?y <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?ccls-hv1 3 ?r <http://www.w3.org/2002/07/owl#onProperty> ?p ?r <http://www.w3.org/2002/07/owl#hasValue> ?v ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?r ?x ?p ?vcls-hv2 3 ?r <http://www.w3.org/2002/07/owl#onProperty> ?p ?r <http://www.w3.org/2002/07/owl#hasValue> ?v ?x ?p ?v ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?r+scm-svf1 5 ?c1 <http://www.w3.org/2002/07/owl#someValuesFrom> ?y1 ?c1 <http://www.w3.org/2002/07/owl#onProperty> ?p ?c2 <http://www.w3.org/2002/07/owl#someValuesFrom> ?y2 ?c2 <http://www.w3.org/2002/07/owl#onProperty> ?p ?y1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?y2 ?c1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c2+scm-svf2 5 ?c1 <http://www.w3.org/2002/07/owl#someValuesFrom> ?y ?c1 <http://www.w3.org/2002/07/owl#onProperty> ?p1 ?c2 <http://www.w3.org/2002/07/owl#someValuesFrom> ?y ?c2 <http://www.w3.org/2002/07/owl#onProperty> ?p2 ?p1 <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?p2 ?c1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c2+scm-avf1 5 ?c1 <http://www.w3.org/2002/07/owl#allValuesFrom> ?y1 ?c1 <http://www.w3.org/2002/07/owl#onProperty> ?p ?c2 <http://www.w3.org/2002/07/owl#allValuesFrom> ?y2 ?c2 <http://www.w3.org/2002/07/owl#onProperty> ?p ?y1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?y2 ?c1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c2+scm-avf2 5 ?c1 <http://www.w3.org/2002/07/owl#allValuesFrom> ?y ?c1 <http://www.w3.org/2002/07/owl#onProperty> ?p1 ?c2 <http://www.w3.org/2002/07/owl#allValuesFrom> ?y ?c2 <http://www.w3.org/2002/07/owl#onProperty> ?p2 ?p1 <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?p2 ?c2 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c1+scm-dom1 2 ?p <http://www.w3.org/2000/01/rdf-schema#domain> ?c1 ?c1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c2 ?p <http://www.w3.org/2000/01/rdf-schema#domain> ?c2+scm-dom2 2 ?p2 <http://www.w3.org/2000/01/rdf-schema#domain> ?c ?p1 <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?p2 ?p1 <http://www.w3.org/2000/01/rdf-schema#domain> ?c+scm-rng1 2 ?p <http://www.w3.org/2000/01/rdf-schema#range> ?c1 ?c1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c2 ?p <http://www.w3.org/2000/01/rdf-schema#range> ?c2+scm-rng2 2 ?p2 <http://www.w3.org/2000/01/rdf-schema#range> ?c ?p1 <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?p2 ?p1 <http://www.w3.org/2000/01/rdf-schema#range> ?cdiff --git a/tests/fixtures/horn/user_rules.tsv b/tests/fixtures/horn/user_rules.tsvindex ed4ab1f5..246cdcf0 100644--- a/tests/fixtures/horn/user_rules.tsv+++ b/tests/fixtures/horn/user_rules.tsv@@ -17,4 +17,12 @@ cls-svf1 4 ?r <http://www.w3.org/2002/07/owl#onProperty> ?p ?r <http://www.w3.orcls-avf 4 ?r <http://www.w3.org/2002/07/owl#onProperty> ?p ?r <http://www.w3.org/2002/07/owl#allValuesFrom> ?c ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?r ?x ?p ?y ?y <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?ccls-hv1 3 ?r <http://www.w3.org/2002/07/owl#onProperty> ?p ?r <http://www.w3.org/2002/07/owl#hasValue> ?v ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?r ?x ?p ?vcls-hv2 3 ?r <http://www.w3.org/2002/07/owl#onProperty> ?p ?r <http://www.w3.org/2002/07/owl#hasValue> ?v ?x ?p ?v ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?r+scm-svf1 5 ?c1 <http://www.w3.org/2002/07/owl#someValuesFrom> ?y1 ?c1 <http://www.w3.org/2002/07/owl#onProperty> ?p ?c2 <http://www.w3.org/2002/07/owl#someValuesFrom> ?y2 ?c2 <http://www.w3.org/2002/07/owl#onProperty> ?p ?y1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?y2 ?c1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c2+scm-svf2 5 ?c1 <http://www.w3.org/2002/07/owl#someValuesFrom> ?y ?c1 <http://www.w3.org/2002/07/owl#onProperty> ?p1 ?c2 <http://www.w3.org/2002/07/owl#someValuesFrom> ?y ?c2 <http://www.w3.org/2002/07/owl#onProperty> ?p2 ?p1 <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?p2 ?c1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c2+scm-avf1 5 ?c1 <http://www.w3.org/2002/07/owl#allValuesFrom> ?y1 ?c1 <http://www.w3.org/2002/07/owl#onProperty> ?p ?c2 <http://www.w3.org/2002/07/owl#allValuesFrom> ?y2 ?c2 <http://www.w3.org/2002/07/owl#onProperty> ?p ?y1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?y2 ?c1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c2+scm-avf2 5 ?c1 <http://www.w3.org/2002/07/owl#allValuesFrom> ?y ?c1 <http://www.w3.org/2002/07/owl#onProperty> ?p1 ?c2 <http://www.w3.org/2002/07/owl#allValuesFrom> ?y ?c2 <http://www.w3.org/2002/07/owl#onProperty> ?p2 ?p1 <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?p2 ?c2 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c1+scm-dom1 2 ?p <http://www.w3.org/2000/01/rdf-schema#domain> ?c1 ?c1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c2 ?p <http://www.w3.org/2000/01/rdf-schema#domain> ?c2+scm-dom2 2 ?p2 <http://www.w3.org/2000/01/rdf-schema#domain> ?c ?p1 <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?p2 ?p1 <http://www.w3.org/2000/01/rdf-schema#domain> ?c+scm-rng1 2 ?p <http://www.w3.org/2000/01/rdf-schema#range> ?c1 ?c1 <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c2 ?p <http://www.w3.org/2000/01/rdf-schema#range> ?c2+scm-rng2 2 ?p2 <http://www.w3.org/2000/01/rdf-schema#range> ?c ?p1 <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?p2 ?p1 <http://www.w3.org/2000/01/rdf-schema#range> ?cevery-supplier-is-compliant 1 ?s <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Supplier> ?s <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Compliant>diff --git a/tests/fixtures/refute/asserted.tsv b/tests/fixtures/refute/asserted.tsvnew file mode 100644index 00000000..ab9716cd--- /dev/null+++ b/tests/fixtures/refute/asserted.tsv@@ -0,0 +1,4 @@+<http://ex.org/Herbivore> <http://www.w3.org/2002/07/owl#disjointWith> <http://ex.org/Carnivore>+<http://ex.org/Lion> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Carnivore>+<http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Lion>+<http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Herbivore>diff --git a/tests/fixtures/refute/bad_missing_prefix.tsv b/tests/fixtures/refute/bad_missing_prefix.tsvnew file mode 100644index 00000000..8e54d706--- /dev/null+++ b/tests/fixtures/refute/bad_missing_prefix.tsv@@ -0,0 +1,2 @@+oo-refute/1+refute cax-dw <http://ex.org/Herbivore> <http://www.w3.org/2002/07/owl#disjointWith> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Herbivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore>diff --git a/tests/fixtures/refute/bad_no_refute_line.tsv b/tests/fixtures/refute/bad_no_refute_line.tsvnew file mode 100644index 00000000..41e7c71e--- /dev/null+++ b/tests/fixtures/refute/bad_no_refute_line.tsv@@ -0,0 +1,2 @@+oo-refute/1+rdfs9 <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Lion> <http://ex.org/Lion> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Carnivore>diff --git a/tests/fixtures/refute/bad_no_version.tsv b/tests/fixtures/refute/bad_no_version.tsvnew file mode 100644index 00000000..1d5f622e--- /dev/null+++ b/tests/fixtures/refute/bad_no_version.tsv@@ -0,0 +1,2 @@+rdfs9 <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Lion> <http://ex.org/Lion> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Carnivore>+refute cax-dw <http://ex.org/Herbivore> <http://www.w3.org/2002/07/owl#disjointWith> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Herbivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore>diff --git a/tests/fixtures/refute/bad_order.tsv b/tests/fixtures/refute/bad_order.tsvnew file mode 100644index 00000000..df460027--- /dev/null+++ b/tests/fixtures/refute/bad_order.tsv@@ -0,0 +1,3 @@+oo-refute/1+rdfs9 <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Lion> <http://ex.org/Lion> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Carnivore>+refute cax-dw <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Herbivore> <http://ex.org/Herbivore> <http://www.w3.org/2002/07/owl#disjointWith> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore>diff --git a/tests/fixtures/refute/bad_prefix.tsv b/tests/fixtures/refute/bad_prefix.tsvnew file mode 100644index 00000000..e17e7963--- /dev/null+++ b/tests/fixtures/refute/bad_prefix.tsv@@ -0,0 +1,3 @@+oo-refute/1+rdfs9 <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Herbivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Lion> <http://ex.org/Lion> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Carnivore>+refute cax-dw <http://ex.org/Herbivore> <http://www.w3.org/2002/07/owl#disjointWith> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Herbivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore>diff --git a/tests/fixtures/refute/bad_refute_not_last.tsv b/tests/fixtures/refute/bad_refute_not_last.tsvnew file mode 100644index 00000000..305e238a--- /dev/null+++ b/tests/fixtures/refute/bad_refute_not_last.tsv@@ -0,0 +1,3 @@+oo-refute/1+refute cax-dw <http://ex.org/Herbivore> <http://www.w3.org/2002/07/owl#disjointWith> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Herbivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore>+rdfs9 <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Lion> <http://ex.org/Lion> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Carnivore>diff --git a/tests/fixtures/refute/bad_two_individuals.tsv b/tests/fixtures/refute/bad_two_individuals.tsvnew file mode 100644index 00000000..eee281bc--- /dev/null+++ b/tests/fixtures/refute/bad_two_individuals.tsv@@ -0,0 +1,3 @@+oo-refute/1+rdfs9 <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Lion> <http://ex.org/Lion> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Carnivore>+refute cax-dw <http://ex.org/Herbivore> <http://www.w3.org/2002/07/owl#disjointWith> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Herbivore> <http://ex.org/nala> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore>diff --git a/tests/fixtures/refute/bad_unasserted_axiom.tsv b/tests/fixtures/refute/bad_unasserted_axiom.tsvnew file mode 100644index 00000000..f6e6b610--- /dev/null+++ b/tests/fixtures/refute/bad_unasserted_axiom.tsv@@ -0,0 +1,3 @@+oo-refute/1+rdfs9 <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Lion> <http://ex.org/Lion> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Carnivore>+refute cax-dw <http://ex.org/Herbivore> <http://www.w3.org/2002/07/owl#disjointWith> <http://ex.org/Lion> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Herbivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Lion>diff --git a/tests/fixtures/refute/bad_unknown_rule.tsv b/tests/fixtures/refute/bad_unknown_rule.tsvnew file mode 100644index 00000000..51be5cc2--- /dev/null+++ b/tests/fixtures/refute/bad_unknown_rule.tsv@@ -0,0 +1,3 @@+oo-refute/1+rdfs9 <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Lion> <http://ex.org/Lion> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Carnivore>+refute cax-adc <http://ex.org/Herbivore> <http://www.w3.org/2002/07/owl#disjointWith> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Herbivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore>diff --git a/tests/fixtures/refute/bad_wrong_predicate.tsv b/tests/fixtures/refute/bad_wrong_predicate.tsvnew file mode 100644index 00000000..8f2fdb50--- /dev/null+++ b/tests/fixtures/refute/bad_wrong_predicate.tsv@@ -0,0 +1,3 @@+oo-refute/1+rdfs9 <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Lion> <http://ex.org/Lion> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Carnivore>+refute cax-dw <http://ex.org/Lion> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Lion> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore>diff --git a/tests/fixtures/refute/consistent_asserted.tsv b/tests/fixtures/refute/consistent_asserted.tsvnew file mode 100644index 00000000..19444fdf--- /dev/null+++ b/tests/fixtures/refute/consistent_asserted.tsv@@ -0,0 +1,3 @@+<http://ex.org/Herbivore> <http://www.w3.org/2002/07/owl#disjointWith> <http://ex.org/Carnivore>+<http://ex.org/Lion> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Carnivore>+<http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Lion>diff --git a/tests/fixtures/refute/consistent_attempt.tsv b/tests/fixtures/refute/consistent_attempt.tsvnew file mode 100644index 00000000..b05b0133--- /dev/null+++ b/tests/fixtures/refute/consistent_attempt.tsv@@ -0,0 +1,3 @@+oo-refute/1+rdfs9 <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Lion> <http://ex.org/Lion> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Carnivore>+refute cax-dw <http://ex.org/Herbivore> <http://www.w3.org/2002/07/owl#disjointWith> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Herbivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore>diff --git a/tests/fixtures/refute/consistent_derivations.tsv b/tests/fixtures/refute/consistent_derivations.tsvnew file mode 100644index 00000000..f1d86d2d--- /dev/null+++ b/tests/fixtures/refute/consistent_derivations.tsv@@ -0,0 +1 @@+rdfs9 <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Lion> <http://ex.org/Lion> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Carnivore>diff --git a/tests/fixtures/refute/derivations.tsv b/tests/fixtures/refute/derivations.tsvnew file mode 100644index 00000000..f1d86d2d--- /dev/null+++ b/tests/fixtures/refute/derivations.tsv@@ -0,0 +1 @@+rdfs9 <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Lion> <http://ex.org/Lion> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Carnivore>diff --git a/tests/fixtures/refute/good.tsv b/tests/fixtures/refute/good.tsvnew file mode 100644index 00000000..b05b0133--- /dev/null+++ b/tests/fixtures/refute/good.tsv@@ -0,0 +1,3 @@+oo-refute/1+rdfs9 <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Lion> <http://ex.org/Lion> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Carnivore>+refute cax-dw <http://ex.org/Herbivore> <http://www.w3.org/2002/07/owl#disjointWith> <http://ex.org/Carnivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Herbivore> <http://ex.org/leo> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Carnivore>diff --git a/tests/fixtures/shaclcore/unknown-datatype-data.nt b/tests/fixtures/shaclcore/unknown-datatype-data.ntindex 4dec3bd1..725c736b 100644--- a/tests/fixtures/shaclcore/unknown-datatype-data.nt+++ b/tests/fixtures/shaclcore/unknown-datatype-data.nt@@ -1 +1 @@-<http://ex.org/alice> <http://ex.org/born> "1999-01-31"^^<http://www.w3.org/2001/XMLSchema#date> .+<http://ex.org/alice> <http://ex.org/note> "<b>hi</b>"^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral> .diff --git a/tests/fixtures/shaclcore/unknown-datatype-shapes.nt b/tests/fixtures/shaclcore/unknown-datatype-shapes.ntindex c91c034a..a545d757 100644--- a/tests/fixtures/shaclcore/unknown-datatype-shapes.nt+++ b/tests/fixtures/shaclcore/unknown-datatype-shapes.nt@@ -1,7 +1,8 @@-# xsd:date: the datatype IRI matches, so the answer turns on well-formedness, and-# this development does not know xsd:date's lexical space. It must decline.+# rdf:XMLLiteral: the datatype IRI matches, so the answer turns on well-formedness,+# and RDF 1.1 says that lexical space is the strings that are well-balanced,+# self-contained XML content. Deciding that needs an XML parser. It must decline.<http://ex.org/S> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/ns/shacl#NodeShape> .<http://ex.org/S> <http://www.w3.org/ns/shacl#targetNode> <http://ex.org/alice> .-<http://ex.org/S> <http://www.w3.org/ns/shacl#property> <http://ex.org/BornShape> .-<http://ex.org/BornShape> <http://www.w3.org/ns/shacl#path> <http://ex.org/born> .-<http://ex.org/BornShape> <http://www.w3.org/ns/shacl#datatype> <http://www.w3.org/2001/XMLSchema#date> .+<http://ex.org/S> <http://www.w3.org/ns/shacl#property> <http://ex.org/NoteShape> .+<http://ex.org/NoteShape> <http://www.w3.org/ns/shacl#path> <http://ex.org/note> .+<http://ex.org/NoteShape> <http://www.w3.org/ns/shacl#datatype> <http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral> .diff --git a/tests/fixtures/shaclcore/unsupported-path-shapes.nt b/tests/fixtures/shaclcore/unsupported-path-shapes.ntnew file mode 100644index 00000000..fc359fe1--- /dev/null+++ b/tests/fixtures/shaclcore/unsupported-path-shapes.nt@@ -0,0 +1,8 @@+# sh:zeroOrMorePath is a transitive closure over the data graph and is the one SHACL+# Core path form this development does not decide. It must be refused by name.+<http://ex.org/S> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/ns/shacl#NodeShape> .+<http://ex.org/S> <http://www.w3.org/ns/shacl#targetClass> <http://ex.org/Person> .+<http://ex.org/S> <http://www.w3.org/ns/shacl#property> <http://ex.org/NameShape> .+<http://ex.org/NameShape> <http://www.w3.org/ns/shacl#path> _:p .+_:p <http://www.w3.org/ns/shacl#zeroOrMorePath> <http://ex.org/name> .+<http://ex.org/NameShape> <http://www.w3.org/ns/shacl#minCount> "1"^^<http://www.w3.org/2001/XMLSchema#integer> .diff --git a/tests/fixtures/shaclcore/unsupported-regex-shapes.nt b/tests/fixtures/shaclcore/unsupported-regex-shapes.ntnew file mode 100644index 00000000..a59879f2--- /dev/null+++ b/tests/fixtures/shaclcore/unsupported-regex-shapes.nt@@ -0,0 +1,8 @@+# The `+` quantifier is outside the regular-expression subset the proved matcher+# decides. The compiler must name the construct rather than drop the constraint or+# approximate it.+<http://ex.org/S> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/ns/shacl#NodeShape> .+<http://ex.org/S> <http://www.w3.org/ns/shacl#targetClass> <http://ex.org/Person> .+<http://ex.org/S> <http://www.w3.org/ns/shacl#property> <http://ex.org/NameShape> .+<http://ex.org/NameShape> <http://www.w3.org/ns/shacl#path> <http://ex.org/name> .+<http://ex.org/NameShape> <http://www.w3.org/ns/shacl#pattern> "^[A-Z]+$" .diff --git a/tests/fixtures/shaclcore/unsupported-shapes.nt b/tests/fixtures/shaclcore/unsupported-shapes.ntindex bca03bb6..9e91ec03 100644--- a/tests/fixtures/shaclcore/unsupported-shapes.nt+++ b/tests/fixtures/shaclcore/unsupported-shapes.nt@@ -1,6 +1,9 @@-# sh:pattern is not implemented. The compiler must refuse and name it.+# sh:prefixes is a SHACL term with no Core constraint meaning that this compiler has+# not implemented. The per-shape guard must refuse the whole shape rather than walk+# past a parameter it does not recognise: that guard is the only thing standing+# between "I checked everything" and "I checked what I happened to know".<http://ex.org/S> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/ns/shacl#NodeShape> .<http://ex.org/S> <http://www.w3.org/ns/shacl#targetClass> <http://ex.org/Person> .<http://ex.org/S> <http://www.w3.org/ns/shacl#property> <http://ex.org/NameShape> .<http://ex.org/NameShape> <http://www.w3.org/ns/shacl#path> <http://ex.org/name> .-<http://ex.org/NameShape> <http://www.w3.org/ns/shacl#pattern> "^A" .+<http://ex.org/NameShape> <http://www.w3.org/ns/shacl#prefixes> <http://ex.org/decl> .diff --git a/tests/lean_horn_certificate_test.rs b/tests/lean_horn_certificate_test.rsindex e696d4fa..e5a21a6c 100644--- a/tests/lean_horn_certificate_test.rs+++ b/tests/lean_horn_certificate_test.rs@@ -203,10 +203,12 @@ fn the_built_in_rules_are_emitted_as_data() {let lines: Vec<&str> = text.lines().filter(|l| !l.is_empty()).collect();assert_eq!(lines.len(),- 19,- "nineteen of the engine's rules are Horn rules; cls-int1 and cls-uni read an RDF list off \- the graph, so their premise count is data rather than fixed by the rule, and they stay as \- hardcoded arms. If this number changed, say which rule moved and why."+ 27,+ "twenty-seven of the engine's rules are Horn rules. Four are not and stay as hardcoded \+ arms: cls-int1, cls-int2, cls-uni and cls-oo all read an RDF list off the graph, so the \+ LIST is a premise and the premise count is data rather than fixed by the rule. That is \+ the boundary of the Horn family, not a gap in it. If this number changed, say which rule \+ moved and why.");// The table printed here is the one the absolute verdict is pinned to, so it// must match the committed fixture byte for byte.diff --git a/tests/lean_refutation_test.rs b/tests/lean_refutation_test.rsnew file mode 100644index 00000000..3fb34916--- /dev/null+++ b/tests/lean_refutation_test.rs@@ -0,0 +1,334 @@+//! `oo-refute/1`: certifying that a graph has NO model.+//!+//! Sixteen rules in the OWL 2 RL profile conclude `false` rather than a triple.+//! The derivation certificate cannot express that, because `Step.conclusion` is+//! a `Triple` and `OOCert.certificate_sound` concludes `Entails`. There is no+//! triple to conclude. `lean/OOCert/Refute.lean` adds the second format, with+//! `cax-dw` as its one rule, and `OOCert.refutation_sound` proved about it.+//!+//! # The two things this file exists to protect+//!+//! **A refutation must be able to fail.** Six forgeries are checked, one per+//! way to lie: an invented disjointness axiom, a premise whose predicate is not+//! `owl:disjointWith`, two class memberships about different individuals, a+//! forged derivation prefix, a missing prefix so that a premise was never+//! derived, and the right three premises in the wrong order. A seventh case is+//! a graph that is genuinely consistent, where the refutation must be rejected+//! because there is nothing to find. `OOCert.feed_is_not_refuted` proves that+//! rejection is correct rather than a limitation.+//!+//! **The verdict must not outrun what was proved.** `Unsat G` means no+//! interpretation satisfies `Model I G` AND `RefuteConditions I`. It is+//! unsatisfiability relative to reading `owl:disjointWith` as disjointness, not+//! absolute unsatisfiability, and the report says so.+//!+//! # The trap, which is why `guard` exists+//!+//! Over a refuted graph every triple is entailed under the disjointness-aware+//! reading, so a derivation certificate carries no information. But `oo-cert`+//! still reports `"ok":true` for it, and what it reports is TRUE: its verdict+//! quantifies over `OOCert.Model I G` alone, a class that is never empty+//! because `Conditions` has no negative condition and cannot notice a clash.+//! `the_old_checker_still_says_yes_to_the_refuted_graph` runs both binaries on+//! the same two files and pins the contradiction between their verdicts, so the+//! contrast is computed here rather than asserted in a docstring.++mod common;++use std::path::{Path, PathBuf};+use std::process::Command;+use std::sync::OnceLock;++fn repo() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+}++fn lean_dir() -> PathBuf {+ repo().join("lean")+}++fn fixture(name: &str) -> PathBuf {+ repo().join("tests").join("fixtures").join("refute").join(name)+}++fn lake_available() -> bool {+ // `.current_dir(lean_dir())`: elan resolves the toolchain from the working+ // directory, and the crate root has no `lean-toolchain` in its ancestry.+ Command::new("lake")+ .arg("--version")+ .current_dir(lean_dir())+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+}++fn skip() -> bool {+ common::skip_unless(+ lake_available(),+ "lake (the Lean 4 build tool)",+ "install elan from https://github.com/leanprover/elan; lean/lean-toolchain pins the version",+ )+}++/// Build once per test binary.+///+/// `oo-refute` is NOT in the lakefile's `defaultTargets`, so a bare `lake build`+/// does not build it and does not typecheck `OOCert/Refute.lean` or+/// `OOCert/RefuteWitness.lean` either. Naming the target here is therefore the+/// only thing that puts those proofs, and the `#guard_msgs` axiom tripwires in+/// them, in front of a compiler. If this line is ever changed to a bare+/// `lake build`, the refutation layer stops being checked and nothing else+/// reports it.+fn built() -> &'static PathBuf {+ static BUILT: OnceLock<PathBuf> = OnceLock::new();+ BUILT.get_or_init(|| {+ for target in ["oo-refute", "oo-cert"] {+ let out = Command::new("lake")+ .arg("build")+ .arg(target)+ .current_dir(lean_dir())+ .output()+ .expect("run lake build");+ assert!(+ out.status.success(),+ "lake build {target} failed:\n{}\n{}",+ String::from_utf8_lossy(&out.stdout),+ String::from_utf8_lossy(&out.stderr)+ );+ }+ lean_dir().join(".lake").join("build").join("bin")+ })+}++fn bin(name: &str) -> PathBuf {+ let exe = built().join(name);+ assert!(exe.exists(), "binary missing at {}", exe.display());+ exe+}++fn refute_bin() -> PathBuf {+ bin("oo-refute")+}++/// Returns (exit code, stdout, stderr).+fn run(exe: &Path, args: &[&Path]) -> (i32, String, String) {+ let mut cmd = Command::new(exe);+ for a in args {+ cmd.arg(a);+ }+ let out = cmd.output().expect("run the checker");+ (+ out.status.code().unwrap_or(-1),+ String::from_utf8_lossy(&out.stdout).to_string(),+ String::from_utf8_lossy(&out.stderr).to_string(),+ )+}++fn check(asserted: &str, refutation: &str) -> (i32, String, String) {+ let (g, r) = (fixture(asserted), fixture(refutation));+ run(&refute_bin(), &[Path::new("check"), &g, &r])+}++fn guard(asserted: &str, derivations: &str, refutation: &str) -> (i32, String, String) {+ let (g, d, r) = (fixture(asserted), fixture(derivations), fixture(refutation));+ run(&refute_bin(), &[Path::new("guard"), &g, &d, &r])+}++fn field<'a>(json: &'a str, key: &str) -> &'a str {+ let pat = format!("\"{key}\":\"");+ let start = json.find(&pat).unwrap_or_else(|| panic!("no {key} in {json}")) + pat.len();+ let rest = &json[start..];+ &rest[..rest.find('"').expect("unterminated")]+}++#[test]+fn a_real_refutation_is_accepted() {+ if skip() {+ return;+ }+ let (code, out, _) = check("asserted.tsv", "good.tsv");+ assert_eq!(code, 0, "{out}");+ assert_eq!(field(&out, "verdict"), "unsatisfiable_under_disjointness", "{out}");+ assert_eq!(field(&out, "theorem"), "OOCert.refutation_fast_sound", "{out}");+ assert_eq!(field(&out, "rule"), "cax-dw", "{out}");+ // The clash is not visible in the asserted triples. `leo rdf:type Carnivore`+ // has to be derived by rdfs9 first, which is why a refutation carries a+ // derivation prefix at all.+ assert!(out.contains("\"prefix\":1"), "the refutation must use its derivation prefix: {out}");+}++#[test]+fn the_verdict_never_claims_absolute_unsatisfiability() {+ // `Unsat G` is relative to `RefuteConditions`. A report that dropped the+ // qualifier would be claiming more than `OOCert.refutation_sound` proves,+ // and `OOCert.saturated_is_a_model` shows the unqualified claim is false:+ // every graph, this one included, still has a model of `Model I G` alone.+ if skip() {+ return;+ }+ let (_, out, _) = check("asserted.tsv", "good.tsv");+ let means = field(&out, "means");+ assert!(+ means.contains("RELATIVE TO"),+ "the verdict must say what it is conditional on: {out}"+ );+ assert!(+ means.contains("owl:disjointWith"),+ "and name the reading it is conditional on: {out}"+ );+}++#[test]+fn every_forgery_is_rejected() {+ if skip() {+ return;+ }+ // Each is a different way to lie, and each must be caught on its own.+ let forgeries = [+ ("bad_unasserted_axiom.tsv", "the disjointness axiom it cites is not in the graph"),+ ("bad_wrong_predicate.tsv", "the first premise is a subClassOf triple, not a disjointness axiom"),+ ("bad_two_individuals.tsv", "the two class memberships are about different individuals"),+ ("bad_prefix.tsv", "the rdfs9 step in the prefix does not conclude what it claims"),+ ("bad_missing_prefix.tsv", "a premise was neither asserted nor derived by an earlier step"),+ ("bad_order.tsv", "the premises are in the wrong order"),+ ];+ for (name, why) in forgeries {+ let (code, out, err) = check("asserted.tsv", name);+ assert_eq!(code, 1, "{name} must be rejected because {why}: {out}{err}");+ assert!(out.contains("\"ok\":false"), "{name}: {out}");+ // A rejection must not be reported as a consistency result.+ assert!(+ field(&out, "means").contains("not a proof of consistency"),+ "{name}: a rejected refutation says nothing about consistency and the report must \+ say so: {out}"+ );+ }+}++#[test]+fn a_consistent_graph_is_not_refuted() {+ // The same refutation, over the same schema, minus the one assertion that+ // makes the clash. `OOCert.feed_is_not_refuted` proves this graph really+ // does have a model satisfying both `Model` and `RefuteConditions`, so the+ // rejection below is correct and not a gap in the checker.+ if skip() {+ return;+ }+ let (code, out, _) = check("consistent_asserted.tsv", "consistent_attempt.tsv");+ assert_eq!(code, 1, "a consistent graph must not be refutable: {out}");+}++#[test]+fn a_malformed_refutation_is_exit_two_not_a_rejection() {+ // Exit 1 means "the checker rejected a step". A file it could not read is a+ // different answer and must not be reported as the first one, or a harness+ // written to the documented contract reads an unparseable file as a checked+ // rejection.+ if skip() {+ return;+ }+ let malformed = [+ ("bad_no_version.tsv", "a derivations.tsv is not a refutation"),+ ("bad_no_refute_line.tsv", "a refutation with no contradiction step proves nothing"),+ ("bad_refute_not_last.tsv", "the contradiction step must be last"),+ ("bad_unknown_rule.tsv", "the rule it cites is not implemented here"),+ ];+ for (name, why) in malformed {+ let (code, _, err) = check("asserted.tsv", name);+ assert_eq!(code, 2, "{name} must be exit 2 because {why}: {err}");+ }+ // The unimplemented rule is named rather than reported as bad syntax: the+ // honest answer is that this checker has no semantic condition for it.+ let (_, _, err) = check("asserted.tsv", "bad_unknown_rule.tsv");+ assert!(err.contains("cax-adc"), "the refused rule must be named: {err}");+ assert!(+ err.contains("cax-dw"),+ "and the report must say which rules ARE implemented: {err}"+ );+}++#[test]+fn an_unreadable_file_is_exit_two() {+ if skip() {+ return;+ }+ let (code, _, _) = run(+ &refute_bin(),+ &[+ Path::new("check"),+ Path::new("/nonexistent/a.tsv"),+ Path::new("/nonexistent/b.tsv"),+ ],+ );+ assert_eq!(+ code, 2,+ "exit 1 means a step was rejected; an unreadable file must not look like that"+ );+}++#[test]+fn the_old_checker_still_says_yes_to_the_refuted_graph() {+ // THE TRAP, computed rather than described. `derivations.tsv` is a valid+ // derivation certificate over a graph that `oo-refute` refutes. `oo-cert`+ // accepts it and is not wrong: its verdict is `OOCert.Entails`, which+ // quantifies over `OOCert.Model I G`, and that class is never empty+ // (`OOCert.saturated_is_a_model`). The guarantee a consumer wants is the+ // disjointness-aware one, and over this graph that one is empty+ // (`OOCert.a_certificate_adds_nothing_when_the_graph_is_refuted`).+ if skip() {+ return;+ }+ let (g, d) = (fixture("asserted.tsv"), fixture("derivations.tsv"));+ let (cert_code, cert_out, _) = run(&bin("oo-cert"), &[&g, &d]);+ assert_eq!(+ cert_code, 0,+ "the derivation certificate must still be accepted by oo-cert, which is the whole \+ problem: {cert_out}"+ );+ assert!(cert_out.contains("\"ok\":true"), "{cert_out}");++ let (ref_code, ref_out, _) = check("asserted.tsv", "good.tsv");+ assert_eq!(ref_code, 0, "and the same graph must be refutable: {ref_out}");+}++#[test]+fn the_guard_refuses_a_certificate_over_a_graph_it_can_refute() {+ if skip() {+ return;+ }+ let (code, out, _) = guard("asserted.tsv", "derivations.tsv", "good.tsv");+ assert_eq!(code, 1, "the guard must refuse: {out}");+ assert!(+ out.contains("\"certificate_ok\":true"),+ "the certificate itself checks, which is exactly why the refusal has to come from \+ somewhere else: {out}"+ );+ assert!(out.contains("\"refuted\":true"), "{out}");+ assert_eq!(field(&out, "verdict"), "certificate_refused_graph_is_unsatisfiable", "{out}");+ assert_eq!(+ field(&out, "theorem"),+ "OOCert.a_certificate_adds_nothing_when_the_graph_is_refuted",+ "{out}"+ );+}++#[test]+fn the_guard_passes_when_nothing_is_refuted() {+ // And it must not refuse everything, or it is a gate that always fires,+ // which is as useless as one that never does.+ if skip() {+ return;+ }+ let (code, out, _) =+ guard("consistent_asserted.tsv", "consistent_derivations.tsv", "consistent_attempt.tsv");+ assert_eq!(code, 0, "{out}");+ assert!(out.contains("\"refuted\":false"), "{out}");+ assert_eq!(field(&out, "theorem"), "OOCert.certificate_sound", "{out}");+ // A pass is not a consistency proof. Only one of the sixteen OWL 2 RL clash+ // rules is implemented, so "no clash found" is the honest wording and the+ // report must use it.+ assert!(+ field(&out, "means").contains("not a proof of consistency"),+ "the passing verdict must not be read as consistency: {out}"+ );+}diff --git a/tests/reason_rl_coverage_test.rs b/tests/reason_rl_coverage_test.rsnew file mode 100644index 00000000..c3b855d0--- /dev/null+++ b/tests/reason_rl_coverage_test.rs@@ -0,0 +1,671 @@+//! The ten OWL 2 RL rules added on the `owl-rl-completeness` branch.+//!+//! `tests/lean_certificate_test.rs` already proves that everything the engine+//! emits is accepted by the checker, over the whole shipped corpus. That is a+//! statement about soundness and it says nothing about whether a rule ever+//! fires, whether it fires the right way round, or whether what it adds is+//! worth having. This file covers those three.+//!+//! # What each section is for+//!+//! * **Coverage.** Each of the ten rules fires at least once on an ontology+//! built for it, and the resulting certificate is accepted. A rule that never+//! fires is a rule nobody has tested.+//! * **Direction.** `scm-avf2` concludes `?c2 rdfs:subClassOf ?c1` where its+//! three siblings conclude `?c1 rdfs:subClassOf ?c2`, because a universal+//! restriction is antitone in its property. The engine must derive the one+//! and NOT the other, and the checker must reject a forged step that runs the+//! other way. `OOCert.the_natural_avf2_direction_is_not_entailed` is the same+//! fact proved against the semantics; this is the same fact observed in the+//! engine.+//! * **Worth.** The four domain-and-range rules fire on schema alone, so they+//! fire on every corpus. What they add is completeness of the EMITTED SCHEMA+//! and not new answers about individuals, because rdfs2 followed by rdfs9+//! already reached the instance-level consequence. That is a limitation of+//! the rules rather than a feature, and+//! `the_domain_rules_add_schema_and_not_answers` is where it is written down+//! in a form that fails if it stops being true.+//!+//! # These gates were seen to fail+//!+//! A gate nobody has watched fail is decoration, so each of these was broken on+//! purpose and the failure recorded.+//!+//! Changing one character in `src/reason.rs`, `emit((r2, rdfs_subclass, r1),+//! "scm-avf2", ...)` to `emit((r1, rdfs_subclass, r2), ...)`, produced:+//!+//! ```text+//! test scm_avf2_concludes_the_subsumption_the_other_way_round ... FAILED+//! scm-avf2 must derive `all hasComponent Wheel` subClassOf `all hasPart Wheel`+//! test every_new_rule_fires_and_the_certificate_is_accepted ... FAILED+//! {"ok":false,"first_rejected":7,"rule":"scm-avf2",+//! "conclusion":"<http://ex.org/AvfSub> <rdfs:subClassOf> <http://ex.org/AvfSup>"}+//! ```+//!+//! so the engine test and the proved checker both refused it, independently.+//! Flipping the matching Lean condition instead, `avf_sp`'s conclusion from+//! `I.sc c2 c1` to `I.sc c1 c2`, fails the Lean build in three places at once:+//! the `scmAvf2` case of `checkStep_sound`, the model in+//! `OOCert.avf_witness_is_a_model`, and the two `#print axioms` guards that+//! depend on it. The direction is written down in three places and they have to+//! agree.+//!+//! The forged lines in `the_checker_rejects_a_forged_step_for_each_new_rule`+//! are appended one at a time to a certificate that is checked and accepted+//! first, so a rejection there cannot be the checker refusing everything.++mod common;++use open_ontologies::graph::GraphStore;+use open_ontologies::reason::{InferenceTarget, Reasoner};+use std::collections::BTreeMap;+use std::path::{Path, PathBuf};+use std::process::Command;+use std::sync::{Arc, OnceLock};++fn repo() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+}++fn lean_dir() -> PathBuf {+ repo().join("lean")+}++fn lake_available() -> bool {+ // `.current_dir(lean_dir())`: elan resolves the toolchain from the working+ // directory and the crate root has no `lean-toolchain` in its ancestry.+ Command::new("lake")+ .arg("--version")+ .current_dir(lean_dir())+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+}++fn skip() -> bool {+ common::skip_unless(+ lake_available(),+ "lake (the Lean 4 build tool)",+ "install elan from https://github.com/leanprover/elan; lean/lean-toolchain pins the version",+ )+}++fn checker() -> &'static Path {+ static BUILT: OnceLock<PathBuf> = OnceLock::new();+ BUILT.get_or_init(|| {+ let out = Command::new("lake")+ .arg("build")+ .current_dir(lean_dir())+ .output()+ .expect("run lake build");+ assert!(+ out.status.success(),+ "lake build failed:\n{}\n{}",+ String::from_utf8_lossy(&out.stdout),+ String::from_utf8_lossy(&out.stderr)+ );+ let exe = lean_dir().join(".lake").join("build").join("bin").join("oo-cert");+ assert!(exe.exists(), "checker binary missing at {}", exe.display());+ exe+ })+}++fn check(dir: &Path) -> (bool, String) {+ let out = Command::new(checker())+ .arg(dir.join("asserted.tsv"))+ .arg(dir.join("derivations.tsv"))+ .output()+ .expect("run oo-cert");+ (+ out.status.success(),+ format!(+ "{}{}",+ String::from_utf8_lossy(&out.stdout),+ String::from_utf8_lossy(&out.stderr)+ ),+ )+}++fn scratch(name: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("oo-rl-cov-{}-{}", name, std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+}++fn run(ttl: &str, profile: &str, dir: Option<&Path>) -> (Arc<GraphStore>, serde_json::Value) {+ let store = Arc::new(GraphStore::new());+ store.load_turtle(ttl, None).unwrap();+ let out =+ Reasoner::run_full(&store, profile, true, InferenceTarget::DefaultGraph, dir).unwrap();+ (store, serde_json::from_str(&out).unwrap())+}++/// `a` is SPARQL's own keyword for `rdf:type`, but `rdfs:subClassOf` and the+/// rest are not built in, so the prefix has to travel with the query. Without+/// it every call here is a parse error rather than a false answer, which is the+/// safe failure but still a failure.+fn holds(store: &Arc<GraphStore>, s: &str, p: &str, o: &str) -> bool {+ store+ .sparql_select(&format!(+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \+ PREFIX owl: <http://www.w3.org/2002/07/owl#> ASK {{ {s} {p} {o} }}"+ ))+ .unwrap()+ .contains("true")+}++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#> .+"#;++/// One ontology that fires all ten of the new rules and nothing has to be+/// contrived: two restriction pairs ordered by filler and by property, a+/// property hierarchy carrying a domain and a range, an intersection with an+/// instance, and an enumeration.+const NEW_RULES: &str = r#"+ # scm-svf1 / scm-avf1: same property, fillers ordered+ :SvfNarrow a owl:Restriction ; owl:onProperty :eats ; owl:someValuesFrom :Apple .+ :SvfWide a owl:Restriction ; owl:onProperty :eats ; owl:someValuesFrom :Fruit .+ :AvfNarrow a owl:Restriction ; owl:onProperty :eats ; owl:allValuesFrom :Apple .+ :AvfWide a owl:Restriction ; owl:onProperty :eats ; owl:allValuesFrom :Fruit .+ :Apple rdfs:subClassOf :Fruit .++ # scm-svf2 / scm-avf2: same filler, properties ordered+ :SvfSub a owl:Restriction ; owl:onProperty :hasPart ; owl:someValuesFrom :Wheel .+ :SvfSup a owl:Restriction ; owl:onProperty :hasComponent ; owl:someValuesFrom :Wheel .+ :AvfSub a owl:Restriction ; owl:onProperty :hasPart ; owl:allValuesFrom :Wheel .+ :AvfSup a owl:Restriction ; owl:onProperty :hasComponent ; owl:allValuesFrom :Wheel .+ :hasPart rdfs:subPropertyOf :hasComponent .++ # scm-dom1 / scm-dom2 / scm-rng1 / scm-rng2+ :hasComponent rdfs:domain :Assembly ; rdfs:range :Component .+ :Assembly rdfs:subClassOf :Artifact .+ :Component rdfs:subClassOf :Thing .++ # cls-int1 and cls-int2+ :Supplier owl:intersectionOf ( :Vendor :Approved ) .+ :acme a :Supplier .+ :both a :Vendor , :Approved .++ # cls-uni and cls-oo+ :Either owl:unionOf ( :Vendor :Approved ) .+ :Weekend owl:oneOf ( :saturday :sunday ) .+"#;++const NEW_RULE_IDS: [&str; 10] = [+ "scm-svf1", "scm-svf2", "scm-avf1", "scm-avf2", "scm-dom1", "scm-dom2", "scm-rng1",+ "scm-rng2", "cls-int2", "cls-oo",+];++#[test]+fn every_new_rule_fires_and_the_certificate_is_accepted() {+ if skip() {+ return;+ }+ let dir = scratch("new-rules");+ let (_, r) = run(&format!("{PREFIXES}{NEW_RULES}"), "owl-rl-ext", Some(&dir));+ let by_rule = r["certificate"]["by_rule"]+ .as_object()+ .expect("by_rule in the response");+ let missing: Vec<&str> = NEW_RULE_IDS+ .iter()+ .copied()+ .filter(|k| !by_rule.contains_key(*k))+ .collect();+ assert!(+ missing.is_empty(),+ "rules that never fired on the ontology built to fire them: {missing:?}\n{r}"+ );+ assert_eq!(+ r["certificate"]["derivations"], r["inferred_count"],+ "one certificate line per inferred triple: {r}"+ );+ let (ok, out) = check(&dir);+ assert!(ok, "the checker rejected the new-rules certificate:\n{out}");+}++/// The trap. Three restriction-ordering rules conclude `c1 subClassOf c2` and+/// this one concludes `c2 subClassOf c1`, so the engine must derive the+/// subsumption in the direction the W3C table gives and must NOT derive the+/// other. Flipping the conclusion in `src/reason.rs` fails the second+/// assertion here, and it fails the Lean build as well.+#[test]+fn scm_avf2_concludes_the_subsumption_the_other_way_round() {+ let ttl = format!(+ "{PREFIXES}+ :AvfSub a owl:Restriction ; owl:onProperty :hasPart ; owl:allValuesFrom :Wheel .+ :AvfSup a owl:Restriction ; owl:onProperty :hasComponent ; owl:allValuesFrom :Wheel .+ :hasPart rdfs:subPropertyOf :hasComponent ."+ );+ let (store, _) = run(&ttl, "owl-rl-ext", None);+ assert!(+ holds(&store, "<http://ex.org/AvfSup>", "rdfs:subClassOf", "<http://ex.org/AvfSub>"),+ "scm-avf2 must derive `all hasComponent Wheel` subClassOf `all hasPart Wheel`: a \+ universal restriction is antitone in its property"+ );+ assert!(+ !holds(&store, "<http://ex.org/AvfSub>", "rdfs:subClassOf", "<http://ex.org/AvfSup>"),+ "the reverse subsumption is NOT entailed and must not be derived; it is the direction \+ scm-svf2, scm-svf1 and scm-avf1 run in, and copying them here is unsound. See \+ OOCert.the_natural_avf2_direction_is_not_entailed"+ );+}++/// And the existential pair runs the way its siblings do, so the test above is+/// pinning a real asymmetry rather than a typo in one direction.+#[test]+fn scm_svf2_concludes_the_subsumption_the_usual_way_round() {+ let ttl = format!(+ "{PREFIXES}+ :SvfSub a owl:Restriction ; owl:onProperty :hasPart ; owl:someValuesFrom :Wheel .+ :SvfSup a owl:Restriction ; owl:onProperty :hasComponent ; owl:someValuesFrom :Wheel .+ :hasPart rdfs:subPropertyOf :hasComponent ."+ );+ let (store, _) = run(&ttl, "owl-rl-ext", None);+ assert!(+ holds(&store, "<http://ex.org/SvfSub>", "rdfs:subClassOf", "<http://ex.org/SvfSup>"),+ "scm-svf2 derives `some hasPart Wheel` subClassOf `some hasComponent Wheel`"+ );+ assert!(+ !holds(&store, "<http://ex.org/SvfSup>", "rdfs:subClassOf", "<http://ex.org/SvfSub>"),+ "and not the reverse"+ );+}++/// `cls-int2` takes an intersection apart, and `cls-int1` still needs every+/// member. The second half is what stops the new rule from being read as+/// "membership in one member is enough".+#[test]+fn cls_int2_takes_the_intersection_apart_without_weakening_cls_int1() {+ let ttl = format!(+ "{PREFIXES}+ :Supplier owl:intersectionOf ( :Vendor :Approved ) .+ :acme a :Supplier .+ :vee a :Vendor ."+ );+ let (store, _) = run(&ttl, "owl-rl-ext", None);+ assert!(+ holds(&store, "<http://ex.org/acme>", "a", "<http://ex.org/Vendor>")+ && holds(&store, "<http://ex.org/acme>", "a", "<http://ex.org/Approved>"),+ "cls-int2: a Supplier is a Vendor and an Approved"+ );+ assert!(+ !holds(&store, "<http://ex.org/vee>", "a", "<http://ex.org/Supplier>"),+ "cls-int1 still needs EVERY member; vee is only a Vendor. See \+ OOCert.membership_in_one_member_does_not_give_the_intersection"+ );+}++/// `cls-oo` types the members the list names and stops there. The condition it+/// rests on is the "at least" half of the enumeration's meaning only.+#[test]+fn cls_oo_types_the_listed_members_and_no_one_else() {+ let ttl = format!(+ "{PREFIXES}+ :Weekend owl:oneOf ( :saturday :sunday ) .+ :monday a :Day ."+ );+ let (store, _) = run(&ttl, "owl-rl-ext", None);+ assert!(+ holds(&store, "<http://ex.org/saturday>", "a", "<http://ex.org/Weekend>")+ && holds(&store, "<http://ex.org/sunday>", "a", "<http://ex.org/Weekend>"),+ "cls-oo types both listed members"+ );+ assert!(+ !holds(&store, "<http://ex.org/monday>", "a", "<http://ex.org/Weekend>"),+ "an individual the list never mentions is not entailed to be a member. See \+ OOCert.an_unlisted_individual_is_not_entailed"+ );+}++/// The honest limit of the four domain-and-range rules, written so that it+/// fails if it stops being true.+///+/// They fire on schema alone and they emit schema. The instance-level+/// consequence was already reachable without them: rdfs2 gives `x rdf:type c1`+/// and rdfs9 gives `x rdf:type c2` from `c1 rdfs:subClassOf c2`, which is why+/// the `rdfs` profile, which has none of these four rules, reaches the same+/// answer about `x`. What `owl-rl` adds is the axiom `p rdfs:domain c2`.+#[test]+fn the_domain_rules_add_schema_and_not_answers() {+ let ttl = format!(+ "{PREFIXES}+ :p rdfs:domain :Narrow ; rdfs:range :NarrowR .+ :Narrow rdfs:subClassOf :Wide .+ :NarrowR rdfs:subClassOf :WideR .+ :x :p :y ."+ );+ let (rdfs_store, _) = run(&ttl, "rdfs", None);+ let (owl_store, _) = run(&ttl, "owl-rl", None);++ // The answer about the individual is the same in both profiles.+ for store in [&rdfs_store, &owl_store] {+ assert!(+ holds(store, "<http://ex.org/x>", "a", "<http://ex.org/Wide>"),+ "rdfs2 then rdfs9 already reaches this, with or without scm-dom1"+ );+ assert!(+ holds(store, "<http://ex.org/y>", "a", "<http://ex.org/WideR>"),+ "and the same on the range side"+ );+ }++ // The schema axiom is what is new.+ assert!(+ !holds(&rdfs_store, "<http://ex.org/p>", "rdfs:domain", "<http://ex.org/Wide>"),+ "the rdfs profile has no scm-dom1, so it must NOT emit the weakened domain; if it does, \+ this test is measuring nothing"+ );+ assert!(+ holds(&owl_store, "<http://ex.org/p>", "rdfs:domain", "<http://ex.org/Wide>"),+ "scm-dom1 emits the weakened domain axiom"+ );+ assert!(+ holds(&owl_store, "<http://ex.org/p>", "rdfs:range", "<http://ex.org/WideR>"),+ "scm-rng1 emits the weakened range axiom"+ );+}++/// A gate that cannot fail is decoration. One forged line per new rule, each+/// appended on its own to a certificate that passes without it, and each+/// rejected.+///+/// The `scm-avf2` entry is the one worth reading: the premises are all+/// asserted, the rule id is real, and the ONLY thing wrong with it is that the+/// conclusion runs the way its three siblings run.+#[test]+fn the_checker_rejects_a_forged_step_for_each_new_rule() {+ if skip() {+ return;+ }+ const TYPE: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>";+ const SC: &str = "<http://www.w3.org/2000/01/rdf-schema#subClassOf>";+ const SP: &str = "<http://www.w3.org/2000/01/rdf-schema#subPropertyOf>";+ const DOM: &str = "<http://www.w3.org/2000/01/rdf-schema#domain>";+ const AVF: &str = "<http://www.w3.org/2002/07/owl#allValuesFrom>";+ const OP: &str = "<http://www.w3.org/2002/07/owl#onProperty>";+ const INT: &str = "<http://www.w3.org/2002/07/owl#intersectionOf>";+ const ONEOF: &str = "<http://www.w3.org/2002/07/owl#oneOf>";+ let e = |s: &str| format!("<http://ex.org/{s}>");++ let forgeries: Vec<(&str, String)> = vec![+ (+ "scm-avf2 with the conclusion the way its three siblings run",+ [+ "scm-avf2".to_string(),+ e("AvfSub"), SC.into(), e("AvfSup"),+ e("AvfSub"), AVF.into(), e("Wheel"),+ e("AvfSub"), OP.into(), e("hasPart"),+ e("AvfSup"), AVF.into(), e("Wheel"),+ e("AvfSup"), OP.into(), e("hasComponent"),+ e("hasPart"), SP.into(), e("hasComponent"),+ ]+ .join("\t"),+ ),+ (+ "scm-dom1 weakening a domain along a subClassOf nobody asserted",+ [+ "scm-dom1".to_string(),+ e("hasComponent"), DOM.into(), e("Ghost"),+ e("hasComponent"), DOM.into(), e("Assembly"),+ e("Assembly"), SC.into(), e("Ghost"),+ ]+ .join("\t"),+ ),+ (+ "cls-int2 concluding a class that is not a member of the list",+ [+ "cls-int2".to_string(),+ e("acme"), TYPE.into(), e("Ghost"),+ e("Supplier"), INT.into(), "_:b0".into(),+ e("acme"), TYPE.into(), e("Supplier"),+ ]+ .join("\t"),+ ),+ (+ "cls-oo typing an individual the enumeration never lists",+ [+ "cls-oo".to_string(),+ e("monday"), TYPE.into(), e("Weekend"),+ e("Weekend"), ONEOF.into(), "_:b1".into(),+ ]+ .join("\t"),+ ),+ ];++ for (why, line) in forgeries {+ let dir = scratch("forged");+ run(&format!("{PREFIXES}{NEW_RULES}"), "owl-rl-ext", Some(&dir));+ let (ok, out) = check(&dir);+ assert!(ok, "the honest certificate must pass first: {out}");++ let path = dir.join("derivations.tsv");+ let mut content = std::fs::read_to_string(&path).unwrap();+ content.push_str(&line);+ content.push('\n');+ std::fs::write(&path, content).unwrap();++ let (ok, out) = check(&dir);+ assert!(!ok, "a forged step must be rejected ({why}):\n{out}");+ let _ = std::fs::remove_dir_all(&dir);+ }+}++/// What the ten rules actually do to the corpus this repository ships.+///+/// The point is the RANKING and not the total. Most of the profile's missing+/// rules fire zero times here because the corpus is schema-heavy and+/// instance-light, so a rule count is a bad way to choose what to implement and+/// a firing count is a good one. This test prints the per-rule totals and+/// asserts the two claims the choice rested on: the schema rules fire, and they+/// fire on files where the instance rules find nothing.+///+/// Run with `-- --nocapture` to read the table.+#[test]+fn the_new_rules_earn_their_place_on_the_shipped_corpus() {+ if skip() {+ return;+ }+ const SIZE_CAP: u64 = 4 * 1024 * 1024;+ const SKIP_DIRS: [&str; 8] = [+ "node_modules", "target", ".lake", ".git", ".venv", "venv", "site-packages", "__pycache__",+ ];+ let out = Command::new("git")+ .args(["ls-files", "-z", "*.ttl", "*.owl", "*.rdf", "*.nt"])+ .current_dir(repo())+ .output()+ .expect("run git ls-files");+ let mut files: Vec<PathBuf> = String::from_utf8_lossy(&out.stdout)+ .split('\0')+ .filter(|p| !p.is_empty())+ .filter(|p| !SKIP_DIRS.iter().any(|d| p.split('/').any(|seg| seg == *d)))+ .map(|p| repo().join(p))+ .collect();+ files.sort();+ assert!(files.len() >= 120, "expected the whole corpus, found {}", files.len());++ let mut totals: BTreeMap<String, u64> = BTreeMap::new();+ let mut files_with_new_rules = 0usize;+ let mut files_schema_only = 0usize;+ let mut reasoned = 0usize;++ for path in &files {+ if std::fs::metadata(path).unwrap().len() > SIZE_CAP {+ continue;+ }+ let store = Arc::new(GraphStore::new());+ if store.load_file(&path.display().to_string()).is_err() {+ continue;+ }+ reasoned += 1;+ let dir = scratch("corpus");+ let Ok(out) =+ Reasoner::run_full(&store, "owl-rl-ext", false, InferenceTarget::DefaultGraph, Some(&dir))+ else {+ let _ = std::fs::remove_dir_all(&dir);+ continue;+ };+ let r: serde_json::Value = serde_json::from_str(&out).unwrap();+ let mut new_here = 0u64;+ let mut old_here = 0u64;+ if let Some(by_rule) = r["certificate"]["by_rule"].as_object() {+ for (rule, n) in by_rule {+ let n = n.as_u64().unwrap_or(0);+ *totals.entry(rule.clone()).or_default() += n;+ if NEW_RULE_IDS.contains(&rule.as_str()) {+ new_here += n;+ } else {+ old_here += n;+ }+ }+ }+ if new_here > 0 {+ files_with_new_rules += 1;+ if old_here == 0 {+ files_schema_only += 1;+ }+ }+ let _ = std::fs::remove_dir_all(&dir);+ }++ eprintln!(+ "--- firings across {reasoned} corpus files that parse and are under the size cap, \+ out of {} tracked ---",+ files.len()+ );+ for (rule, n) in &totals {+ let tag = if NEW_RULE_IDS.contains(&rule.as_str()) { "NEW" } else { " " };+ eprintln!("{tag} {rule:>10} {n}");+ }+ let new_total: u64 = NEW_RULE_IDS+ .iter()+ .map(|r| totals.get(*r).copied().unwrap_or(0))+ .sum();+ eprintln!(+ "new-rule firings {new_total}, on {files_with_new_rules} files, \+ of which {files_schema_only} derived NOTHING from the older rules"+ );++ assert!(+ new_total > 0,+ "the ten rules fired zero times on the whole corpus, so nothing here was measured"+ );+ assert!(+ totals.get("scm-dom1").copied().unwrap_or(0) > 0+ || totals.get("scm-rng1").copied().unwrap_or(0) > 0,+ "the domain-and-range rules fire on schema alone, so a schema-heavy corpus must trigger \+ them; if this fails the gap analysis that chose them was wrong: {totals:?}"+ );++ // The half of the measurement that is bad news, kept here rather than in a+ // note nobody reads. Three of the ten fire ZERO times on everything this+ // repository tracks. They are implemented because they are part of the+ // profile and because the fourth member of their family is the single+ // biggest contributor below, not because a file here needs them, and the+ // honest way to say so is an assertion that fails the day it stops being+ // true.+ for silent in ["scm-svf2", "scm-avf1", "scm-avf2"] {+ assert_eq!(+ totals.get(silent).copied().unwrap_or(0),+ 0,+ "{silent} was measured at zero across the whole corpus. A non-zero count is good \+ news and wants this list shortened rather than the rule removed: {totals:?}"+ );+ }+}++/// The numbers, on one file rather than on an aggregate.+///+/// A corpus total moves whenever anyone adds an RDF file, so it cannot be+/// pinned. `benchmark/reference/pizza-reference.owl` is the pizza ontology with+/// 156 `owl:someValuesFrom` and 49 `owl:allValuesFrom` axioms, it is the file+/// the restriction-ordering rules were chosen on, and it does not move.+///+/// Read the zeroes as carefully as the counts. `scm-avf1` and `scm-avf2` draw+/// nothing here despite 49 universal restrictions, because the pizza ontology+/// uses them as closure axioms whose fillers are anonymous unions, and no two+/// of those stand in a subclass or subproperty relation.+#[test]+fn the_measured_shape_of_one_committed_file() {+ let path = repo().join("benchmark/reference/pizza-reference.owl");+ assert!(path.exists(), "the measured file is missing: {}", path.display());+ let store = Arc::new(GraphStore::new());+ store.load_file(&path.display().to_string()).unwrap();+ let dir = scratch("pizza");+ let out = Reasoner::run_full(+ &store, "owl-rl-ext", false, InferenceTarget::DefaultGraph, Some(&dir),+ )+ .unwrap();+ let r: serde_json::Value = serde_json::from_str(&out).unwrap();+ let by_rule: BTreeMap<String, u64> = r["certificate"]["by_rule"]+ .as_object()+ .expect("by_rule")+ .iter()+ .map(|(k, v)| (k.clone(), v.as_u64().unwrap_or(0)))+ .collect();+ eprintln!("pizza-reference.owl inferred={} by_rule={by_rule:?}", r["inferred_count"]);++ for (rule, want) in [+ ("scm-svf1", 101u64),+ ("scm-dom1", 12),+ ("scm-rng1", 14),+ ("cls-int2", 5),+ ("cls-oo", 5),+ ("scm-svf2", 0),+ ("scm-avf1", 0),+ ("scm-avf2", 0),+ ("scm-dom2", 0),+ ("scm-rng2", 0),+ ] {+ assert_eq!(+ by_rule.get(rule).copied().unwrap_or(0),+ want,+ "{rule} on pizza-reference.owl: {by_rule:?}"+ );+ }+ let _ = std::fs::remove_dir_all(&dir);+}++/// Rules this engine deliberately does not run, kept out by a test rather than+/// by a comment. Each is a sound OWL 2 RL rule, and the reason for each is on+/// `Reasoner` in `src/reason.rs`. A certificate line citing one would mean the+/// decision was reversed without the semantic condition that has to come with+/// it, and the Lean side would refuse the certificate rather than the engine+/// refusing to emit it.+#[test]+fn the_rules_that_were_left_out_stay_out() {+ let dir = scratch("left-out");+ let (_, r) = run(&format!("{PREFIXES}{NEW_RULES}"), "owl-rl-ext", Some(&dir));+ let by_rule = r["certificate"]["by_rule"].as_object().expect("by_rule");+ for unwanted in [+ "eq-ref", "eq-rep-s", "eq-rep-p", "eq-rep-o",+ "scm-cls", "scm-op", "scm-dp",+ "dt-type1", "dt-type2", "dt-eq", "dt-diff", "dt-not-type",+ "cax-dw", "cls-com", "cls-maxc1", "prp-irp", "prp-asyp", "prp-pdw", "prp-npa1",+ ] {+ assert!(+ !by_rule.contains_key(unwanted),+ "{unwanted} is not implemented and must not appear in a certificate: {r}"+ );+ }+ let _ = std::fs::remove_dir_all(&dir);++ // `eq-ref` is the one with a visible consequence. It asserts `owl:sameAs`+ // reflexivity for every term in every position, so it would put a+ // derivation into the EMPTY graph, and `OOCert.not_everything_is_entailed`+ // is proved against a graph that has none.+ let empty = Arc::new(GraphStore::new());+ let out =+ Reasoner::run_full(&empty, "owl-rl-ext", false, InferenceTarget::DefaultGraph, None)+ .unwrap();+ let e: serde_json::Value = serde_json::from_str(&out).unwrap();+ assert_eq!(+ e["inferred_count"].as_u64().unwrap(),+ 0,+ "the empty graph must still derive nothing: {e}"+ );+}+diff --git a/tests/shacl_core_verified_test.rs b/tests/shacl_core_verified_test.rsindex 8409ba94..ea11e812 100644--- a/tests/shacl_core_verified_test.rs+++ b/tests/shacl_core_verified_test.rs@@ -71,7 +71,7 @@mod common;-use open_ontologies::graph::GraphStore;+use oxigraph::io::{RdfFormat, RdfParser};use oxigraph::sparql::{QueryResults, SparqlEvaluator};use oxigraph::store::Store;@@ -279,8 +279,26 @@ fn short(iri: &str) -> String {}/// Canonical comparison form. IRIs lose their angle brackets, blank nodes collapse-/// to `_:`, literals are left as printed. Applied to both sides, so the two are-/// symmetric.+/// to `_:`, and a literal is passed through an Oxigraph store once. Applied to both+/// sides, so the two are symmetric.+///+/// # Why a literal goes through a store+///+/// Oxigraph encodes an XSD-typed literal as a native value and hands back the+/// CANONICAL lexical form on the way out, so `"4.0"^^xsd:decimal` comes out of a+/// store as `"4"^^xsd:decimal`. The expected side of every comparison is read out of+/// a `Store` with SPARQL, so it has already been through that; the produced side+/// comes straight from the validator, which is now fed a term-faithful graph (see+/// `to_ntriples`) and so has not. Putting both through the same step is what keeps+/// the lens symmetric. Canonicalisation is idempotent, so the expected side is+/// unchanged by it.+///+/// What it costs, stated rather than discovered: two lexical forms of one value+/// within one datatype become one comparison key, so a validator that reported+/// `"4.0"^^xsd:decimal` where the Working Group wrote `"4"^^xsd:decimal` is not+/// caught here. Two DIFFERENT datatypes never merge, so `"4"^^xsd:integer` and+/// `"4.0"^^xsd:decimal` stay distinct and a validator confusing those two is still+/// caught.fn canon(term: &str) -> String {let t = term.trim();if t.starts_with("_:") {@@ -289,9 +307,32 @@ fn canon(term: &str) -> String {if let Some(inner) = t.strip_prefix('<').and_then(|s| s.strip_suffix('>')) {return inner.to_string();}+ if t.starts_with('"') {+ return literal_canon(t);+ }t.to_string()}+/// One literal through an Oxigraph store and back. Anything that will not make the+/// round trip is handed back untouched, so a term this cannot parse turns into a+/// disagreement rather than into a silent match.+fn literal_canon(lit: &str) -> String {+ let Ok(store) = Store::new() else { return lit.to_string() };+ let line = format!("<urn:x-oo-canon:s> <urn:x-oo-canon:p> {lit} .\n");+ let parser =+ RdfParser::from_format(RdfFormat::NTriples).for_reader(Cursor::new(line.into_bytes()));+ for quad in parser {+ let Ok(quad) = quad else { return lit.to_string() };+ if store.insert(&quad).is_err() {+ return lit.to_string();+ }+ }+ match store.iter().next() {+ Some(Ok(q)) => q.object.to_string(),+ _ => lit.to_string(),+ }+}+fn rows(store: &Store, query: &str) -> anyhow::Result<Vec<HashMap<String, String>>> {let mut out = Vec::new();if let QueryResults::Solutions(solutions) =@@ -470,22 +511,50 @@ fn read_entry(store: &Store, manifest: &Path, entry: &str) -> anyhow::Result<Tes// Running one test// ─────────────────────────────────────────────────────────────────────────────-/// Turtle to N-Triples through the engine's own parser, with the file's IRI as-/// base. The Lean bridge reads N-Triples only, on purpose: prefix and base-/// resolution are exactly the kind of work that is easy to get subtly wrong, and-/// doing it here rather than in Lean keeps it out of the verified path AND makes-/// this harness resolve IRIs the same way the expected reports do.+/// Turtle to N-Triples with the file's IRI as base. The Lean bridge reads+/// N-Triples only, on purpose: prefix and base resolution are exactly the kind of+/// work that is easy to get subtly wrong, and doing it here rather than in Lean+/// keeps it out of the verified path AND makes this harness resolve IRIs the same+/// way the expected reports do.////// This is the one part of the pipeline whose correctness is assumed rather than/// proved or measured. A mis-resolved IRI would show up as a disagreement, not as a/// false pass, because the expected side resolves through the same code.+///+/// # It goes parser to serialiser, and no longer through the engine's store+///+/// It used to load the Turtle into `GraphStore` and serialise that. **That round+/// trip does not preserve RDF terms.** Oxigraph encodes an XSD-typed literal as a+/// native value and hands back the CANONICAL lexical form on the way out, so+/// `"1"^^xsd:boolean` in a shapes file arrived at the validator as+/// `"true"^^xsd:boolean`. SHACL reads several parameter values as terms rather+/// than as values, and `core/property/uniqueLang-002` is the Working Group's test+/// for exactly that distinction: it says in a comment that `"1"^^xsd:boolean` must+/// NOT activate `sh:uniqueLang`. Under the old conversion no validator could pass+/// it, because the distinction was destroyed before the validator ran.+///+/// The finding is about `GraphStore`, which this task does not own, so it is+/// reported rather than fixed there: **`GraphStore::load_turtle` followed by+/// `GraphStore::serialize("ntriples")` is not term-preserving.** Anything in `src/`+/// that round-trips a graph through the store and then compares terms, SHACL+/// validation included, inherits that.+///+/// Parsing is still Oxigraph's, so base and prefix resolution are unchanged.+/// Triples are deduplicated and sorted here because the store used to do both, and+/// the compiler in `lean/Shacl/Compile.lean` reads `sh:path` as "exactly one+/// object" and would refuse a shapes graph that merely repeated a triple.fn to_ntriples(path: &Path) -> Result<String, String> {- let store = GraphStore::new();let text = std::fs::read_to_string(path).map_err(|e| format!("unreadable: {e}"))?;- store- .load_turtle(&text, Some(&base_of(path)))- .map_err(|e| format!("does not parse: {}", first_line(&e.to_string())))?;- store.serialize("ntriples").map_err(|e| format!("will not re-serialise: {e}"))+ let parser = RdfParser::from_format(RdfFormat::Turtle)+ .with_base_iri(base_of(path))+ .map_err(|e| format!("has an unusable base IRI: {e}"))?+ .for_reader(Cursor::new(text.into_bytes()));+ let mut lines: BTreeSet<String> = BTreeSet::new();+ for quad in parser {+ let q = quad.map_err(|e| format!("does not parse: {}", first_line(&e.to_string())))?;+ lines.insert(format!("{} {} {} .", q.subject, q.predicate, q.object));+ }+ Ok(lines.into_iter().collect::<Vec<_>>().join("\n"))}/// The outcome of one test, plus how many targeted shapes the compiler found.@@ -512,6 +581,9 @@ fn run_case(tc: &TestCase, idx: usize) -> (Outcome, Option<u64>) {return (Outcome::Error(format!("cannot write scratch shapes graph: {e}")), None);}+ if std::env::var("OO_SHACL_DUMP").as_deref() == Ok(tc.name.as_str()) {+ eprintln!("---- {} data ----\n{data_nt}\n---- shapes ----\n{shapes_nt}", tc.name);+ }let v = run_bridge(&dp, &sp);let shapes_found = v.json["shapes"].as_u64();let outcome = match v.code {@@ -832,9 +904,14 @@ fn the_bridge_refuses_what_it_cannot_check() {dup.raw);- // Four refusals, each naming what it refused.- let refusals: [(&str, &str, &str); 4] = [- ("conforming-data.nt", "unsupported-shapes.nt", "shacl#pattern"),+ // Six refusals, each naming what it refused. One per way the pipeline can+ // decline: an unknown parameter, an unimplemented path form, a regular+ // expression outside the proved subset, recursion, the extension mechanism, and+ // a datatype whose lexical space is not implemented.+ let refusals: [(&str, &str, &str); 6] = [+ ("conforming-data.nt", "unsupported-shapes.nt", "shacl#prefixes"),+ ("conforming-data.nt", "unsupported-path-shapes.nt", "zeroOrMorePath"),+ ("conforming-data.nt", "unsupported-regex-shapes.nt", "'+'"),("conforming-data.nt", "recursive-shapes.nt", "recursive"),("conforming-data.nt", "component-shapes.nt", "extension mechanism"),("unknown-datatype-data.nt", "unknown-datatype-shapes.nt", "lexical space"),@@ -932,21 +1009,24 @@ fn the_verified_conformance_report() {suite commit: PASS 36 / FAIL 24 / UNDETERMINED 60. It answers more and is wrong more.");- // Where the undetermined tests went, clustered, with one test named per- // cluster so the next piece of work can be picked by evidence.- let mut clusters: BTreeMap<String, (usize, String)> = BTreeMap::new();+ // Where the undetermined tests went, clustered, with every test named under+ // its cluster so the next piece of work can be picked by evidence rather than+ // by guessing which tests a cluster holds.+ let mut clusters: BTreeMap<String, Vec<String>> = BTreeMap::new();for (tc, o) in r.cases.iter().zip(r.outcomes.iter()) {if let Outcome::Undetermined(d) = o {- let e = clusters.entry(refusal_class(d)).or_insert((0, tc.name.clone()));- e.0 += 1;+ clusters.entry(refusal_class(d)).or_default().push(tc.name.clone());}}if !clusters.is_empty() {- eprintln!("\n UNDETERMINED by reason, with one test named per reason:");- let mut rows: Vec<(&String, &(usize, String))> = clusters.iter().collect();- rows.sort_by(|a, b| b.1.0.cmp(&a.1.0).then(a.0.cmp(b.0)));- for (why, (n, example)) in rows {- eprintln!(" {n:>4} {why} e.g. {example}");+ eprintln!("\n UNDETERMINED by reason, with every test named under its reason:");+ let mut rows: Vec<(&String, &Vec<String>)> = clusters.iter().collect();+ rows.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then(a.0.cmp(b.0)));+ for (why, names) in rows {+ eprintln!(" {:>4} {why}", names.len());+ for n in names {+ eprintln!(" {n}");+ }}}