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 the answer that had no certificate: a closed tableau, checked in Lean (#200)
Fabio Rovai902d5dcb0b6e
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 660c9f75..31c376be 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -452,6 +452,13 @@ jobs:run: OO_REQUIRE_FIXTURES=1 cargo test --test shacl_core_verified_test -- --nocapture- name: Check the description-logic model certificatesrun: OO_REQUIRE_FIXTURES=1 cargo test --test dl_model_certificate_test -- --nocapture+ - name: Check the description-logic refutation certificates+ # The other half of the line above. That one certifies that an ontology+ # HAS a model by exhibiting one; this certifies that it has NONE by+ # exhibiting a closed tableau, and the verdicts are different sentences.+ # Strict, because the emitter and the checker are both in this+ # repository and a skip here would hide the whole loop.+ run: OO_REQUIRE_FIXTURES=1 cargo test --test dl_refutation_certificate_test -- --nocapture- name: Pinpoint justifications, and check each one through the proved checker# Strict rather than excepted. The only thing this file skips on is# benchmark/reference/pizza-reference.owl, which ships with thediff --git a/docs/ci-gates.md b/docs/ci-gates.mdindex 1c681bf2..55f50160 100644--- a/docs/ci-gates.md+++ b/docs/ci-gates.md@@ -58,6 +58,7 @@ job invokes the file at all.| `provenance_test.rs` | the same shipped ontology | `lean` job | **strict** || `shacl_core_verified_test.rs` | lake + vendored W3C SHACL suite | `lean` job | **strict** || `dl_model_certificate_test.rs` | lake + `oo-dlmodel` | `lean` job | **strict** |+| `dl_refutation_certificate_test.rs` | lake + `oo-dlrefute` | `lean` job | **strict** || `lean_refutation_test.rs` | lake + `oo-refute` | `lean` job | **strict** || `lean_refutation_producer_test.rs` | lake + `oo-refute` | `lean` job | **strict** || `lean_mixed_certificate_test.rs` | lake | `lean` job | **strict** |diff --git a/lean/Dl/All.lean b/lean/Dl/All.leanindex a9222274..3748bb14 100644--- a/lean/Dl/All.lean+++ b/lean/Dl/All.lean@@ -1,9 +1,13 @@import Dl.Syntaximport Dl.Semantics+import Dl.General+import Dl.Tableauimport Dl.Countimport Dl.Checkimport Dl.Parseimport Dl.Witness+import Dl.Refute+import Dl.TableauDemo/-!# `Dl`: a model certificate for the SHIQ tableaux reasonerdiff --git a/lean/Dl/General.lean b/lean/Dl/General.leannew file mode 100644index 00000000..0efa53e4--- /dev/null+++ b/lean/Dl/General.lean@@ -0,0 +1,204 @@+import Dl.Semantics++/-!+# Interpretations that may be infinite, and what "unsatisfiable" means++`Dl/Semantics.lean` carries `Interp`, whose carrier is `dom : List Name`. That is+the right shape for EXHIBITING a model, which is what `oo-dlmodel` does: a finite+model is a model, so `Dl.satisfiable_of_checkModel` is sound as it stands.++It is the wrong shape for the opposite claim. "No `Interp` models `A`" says only+that `A` has no FINITE model, and that is strictly weaker than unsatisfiability+for the fragment this engine covers. SHIQ lacks the finite model property:+inverse roles together with number restrictions can force every model to be+infinite, so an axiom set with no finite model can still be perfectly+satisfiable. Reporting such a set as inconsistent would be unsound.++So a refutation certificate needs a semantics whose carrier is an arbitrary type.+That is this file. Nothing here computes; it is the target the tableau soundness+theorem in `Dl/Tableau.lean` aims at, and `finite_model_is_a_model` below is what+stops the two semantics drifting apart.+-/+namespace Dl++/-- An interpretation over an arbitrary carrier. The carrier is the type itself+rather than a distinguished subset, so there is no well-formedness side condition+to carry: every element of `α` is a domain element by construction. -/+structure GInterp (α : Type) where+ /-- The carrier. A PREDICATE rather than the whole type, for one reason that+ is worth stating: it makes the bridge from a finite `Interp` almost+ definitional, since `x ∈ I.dom` maps straight onto it. Carrying the carrier as+ the type itself reads more cleanly and pushes the whole cost into a subtype+ construction that the counting clauses then have to be transported across. -/+ dom : α → Prop+ cext : Name → α → Prop+ rext : Name → α → α → Prop+ ind : Name → α++/-- At least `n` distinct elements satisfy `P`. Stated with a list of distinct+witnesses, exactly as the finite version is, so the two read the same. -/+def GAtLeast {α : Type} (n : Nat) (P : α → Prop) : Prop :=+ ∃ ys : List α, ys.Nodup ∧ ys.length = n ∧ ∀ y ∈ ys, P y++/-- At most `n` distinct elements satisfy `P`. -/+def GAtMost {α : Type} (n : Nat) (P : α → Prop) : Prop :=+ ∀ ys : List α, ys.Nodup → (∀ y ∈ ys, P y) → ys.length ≤ n++/-- `x` is in the extension of `c`. Clause for clause the same as `Sat`, with+membership in a list replaced by a relation. -/+def GSat {α : Type} (I : GInterp α) : Concept → α → Prop+ | .top, _ => True+ | .bot, _ => False+ | .atom a, x => I.cext a x+ | .neg c, x => ¬ GSat I c x+ | .and c d, x => GSat I c x ∧ GSat I d x+ | .or c d, x => GSat I c x ∨ GSat I d x+ | .ex r c, x => ∃ y, I.rext r x y ∧ GSat I c y+ | .all r c, x => ∀ y, I.rext r x y → GSat I c y++ | .min n r c, x => GAtLeast n (fun y => I.rext r x y ∧ GSat I c y)+ | .max n r c, x => GAtMost n (fun y => I.rext r x y ∧ GSat I c y)++/-- The axiom holds in `I`. No `∈ dom` guards: the carrier is the whole type. -/+def GHolds {α : Type} (I : GInterp α) : Axiom → Prop+ | .sub c d => ∀ x, I.dom x → GSat I c x → GSat I d x+ | .disjoint c d => ∀ x, I.dom x → ¬ (GSat I c x ∧ GSat I d x)+ | .dom r c => ∀ x, I.dom x → (∃ y, I.rext r x y) → GSat I c x+ | .rng r c => ∀ x, I.dom x → ∀ y, I.rext r x y → GSat I c y+ | .subrole r s => ∀ x, I.dom x → ∀ y, I.rext r x y → I.rext s x y+ | .trans r => ∀ x, I.dom x → ∀ y, I.rext r x y → ∀ z, I.rext r y z → I.rext r x z+ | .sym r => ∀ x, I.dom x → ∀ y, I.rext r x y → I.rext r y x+ | .inv r s =>+ (∀ x, I.dom x → ∀ y, I.rext r x y → I.rext s y x) ∧+ (∀ x, I.dom x → ∀ y, I.rext s x y → I.rext r y x)+ | .invfunc r => ∀ y, I.dom y → GAtMost 1 (fun x => I.dom x ∧ I.rext r x y)+ | .inst a c => GSat I c (I.ind a)+ | .rel a r b => I.rext r (I.ind a) (I.ind b)+ | .indiv a => I.dom (I.ind a)+ | .nonempty c => ∃ x, I.dom x ∧ GSat I c x++/-- `I` is a model of `A`, over a carrier that is not empty. -/+structure GModels {α : Type} (I : GInterp α) (A : List Axiom) : Prop where+ /-- The carrier is not empty, for the reason `WellFormed` gives: without it+ every subclass axiom holds vacuously and satisfiability would mean nothing. -/+ nonempty : ∃ x, I.dom x+ /-- Roles the axioms mention do not lead out of the carrier.++ The finite side carries the same clause as `WellFormed.rextInDom`, and for the+ same reason: without it `GSat` could be evaluated at a point no axiom ever+ constrains. It is also what the existential tableau rule needs, since the+ witness it invents has to be a carrier element for the axioms to bite on it.+ Restricted to mentioned roles exactly as the finite clause is, which is what+ lets the bridge below supply it unchanged. -/+ rextDom : ∀ r ∈ roleNames A, ∀ x y, I.dom x → I.rext r x y → I.dom y+ holds : ∀ a ∈ A, GHolds I a++/-- `A` has NO model, of any size.++This is the statement a refutation certificate has to earn, and it is the reason+this file exists. The quantifier ranges over every carrier type, so it is not+satisfied by ruling out the finite ones. -/+def Unsatisfiable (A : List Axiom) : Prop :=+ ∀ (α : Type) (I : GInterp α), ¬ GModels I A++/-- A finite interpretation read as a general one. Every clause is the finite+one with list membership turned into a predicate. -/+def GInterp.ofInterp (I : Interp) : GInterp Name where+ dom x := x ∈ I.dom+ cext a x := x ∈ I.cext a+ rext r x y := y ∈ I.rext r x+ ind := I.ind++/-! The projections, as simp lemmas. Unfolding `GInterp.ofInterp` itself leaves+a structure literal in the goal that the induction hypothesis no longer matches,+so the clauses are given by name instead. -/++@[simp] theorem ofInterp_dom (I : Interp) (x : Name) :+ (GInterp.ofInterp I).dom x ↔ x ∈ I.dom := Iff.rfl++@[simp] theorem ofInterp_cext (I : Interp) (a x : Name) :+ (GInterp.ofInterp I).cext a x ↔ x ∈ I.cext a := Iff.rfl++@[simp] theorem ofInterp_rext (I : Interp) (r x y : Name) :+ (GInterp.ofInterp I).rext r x y ↔ y ∈ I.rext r x := Iff.rfl++@[simp] theorem ofInterp_ind (I : Interp) (a : Name) :+ (GInterp.ofInterp I).ind a = I.ind a := rfl++/-- Satisfaction agrees, clause for clause. The counting cases go through+because both sides quantify over `List Name` with `Nodup`, which is why the+carrier is a predicate over `α` rather than a subtype. -/+theorem gsat_ofInterp (I : Interp) (c : Concept) (x : Name) :+ GSat (GInterp.ofInterp I) c x ↔ Sat I c x := by+ induction c generalizing x with+ | top => exact Iff.rfl+ | bot => exact Iff.rfl+ | atom a => simp [GSat, Sat, GInterp.ofInterp]+ | neg c ih => simp [GSat, Sat, ih]+ | and c d ihc ihd => simp [GSat, Sat, ihc, ihd]+ | or c d ihc ihd => simp [GSat, Sat, ihc, ihd]+ | ex r c ih => simp [GSat, Sat, ih]+ | all r c ih => simp [GSat, Sat, ih]+ | min n r c ih =>+ simp only [GSat, Sat, GAtLeast, AtLeast, ofInterp_rext]+ constructor+ · rintro ⟨ys, hnd, hlen, hmem⟩+ exact ⟨ys, hnd, hlen, fun y hy => ⟨(hmem y hy).1, (ih y).mp (hmem y hy).2⟩⟩+ · rintro ⟨ys, hnd, hlen, hmem⟩+ exact ⟨ys, hnd, hlen, fun y hy => ⟨(hmem y hy).1, (ih y).mpr (hmem y hy).2⟩⟩+ | max n r c ih =>+ simp only [GSat, Sat, GAtMost, AtMost, ofInterp_rext]+ constructor+ · intro h ys hnd hmem+ exact h ys hnd (fun y hy => ⟨(hmem y hy).1, (ih y).mpr (hmem y hy).2⟩)+ · intro h ys hnd hmem+ exact h ys hnd (fun y hy => ⟨(hmem y hy).1, (ih y).mp (hmem y hy).2⟩)++/-- The bridge, and the reason the two semantics cannot drift apart: a finite+model IS a model, so anything this file calls unsatisfiable has no finite model+either.++Carried as a theorem rather than assumed, because the whole value of the+refutation layer is that its conclusion contradicts the model layer's. If these+two notions of model were unrelated, `oo-dlmodel` accepting a model and+`oo-refute` accepting a refutation of the same axiom set would not be a+contradiction, and neither result would mean anything. -/+theorem no_finite_model_of_unsatisfiable {A : List Axiom} (h : Unsatisfiable A) :+ ¬ Satisfiable A := by+ rintro ⟨I, hI⟩+ refine h Name (GInterp.ofInterp I) ⟨?_, ?_, ?_⟩+ · cases hd : I.dom with+ | nil => exact absurd hd hI.wf.nonempty+ | cons a as => exact ⟨a, by simp [hd]⟩+ · intro r hr x y hx hxy+ exact hI.wf.rextInDom r hr x hx y hxy+ · intro ax hax+ have hh := hI.holds ax hax+ cases ax with+ | dom r c =>+ -- The one clause the two semantics phrase differently: the finite side+ -- says the successor list is non-empty, the general side says a+ -- successor exists. `List.ne_nil_of_mem` is the whole of the gap.+ intro x hx hex+ obtain ⟨y, hy⟩ := hex+ exact (gsat_ofInterp I c x).mpr (hh x hx (List.ne_nil_of_mem hy))+ | sub c d => simp_all [GHolds, Holds, gsat_ofInterp]+ | disjoint c d => simp_all [GHolds, Holds, gsat_ofInterp]+ | rng r c =>+ intro x hx y hy+ exact (gsat_ofInterp I c y).mpr (hh x hx y hy)+ | subrole r s => simp_all [GHolds, Holds]+ | trans r =>+ intro x hx y hy z hz+ exact hh x hx y hy z hz+ | sym r => simp_all [GHolds, Holds]+ | inv r s => simp_all [GHolds, Holds]+ | invfunc r =>+ intro y hy ys hnd hmem+ exact hh y hy ys hnd hmem+ | inst a c => simp_all [GHolds, Holds, gsat_ofInterp]+ | rel a r b => simp_all [GHolds, Holds]+ | indiv a => simp_all [GHolds, Holds]+ | nonempty c => simp_all [GHolds, Holds, gsat_ofInterp]++end Dldiff --git a/lean/Dl/Parse.lean b/lean/Dl/Parse.leanindex 1df450f7..adb58d7c 100644--- a/lean/Dl/Parse.lean+++ b/lean/Dl/Parse.lean@@ -1,4 +1,5 @@import Dl.Check+import Dl.Refuteimport Std.Data.HashMap/-!@@ -129,4 +130,110 @@ def parseModel (content : String) : Except String Interp := do| _ => throw s!"model line {n}: not a well-formed model fact"return t.toInterp+/-! ## The refutation certificate++One token stream in prefix order, exactly like the concept grammar and for the+same reason: every constructor has a fixed arity, so there are no parentheses+and nothing to get unbalanced. The two variable-length rules carry an explicit+count before their name list, which is what keeps the arity fixed.++Newlines are not significant. A producer that writes one step per line and a+producer that writes the whole tree on one line are the same certificate, and+the parser cannot tell them apart. That is deliberate: the tree structure is+carried by the arities, so indentation can be for a human without any risk of+becoming load-bearing. -/++/-- Read exactly `k` names. -/+def names? : Nat → List String → Option (List Name × List String)+ | 0, ts => some ([], ts)+ | k + 1, t :: ts => (names? k ts).map (fun p => (t :: p.1, p.2))+ | _ + 1, [] => none++/-- Prefix parser for a certificate. The fuel is the token count, which strictly+bounds the recursion because every step consumes its own keyword first. -/+def cert? : Nat → List String → Option (Cert × List String)+ | 0, _ => none+ | _ + 1, [] => none+ | fuel + 1, t :: ts =>+ match t, ts with+ | "bot", x :: ts' => some (.botC x, ts')+ | "diff", x :: ts' => some (.diffC x, ts')+ | "disjoint", x :: ts' => do+ let (c, ts1) ← concept? fuel ts'+ let (d, ts2) ← concept? fuel ts1+ some (.disjC x c d, ts2)+ | "neg", x :: ts' => (concept? fuel ts').map (fun p => (.negC x p.1, p.2))+ | "minmax", x :: r :: m :: n :: ts' => do+ let m ← m.toNat?+ let n ← n.toNat?+ let (c, ts1) ← concept? fuel ts'+ some (.minmaxC x r c m n, ts1)+ | "maxclash", x :: r :: n :: k :: ts' => do+ let n ← n.toNat?+ let k ← k.toNat?+ let (ys, ts1) ← names? k ts'+ let (c, ts2) ← concept? fuel ts1+ some (.maxC x r c n ys, ts2)+ | "inst", a :: ts' => do+ let (c, ts1) ← concept? fuel ts'+ let (k, ts2) ← cert? fuel ts1+ some (.instS a c k, ts2)+ | "rel", a :: r :: b :: ts' => (cert? fuel ts').map (fun p => (.relS a r b p.1, p.2))+ | "sub", x :: ts' => do+ let (c, ts1) ← concept? fuel ts'+ let (d, ts2) ← concept? fuel ts1+ let (k, ts3) ← cert? fuel ts2+ some (.subS x c d k, ts3)+ | "domain", x :: y :: r :: ts' => do+ let (c, ts1) ← concept? fuel ts'+ let (k, ts2) ← cert? fuel ts1+ some (.domS x y r c k, ts2)+ | "range", x :: y :: r :: ts' => do+ let (c, ts1) ← concept? fuel ts'+ let (k, ts2) ← cert? fuel ts1+ some (.rngS x y r c k, ts2)+ | "subrole", x :: y :: r :: u :: ts' =>+ (cert? fuel ts').map (fun p => (.subroleS x y r u p.1, p.2))+ | "nonempty", y :: ts' => do+ let (c, ts1) ← concept? fuel ts'+ let (k, ts2) ← cert? fuel ts1+ some (.nonemptyS y c k, ts2)+ | "and", x :: ts' => do+ let (c, ts1) ← concept? fuel ts'+ let (d, ts2) ← concept? fuel ts1+ let (k, ts3) ← cert? fuel ts2+ some (.andS x c d k, ts3)+ | "all", x :: y :: r :: ts' => do+ let (c, ts1) ← concept? fuel ts'+ let (k, ts2) ← cert? fuel ts1+ some (.allS x y r c k, ts2)+ | "some", x :: y :: r :: ts' => do+ let (c, ts1) ← concept? fuel ts'+ let (k, ts2) ← cert? fuel ts1+ some (.exS x y r c k, ts2)+ | "min", x :: r :: n :: k :: ts' => do+ let n ← n.toNat?+ let k ← k.toNat?+ let (ys, ts1) ← names? k ts'+ let (c, ts2) ← concept? fuel ts1+ let (kid, ts3) ← cert? fuel ts2+ some (.minS x r c n ys kid, ts3)+ | "or", x :: ts' => do+ let (c, ts1) ← concept? fuel ts'+ let (d, ts2) ← concept? fuel ts1+ let (l, ts3) ← cert? fuel ts2+ let (r, ts4) ← cert? fuel ts3+ some (.orS x c d l r, ts4)+ | _, _ => none++/-- A certificate is the WHOLE file. Trailing tokens are a parse error, not+something to ignore: a producer that emitted a second tree, or truncated the+first, must not be read as having emitted one good one. -/+def parseCert (content : String) : Except String Cert :=+ let ts := tokens ((content.replace "\r\n" " ").replace "\n" " " |>.replace "\t" " ")+ match cert? (ts.length + 1) ts with+ | some (c, []) => .ok c+ | some (_, rest) => .error s!"certificate: {rest.length} tokens left over after the tree"+ | none => .error "certificate: not a well-formed derivation"+end Dl.Parsediff --git a/lean/Dl/Refute.lean b/lean/Dl/Refute.leannew file mode 100644index 00000000..6cd94952--- /dev/null+++ b/lean/Dl/Refute.lean@@ -0,0 +1,220 @@+import Dl.Tableau++/-!+# Replaying a closed tableau++`Dl/Tableau.lean` says what a refutation IS. This says how to check one that+arrived as bytes.++The shape is the one `Dl/Check.lean` already uses for models: a `Bool`-valued+function over a datatype the producer fills in, and one theorem saying `true`+implies the thing. The checker is total and decides only membership, length,+distinctness and freshness, so a certificate that lies is rejected rather than+believed; nothing here searches, and nothing here has to terminate for a reason+more subtle than the certificate being a finite tree.++The asymmetry worth naming: the producer may be wrong, may be buggy, may have+been handed a broken ontology, and none of that can make this accept. What it+CAN do is fail to find a refutation that exists, and this file says nothing+about that. Soundness only.+-/+namespace Dl++/-- A closed tableau as a producer writes it: one constructor per rule, each+carrying the side conditions it needs and its children.++The clash constructors are the leaves. Everything else has one child, except+the disjunction, which has two and is the only reason this is a tree. -/+inductive Cert where+ /-- `x : ⊥`. -/+ | botC (x : Name)+ /-- `x : C` against `x : ¬C`. -/+ | negC (x : Name) (c : Concept)+ /-- `x ≠ x`. -/+ | diffC (x : Name)+ /-- `x` in two classes the ontology declares disjoint. -/+ | disjC (x : Name) (c d : Concept)+ /-- `x : ≥m R.C` against `x : ≤n R.C`, `n < m`. Needs no witnesses. -/+ | minmaxC (x r : Name) (c : Concept) (m n : Nat)+ /-- `n+1` distinct successors against `x : ≤n R.C`. -/+ | maxC (x r : Name) (c : Concept) (n : Nat) (ys : List Name)+ | instS (a : Name) (c : Concept) (k : Cert)+ | relS (a r b : Name) (k : Cert)+ | subS (x : Name) (c d : Concept) (k : Cert)+ | domS (x y r : Name) (c : Concept) (k : Cert)+ | rngS (x y r : Name) (c : Concept) (k : Cert)+ | subroleS (x y r t : Name) (k : Cert)+ | nonemptyS (y : Name) (c : Concept) (k : Cert)+ | andS (x : Name) (c d : Concept) (k : Cert)+ | allS (x y r : Name) (c : Concept) (k : Cert)+ | exS (x y r : Name) (c : Concept) (k : Cert)+ | minS (x r : Name) (c : Concept) (n : Nat) (ys : List Name) (k : Cert)+ | orS (x : Name) (c d : Concept) (l r : Cert)+deriving Repr, Inhabited++/-- Does the branch put `x` in the carrier?++Several rules need `I.dom (σ x)` and the branch supplies it only through a+concept entry, so they carry `∃ e, x : e ∈ Γ`. That is an existential over+`Concept` and so not decidable by `decide`; this searches the branch instead,+which is the same claim and is a scan. -/+def hasConc (Γ : List Constraint) (x : Name) : Bool :=+ Γ.any (fun κ => match κ with | .conc y _ => y == x | _ => false)++theorem hasConc_sound {Γ : List Constraint} {x : Name} (h : hasConc Γ x = true) :+ ∃ e, Constraint.conc x e ∈ Γ := by+ obtain ⟨κ, hκ, hp⟩ := List.any_eq_true.mp h+ cases κ with+ | conc y e => exact ⟨e, by simpa using (by simpa using hp : y = x) ▸ hκ⟩+ | role _ _ _ => simp at hp+ | diff _ _ => simp at hp++/-- Replay the certificate against the branch. Every side condition of every+rule is decided here, so nothing is taken on the producer's word. -/+def check (A : List Axiom) : Cert → List Constraint → Bool+ | .botC x, Γ => decide (Constraint.conc x .bot ∈ Γ)+ | .negC x c, Γ =>+ decide (Constraint.conc x c ∈ Γ) && decide (Constraint.conc x (.neg c) ∈ Γ)+ | .diffC x, Γ => decide (Constraint.diff x x ∈ Γ)+ | .disjC x c d, Γ =>+ decide (Axiom.disjoint c d ∈ A) && decide (Constraint.conc x c ∈ Γ)+ && decide (Constraint.conc x d ∈ Γ)+ | .minmaxC x r c m n, Γ =>+ decide (Constraint.conc x (.min m r c) ∈ Γ)+ && decide (Constraint.conc x (.max n r c) ∈ Γ) && decide (n < m)+ | .maxC x r c n ys, Γ =>+ decide (Constraint.conc x (.max n r c) ∈ Γ)+ && decide (ys.length = n + 1) && decide ys.Nodup+ && decide (∀ a ∈ ys, ∀ b ∈ ys, a ≠ b → Constraint.diff a b ∈ Γ)+ && decide (∀ y ∈ ys, Constraint.role r x y ∈ Γ)+ && decide (∀ y ∈ ys, Constraint.conc y c ∈ Γ)+ | .instS a c k, Γ =>+ decide (Axiom.inst a c ∈ A) && decide (Axiom.indiv a ∈ A)+ && check A k (Constraint.conc a c :: Γ)+ | .relS a r b k, Γ =>+ decide (Axiom.rel a r b ∈ A) && check A k (Constraint.role r a b :: Γ)+ | .subS x c d k, Γ =>+ decide (Axiom.sub c d ∈ A) && decide (Constraint.conc x c ∈ Γ)+ && check A k (Constraint.conc x d :: Γ)+ | .domS x y r c k, Γ =>+ decide (Axiom.dom r c ∈ A) && decide (Constraint.role r x y ∈ Γ) && hasConc Γ x+ && check A k (Constraint.conc x c :: Γ)+ | .rngS x y r c k, Γ =>+ decide (Axiom.rng r c ∈ A) && decide (r ∈ roleNames A)+ && decide (Constraint.role r x y ∈ Γ) && hasConc Γ x+ && check A k (Constraint.conc y c :: Γ)+ | .subroleS x y r t k, Γ =>+ decide (Axiom.subrole r t ∈ A) && decide (Constraint.role r x y ∈ Γ) && hasConc Γ x+ && check A k (Constraint.role t x y :: Γ)+ | .nonemptyS y c k, Γ =>+ decide (Axiom.nonempty c ∈ A) && decide (y ∉ branchNames Γ) && decide (y ∉ indNames A)+ && check A k (Constraint.conc y c :: Γ)+ | .andS x c d k, Γ =>+ decide (Constraint.conc x (.and c d) ∈ Γ)+ && check A k (Constraint.conc x c :: Constraint.conc x d :: Γ)+ | .allS x y r c k, Γ =>+ decide (Constraint.conc x (.all r c) ∈ Γ) && decide (Constraint.role r x y ∈ Γ)+ && decide (r ∈ roleNames A) && check A k (Constraint.conc y c :: Γ)+ | .exS x y r c k, Γ =>+ decide (Constraint.conc x (.ex r c) ∈ Γ) && decide (r ∈ roleNames A)+ && decide (y ∉ branchNames Γ) && decide (y ∉ indNames A)+ && check A k (Constraint.role r x y :: Constraint.conc y c :: Γ)+ | .minS x r c n ys k, Γ =>+ decide (Constraint.conc x (.min n r c) ∈ Γ) && decide (r ∈ roleNames A)+ && decide (ys.length = n) && decide ys.Nodup+ && decide (∀ y ∈ ys, y ∉ branchNames Γ) && decide (∀ y ∈ ys, y ∉ indNames A)+ && check A k (minExpand r x c ys ++ Γ)+ | .orS x c d l r, Γ =>+ decide (Constraint.conc x (.or c d) ∈ Γ)+ && check A l (Constraint.conc x c :: Γ) && check A r (Constraint.conc x d :: Γ)++/-- **What the checker accepts really is closed.**++One case per constructor, and each is the same two moves: take the decided side+conditions apart, then hand them to the rule of `Dl/Tableau.lean` that has+exactly those hypotheses. No case reasons about the tableau; the reasoning was+done once, there. -/+theorem closed_of_check {A : List Axiom} :+ ∀ (t : Cert) (Γ : List Constraint), check A t Γ = true → Closed A Γ := by+ intro t+ induction t with+ | botC x => intro Γ h; exact .bot (by simpa [check] using h)+ | negC x c =>+ intro Γ h+ simp only [check, Bool.and_eq_true, decide_eq_true_eq] at h+ exact .neg h.1 h.2+ | diffC x => intro Γ h; exact .diff (by simpa [check] using h)+ | disjC x c d =>+ intro Γ h+ simp only [check, Bool.and_eq_true, decide_eq_true_eq] at h+ exact .disjointClash h.1.1 h.1.2 h.2+ | minmaxC x r c m n =>+ intro Γ h+ simp only [check, Bool.and_eq_true, decide_eq_true_eq] at h+ exact .minmaxClash h.1.1 h.1.2 h.2+ | maxC x r c n ys =>+ intro Γ h+ simp only [check, Bool.and_eq_true, decide_eq_true_eq] at h+ exact .maxClash h.1.1.1.1.1 h.1.1.1.1.2 h.1.1.1.2 h.1.1.2 h.1.2 h.2+ | instS a c k ih =>+ intro Γ h+ simp only [check, Bool.and_eq_true, decide_eq_true_eq] at h+ exact .instR h.1.1 h.1.2 (ih _ h.2)+ | relS a r b k ih =>+ intro Γ h+ simp only [check, Bool.and_eq_true, decide_eq_true_eq] at h+ exact .relR h.1 (ih _ h.2)+ | subS x c d k ih =>+ intro Γ h+ simp only [check, Bool.and_eq_true, decide_eq_true_eq] at h+ exact .subR h.1.1 h.1.2 (ih _ h.2)+ | domS x y r c k ih =>+ intro Γ h+ simp only [check, Bool.and_eq_true, decide_eq_true_eq] at h+ exact .domR h.1.1.1 h.1.1.2 (hasConc_sound h.1.2) (ih _ h.2)+ | rngS x y r c k ih =>+ intro Γ h+ simp only [check, Bool.and_eq_true, decide_eq_true_eq] at h+ exact .rngR h.1.1.1.1 h.1.1.1.2 h.1.1.2 (hasConc_sound h.1.2) (ih _ h.2)+ | subroleS x y r t k ih =>+ intro Γ h+ simp only [check, Bool.and_eq_true, decide_eq_true_eq] at h+ exact .subroleR h.1.1.1 h.1.1.2 (hasConc_sound h.1.2) (ih _ h.2)+ | nonemptyS y c k ih =>+ intro Γ h+ simp only [check, Bool.and_eq_true, decide_eq_true_eq] at h+ exact .nonemptyR h.1.1.1 h.1.1.2 h.1.2 (ih _ h.2)+ | andS x c d k ih =>+ intro Γ h+ simp only [check, Bool.and_eq_true, decide_eq_true_eq] at h+ exact .andR h.1 (ih _ h.2)+ | allS x y r c k ih =>+ intro Γ h+ simp only [check, Bool.and_eq_true, decide_eq_true_eq] at h+ exact .allR h.1.1.1 h.1.1.2 h.1.2 (ih _ h.2)+ | exS x y r c k ih =>+ intro Γ h+ simp only [check, Bool.and_eq_true, decide_eq_true_eq] at h+ exact .exR h.1.1.1.1 h.1.1.1.2 h.1.1.2 h.1.2 (ih _ h.2)+ | minS x r c n ys k ih =>+ intro Γ h+ simp only [check, Bool.and_eq_true, decide_eq_true_eq] at h+ exact .minR h.1.1.1.1.1.1 h.1.1.1.1.1.2 h.1.1.1.1.2 h.1.1.1.2 h.1.1.2 h.1.2 (ih _ h.2)+ | orS x c d l r ihl ihr =>+ intro Γ h+ simp only [check, Bool.and_eq_true, decide_eq_true_eq] at h+ exact .orR h.1.1 (ihl _ h.1.2) (ihr _ h.2)++/-- The whole story in one line: a certificate that checks against the EMPTY+branch means the axiom set has no model, of any size, finite or not. -/+theorem unsatisfiable_of_check {A : List Axiom} {t : Cert} (h : check A t [] = true) :+ Unsatisfiable A :=+ unsatisfiable_of_closed (closed_of_check t [] h)++/-- And so no finite model either, which is the form the rest of the repository+states its verdicts in. -/+theorem no_model_of_check {A : List Axiom} {t : Cert} (h : check A t [] = true) :+ ¬ Satisfiable A :=+ no_finite_model_of_unsatisfiable (unsatisfiable_of_check h)++end Dldiff --git a/lean/Dl/Tableau.lean b/lean/Dl/Tableau.leannew file mode 100644index 00000000..f13bfb55--- /dev/null+++ b/lean/Dl/Tableau.lean@@ -0,0 +1,829 @@+import Dl.General++/-!+# A closed tableau is a refutation, and it needs no blocking argument++`DlMain.lean` records that certifying an INCONSISTENCY "needs a closed tableau+with its blocking argument". The first half is right and the second is not, and+the distinction is what makes this file affordable.++Blocking exists so that a reasoner SEARCHING for a model terminates: it is what+makes "no clash was reachable" a decidable answer, and it is the hard part of+any completeness proof. A refutation claims nothing of the sort. A closed+tableau is a finite object in which every branch already ended in a clash, so+the derivation to each clash is finite and blocking never enters it. The checker+replays a finite tree.++What is needed instead is that every rule PRESERVES SATISFIABILITY downward:+if the branch before the rule had a model, some branch after it does too. Then a+tree whose every leaf is unsatisfiable has an unsatisfiable root, which is the+theorem at the bottom of this file.++## What a branch is++A branch is a list of constraints about named individuals, exactly the shape a+tableau reasoner carries: `x : C`, `(x, y) : R`, and `x ≠ y` for the+inequalities number restrictions introduce. Satisfaction is relative to an+interpretation AND an assignment from those names to carrier elements, because+the names in a tableau are syntax the reasoner invented, not individuals the+ontology mentions.+-/+namespace Dl++/-- One entry on a tableau branch. -/+inductive Constraint where+ | conc (x : Name) (c : Concept)+ | role (r : Name) (x y : Name)+ | diff (x y : Name)+deriving DecidableEq, Repr, Inhabited++/-- The names a constraint mentions. Freshness for the existential rule is+stated against this, and nothing else. -/+def Constraint.names : Constraint → List Name+ | .conc x _ => [x]+ | .role _ x y => [x, y]+ | .diff x y => [x, y]++/-- The names a branch mentions. -/+def branchNames (Γ : List Constraint) : List Name :=+ Γ.flatMap Constraint.names++/-- An assignment sends the tableau's invented names to carrier elements. -/+abbrev Assign (α : Type) := Name → α++/-- The constraint holds under `I` and `σ`. -/+def CHolds {α : Type} (I : GInterp α) (σ : Assign α) : Constraint → Prop+ | .conc x c => I.dom (σ x) ∧ GSat I c (σ x)+ | .role r x y => I.rext r (σ x) (σ y)+ | .diff x y => σ x ≠ σ y++/-- The branch has a model: an interpretation of the axioms, and an assignment+under which every constraint on the branch holds.++The assignment must AGREE WITH `I.ind` on every individual the axioms name.+Without that clause the axioms and the branch talk past each other: `.inst a C`+is a claim about `I.ind a` while `CHolds` reads `σ a`, so no rule could ever+move an assertion out of `A` and onto `Γ`. Since `Γ` starts empty, a calculus+without such a rule refutes nothing at all, and the capstone theorem below is+true of no derivation. The clause costs the rules that invent witnesses one+extra side condition each: a fresh name must also be new to the axioms.++It costs the capstone theorem nothing, because `I.ind` is itself an assignment,+so the empty branch is satisfied by taking `σ := I.ind`. -/+def BranchSat (A : List Axiom) (Γ : List Constraint) : Prop :=+ ∃ (α : Type) (I : GInterp α) (σ : Assign α),+ GModels I A ∧ (∀ a ∈ indNames A, σ a = I.ind a) ∧ ∀ κ ∈ Γ, CHolds I σ κ++/-! ## The rules, each as a lemma about satisfiability++Every rule is stated in the direction a refutation needs: if the branch BEFORE+the rule is satisfiable, then the branch AFTER it is too, or in the branching+case one of the two is. Read contrapositively, which is how the tableau uses+them, an unsatisfiable successor forces an unsatisfiable predecessor.+-/++/-- Conjunction. `x : C ⊓ D` licenses `x : C` and `x : D`. -/+theorem and_sound {A : List Axiom} {Γ : List Constraint} {x : Name} {c d : Concept}+ (hmem : Constraint.conc x (.and c d) ∈ Γ) (h : BranchSat A Γ) :+ BranchSat A (Constraint.conc x c :: Constraint.conc x d :: Γ) := by+ obtain ⟨α, I, σ, hM, hag, hΓ⟩ := h+ refine ⟨α, I, σ, hM, hag, ?_⟩+ intro κ hκ+ have hx := hΓ _ hmem+ simp only [CHolds, GSat] at hx+ rcases hκ with _ | ⟨_, hκ⟩+ · exact ⟨hx.1, hx.2.1⟩+ · rcases hκ with _ | ⟨_, hκ⟩+ · exact ⟨hx.1, hx.2.2⟩+ · exact hΓ _ hκ++/-- Universal restriction. `x : ∀R.C` with an `R`-edge to `y` licenses `y : C`.+The domain side comes from the range of the edge being in the carrier, which is+what `GModels` gives for every role the axioms mention. -/+theorem all_sound {A : List Axiom} {Γ : List Constraint} {x y r : Name} {c : Concept}+ (hall : Constraint.conc x (.all r c) ∈ Γ)+ (hedge : Constraint.role r x y ∈ Γ)+ (hr : r ∈ roleNames A)+ (h : BranchSat A Γ) :+ BranchSat A (Constraint.conc y c :: Γ) := by+ obtain ⟨α, I, σ, hM, hag, hΓ⟩ := h+ refine ⟨α, I, σ, hM, hag, ?_⟩+ intro κ hκ+ rcases hκ with _ | ⟨_, hκ⟩+ · have hx := hΓ _ hall+ have he := hΓ _ hedge+ simp only [CHolds, GSat] at hx he+ -- The target is in the carrier because the edge is, which is what `hr` and+ -- `rextDom` say together. Asking the branch for a concept entry on `y`+ -- instead, as this used to, refuses to propagate into an individual the+ -- ontology relates but never classifies, and those are common.+ exact ⟨hM.rextDom r hr (σ x) (σ y) hx.1 he, hx.2 (σ y) he⟩+ · exact hΓ _ hκ++/-- Disjunction. `x : C ⊔ D` licenses a split, and a model of the branch is a+model of one side or the other. This is the only rule that branches, and the+theorem at the bottom is what turns "both children closed" into a refutation. -/+theorem or_sound {A : List Axiom} {Γ : List Constraint} {x : Name} {c d : Concept}+ (hmem : Constraint.conc x (.or c d) ∈ Γ) (h : BranchSat A Γ) :+ BranchSat A (Constraint.conc x c :: Γ) ∨ BranchSat A (Constraint.conc x d :: Γ) := by+ obtain ⟨α, I, σ, hM, hag, hΓ⟩ := h+ have hx := hΓ _ hmem+ simp only [CHolds, GSat] at hx+ rcases hx.2 with hc | hd+ · refine Or.inl ⟨α, I, σ, hM, hag, ?_⟩+ intro κ hκ+ rcases hκ with _ | ⟨_, hκ⟩+ · exact ⟨hx.1, hc⟩+ · exact hΓ _ hκ+ · refine Or.inr ⟨α, I, σ, hM, hag, ?_⟩+ intro κ hκ+ rcases hκ with _ | ⟨_, hκ⟩+ · exact ⟨hx.1, hd⟩+ · exact hΓ _ hκ++/-! ## Freshness, and the rule that invents an individual++The existential rule is the only one that adds a name the branch did not have.+Its soundness is therefore not just "a model of the premise satisfies the+conclusion": the model has a witness, but the ASSIGNMENT has to be extended to+send the new name to it, and that extension must not disturb the constraints+already on the branch. That is the substitution lemma below, and freshness is+exactly the hypothesis that makes it hold. -/++/-- Two assignments agreeing on the names a constraint mentions satisfy it+alike. -/+theorem cholds_congr {α : Type} {I : GInterp α} {σ τ : Assign α} {κ : Constraint}+ (h : ∀ n ∈ κ.names, σ n = τ n) : CHolds I σ κ ↔ CHolds I τ κ := by+ cases κ with+ | conc x c => simp [CHolds, h x (by simp [Constraint.names])]+ | role r x y =>+ simp [CHolds, h x (by simp [Constraint.names]), h y (by simp [Constraint.names])]+ | diff x y =>+ simp [CHolds, h x (by simp [Constraint.names]), h y (by simp [Constraint.names])]++/-- Updating an assignment at a name the branch never mentions changes nothing+on that branch. -/+theorem branch_update_fresh {α : Type} {I : GInterp α} {σ : Assign α}+ {Γ : List Constraint} {y : Name} {w : α}+ (hfresh : y ∉ branchNames Γ) (hΓ : ∀ κ ∈ Γ, CHolds I σ κ) :+ ∀ κ ∈ Γ, CHolds I (fun n => if n = y then w else σ n) κ := by+ intro κ hκ+ refine (cholds_congr ?_).mp (hΓ κ hκ)+ intro n hn+ have : n ≠ y := by+ rintro rfl+ exact hfresh (List.mem_flatMap.mpr ⟨κ, hκ, hn⟩)+ simp [this]++/-- **The existential rule.** `x : ∃R.C` licenses a fresh `y` with an `R`-edge+from `x` and `y : C`.++`y` must not already occur on the branch. That is the whole of the side+condition, and without it the rule is unsound: reusing a name would assert that+an individual the branch already constrains is the witness, which no model+need agree to.++`r` must be a role the axioms mention, which is what puts the witness in the+carrier. Every role a tableau for `A` ever works with comes from a concept in+`A`, so this costs a producer nothing. -/+theorem ex_sound {A : List Axiom} {Γ : List Constraint} {x y r : Name} {c : Concept}+ (hmem : Constraint.conc x (.ex r c) ∈ Γ)+ (hr : r ∈ roleNames A)+ (hfresh : y ∉ branchNames Γ)+ (hfreshA : y ∉ indNames A)+ (h : BranchSat A Γ) :+ BranchSat A (Constraint.role r x y :: Constraint.conc y c :: Γ) := by+ obtain ⟨α, I, σ, hM, hag, hΓ⟩ := h+ have hx := hΓ _ hmem+ simp only [CHolds, GSat] at hx+ obtain ⟨w, hedge, hsat⟩ := hx.2+ -- `x` is on the branch and `y` is not, so they are different names and the+ -- update leaves `σ x` alone.+ have hxy : x ≠ y := by+ rintro rfl+ exact hfresh (List.mem_flatMap.mpr ⟨_, hmem, by simp [Constraint.names]⟩)+ refine ⟨α, I, fun n => if n = y then w else σ n, hM, ?_, ?_⟩+ · intro a ha+ have : a ≠ y := by rintro rfl; exact hfreshA ha+ simpa [this] using hag a ha+ intro κ hκ+ rcases hκ with _ | ⟨_, hκ⟩+ · simpa [CHolds, hxy, if_neg hxy] using hedge+ · rcases hκ with _ | ⟨_, hκ⟩+ · refine ⟨?_, ?_⟩+ · simpa using hM.rextDom r hr (σ x) w hx.1 hedge+ · simpa using hsat+ · exact branch_update_fresh hfresh hΓ _ hκ++/-! ## The ≥ rule++`x : ≥n R.C` invents `n` witnesses in one step, which is the existential rule's+freshness argument generalised from a name to a list. Two things get harder.+The witnesses must be pairwise DISTINCT, or the rule would be vacuous whenever+`n > 1`, so the rule emits the inequalities as well as the edges. And the+assignment is extended at `n` names simultaneously rather than one, so+`branch_update_fresh` has to be redone for a list of updates.+-/++/-- Every inequality between distinct members of a list, both ways round.++Both ways round on purpose: `clash_max` asks for `diff a b` for an unordered+pair, and a producer should not have to guess which orientation this file+happened to emit. -/+def pairDiffs : List Name → List Constraint+ | [] => []+ | y :: ys => ys.flatMap (fun z => [Constraint.diff y z, Constraint.diff z y]) ++ pairDiffs ys++/-- Only genuine inequalities come out. Needs `Nodup`, because the list is what+supplies `a ≠ b`. -/+theorem mem_pairDiffs {ys : List Name} (hnd : ys.Nodup) :+ ∀ κ ∈ pairDiffs ys, ∃ a ∈ ys, ∃ b ∈ ys, a ≠ b ∧ κ = Constraint.diff a b := by+ induction ys with+ | nil => intro κ hκ; simp [pairDiffs] at hκ+ | cons y ys ih =>+ obtain ⟨hy, hnd'⟩ := List.nodup_cons.mp hnd+ intro κ hκ+ rcases List.mem_append.mp hκ with hκ | hκ+ · obtain ⟨z, hz, hz'⟩ := List.mem_flatMap.mp hκ+ have hne : y ≠ z := by rintro rfl; exact hy hz+ simp only [List.mem_cons, List.not_mem_nil, or_false] at hz'+ rcases hz' with rfl | rfl+ · exact ⟨y, by simp, z, by simp [hz], hne, rfl⟩+ · exact ⟨z, by simp [hz], y, by simp, fun hc => hne hc.symm, rfl⟩+ · obtain ⟨a, ha, b, hb, hne, rfl⟩ := ih hnd' κ hκ+ exact ⟨a, by simp [ha], b, by simp [hb], hne, rfl⟩++/-- And every genuine inequality is there. This is the direction a producer+needs: having run the ≥ rule, the branch really does carry the `diff`+constraints `clash_max` will ask for. -/+theorem mem_pairDiffs_of :+ ∀ {ys : List Name}, ∀ a ∈ ys, ∀ b ∈ ys, a ≠ b → Constraint.diff a b ∈ pairDiffs ys := by+ intro ys+ induction ys with+ | nil => intro a ha; cases ha+ | cons y ys ih =>+ intro a ha b hb hab+ by_cases hay : a = y+ · subst hay+ have hb' : b ∈ ys := (List.mem_cons.mp hb).resolve_left (fun hc => hab hc.symm)+ exact List.mem_append_left _ (List.mem_flatMap.mpr ⟨b, hb', by simp⟩)+ · have ha' : a ∈ ys := (List.mem_cons.mp ha).resolve_left hay+ by_cases hby : b = y+ · subst hby+ exact List.mem_append_left _ (List.mem_flatMap.mpr ⟨a, ha', by simp⟩)+ · have hb' : b ∈ ys := (List.mem_cons.mp hb).resolve_left hby+ exact List.mem_append_right _ (ih a ha' b hb' hab)++/-- What the ≥ rule adds to the branch: an `R`-edge to each witness, the+concept at each witness, and every inequality between them. -/+def minExpand (r x : Name) (c : Concept) (ys : List Name) : List Constraint :=+ ys.map (fun y => Constraint.role r x y)+ ++ ys.map (fun y => Constraint.conc y c)+ ++ pairDiffs ys++/-- Extend an assignment at a list of names at once, pairing them off with a+list of carrier elements. Mismatched lengths fall through to the original+assignment; every use here supplies equal lengths. -/+def assignList {α : Type} (σ : Assign α) : List Name → List α → Assign α+ | y :: ys, w :: ws => fun n => if n = y then w else assignList σ ys ws n+ | _, _ => σ++/-- The list version of `branch_update_fresh`: names outside the list are+untouched, so everything already on the branch survives. -/+theorem assignList_not_mem {α : Type} (σ : Assign α) :+ ∀ (ys : List Name) (ws : List α) (n : Name), n ∉ ys → assignList σ ys ws n = σ n := by+ intro ys+ induction ys with+ | nil => intro ws n _; cases ws <;> rfl+ | cons y ys ih =>+ intro ws n hn+ cases ws with+ | nil => rfl+ | cons w ws =>+ have hne : n ≠ y := by rintro rfl; exact hn (by simp)+ simp only [assignList, if_neg hne]+ exact ih ws n (fun h => hn (by simp [h]))++/-- Each name in the list lands on an element of the list it was paired with.+This is what carries the ≥ property from the carrier elements to the witnesses. -/+theorem assignList_mem {α : Type} (σ : Assign α) :+ ∀ (ys : List Name) (ws : List α), ys.Nodup → ys.length = ws.length →+ ∀ y ∈ ys, assignList σ ys ws y ∈ ws := by+ intro ys+ induction ys with+ | nil => intro _ _ _ a ha; cases ha+ | cons y ys ih =>+ intro ws hnd hlen a ha+ cases ws with+ | nil => simp at hlen+ | cons w ws =>+ obtain ⟨hy, hnd'⟩ := List.nodup_cons.mp hnd+ simp only [List.length_cons, Nat.add_right_cancel_iff] at hlen+ by_cases hay : a = y+ · subst hay; simp [assignList]+ · have ha' : a ∈ ys := (List.mem_cons.mp ha).resolve_left hay+ simp only [assignList, if_neg hay]+ exact List.mem_cons_of_mem _ (ih ws hnd' hlen a ha')++/-- Distinct names land on distinct elements. This is what makes the emitted+inequalities true, and it is why the rule needs the witnesses to be `Nodup` on+both sides: distinct names paired with a repeated element would not satisfy the+`diff` constraints the rule itself adds. -/+theorem assignList_inj {α : Type} (σ : Assign α) :+ ∀ (ys : List Name) (ws : List α), ys.Nodup → ws.Nodup → ys.length = ws.length →+ ∀ a ∈ ys, ∀ b ∈ ys, a ≠ b → assignList σ ys ws a ≠ assignList σ ys ws b := by+ intro ys+ induction ys with+ | nil => intro _ _ _ _ a ha; cases ha+ | cons y ys ih =>+ intro ws hnd hwnd hlen a ha b hb hab+ cases ws with+ | nil => simp at hlen+ | cons w ws =>+ obtain ⟨hy, hnd'⟩ := List.nodup_cons.mp hnd+ obtain ⟨hw, hwnd'⟩ := List.nodup_cons.mp hwnd+ simp only [List.length_cons, Nat.add_right_cancel_iff] at hlen+ by_cases hay : a = y+ · subst hay+ have hb' : b ∈ ys := (List.mem_cons.mp hb).resolve_left (fun hc => hab hc.symm)+ have hbne : b ≠ a := fun hc => hab hc.symm+ simp only [assignList, if_neg hbne, if_true]+ intro hcon+ exact hw (by rw [hcon]; exact assignList_mem σ ys ws hnd' hlen b hb')+ · have ha' : a ∈ ys := (List.mem_cons.mp ha).resolve_left hay+ by_cases hby : b = y+ · subst hby+ simp only [assignList, if_neg hay, if_true]+ intro hcon+ exact hw (by rw [← hcon]; exact assignList_mem σ ys ws hnd' hlen a ha')+ · have hb' : b ∈ ys := (List.mem_cons.mp hb).resolve_left hby+ simp only [assignList, if_neg hay, if_neg hby]+ exact ih ws hnd' hwnd' hlen a ha' b hb' hab++/-- **The ≥ rule.** `x : ≥n R.C` licenses `n` pairwise distinct fresh witnesses,+each an `R`-successor of `x` satisfying `C`.++The side condition is the existential rule's, once per name, plus one more:+the names must be distinct from EACH OTHER as well as absent from the branch.+Dropping that would let a producer emit `n` copies of one name and then read+off the inequalities as a clash, which is the whole rule's soundness gone.++`hr` plays the same part it does in `ex_sound`: it is what puts the invented+witnesses in the carrier, via `GModels.rextDom`. -/+theorem min_sound {A : List Axiom} {Γ : List Constraint} {x r : Name} {c : Concept}+ {n : Nat} {ys : List Name}+ (hmem : Constraint.conc x (.min n r c) ∈ Γ)+ (hr : r ∈ roleNames A)+ (hlen : ys.length = n)+ (hnd : ys.Nodup)+ (hfresh : ∀ y ∈ ys, y ∉ branchNames Γ)+ (hfreshA : ∀ y ∈ ys, y ∉ indNames A)+ (h : BranchSat A Γ) :+ BranchSat A (minExpand r x c ys ++ Γ) := by+ obtain ⟨α, I, σ, hM, hag, hΓ⟩ := h+ have hx := hΓ _ hmem+ simp only [CHolds, GSat, GAtLeast] at hx+ obtain ⟨ws, hwnd, hwlen, hwP⟩ := hx.2+ have hlen' : ys.length = ws.length := by omega+ -- `x` is on the branch and every witness is not, so the update leaves `σ x`+ -- alone. Exactly the `x ≠ y` step of `ex_sound`, once for the whole list.+ have hxys : x ∉ ys := fun hc =>+ hfresh x hc (List.mem_flatMap.mpr ⟨_, hmem, by simp [Constraint.names]⟩)+ have hτx : assignList σ ys ws x = σ x := assignList_not_mem σ ys ws x hxys+ refine ⟨α, I, assignList σ ys ws, hM, ?_, ?_⟩+ · intro a ha+ exact (assignList_not_mem σ ys ws a (fun hc => hfreshA a hc ha)).trans (hag a ha)+ intro κ hκ+ rcases List.mem_append.mp hκ with hκ | hκ+ · rcases List.mem_append.mp hκ with hκ | hκ+ · rcases List.mem_append.mp hκ with hκ | hκ+ · obtain ⟨y, hy, rfl⟩ := List.mem_map.mp hκ+ have hw := hwP _ (assignList_mem σ ys ws hnd hlen' y hy)+ simpa [CHolds, hτx] using hw.1+ · obtain ⟨y, hy, rfl⟩ := List.mem_map.mp hκ+ have hw := hwP _ (assignList_mem σ ys ws hnd hlen' y hy)+ exact ⟨hM.rextDom r hr (σ x) _ hx.1 hw.1, hw.2⟩+ · obtain ⟨a, ha, b, hb, hne, rfl⟩ := mem_pairDiffs hnd κ hκ+ exact assignList_inj σ ys ws hnd hwnd hlen' a ha b hb hne+ · refine (cholds_congr ?_).mp (hΓ κ hκ)+ intro m hm+ have hmys : m ∉ ys := fun hc => hfresh m hc (List.mem_flatMap.mpr ⟨κ, hκ, hm⟩)+ exact (assignList_not_mem σ ys ws m hmys).symm++/-! ## The rules that read the axioms++Nothing above this point can move a fact out of `A` and onto `Γ`, and `Γ`+starts empty, so on its own the calculus above refutes nothing whatever: the+capstone theorem would be true of no derivation at all. These are the rules+that start a derivation and then keep it fed.++They are also where the agreement clause in `BranchSat` earns its place. An+axiom `a : C` is a claim about `I.ind a`; a branch entry `a : C` is a claim+about `σ a`. The clause is what makes those the same claim.+-/++/-- **The assertion rule.** `a : C` among the axioms is `a : C` on the branch.++`hind` is doing real work and is not bureaucracy. `GHolds (.inst a c)` says only+that `I.ind a` satisfies `c`, and in a general interpretation the carrier is a+PREDICATE rather than the type, so being named is not the same as being in the+domain. `CHolds` demands the domain, so the producer must point at the axiom+that supplies it. -/+theorem inst_sound {A : List Axiom} {Γ : List Constraint} {a : Name} {c : Concept}+ (hmem : Axiom.inst a c ∈ A) (hind : Axiom.indiv a ∈ A)+ (h : BranchSat A Γ) : BranchSat A (Constraint.conc a c :: Γ) := by+ obtain ⟨α, I, σ, hM, hag, hΓ⟩ := h+ have hσa : σ a = I.ind a := hag a (List.mem_flatMap.mpr ⟨_, hmem, by simp [Axiom.inds]⟩)+ refine ⟨α, I, σ, hM, hag, ?_⟩+ intro κ hκ+ rcases hκ with _ | ⟨_, hκ⟩+ · show I.dom (σ a) ∧ GSat I c (σ a)+ rw [hσa]+ exact ⟨hM.holds _ hind, hM.holds _ hmem⟩+ · exact hΓ _ hκ++/-- **The role assertion rule.** `(a, b) : R` among the axioms is an edge on the+branch. -/+theorem rel_sound {A : List Axiom} {Γ : List Constraint} {a r b : Name}+ (hmem : Axiom.rel a r b ∈ A) (h : BranchSat A Γ) :+ BranchSat A (Constraint.role r a b :: Γ) := by+ obtain ⟨α, I, σ, hM, hag, hΓ⟩ := h+ have hσa : σ a = I.ind a := hag a (List.mem_flatMap.mpr ⟨_, hmem, by simp [Axiom.inds]⟩)+ have hσb : σ b = I.ind b := hag b (List.mem_flatMap.mpr ⟨_, hmem, by simp [Axiom.inds]⟩)+ refine ⟨α, I, σ, hM, hag, ?_⟩+ intro κ hκ+ rcases hκ with _ | ⟨_, hκ⟩+ · show I.rext r (σ a) (σ b)+ rw [hσa, hσb]+ exact hM.holds _ hmem+ · exact hΓ _ hκ++/-- **The subsumption rule.** `C ⊑ D` and `x : C` give `x : D`.++This is the one that makes a TBox bite. It is also why the branch entry carries+`I.dom` alongside the concept: `GHolds (.sub c d)` is guarded by the domain, so+without it the rule could not fire. -/+theorem sub_sound {A : List Axiom} {Γ : List Constraint} {x : Name} {c d : Concept}+ (hsub : Axiom.sub c d ∈ A) (hx : Constraint.conc x c ∈ Γ) (h : BranchSat A Γ) :+ BranchSat A (Constraint.conc x d :: Γ) := by+ obtain ⟨α, I, σ, hM, hag, hΓ⟩ := h+ have hc := hΓ _ hx+ refine ⟨α, I, σ, hM, hag, ?_⟩+ intro κ hκ+ rcases hκ with _ | ⟨_, hκ⟩+ · exact ⟨hc.1, hM.holds _ hsub (σ x) hc.1 hc.2⟩+ · exact hΓ _ hκ++/-- **The domain rule.** An `R`-edge out of `x` puts `x` in `R`'s domain.++`hdom` is the branch's evidence that `x` is in the carrier, the same device+`all_sound` uses: an edge alone does not say its source is a domain element,+because `GInterp.rext` is unrestricted. -/+theorem dom_sound {A : List Axiom} {Γ : List Constraint} {x y r : Name} {c : Concept}+ (hax : Axiom.dom r c ∈ A) (hedge : Constraint.role r x y ∈ Γ)+ (hdom : ∃ e, Constraint.conc x e ∈ Γ) (h : BranchSat A Γ) :+ BranchSat A (Constraint.conc x c :: Γ) := by+ obtain ⟨α, I, σ, hM, hag, hΓ⟩ := h+ obtain ⟨e, he⟩ := hdom+ have hxd := (hΓ _ he).1+ have hE := hΓ _ hedge+ refine ⟨α, I, σ, hM, hag, ?_⟩+ intro κ hκ+ rcases hκ with _ | ⟨_, hκ⟩+ · exact ⟨hxd, hM.holds _ hax (σ x) hxd ⟨σ y, hE⟩⟩+ · exact hΓ _ hκ++/-- **The range rule.** An `R`-edge into `y` puts `y` in `R`'s range.++`hr` supplies `I.dom (σ y)` through `GModels.rextDom`, exactly as it does for+the witnesses the existential and ≥ rules invent. -/+theorem rng_sound {A : List Axiom} {Γ : List Constraint} {x y r : Name} {c : Concept}+ (hax : Axiom.rng r c ∈ A) (hr : r ∈ roleNames A)+ (hedge : Constraint.role r x y ∈ Γ)+ (hdom : ∃ e, Constraint.conc x e ∈ Γ) (h : BranchSat A Γ) :+ BranchSat A (Constraint.conc y c :: Γ) := by+ obtain ⟨α, I, σ, hM, hag, hΓ⟩ := h+ obtain ⟨e, he⟩ := hdom+ have hxd := (hΓ _ he).1+ have hE := hΓ _ hedge+ refine ⟨α, I, σ, hM, hag, ?_⟩+ intro κ hκ+ rcases hκ with _ | ⟨_, hκ⟩+ · exact ⟨hM.rextDom r hr (σ x) (σ y) hxd hE, hM.holds _ hax (σ x) hxd (σ y) hE⟩+ · exact hΓ _ hκ++/-- **The role hierarchy rule.** `R ⊑ S` turns an `R`-edge into an `S`-edge. -/+theorem subrole_sound {A : List Axiom} {Γ : List Constraint} {x y r t : Name}+ (hax : Axiom.subrole r t ∈ A) (hedge : Constraint.role r x y ∈ Γ)+ (hdom : ∃ e, Constraint.conc x e ∈ Γ) (h : BranchSat A Γ) :+ BranchSat A (Constraint.role t x y :: Γ) := by+ obtain ⟨α, I, σ, hM, hag, hΓ⟩ := h+ obtain ⟨e, he⟩ := hdom+ have hxd := (hΓ _ he).1+ have hE := hΓ _ hedge+ refine ⟨α, I, σ, hM, hag, ?_⟩+ intro κ hκ+ rcases hκ with _ | ⟨_, hκ⟩+ · exact hM.holds _ hax (σ x) hxd (σ y) hE+ · exact hΓ _ hκ++/-- **The witness rule.** A non-emptiness axiom names a fresh individual for the+concept it asserts.++This is the entry point for a satisfiability question. "Is `C` satisfiable under+`T`?" is asked by putting `.nonempty C` into the axioms, and refuting it is what+this rule makes reachable from the empty branch. -/+theorem nonempty_sound {A : List Axiom} {Γ : List Constraint} {y : Name} {c : Concept}+ (hax : Axiom.nonempty c ∈ A)+ (hfresh : y ∉ branchNames Γ) (hfreshA : y ∉ indNames A)+ (h : BranchSat A Γ) : BranchSat A (Constraint.conc y c :: Γ) := by+ obtain ⟨α, I, σ, hM, hag, hΓ⟩ := h+ obtain ⟨w, hwd, hwc⟩ := hM.holds _ hax+ refine ⟨α, I, fun n => if n = y then w else σ n, hM, ?_, ?_⟩+ · intro a ha+ have : a ≠ y := by rintro rfl; exact hfreshA ha+ simpa [this] using hag a ha+ · intro κ hκ+ rcases hκ with _ | ⟨_, hκ⟩+ · exact ⟨by simpa using hwd, by simpa using hwc⟩+ · exact branch_update_fresh hfresh hΓ _ hκ++/-! ## Clashes++A clash is a branch that no interpretation can satisfy, and each is a small+lemma rather than an entry in a list the checker trusts. -/++/-- `x : ⊥`. -/+theorem clash_bot {A : List Axiom} {Γ : List Constraint} {x : Name}+ (h : Constraint.conc x .bot ∈ Γ) : ¬ BranchSat A Γ := by+ rintro ⟨α, I, σ, _, _, hΓ⟩+ exact (hΓ _ h).2++/-- `x : C` and `x : ¬C`. -/+theorem clash_neg {A : List Axiom} {Γ : List Constraint} {x : Name} {c : Concept}+ (hp : Constraint.conc x c ∈ Γ) (hn : Constraint.conc x (.neg c) ∈ Γ) :+ ¬ BranchSat A Γ := by+ rintro ⟨α, I, σ, _, _, hΓ⟩+ have hpos := (hΓ _ hp).2+ have hneg := (hΓ _ hn).2+ simp only [GSat] at hneg+ exact hneg hpos++/-- `Nodup` survives a map that is injective ON THE LIST. Core Lean carries the+globally injective version; the branch only ever gives injectivity where it has+asserted `diff`, so this is the shape needed. -/+theorem nodup_map_of_injOn {α β : Type} {f : α → β} :+ ∀ {l : List α}, l.Nodup → (∀ a ∈ l, ∀ b ∈ l, f a = f b → a = b) → (l.map f).Nodup+ | [], _, _ => by simp+ | a :: t, hnd, hinj => by+ rw [List.nodup_cons] at hnd+ refine List.nodup_cons.mpr ⟨?_, ?_⟩+ · intro hmem+ obtain ⟨b, hb, hfb⟩ := List.mem_map.mp hmem+ have : a = b := hinj a (by simp) b (by simp [hb]) hfb.symm+ exact hnd.1 (this ▸ hb)+ · exact nodup_map_of_injOn hnd.2+ (fun p hp q hq h => hinj p (by simp [hp]) q (by simp [hq]) h)++/-- **The cardinality clash.** `x : ≤n R.C` with `n+1` pairwise distinct+`R`-successors all in `C`.++This is where the ≤ restriction earns its place in a REFUTATION, and it is a+clash rather than a rule. The merging rule that identifies two successors is a+COMPLETENESS device: a model search needs it to collapse a branch into a model.+A refutation never needs to build a model, so it never needs to merge, exactly+as it never needs blocking. What it needs is the observation that `n+1`+distinct witnesses contradict a bound of `n`, and that is this lemma.++The distinctness comes from `diff` constraints on the branch rather than from+the names differing, because two different names may denote the same element+unless the branch has said otherwise. -/+theorem clash_max {A : List Axiom} {Γ : List Constraint} {x r : Name} {c : Concept}+ {n : Nat} {ys : List Name}+ (hmax : Constraint.conc x (.max n r c) ∈ Γ)+ (hlen : ys.length = n + 1)+ (hnd : ys.Nodup)+ (hdiff : ∀ a ∈ ys, ∀ b ∈ ys, a ≠ b → Constraint.diff a b ∈ Γ)+ (hedge : ∀ y ∈ ys, Constraint.role r x y ∈ Γ)+ (hc : ∀ y ∈ ys, Constraint.conc y c ∈ Γ) :+ ¬ BranchSat A Γ := by+ rintro ⟨α, I, σ, _, _, hΓ⟩+ have hx := hΓ _ hmax+ simp only [CHolds, GSat, GAtMost] at hx+ -- The images are distinct, because the branch asserted the names differ.+ have hmapnd : (ys.map σ).Nodup := by+ refine nodup_map_of_injOn hnd ?_+ intro a ha b hb hab+ by_cases hne : a = b+ · exact hne+ · exact absurd hab (hΓ _ (hdiff a ha b hb hne))+ have hmem : ∀ z ∈ ys.map σ, I.rext r (σ x) z ∧ GSat I c z := by+ intro z hz+ obtain ⟨y, hy, rfl⟩ := List.mem_map.mp hz+ exact ⟨hΓ _ (hedge y hy), (hΓ _ (hc y hy)).2⟩+ have := hx.2 (ys.map σ) hmapnd hmem+ simp only [List.length_map, hlen] at this+ omega++/-- **The bound clash.** `x : ≥m R.C` against `x : ≤n R.C` with `n < m`.++Cheaper than `clash_max` and worth having separately: it needs no witnesses on+the branch at all, so a producer can close this without ever running the ≥+rule. The two bounds contradict each other directly, because the list the lower+bound promises is itself a list the upper bound must measure. -/+theorem clash_minmax {A : List Axiom} {Γ : List Constraint} {x r : Name} {c : Concept}+ {m n : Nat}+ (hmin : Constraint.conc x (.min m r c) ∈ Γ)+ (hmax : Constraint.conc x (.max n r c) ∈ Γ)+ (hlt : n < m) : ¬ BranchSat A Γ := by+ rintro ⟨α, I, σ, _, _, hΓ⟩+ have hge := (hΓ _ hmin).2+ have hle := (hΓ _ hmax).2+ simp only [GSat, GAtLeast] at hge+ simp only [GSat, GAtMost] at hle+ obtain ⟨ys, hnd, hlen, hmem⟩ := hge+ have := hle ys hnd hmem+ omega++/-- **The disjointness clash.** `C ⊓ D ⊑ ⊥` with an `x` in both.++Worth a rule of its own rather than a translation to `C ⊑ ¬D`, even though the+two say the same thing about every interpretation. The certificate has to cite+an axiom that is IN the axiom file, and the axiom file is a transcription of the+ontology. Rewriting disjointness on the way in would make the certificate be+about a different axiom set from the one the reader was handed. -/+theorem clash_disjoint {A : List Axiom} {Γ : List Constraint} {x : Name} {c d : Concept}+ (hax : Axiom.disjoint c d ∈ A)+ (hc : Constraint.conc x c ∈ Γ) (hd : Constraint.conc x d ∈ Γ) : ¬ BranchSat A Γ := by+ rintro ⟨α, I, σ, hM, _, hΓ⟩+ exact hM.holds _ hax (σ x) (hΓ _ hc).1 ⟨(hΓ _ hc).2, (hΓ _ hd).2⟩++/-- `x ≠ x`. The inequality rule for number restrictions introduces these, and+a branch that has asserted an individual differs from itself is closed. -/+theorem clash_diff {A : List Axiom} {Γ : List Constraint} {x : Name}+ (h : Constraint.diff x x ∈ Γ) : ¬ BranchSat A Γ := by+ rintro ⟨α, I, σ, _, _, hΓ⟩+ exact (hΓ _ h) rfl++/-! ## The certificate, and what a checked one buys++A closed tableau is an inductive object: each constructor is one rule+application or one clash, and the recursive arguments are the branches it+produced. That is the shape a producer emits and a checker replays, and it is+finite by construction, which is the whole reason no blocking argument appears+anywhere in this file. -/++/-- `Closed A Γ` is a closed tableau for the branch `Γ` under the axioms `A`.++Each constructor carries the side conditions its rule needs, so an ill-formed+certificate is not a `Closed` at all and there is nothing for the checker to+trust beyond the constructors themselves. -/+inductive Closed (A : List Axiom) : List Constraint → Prop where+ | bot {Γ x} (h : Constraint.conc x .bot ∈ Γ) : Closed A Γ+ | neg {Γ x c} (hp : Constraint.conc x c ∈ Γ)+ (hn : Constraint.conc x (.neg c) ∈ Γ) : Closed A Γ+ | diff {Γ x} (h : Constraint.diff x x ∈ Γ) : Closed A Γ+ /-- Disjointness: an individual in two classes the ontology declares apart. -/+ | disjointClash {Γ : List Constraint} {x : Name} {c d : Concept}+ (hax : Axiom.disjoint c d ∈ A)+ (hc : Constraint.conc x c ∈ Γ) (hd : Constraint.conc x d ∈ Γ) : Closed A Γ+ | andR {Γ x c d} (hmem : Constraint.conc x (.and c d) ∈ Γ)+ (next : Closed A (Constraint.conc x c :: Constraint.conc x d :: Γ)) : Closed A Γ+ | allR {Γ x y r c} (hall : Constraint.conc x (.all r c) ∈ Γ)+ (hedge : Constraint.role r x y ∈ Γ) (hr : r ∈ roleNames A)+ (next : Closed A (Constraint.conc y c :: Γ)) : Closed A Γ+ | orR {Γ x c d} (hmem : Constraint.conc x (.or c d) ∈ Γ)+ (left : Closed A (Constraint.conc x c :: Γ))+ (right : Closed A (Constraint.conc x d :: Γ)) : Closed A Γ+ /-- The existential rule. `hfresh` is what keeps it sound and `hr` is what+ puts the invented witness in the carrier. -/+ | exR {Γ : List Constraint} {x y r : Name} {c : Concept} (hmem : Constraint.conc x (.ex r c) ∈ Γ)+ (hr : r ∈ roleNames A)+ (hfresh : y ∉ branchNames Γ) (hfreshA : y ∉ indNames A)+ (next : Closed A (Constraint.role r x y :: Constraint.conc y c :: Γ)) : Closed A Γ+ /-- Assertion: an axiom `a : C` becomes a branch entry. `hind` is what puts+ `a` in the carrier. -/+ | instR {Γ : List Constraint} {a : Name} {c : Concept}+ (hmem : Axiom.inst a c ∈ A) (hind : Axiom.indiv a ∈ A)+ (next : Closed A (Constraint.conc a c :: Γ)) : Closed A Γ+ /-- Role assertion: an axiom `(a, b) : R` becomes an edge. -/+ | relR {Γ : List Constraint} {a r b : Name} (hmem : Axiom.rel a r b ∈ A)+ (next : Closed A (Constraint.role r a b :: Γ)) : Closed A Γ+ /-- Subsumption: the rule that makes a TBox bite. -/+ | subR {Γ : List Constraint} {x : Name} {c d : Concept}+ (hsub : Axiom.sub c d ∈ A) (hx : Constraint.conc x c ∈ Γ)+ (next : Closed A (Constraint.conc x d :: Γ)) : Closed A Γ+ /-- Domain. -/+ | domR {Γ : List Constraint} {x y r : Name} {c : Concept}+ (hax : Axiom.dom r c ∈ A) (hedge : Constraint.role r x y ∈ Γ)+ (hdom : ∃ e, Constraint.conc x e ∈ Γ)+ (next : Closed A (Constraint.conc x c :: Γ)) : Closed A Γ+ /-- Range. -/+ | rngR {Γ : List Constraint} {x y r : Name} {c : Concept}+ (hax : Axiom.rng r c ∈ A) (hr : r ∈ roleNames A)+ (hedge : Constraint.role r x y ∈ Γ) (hdom : ∃ e, Constraint.conc x e ∈ Γ)+ (next : Closed A (Constraint.conc y c :: Γ)) : Closed A Γ+ /-- Role hierarchy. -/+ | subroleR {Γ : List Constraint} {x y r t : Name}+ (hax : Axiom.subrole r t ∈ A) (hedge : Constraint.role r x y ∈ Γ)+ (hdom : ∃ e, Constraint.conc x e ∈ Γ)+ (next : Closed A (Constraint.role t x y :: Γ)) : Closed A Γ+ /-- Non-emptiness: the entry point from the EMPTY branch, and so the rule a+ satisfiability question is asked through. -/+ | nonemptyR {Γ : List Constraint} {y : Name} {c : Concept}+ (hax : Axiom.nonempty c ∈ A)+ (hfresh : y ∉ branchNames Γ) (hfreshA : y ∉ indNames A)+ (next : Closed A (Constraint.conc y c :: Γ)) : Closed A Γ+ /-- The ≥ rule. `hfresh` and `hnd` together are the side condition: the+ witnesses are new to the branch AND distinct from each other. -/+ | minR {Γ : List Constraint} {x r : Name} {c : Concept} {n : Nat} {ys : List Name}+ (hmem : Constraint.conc x (.min n r c) ∈ Γ)+ (hr : r ∈ roleNames A)+ (hlen : ys.length = n) (hnd : ys.Nodup)+ (hfresh : ∀ y ∈ ys, y ∉ branchNames Γ) (hfreshA : ∀ y ∈ ys, y ∉ indNames A)+ (next : Closed A (minExpand r x c ys ++ Γ)) : Closed A Γ+ /-- The bound clash: a lower bound above an upper bound on the same role and+ concept. Needs no witnesses, so it closes without running the ≥ rule. -/+ | minmaxClash {Γ : List Constraint} {x r : Name} {c : Concept} {m n : Nat}+ (hmin : Constraint.conc x (.min m r c) ∈ Γ)+ (hmax : Constraint.conc x (.max n r c) ∈ Γ)+ (hlt : n < m) : Closed A Γ+ /-- The cardinality clash: `n+1` pairwise distinct successors against a+ bound of `n`. A leaf, not a rule, which is why no merging appears here. -/+ | maxClash {Γ : List Constraint} {x r : Name} {c : Concept} {n : Nat} {ys : List Name} (hmax : Constraint.conc x (.max n r c) ∈ Γ)+ (hlen : ys.length = n + 1) (hnd : ys.Nodup)+ (hdiff : ∀ a ∈ ys, ∀ b ∈ ys, a ≠ b → Constraint.diff a b ∈ Γ)+ (hedge : ∀ y ∈ ys, Constraint.role r x y ∈ Γ)+ (hc : ∀ y ∈ ys, Constraint.conc y c ∈ Γ) : Closed A Γ++/-- **A closed tableau is a refutation.**++By induction on the tableau. Every clash constructor is a branch nothing can+satisfy; every rule constructor preserves satisfiability downward, so an+unsatisfiable child forces an unsatisfiable parent. The disjunction case is the+only one with two children and it needs both, which is exactly why a tableau is+a tree rather than a list. -/+theorem closed_sound {A : List Axiom} {Γ : List Constraint} (h : Closed A Γ) :+ ¬ BranchSat A Γ := by+ induction h with+ | bot hb => exact clash_bot hb+ | neg hp hn => exact clash_neg hp hn+ | diff hd => exact clash_diff hd+ | disjointClash hax hc hd => exact clash_disjoint hax hc hd+ | andR hmem _ ih => exact fun hs => ih (and_sound hmem hs)+ | allR hall hedge hr _ ih => exact fun hs => ih (all_sound hall hedge hr hs)+ | orR hmem _ _ ihl ihr =>+ intro hs+ rcases or_sound hmem hs with hl | hr+ · exact ihl hl+ · exact ihr hr+ | instR hmem hind _ ih => exact fun hs => ih (inst_sound hmem hind hs)+ | relR hmem _ ih => exact fun hs => ih (rel_sound hmem hs)+ | subR hsub hx _ ih => exact fun hs => ih (sub_sound hsub hx hs)+ | domR hax hedge hdom _ ih => exact fun hs => ih (dom_sound hax hedge hdom hs)+ | rngR hax hr hedge hdom _ ih => exact fun hs => ih (rng_sound hax hr hedge hdom hs)+ | subroleR hax hedge hdom _ ih => exact fun hs => ih (subrole_sound hax hedge hdom hs)+ | nonemptyR hax hfresh hfreshA _ ih =>+ exact fun hs => ih (nonempty_sound hax hfresh hfreshA hs)+ | exR hmem hr hfresh hfreshA _ ih => exact fun hs => ih (ex_sound hmem hr hfresh hfreshA hs)+ | minR hmem hr hlen hnd hfresh hfreshA _ ih =>+ exact fun hs => ih (min_sound hmem hr hlen hnd hfresh hfreshA hs)+ | minmaxClash hmin hmax hlt => exact clash_minmax hmin hmax hlt+ | maxClash hmax hlen hnd hdiff hedge hc => exact clash_max hmax hlen hnd hdiff hedge hc++/-- **A closed tableau on the empty branch means the axioms have no model.**++This is the statement `oo-refute` would print for a description-logic+refutation, and the one `DlMain.lean` currently says is not produced. It is+`Unsatisfiable` from `Dl/General.lean`, so it quantifies over every carrier and+is not the weaker claim that no FINITE model exists.++The assignment is the only thing needing construction: `BranchSat` carries one+and the empty branch constrains it nowhere, so any constant map into the+carrier will do, and `GModels.nonempty` is what says there is something to map+to. -/+theorem unsatisfiable_of_closed {A : List Axiom} (h : Closed A []) : Unsatisfiable A := by+ intro α I hM+ refine closed_sound h ⟨α, I, I.ind, hM, fun _ _ => rfl, ?_⟩+ intro κ hκ+ exact absurd hκ (List.not_mem_nil)++/-! ## Axioms, pinned++The same footprint the rest of the directory carries. A `sorry` anywhere above,+or a `native_decide` smuggled into a rule, changes one of these lines and the+build fails. -/++/-- info: 'Dl.closed_sound' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms closed_sound++/-- info: 'Dl.unsatisfiable_of_closed' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms unsatisfiable_of_closed++/-- info: 'Dl.min_sound' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms min_sound++end Dldiff --git a/lean/Dl/TableauDemo.lean b/lean/Dl/TableauDemo.leannew file mode 100644index 00000000..57934098--- /dev/null+++ b/lean/Dl/TableauDemo.lean@@ -0,0 +1,181 @@+import Dl.Refute++/-!+# The calculus refutes something++`Dl/Tableau.lean` proves that a closed tableau is a refutation. That theorem was+true of nothing at all until the axiom rules went in: every rule read from the+branch, the branch starts empty, so no derivation could begin and+`Closed A []` had no inhabitants. This file is the gate on that. It builds+closed tableaux by hand and reads `Unsatisfiable` off them, so if the calculus+ever goes vacuous again, `lake build` fails here rather than passing quietly.++Two derivations, chosen to exercise the two halves that were missing:++* `contradictory_unsat` runs the assertion, subsumption and clash rules. It is+ the smallest thing a TBox can get wrong.+* `cardinality_unsat` runs the ≥ rule, which invents two distinct witnesses at+ once, then closes on the ≤ bound that those witnesses violate. Nothing else+ in the file exercises `minExpand`, `pairDiffs` or `assignList`.+-/+namespace Dl.Demo+open Dl++/-! ## `C ⊑ D`, `C ⊑ ¬D`, and `C` is not empty -/++def A₁ : List Axiom :=+ [ .nonempty (.atom "C"), .sub (.atom "C") (.atom "D"),+ .sub (.atom "C") (.neg (.atom "D")) ]++theorem closed₁ : Closed A₁ [] := by+ refine .nonemptyR (c := .atom "C") (y := "w") (by simp [A₁]) (by simp [branchNames]) (by decide) ?_+ refine .subR (c := .atom "C") (d := .atom "D") (x := "w") (by simp [A₁]) (by simp) ?_+ refine .subR (c := .atom "C") (d := .neg (.atom "D")) (x := "w") (by simp [A₁]) (by simp) ?_+ exact .neg (c := .atom "D") (x := "w") (by simp) (by simp)++theorem contradictory_unsat : Unsatisfiable A₁ := unsatisfiable_of_closed closed₁++/-! ## `≥2 R.C` against `≤1 R.D`, with `C ⊑ D`++The ≥ rule invents `u` and `v`, distinct and both `C`. Subsumption lifts each to+`D`. Then `u` and `v` are two distinct `R`-successors in `D` where at most one+was allowed, which is `clash_max` with `n = 1`. This is the derivation that+merging would otherwise be needed for, and it does not need merging: the bound+enters as a clash rather than as a rule. -/++def A₂ : List Axiom :=+ [ .nonempty (.and (.min 2 "R" (.atom "C")) (.max 1 "R" (.atom "D"))),+ .sub (.atom "C") (.atom "D") ]++theorem closed₂ : Closed A₂ [] := by+ refine .nonemptyR (c := .and (.min 2 "R" (.atom "C")) (.max 1 "R" (.atom "D")))+ (y := "x") (by simp [A₂]) (by simp [branchNames]) (by decide) ?_+ refine .andR (x := "x") (c := .min 2 "R" (.atom "C")) (d := .max 1 "R" (.atom "D"))+ (by simp) ?_+ refine .minR (x := "x") (r := "R") (c := .atom "C") (n := 2) (ys := ["u", "v"])+ (by simp) (by simp [roleNames, A₂, Axiom.roles, Concept.roles])+ (by simp) (by decide) (by decide) (by decide) ?_+ refine .subR (c := .atom "C") (d := .atom "D") (x := "u") (by simp [A₂])+ (by simp [minExpand, pairDiffs]) ?_+ refine .subR (c := .atom "C") (d := .atom "D") (x := "v") (by simp [A₂])+ (by simp [minExpand, pairDiffs]) ?_+ exact .maxClash (x := "x") (r := "R") (c := .atom "D") (n := 1) (ys := ["u", "v"])+ (by simp [minExpand, pairDiffs]) (by simp) (by decide)+ (by decide) (by simp [minExpand, pairDiffs]) (by simp)++theorem cardinality_unsat : Unsatisfiable A₂ := unsatisfiable_of_closed closed₂++/-! ## The negative control++A gate that cannot fail is not a gate. This says the format cannot certify a+satisfiable ontology: hand it one that HAS a model and no closed tableau exists+for it, whatever a producer claims. It follows from soundness alone and needs no+completeness argument, which is the asymmetry the whole design rests on. -/+theorem no_closed_of_satisfiable {A : List Axiom} (h : Satisfiable A) :+ Closed A [] → False :=+ fun hc => no_finite_model_of_unsatisfiable (unsatisfiable_of_closed hc) h++/-! ## The same two derivations, as certificates a producer could send++Above, the tableaux are Lean terms built by hand. Here they are `Cert` values,+which is the form `src/tableaux.rs` writes and `Dl/Parse.lean` reads. The point+of repeating them is that `check` decides every side condition itself, so these+lines are a test of the CHECKER rather than of the calculus. -/++def cert₁ : Cert :=+ .nonemptyS "w" (.atom "C") <|+ .subS "w" (.atom "C") (.atom "D") <|+ .subS "w" (.atom "C") (.neg (.atom "D")) <|+ .negC "w" (.atom "D")++/-- info: true -/+#guard_msgs in #eval check A₁ cert₁ []++theorem contradictory_unsat' : Unsatisfiable A₁ := unsatisfiable_of_check (t := cert₁) (by decide)++def cert₂ : Cert :=+ .nonemptyS "x" (.and (.min 2 "R" (.atom "C")) (.max 1 "R" (.atom "D"))) <|+ .andS "x" (.min 2 "R" (.atom "C")) (.max 1 "R" (.atom "D")) <|+ .minS "x" "R" (.atom "C") 2 ["u", "v"] <|+ .subS "u" (.atom "C") (.atom "D") <|+ .subS "v" (.atom "C") (.atom "D") <|+ .maxC "x" "R" (.atom "D") 1 ["u", "v"]++/-- info: true -/+#guard_msgs in #eval check A₂ cert₂ []++theorem cardinality_unsat' : Unsatisfiable A₂ := unsatisfiable_of_check (t := cert₂) (by decide)++/-! ## Forgeries++A checker that cannot reject is not a checker. Each of these is one of the two+certificates above with a single thing changed, and each change is one a buggy+or a dishonest producer would plausibly make.++-- The two witnesses are the same name, so they are not two witnesses. This is+-- the forgery the ≥ rule's `Nodup` side condition exists to stop; without it+-- the leaf below would read one individual as a crowd.+-/++/-- info: false -/+#guard_msgs in+#eval check A₂ (.nonemptyS "x" (.and (.min 2 "R" (.atom "C")) (.max 1 "R" (.atom "D"))) <|+ .andS "x" (.min 2 "R" (.atom "C")) (.max 1 "R" (.atom "D")) <|+ .minS "x" "R" (.atom "C") 2 ["u", "u"] <|+ .maxC "x" "R" (.atom "C") 1 ["u", "u"]) []++-- A witness reuses a name the branch already constrains. Freshness is the whole+-- of the ∃ and ≥ rules' soundness, and `x` is on the branch already.+/-- info: false -/+#guard_msgs in+#eval check A₂ (.nonemptyS "x" (.and (.min 2 "R" (.atom "C")) (.max 1 "R" (.atom "D"))) <|+ .andS "x" (.min 2 "R" (.atom "C")) (.max 1 "R" (.atom "D")) <|+ .minS "x" "R" (.atom "C") 2 ["x", "v"] <|+ .maxC "x" "R" (.atom "D") 1 ["x", "v"]) []++-- The bound is claimed tighter than the axiom says: `≤1` is in the ontology and+-- `≤0` is in the certificate, so the leaf cites a constraint the branch lacks.+/-- info: false -/+#guard_msgs in+#eval check A₂ (.nonemptyS "x" (.and (.min 2 "R" (.atom "C")) (.max 1 "R" (.atom "D"))) <|+ .andS "x" (.min 2 "R" (.atom "C")) (.max 1 "R" (.atom "D")) <|+ .minS "x" "R" (.atom "C") 2 ["u", "v"] <|+ .maxC "x" "R" (.atom "D") 0 ["u"]) []++-- The subsumption steps cite an axiom nobody asserted. This is the laundering+-- move: a derivation that reads correctly resting on a premise off the books.+/-- info: false -/+#guard_msgs in+#eval check A₁ (.nonemptyS "w" (.atom "C") <|+ .subS "w" (.atom "C") (.atom "E") <|+ .subS "w" (.atom "C") (.neg (.atom "E")) <|+ .negC "w" (.atom "E")) []++-- And the empty gesture: a bare clash claimed on a branch that carries nothing.+/-- info: false -/+#guard_msgs in+#eval check A₁ (.botC "w") []++/-! ## Axioms, pinned++These are the evidence that the calculus is not vacuous and that the checker+agrees with it, so they are the lines that matter most: a footprint change here+means a refutation stopped being a refutation. -/++/-- info: 'Dl.Demo.contradictory_unsat' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms contradictory_unsat++/-- info: 'Dl.Demo.cardinality_unsat' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms cardinality_unsat++/-- info: 'Dl.Demo.contradictory_unsat'' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms contradictory_unsat'++/-- info: 'Dl.Demo.cardinality_unsat'' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms cardinality_unsat'++end Dl.Demodiff --git a/lean/DlMain.lean b/lean/DlMain.leanindex fdf2ba9f..1712842e 100644--- a/lean/DlMain.lean+++ b/lean/DlMain.lean@@ -17,10 +17,13 @@ Exit codes, matching the convention `oo-cert` uses: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 UNSATISFIABILITY. That answer has its own certificate and its own+ checker, `oo-dlrefute`, and the two must never be read for one another. This header used+ to say certifying it "needs a closed tableau with its blocking argument". Half of that+ was right. A closed tableau is what it needs. Blocking is a COMPLETENESS device, there so+ that a SEARCH for a model terminates, and a refutation never needs one: a closed tableau+ is already a finite tree whose every branch ended in a clash. `lean/Dl/Tableau.lean` is+ the proof and it carries no blocking argument anywhere;* 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;diff --git a/lean/DlRefuteMain.lean b/lean/DlRefuteMain.leannew file mode 100644index 00000000..f7259550--- /dev/null+++ b/lean/DlRefuteMain.lean@@ -0,0 +1,149 @@+import Dl.All++/-!+`oo-dlrefute AXIOMS.tsv REFUTATION.cert`++Reads an axiom set and a closed tableau, replays the tableau, and prints one+JSON object.++Exit codes, matching the convention `oo-cert` and `oo-dlmodel` use:++* `0` the tableau is closed, so the axiom set has NO MODEL, of any size, finite+ or infinite. The statement covering that is `Dl.unsatisfiable_of_check`, and+ `Dl.no_model_of_check` is the same verdict in the finite form the rest of the+ repository states its answers in.+* `1` the tableau is not closed. That is a statement about the certificate and+ NOT about the ontology: a producer can fail to find a refutation that exists,+ and this exit code never means the ontology is consistent.+* `2` a file could not be read or parsed. No verdict either way.++This is the other half of `oo-dlmodel`. That one certifies SATISFIABILITY by+exhibiting a model; this one certifies UNSATISFIABILITY by exhibiting a+refutation, and the two are asymmetric on purpose. A model is a finite object+that can be checked by evaluation. A refutation cannot be, because the thing it+denies is a claim about every interpretation including the infinite ones, which+is why `Dl/General.lean` exists at all: the finite semantics literally cannot+state the conclusion.++What exit 0 does NOT say:++* it says nothing about whether `AXIOMS.tsv` is your 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 two+ files;+* it says nothing about transitive, symmetric, inverse or inverse-functional+ roles. The calculus has no rules for them, so an ontology inconsistent only+ through those cannot be refuted here. The emitter declines rather than+ guessing, and "no certificate" is not a verdict.++The diagnostic that names the failing step is unverified and runs only after the+verified checker has already said no. It restates the side conditions a second+time, so it can be wrong about WHICH step failed; it cannot be wrong about THAT+one did, because the verified checker decided that.+-/+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 ++ "\""++def stepKind : Cert → String+ | .botC .. => "bot-clash"+ | .negC .. => "negation-clash"+ | .diffC .. => "inequality-clash"+ | .disjC .. => "disjointness-clash"+ | .minmaxC .. => "bound-clash"+ | .maxC .. => "cardinality-clash"+ | .instS .. => "assertion"+ | .relS .. => "role-assertion"+ | .subS .. => "subsumption"+ | .domS .. => "domain"+ | .rngS .. => "range"+ | .subroleS .. => "role-hierarchy"+ | .nonemptyS .. => "non-emptiness"+ | .andS .. => "conjunction"+ | .allS .. => "universal"+ | .exS .. => "existential"+ | .minS .. => "at-least"+ | .orS .. => "disjunction"++def steps : Cert → Nat+ | .botC .. | .negC .. | .diffC .. | .disjC .. | .minmaxC .. | .maxC .. => 1+ | .instS _ _ k | .relS _ _ _ k | .subS _ _ _ k | .domS _ _ _ _ k+ | .rngS _ _ _ _ k | .subroleS _ _ _ _ k | .nonemptyS _ _ k | .andS _ _ _ k+ | .allS _ _ _ _ k | .exS _ _ _ _ k | .minS _ _ _ _ _ k => 1 + steps k+ | .orS _ _ _ l r => 1 + steps l + steps r++/-- The children of a step, each with the branch it is checked against. Mirrors+`Dl.check` and is not proved to; it is read only by the diagnostic. -/+def children : Cert → List Constraint → List (Cert × List Constraint)+ | .instS a c k, Γ => [(k, Constraint.conc a c :: Γ)]+ | .relS a r b k, Γ => [(k, Constraint.role r a b :: Γ)]+ | .subS x _ d k, Γ => [(k, Constraint.conc x d :: Γ)]+ | .domS x _ _ c k, Γ => [(k, Constraint.conc x c :: Γ)]+ | .rngS _ y _ c k, Γ => [(k, Constraint.conc y c :: Γ)]+ | .subroleS x y _ t k, Γ => [(k, Constraint.role t x y :: Γ)]+ | .nonemptyS y c k, Γ => [(k, Constraint.conc y c :: Γ)]+ | .andS x c d k, Γ => [(k, Constraint.conc x c :: Constraint.conc x d :: Γ)]+ | .allS _ y _ c k, Γ => [(k, Constraint.conc y c :: Γ)]+ | .exS x y r c k, Γ => [(k, Constraint.role r x y :: Constraint.conc y c :: Γ)]+ | .minS x r c _ ys k, Γ => [(k, minExpand r x c ys ++ Γ)]+ | .orS x c d l r, Γ => [(l, Constraint.conc x c :: Γ), (r, Constraint.conc x d :: Γ)]+ | _, _ => []++/-- Descend to the shallowest step whose own side conditions fail, or to the+shallowest step none of whose children check. Fuel is the tree size. -/+def firstBad (A : List Axiom) : Nat → Cert → List Constraint → String+ | 0, t, _ => stepKind t+ | fuel + 1, t, Γ =>+ match (children t Γ).find? (fun p => !check A p.1 p.2) with+ | some p => firstBad A fuel p.1 p.2+ | none => stepKind t++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 cPath : String) : IO UInt32 := do+ let axTxt ← match ← readOrFail axPath with+ | .ok s => pure s+ | .error c => return c+ let cTxt ← match ← readOrFail cPath with+ | .ok s => pure s+ | .error c => return c+ match Parse.parseAxioms axTxt, Parse.parseCert cTxt with+ | .ok A, .ok t =>+ if check A t [] then+ IO.println ("{\"ok\":true,\"axioms\":" ++ toString A.length +++ ",\"steps\":" ++ toString (steps t) +++ ",\"verdict\":\"unsatisfiable\"" +++ ",\"theorem\":\"Dl.unsatisfiable_of_check\"}")+ return 0+ else+ IO.println ("{\"ok\":false,\"axioms\":" ++ toString A.length +++ ",\"steps\":" ++ toString (steps t) +++ ",\"first_rejected\":" ++ jsonStr (firstBad A (steps t) t []) +++ ",\"note\":\"a rejected refutation says nothing about the ontology\"}")+ 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, c] => run a c+ | _ =>+ IO.eprintln "usage: oo-dlrefute AXIOMS.tsv REFUTATION.cert"+ return 2diff --git a/lean/lakefile.toml b/lean/lakefile.tomlindex 356ed2b1..de50bd91 100644--- a/lean/lakefile.toml+++ b/lean/lakefile.toml@@ -1,6 +1,6 @@name = "oocert"version = "0.1.0"-defaultTargets = ["OOCert", "oo-cert", "oo-horn", "Shacl", "oo-shacl", "oo-refute", "Dl", "oo-dlmodel", "Fol", "oo-folmodel", "Institution"]+defaultTargets = ["OOCert", "oo-cert", "oo-horn", "Shacl", "oo-shacl", "oo-refute", "Dl", "oo-dlmodel", "oo-dlrefute", "Fol", "oo-folmodel", "Institution"]# 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@@ -51,6 +51,16 @@ name = "Dl"name = "oo-dlmodel"root = "DlMain"+# The refutation half. `oo-dlmodel` certifies that an ontology HAS a model by+# exhibiting one; this certifies that it has NONE by exhibiting a closed+# tableau. Its own executable for the same reason `oo-refute` is separate from+# `oo-cert`: the verdicts are different sentences and must never be read for+# one another. Exit 1 here means the certificate did not check, never that the+# ontology is consistent.+[[lean_exe]]+name = "oo-dlrefute"+root = "DlRefuteMain"+# The first-order model certificate. A solver's `sat` answer plus the finite# structure it built, checked against the problem it was given. Separate from# `Dl` on purpose and NOT built on it: `Dl.Sat` evaluates at one free variablediff --git a/src/dl_refute.rs b/src/dl_refute.rsnew file mode 100644index 00000000..dbaf61b6--- /dev/null+++ b/src/dl_refute.rs@@ -0,0 +1,994 @@+//! Certifying UNSATISFIABILITY, the half `src/tableaux.rs` could not certify.+//!+//! `ModelOutcome` hands over a finite interpretation when the answer is yes.+//! That works because a model is a finite object and checking it is evaluation.+//! The negative answer has no such object. "This ontology has no model" is a+//! claim about every interpretation, including the infinite ones SHIQ forces,+//! so nothing finite can be exhibited and nothing can be evaluated. What can be+//! exhibited is a DERIVATION: a closed tableau, whose every leaf is a branch no+//! interpretation satisfies and whose every step preserves satisfiability+//! downward. `lean/Dl/Tableau.lean` proves that; `lean/Dl/Refute.lean` checks+//! one; this writes one.+//!+//! # Why this is a second prover rather than instrumentation+//!+//! The obvious move is to record what `Tableau::expand` did and print it. That+//! would be wrong, and not only awkward. The fast reasoner uses blocking,+//! merging, inverse propagation and absorbed GCIs. Blocking and merging are+//! COMPLETENESS devices: they exist so that a search for a model terminates.+//! A refutation needs none of them, and the certified calculus deliberately has+//! neither, so most of what the fast engine records could not be written down+//! here anyway.+//!+//! So this is a small independent search over the certified rules only. It is+//! slower and weaker than `Tableau`, and that is the correct trade: if it finds+//! a refutation, the refutation is checkable; if it does not, `Tableau`'s answer+//! stands exactly as it did before, as testimony. Nothing about this module can+//! make a wrong answer look right, because it does not decide anything. The+//! Lean checker does, from the bytes.+//!+//! # What it cannot do+//!+//! Transitive, symmetric, inverse and inverse-functional roles have no rules in+//! the certified calculus, so an ontology inconsistent only through one of+//! those gets no certificate. The emitter says so rather than guessing.++use crate::tableaux::{axiom_line, name_is_safe, Concept, DlAxiom, Interner};+use std::collections::HashSet;+use std::path::Path;++// ── The Lean-side concept shape ─────────────────────────────────────────++/// A concept as `lean/Dl/Syntax.lean` spells it.+///+/// Not the same type as [`Concept`]. The reasoner's concepts are in negation+/// normal form with n-ary conjunction and disjunction; Lean's have an arbitrary+/// negation and binary connectives. The difference matters because the rules+/// fire on the Lean shape: applying the ∧-rule to `And([c, d, e])` gives two+/// conclusions in Lean, `c` and `and d e`, not three.+#[derive(Clone, PartialEq, Eq, Hash, Debug)]+pub(crate) enum Lc {+ Top,+ Bot,+ Atom(u32),+ Neg(Box<Lc>),+ And(Box<Lc>, Box<Lc>),+ Or(Box<Lc>, Box<Lc>),+ Ex(u32, Box<Lc>),+ All(u32, Box<Lc>),+ /// `≥n R.C`, written `(n, role, filler)`.+ Min(u32, u32, Box<Lc>),+ /// `≤n R.C`.+ Max(u32, u32, Box<Lc>),+}++/// Fold an n-ary list the way `write_nary` in `src/tableaux.rs` does, which is+/// right-associatively with the connective's unit for the empty list.+///+/// This MUST agree with that function, because the certificate cites concepts+/// that have to be equal, as terms, to the ones in `axioms.tsv`. The agreement+/// is not asserted: `lowering_agrees_with_the_axiom_writer` below renders both+/// ways and compares the strings.+fn lower_nary(cs: &[Concept], and: bool) -> Lc {+ match cs.split_first() {+ None => {+ if and {+ Lc::Top+ } else {+ Lc::Bot+ }+ }+ Some((head, [])) => lower(head),+ Some((head, rest)) => {+ let (h, t) = (Box::new(lower(head)), Box::new(lower_nary(rest, and)));+ if and {+ Lc::And(h, t)+ } else {+ Lc::Or(h, t)+ }+ }+ }+}++pub(crate) fn lower(c: &Concept) -> Lc {+ match c {+ Concept::Top => Lc::Top,+ Concept::Bottom => Lc::Bot,+ Concept::Atom(a) => Lc::Atom(*a),+ Concept::NegAtom(a) => Lc::Neg(Box::new(Lc::Atom(*a))),+ Concept::And(cs) => lower_nary(cs, true),+ Concept::Or(cs) => lower_nary(cs, false),+ Concept::Exists(r, f) => Lc::Ex(*r, Box::new(lower(f))),+ Concept::ForAll(r, f) => Lc::All(*r, Box::new(lower(f))),+ Concept::MinCard(r, n, f) => Lc::Min(*n, *r, Box::new(lower(f))),+ Concept::MaxCard(r, n, f) => Lc::Max(*n, *r, Box::new(lower(f))),+ }+}++/// The one place a name reaches the certificate, and therefore the one place the+/// round-trip guard has to be. Same discipline as the model emitter's+/// `push_name`, and for the same reason: the grammar is space-separated, so a+/// name carrying a space would be read back as two tokens.+fn push_name(out: &mut String, it: &Interner, id: u32, bad: &mut Option<String>) {+ let s = it.resolve(id);+ if !name_is_safe(s) && bad.is_none() {+ *bad = Some(s.to_string());+ }+ out.push_str(s);+}++fn write_lc(out: &mut String, it: &Interner, c: &Lc, bad: &mut Option<String>) {+ match c {+ Lc::Top => out.push_str("top"),+ Lc::Bot => out.push_str("bot"),+ Lc::Atom(a) => {+ out.push_str("atom ");+ push_name(out, it, *a, bad);+ }+ Lc::Neg(f) => {+ out.push_str("not ");+ write_lc(out, it, f, bad);+ }+ Lc::And(f, g) => {+ out.push_str("and ");+ write_lc(out, it, f, bad);+ out.push(' ');+ write_lc(out, it, g, bad);+ }+ Lc::Or(f, g) => {+ out.push_str("or ");+ write_lc(out, it, f, bad);+ out.push(' ');+ write_lc(out, it, g, bad);+ }+ Lc::Ex(r, f) => {+ out.push_str("some ");+ push_name(out, it, *r, bad);+ out.push(' ');+ write_lc(out, it, f, bad);+ }+ Lc::All(r, f) => {+ out.push_str("all ");+ push_name(out, it, *r, bad);+ out.push(' ');+ write_lc(out, it, f, bad);+ }+ Lc::Min(n, r, f) => {+ out.push_str("min ");+ out.push_str(&n.to_string());+ out.push(' ');+ push_name(out, it, *r, bad);+ out.push(' ');+ write_lc(out, it, f, bad);+ }+ Lc::Max(n, r, f) => {+ out.push_str("max ");+ out.push_str(&n.to_string());+ out.push(' ');+ push_name(out, it, *r, bad);+ out.push(' ');+ write_lc(out, it, f, bad);+ }+ }+}++// ── Branches ────────────────────────────────────────────────────────────++/// One entry on a tableau branch, mirroring `Dl.Constraint`.+#[derive(Clone, PartialEq, Eq, Hash, Debug)]+enum C {+ Conc(u32, Lc),+ Role(u32, u32, u32),+ Diff(u32, u32),+}++/// A branch, kept as a set for membership and as a vector for order.+///+/// `fired` records which generating rule applications have already happened, so+/// the ∃ and ≥ rules cannot invent witnesses for the same constraint forever.+/// That is the only thing standing between this search and an infinite one, and+/// it is why this prover is incomplete rather than non-terminating: a genuine+/// SHIQ model can need an infinite chain, and refusing to build one costs+/// nothing here because a refutation never needs it.+#[derive(Clone, Default)]+struct Branch {+ set: HashSet<C>,+ conc_of: HashSet<u32>,+ fired: HashSet<(u32, Lc)>,+ fired_ne: HashSet<usize>,+}++impl Branch {+ fn has(&self, c: &C) -> bool {+ self.set.contains(c)+ }++ fn add(&mut self, c: C) -> bool {+ if let C::Conc(x, _) = &c {+ self.conc_of.insert(*x);+ }+ self.set.insert(c)+ }++ fn has_conc(&self, x: u32) -> bool {+ self.conc_of.contains(&x)+ }++ fn concepts(&self) -> Vec<(u32, Lc)> {+ let mut v: Vec<(u32, Lc)> = self+ .set+ .iter()+ .filter_map(|c| match c {+ C::Conc(x, f) => Some((*x, f.clone())),+ _ => None,+ })+ .collect();+ v.sort_by_key(|(x, f)| (*x, format!("{f:?}")));+ v+ }++ fn edges(&self) -> Vec<(u32, u32, u32)> {+ let mut v: Vec<(u32, u32, u32)> = self+ .set+ .iter()+ .filter_map(|c| match c {+ C::Role(r, x, y) => Some((*r, *x, *y)),+ _ => None,+ })+ .collect();+ v.sort_unstable();+ v+ }+}++// ── The certificate tree ────────────────────────────────────────────────++/// A step of a closed tableau, mirroring `Dl.Cert` constructor for constructor.+enum Step {+ Bot(u32),+ NegC(u32, Lc),+ DisjC(u32, Lc, Lc),+ DiffC(u32),+ MinMax(u32, u32, Lc, u32, u32),+ MaxC(u32, u32, Lc, u32, Vec<u32>),+ Inst(u32, Lc, Box<Step>),+ Rel(u32, u32, u32, Box<Step>),+ Sub(u32, Lc, Lc, Box<Step>),+ Dom(u32, u32, u32, Lc, Box<Step>),+ Rng(u32, u32, u32, Lc, Box<Step>),+ SubRole(u32, u32, u32, u32, Box<Step>),+ NonEmpty(u32, Lc, Box<Step>),+ AndS(u32, Lc, Lc, Box<Step>),+ AllS(u32, u32, u32, Lc, Box<Step>),+ ExS(u32, u32, u32, Lc, Box<Step>),+ MinS(u32, u32, Lc, u32, Vec<u32>, Box<Step>),+ OrS(u32, Lc, Lc, Box<Step>, Box<Step>),+}++fn count(s: &Step) -> usize {+ match s {+ Step::Bot(..)+ | Step::NegC(..)+ | Step::DisjC(..)+ | Step::DiffC(..)+ | Step::MinMax(..)+ | Step::MaxC(..) => 1,+ Step::Inst(_, _, k)+ | Step::Rel(_, _, _, k)+ | Step::Sub(_, _, _, k)+ | Step::Dom(_, _, _, _, k)+ | Step::Rng(_, _, _, _, k)+ | Step::SubRole(_, _, _, _, k)+ | Step::NonEmpty(_, _, k)+ | Step::AndS(_, _, _, k)+ | Step::AllS(_, _, _, _, k)+ | Step::ExS(_, _, _, _, k)+ | Step::MinS(_, _, _, _, _, k) => 1 + count(k),+ Step::OrS(_, _, _, l, r) => 1 + count(l) + count(r),+ }+}++/// Render the tree in the prefix order `Dl.Parse.cert?` reads.+///+/// Indentation is for a human only. Newlines are not significant in the format,+/// because the arities carry the tree shape, so nothing here can become+/// load-bearing by accident.+fn write_step(out: &mut String, it: &Interner, s: &Step, ind: usize, bad: &mut Option<String>) {+ let pad = " ".repeat(ind);+ let kid = |out: &mut String, k: &Step, bad: &mut Option<String>| {+ out.push('\n');+ write_step(out, it, k, ind + 1, bad);+ };+ let n = |out: &mut String, id: u32, bad: &mut Option<String>| {+ push_name(out, it, id, bad);+ };+ out.push_str(&pad);+ match s {+ Step::Bot(x) => {+ out.push_str("bot ");+ n(out, *x, bad);+ }+ Step::DiffC(x) => {+ out.push_str("diff ");+ n(out, *x, bad);+ }+ Step::NegC(x, c) => {+ out.push_str("neg ");+ n(out, *x, bad);+ out.push(' ');+ write_lc(out, it, c, bad);+ }+ Step::DisjC(x, c, d) => {+ out.push_str("disjoint ");+ n(out, *x, bad);+ out.push(' ');+ write_lc(out, it, c, bad);+ out.push(' ');+ write_lc(out, it, d, bad);+ }+ Step::MinMax(x, r, c, m, k) => {+ out.push_str("minmax ");+ n(out, *x, bad);+ out.push(' ');+ n(out, *r, bad);+ out.push_str(&format!(" {m} {k} "));+ write_lc(out, it, c, bad);+ }+ Step::MaxC(x, r, c, k, ys) => {+ out.push_str("maxclash ");+ n(out, *x, bad);+ out.push(' ');+ n(out, *r, bad);+ out.push_str(&format!(" {k} {} ", ys.len()));+ for y in ys {+ n(out, *y, bad);+ out.push(' ');+ }+ write_lc(out, it, c, bad);+ }+ Step::Inst(a, c, k) => {+ out.push_str("inst ");+ n(out, *a, bad);+ out.push(' ');+ write_lc(out, it, c, bad);+ kid(out, k, bad);+ }+ Step::Rel(a, r, b, k) => {+ out.push_str("rel ");+ n(out, *a, bad);+ out.push(' ');+ n(out, *r, bad);+ out.push(' ');+ n(out, *b, bad);+ kid(out, k, bad);+ }+ Step::Sub(x, c, d, k) => {+ out.push_str("sub ");+ n(out, *x, bad);+ out.push(' ');+ write_lc(out, it, c, bad);+ out.push(' ');+ write_lc(out, it, d, bad);+ kid(out, k, bad);+ }+ Step::Dom(x, y, r, c, k) => {+ out.push_str("domain ");+ n(out, *x, bad);+ out.push(' ');+ n(out, *y, bad);+ out.push(' ');+ n(out, *r, bad);+ out.push(' ');+ write_lc(out, it, c, bad);+ kid(out, k, bad);+ }+ Step::Rng(x, y, r, c, k) => {+ out.push_str("range ");+ n(out, *x, bad);+ out.push(' ');+ n(out, *y, bad);+ out.push(' ');+ n(out, *r, bad);+ out.push(' ');+ write_lc(out, it, c, bad);+ kid(out, k, bad);+ }+ Step::SubRole(x, y, r, t, k) => {+ out.push_str("subrole ");+ n(out, *x, bad);+ out.push(' ');+ n(out, *y, bad);+ out.push(' ');+ n(out, *r, bad);+ out.push(' ');+ n(out, *t, bad);+ kid(out, k, bad);+ }+ Step::NonEmpty(y, c, k) => {+ out.push_str("nonempty ");+ n(out, *y, bad);+ out.push(' ');+ write_lc(out, it, c, bad);+ kid(out, k, bad);+ }+ Step::AndS(x, c, d, k) => {+ out.push_str("and ");+ n(out, *x, bad);+ out.push(' ');+ write_lc(out, it, c, bad);+ out.push(' ');+ write_lc(out, it, d, bad);+ kid(out, k, bad);+ }+ Step::AllS(x, y, r, c, k) => {+ out.push_str("all ");+ n(out, *x, bad);+ out.push(' ');+ n(out, *y, bad);+ out.push(' ');+ n(out, *r, bad);+ out.push(' ');+ write_lc(out, it, c, bad);+ kid(out, k, bad);+ }+ Step::ExS(x, y, r, c, k) => {+ out.push_str("some ");+ n(out, *x, bad);+ out.push(' ');+ n(out, *y, bad);+ out.push(' ');+ n(out, *r, bad);+ out.push(' ');+ write_lc(out, it, c, bad);+ kid(out, k, bad);+ }+ Step::MinS(x, r, c, k, ys, next) => {+ out.push_str("min ");+ n(out, *x, bad);+ out.push(' ');+ n(out, *r, bad);+ out.push_str(&format!(" {k} {} ", ys.len()));+ for y in ys {+ n(out, *y, bad);+ out.push(' ');+ }+ write_lc(out, it, c, bad);+ kid(out, next, bad);+ }+ Step::OrS(x, c, d, l, r) => {+ out.push_str("or ");+ n(out, *x, bad);+ out.push(' ');+ write_lc(out, it, c, bad);+ out.push(' ');+ write_lc(out, it, d, bad);+ kid(out, l, bad);+ kid(out, r, bad);+ }+ }+}++// ── The axioms, in the shape the rules read them ────────────────────────++/// The axioms the certified calculus has rules for. Everything else is dropped+/// here and named in [`RefuteOutcome::NotFound`] if the search fails, so a+/// reader can tell "no refutation exists" from "no refutation this calculus can+/// write".+struct Rules {+ subs: Vec<(Lc, Lc)>,+ disjoints: Vec<(Lc, Lc)>,+ domains: Vec<(u32, Lc)>,+ ranges: Vec<(u32, Lc)>,+ subroles: Vec<(u32, u32)>,+ insts: Vec<(u32, Lc)>,+ rels: Vec<(u32, u32, u32)>,+ indivs: HashSet<u32>,+ nonempties: Vec<Lc>,+ /// Role names the axiom set mentions, which is what `roleNames A` is in+ /// Lean and what several rules need to put a target in the carrier.+ roles: HashSet<u32>,+ /// Individual names the axiom set mentions. Invented witnesses must avoid+ /// these, or the assignment the soundness proof builds would disagree with+ /// `I.ind` and the rule would be unsound.+ inds: HashSet<u32>,+ /// Axiom kinds present in the ontology that this calculus cannot use.+ unsupported: Vec<&'static str>,+}++fn concept_roles(c: &Concept, out: &mut HashSet<u32>) {+ match c {+ Concept::Top | Concept::Bottom | Concept::Atom(_) | Concept::NegAtom(_) => {}+ Concept::And(cs) | Concept::Or(cs) => cs.iter().for_each(|d| concept_roles(d, out)),+ Concept::Exists(r, f) | Concept::ForAll(r, f) => {+ out.insert(*r);+ concept_roles(f, out);+ }+ Concept::MinCard(r, _, f) | Concept::MaxCard(r, _, f) => {+ out.insert(*r);+ concept_roles(f, out);+ }+ }+}++impl Rules {+ fn new(axioms: &[DlAxiom]) -> Rules {+ let mut r = Rules {+ subs: vec![],+ disjoints: vec![],+ domains: vec![],+ ranges: vec![],+ subroles: vec![],+ insts: vec![],+ rels: vec![],+ indivs: HashSet::new(),+ nonempties: vec![],+ roles: HashSet::new(),+ inds: HashSet::new(),+ unsupported: vec![],+ };+ let note = |r: &mut Rules, k: &'static str| {+ if !r.unsupported.contains(&k) {+ r.unsupported.push(k);+ }+ };+ for a in axioms {+ // `roleNames` and `indNames` in `lean/Dl/Syntax.lean`, clause for+ // clause. They are computed from EVERY axiom, including the ones+ // this calculus has no rule for, because that is what the Lean side+ // computes and the two have to agree.+ match a {+ DlAxiom::Sub(c, d) | DlAxiom::Disjoint(c, d) => {+ concept_roles(c, &mut r.roles);+ concept_roles(d, &mut r.roles);+ }+ DlAxiom::Domain(role, c) | DlAxiom::Range(role, c) => {+ r.roles.insert(*role);+ concept_roles(c, &mut r.roles);+ }+ DlAxiom::Inst(i, c) => {+ r.inds.insert(*i);+ concept_roles(c, &mut r.roles);+ }+ DlAxiom::NonEmpty(c) => concept_roles(c, &mut r.roles),+ DlAxiom::SubRole(a1, b1) | DlAxiom::Inv(a1, b1) => {+ r.roles.insert(*a1);+ r.roles.insert(*b1);+ }+ DlAxiom::Trans(role) | DlAxiom::Sym(role) | DlAxiom::InvFunc(role) => {+ r.roles.insert(*role);+ }+ DlAxiom::Rel(a1, role, b1) => {+ r.roles.insert(*role);+ r.inds.insert(*a1);+ r.inds.insert(*b1);+ }+ DlAxiom::Indiv(i) => {+ r.inds.insert(*i);+ }+ }+ match a {+ DlAxiom::Sub(c, d) => r.subs.push((lower(c), lower(d))),+ DlAxiom::Disjoint(c, d) => r.disjoints.push((lower(c), lower(d))),+ DlAxiom::Domain(role, c) => r.domains.push((*role, lower(c))),+ DlAxiom::Range(role, c) => r.ranges.push((*role, lower(c))),+ DlAxiom::SubRole(a1, b1) => r.subroles.push((*a1, *b1)),+ DlAxiom::Inst(i, c) => r.insts.push((*i, lower(c))),+ DlAxiom::Rel(a1, role, b1) => r.rels.push((*a1, *role, *b1)),+ DlAxiom::Indiv(i) => {+ r.indivs.insert(*i);+ }+ DlAxiom::NonEmpty(c) => r.nonempties.push(lower(c)),+ DlAxiom::Trans(_) => note(&mut r, "trans"),+ DlAxiom::Sym(_) => note(&mut r, "sym"),+ DlAxiom::Inv(..) => note(&mut r, "inv"),+ DlAxiom::InvFunc(_) => note(&mut r, "invfunc"),+ }+ }+ r+ }+}++// ── The search ──────────────────────────────────────────────────────────++struct Prover<'a> {+ rules: &'a Rules,+ /// Fresh names, interned as they are invented. Checked against `inds`+ /// rather than assumed distinct from it.+ fresh: Vec<u32>,+ next_fresh: usize,+ budget: usize,+}++impl<'a> Prover<'a> {+ /// A name no axiom mentions. The Lean rules require exactly that, on top of+ /// the name being new to the branch.+ fn fresh_name(&mut self, it: &mut Interner) -> Option<u32> {+ for k in 0..64 {+ let id = it.intern(&format!("_oo_w{}_{}", self.next_fresh, k));+ if !self.rules.inds.contains(&id) && !self.fresh.contains(&id) {+ self.next_fresh += 1;+ self.fresh.push(id);+ return Some(id);+ }+ }+ None+ }++ fn spend(&mut self) -> bool {+ if self.budget == 0 {+ return false;+ }+ self.budget -= 1;+ true+ }++ /// A clash on this branch, if there is one.+ fn clash(&self, br: &Branch) -> Option<Step> {+ for (x, c) in br.concepts() {+ if c == Lc::Bot {+ return Some(Step::Bot(x));+ }+ if br.has(&C::Conc(x, Lc::Neg(Box::new(c.clone())))) {+ return Some(Step::NegC(x, c));+ }+ if br.has(&C::Diff(x, x)) {+ return Some(Step::DiffC(x));+ }+ if let Lc::Min(m, r, f) = &c {+ for (y, d) in br.concepts() {+ if y != x {+ continue;+ }+ if let Lc::Max(n, r2, g) = &d+ && r == r2+ && f == g+ && n < m+ {+ return Some(Step::MinMax(x, *r, (**f).clone(), *m, *n));+ }+ }+ }+ }+ for (c, d) in &self.rules.disjoints {+ for (x, f) in br.concepts() {+ if &f == c && br.has(&C::Conc(x, d.clone())) {+ return Some(Step::DisjC(x, c.clone(), d.clone()));+ }+ }+ }+ // The cardinality clash: more pairwise-distinct successors in the filler+ // than the bound allows. The witnesses have to be distinct ON THE+ // BRANCH, which is what the ≥ rule's inequalities are for.+ for (x, c) in br.concepts() {+ let Lc::Max(n, r, f) = &c else { continue };+ let mut ys: Vec<u32> = br+ .edges()+ .into_iter()+ .filter(|(rr, xx, _)| rr == r && *xx == x)+ .map(|(_, _, y)| y)+ .filter(|y| br.has(&C::Conc(*y, (**f).clone())))+ .collect();+ ys.sort_unstable();+ ys.dedup();+ let mut picked: Vec<u32> = vec![];+ for y in ys {+ if picked+ .iter()+ .all(|&p| br.has(&C::Diff(p, y)) && br.has(&C::Diff(y, p)))+ {+ picked.push(y);+ }+ if picked.len() == *n as usize + 1 {+ return Some(Step::MaxC(x, *r, (**f).clone(), *n, picked));+ }+ }+ }+ None+ }++ /// The first rule that adds something the branch does not already carry.+ /// Every one of these strictly grows the branch, which is what keeps the+ /// deterministic phase finite.+ #[allow(clippy::type_complexity)]+ fn det(&self, br: &Branch) -> Option<(Branch, Box<dyn Fn(Box<Step>) -> Step>)> {+ // Conjunction first: it is the cheapest and it feeds everything else.+ for (x, c) in br.concepts() {+ if let Lc::And(f, g) = &c {+ let (a, b) = (C::Conc(x, (**f).clone()), C::Conc(x, (**g).clone()));+ if !br.has(&a) || !br.has(&b) {+ let mut nb = br.clone();+ nb.add(a);+ nb.add(b);+ let (fc, gc) = ((**f).clone(), (**g).clone());+ return Some((nb, Box::new(move |k| Step::AndS(x, fc.clone(), gc.clone(), k))));+ }+ }+ }+ for (a, c) in &self.rules.insts {+ if !self.rules.indivs.contains(a) {+ continue;+ }+ let goal = C::Conc(*a, c.clone());+ if !br.has(&goal) {+ let mut nb = br.clone();+ nb.add(goal);+ let (aa, cc) = (*a, c.clone());+ return Some((nb, Box::new(move |k| Step::Inst(aa, cc.clone(), k))));+ }+ }+ for (a, r, b) in &self.rules.rels {+ let goal = C::Role(*r, *a, *b);+ if !br.has(&goal) {+ let mut nb = br.clone();+ nb.add(goal);+ let (aa, rr, bb) = (*a, *r, *b);+ return Some((nb, Box::new(move |k| Step::Rel(aa, rr, bb, k))));+ }+ }+ for (c, d) in &self.rules.subs {+ for (x, f) in br.concepts() {+ if &f != c {+ continue;+ }+ let goal = C::Conc(x, d.clone());+ if !br.has(&goal) {+ let mut nb = br.clone();+ nb.add(goal);+ let (cc, dd) = (c.clone(), d.clone());+ return Some((nb, Box::new(move |k| Step::Sub(x, cc.clone(), dd.clone(), k))));+ }+ }+ }+ for (r, x, y) in br.edges() {+ for (role, c) in &self.rules.domains {+ if *role != r || !br.has_conc(x) {+ continue;+ }+ let goal = C::Conc(x, c.clone());+ if !br.has(&goal) {+ let mut nb = br.clone();+ nb.add(goal);+ let cc = c.clone();+ return Some((nb, Box::new(move |k| Step::Dom(x, y, r, cc.clone(), k))));+ }+ }+ for (role, c) in &self.rules.ranges {+ if *role != r || !br.has_conc(x) || !self.rules.roles.contains(&r) {+ continue;+ }+ let goal = C::Conc(y, c.clone());+ if !br.has(&goal) {+ let mut nb = br.clone();+ nb.add(goal);+ let cc = c.clone();+ return Some((nb, Box::new(move |k| Step::Rng(x, y, r, cc.clone(), k))));+ }+ }+ for (role, t) in &self.rules.subroles {+ if *role != r || !br.has_conc(x) {+ continue;+ }+ let goal = C::Role(*t, x, y);+ if !br.has(&goal) {+ let mut nb = br.clone();+ nb.add(goal);+ let tt = *t;+ return Some((nb, Box::new(move |k| Step::SubRole(x, y, r, tt, k))));+ }+ }+ }+ for (x, c) in br.concepts() {+ let Lc::All(r, f) = &c else { continue };+ if !self.rules.roles.contains(r) {+ continue;+ }+ for (rr, xx, y) in br.edges() {+ if rr != *r || xx != x {+ continue;+ }+ let goal = C::Conc(y, (**f).clone());+ if !br.has(&goal) {+ let mut nb = br.clone();+ nb.add(goal);+ let (rrr, ff) = (*r, (**f).clone());+ return Some((nb, Box::new(move |k| Step::AllS(x, y, rrr, ff.clone(), k))));+ }+ }+ }+ None+ }++ fn close(&mut self, br: &Branch, it: &mut Interner) -> Option<Step> {+ if !self.spend() {+ return None;+ }+ if let Some(leaf) = self.clash(br) {+ return Some(leaf);+ }+ if let Some((nb, wrap)) = self.det(br) {+ return self.close(&nb, it).map(|k| wrap(Box::new(k)));+ }+ // Non-emptiness: the only rule that fires on an empty branch, so without+ // it a pure TBox question never starts. Once per axiom.+ for (i, c) in self.rules.nonempties.iter().enumerate() {+ if br.fired_ne.contains(&i) {+ continue;+ }+ let y = self.fresh_name(it)?;+ let mut nb = br.clone();+ nb.fired_ne.insert(i);+ nb.add(C::Conc(y, c.clone()));+ let cc = c.clone();+ return self+ .close(&nb, it)+ .map(|k| Step::NonEmpty(y, cc, Box::new(k)));+ }+ // Disjunction. Both children must close, which is the only reason a+ // tableau is a tree rather than a list.+ for (x, c) in br.concepts() {+ let Lc::Or(f, g) = &c else { continue };+ let mut lb = br.clone();+ lb.add(C::Conc(x, (**f).clone()));+ let mut rb = br.clone();+ rb.add(C::Conc(x, (**g).clone()));+ let l = self.close(&lb, it)?;+ let r = self.close(&rb, it)?;+ return Some(Step::OrS(+ x,+ (**f).clone(),+ (**g).clone(),+ Box::new(l),+ Box::new(r),+ ));+ }+ // Generating rules last, and once per constraint.+ for (x, c) in br.concepts() {+ if br.fired.contains(&(x, c.clone())) {+ continue;+ }+ match &c {+ Lc::Ex(r, f) => {+ if !self.rules.roles.contains(r) {+ continue;+ }+ let y = self.fresh_name(it)?;+ let mut nb = br.clone();+ nb.fired.insert((x, c.clone()));+ nb.add(C::Role(*r, x, y));+ nb.add(C::Conc(y, (**f).clone()));+ let (rr, ff) = (*r, (**f).clone());+ return self+ .close(&nb, it)+ .map(|k| Step::ExS(x, y, rr, ff, Box::new(k)));+ }+ Lc::Min(n, r, f) => {+ if !self.rules.roles.contains(r) {+ continue;+ }+ let mut ys = vec![];+ for _ in 0..*n {+ let y = self.fresh_name(it)?;+ ys.push(y);+ }+ let mut nb = br.clone();+ nb.fired.insert((x, c.clone()));+ for &y in &ys {+ nb.add(C::Role(*r, x, y));+ nb.add(C::Conc(y, (**f).clone()));+ }+ for &a in &ys {+ for &b in &ys {+ if a != b {+ nb.add(C::Diff(a, b));+ }+ }+ }+ let (rr, ff, nn, yy) = (*r, (**f).clone(), *n, ys.clone());+ return self+ .close(&nb, it)+ .map(|k| Step::MinS(x, rr, ff, nn, yy, Box::new(k)));+ }+ _ => {}+ }+ }+ None+ }+}++// ── The public face ─────────────────────────────────────────────────────++/// What [`certify_unsatisfiable`] did.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum RefuteOutcome {+ /// `axioms.tsv` and `refutation.cert` were written. `oo-dlrefute` is what+ /// turns that into a verified statement; this layer only claims to have+ /// written a tree it believes closes.+ Certified { axioms: usize, steps: usize },+ /// The search found no closed tableau within the budget. This is NOT a+ /// claim that the ontology is consistent, and the string says what the+ /// calculus could not use.+ NotFound(String),+ /// A certificate could not be written even though a tree was found, because+ /// a name would not survive the round trip.+ Refused(String),+}++impl RefuteOutcome {+ pub fn is_certified(&self) -> bool {+ matches!(self, RefuteOutcome::Certified { .. })+ }++ pub fn describe(&self) -> String {+ match self {+ RefuteOutcome::Certified { axioms, steps } => {+ format!("certified: {axioms} axioms refuted in {steps} steps")+ }+ RefuteOutcome::NotFound(why) => format!("no certificate: {why}"),+ RefuteOutcome::Refused(why) => format!("no certificate: {why}"),+ }+ }+}++/// The default search budget, in rule applications.+pub const DEFAULT_BUDGET: usize = 20_000;++/// Look for a closed tableau over `axioms`, and write it if one is found.+///+/// Writes two files into `dir`: `axioms.tsv`, which is the same transcription+/// the model certificate uses, and `refutation.cert`. Check them with+/// `oo-dlrefute AXIOMS.tsv REFUTATION.cert`.+pub(crate) fn certify_unsatisfiable(+ axioms: &[DlAxiom],+ interner: &mut Interner,+ dir: &Path,+ budget: usize,+) -> anyhow::Result<RefuteOutcome> {+ let rules = Rules::new(axioms);+ let mut prover = Prover {+ rules: &rules,+ fresh: vec![],+ next_fresh: 0,+ budget,+ };+ let start = Branch::default();+ let Some(tree) = prover.close(&start, interner) else {+ let mut why = format!("no closed tableau within {budget} steps");+ if !rules.unsupported.is_empty() {+ why.push_str(&format!(+ "; the calculus has no rules for {} and dropped {} axiom kind(s), \+ so an inconsistency that needs one of those cannot be written here",+ rules.unsupported.join(", "),+ rules.unsupported.len()+ ));+ }+ return Ok(RefuteOutcome::NotFound(why));+ };++ // Same discipline as the model emitter: build the text first and let+ // `push_name` record the first refusal, so the coverage question cannot+ // arise from two loops disagreeing about which names were checked.+ let mut bad: Option<String> = None;+ let mut axiom_text = String::new();+ for a in axioms {+ axiom_text.push_str(&axiom_line(interner, a, &mut bad));+ axiom_text.push('\n');+ }+ let mut cert_text = String::new();+ write_step(&mut cert_text, interner, &tree, 0, &mut bad);+ cert_text.push('\n');++ if let Some(name) = bad {+ return Ok(RefuteOutcome::Refused(format!(+ "the name {name:?} carries a space, a tab, a newline or nothing at all, \+ so it would not survive the round trip through the certificate"+ )));+ }++ std::fs::create_dir_all(dir)?;+ std::fs::write(dir.join("axioms.tsv"), axiom_text)?;+ std::fs::write(dir.join("refutation.cert"), cert_text)?;+ Ok(RefuteOutcome::Certified {+ axioms: axioms.len(),+ steps: count(&tree),+ })+}diff --git a/src/lib.rs b/src/lib.rsindex 8f7d36cd..4cd49a2e 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -24,6 +24,7 @@ pub mod communities;pub mod config;pub mod cq;pub mod defects;+pub mod dl_refute;pub mod dlp;pub mod drift;pub mod dynamics;diff --git a/src/tableaux.rs b/src/tableaux.rsindex 751949e8..a2e5767a 100644--- a/src/tableaux.rs+++ b/src/tableaux.rs@@ -207,6 +207,7 @@ impl RawConcept {// ── String Interner ─────────────────────────────────────────────────────+#[derive(Clone)]pub struct Interner {to_id: HashMap<String, u32>,to_str: Vec<String>,@@ -220,7 +221,7 @@ impl Interner {}}- fn intern(&mut self, s: &str) -> u32 {+ pub(crate) fn intern(&mut self, s: &str) -> u32 {if let Some(&id) = self.to_id.get(s) {return id;}@@ -3681,7 +3682,7 @@ use std::path::Path;/// An axiom in the fragment `lean/Dl/` covers, over interned identifiers.#[derive(Clone, Debug)]-enum DlAxiom {+pub(crate) enum DlAxiom {Sub(Concept, Concept),Disjoint(Concept, Concept),Domain(u32, Concept),@@ -3774,7 +3775,7 @@ impl ModelOutcome {/// proptest below can only sample. All four are ASCII and no ASCII byte occurs/// inside a multi-byte UTF-8 sequence, so the byte-level test and/// `str::contains` over a `char` array agree on every `&str`.-fn name_is_safe(s: &str) -> bool {+pub(crate) fn name_is_safe(s: &str) -> bool {crate::boundary_core::name_is_safe_bytes(s.as_bytes())}@@ -3795,7 +3796,7 @@ fn name_is_safe(s: &str) -> bool {/// certificate. It is a sink rather than a `Result` so the serialisers stay/// total and keep their shape; a certificate is written only after the caller/// has looked at it.-fn push_name(out: &mut String, interner: &Interner, id: u32, bad: &mut Option<String>) {+pub(crate) fn push_name(out: &mut String, interner: &Interner, id: u32, bad: &mut Option<String>) {let s = interner.resolve(id);if !name_is_safe(s) && bad.is_none() {*bad = Some(s.to_string());@@ -3873,13 +3874,13 @@ fn write_nary(}}-fn concept_string(interner: &Interner, c: &Concept, bad: &mut Option<String>) -> String {+pub(crate) fn concept_string(interner: &Interner, c: &Concept, bad: &mut Option<String>) -> String {let mut s = String::new();write_concept(&mut s, interner, c, bad);s}-fn axiom_line(interner: &Interner, a: &DlAxiom, bad: &mut Option<String>) -> String {+pub(crate) fn axiom_line(interner: &Interner, a: &DlAxiom, bad: &mut Option<String>) -> String {// Every name in the line goes through `push_name`, including the ones that// are not inside a concept, so `bad` is set by the time the line exists.let cs = |c: &Concept, bad: &mut Option<String>| concept_string(interner, c, bad);@@ -4632,6 +4633,111 @@ impl DlReasoner {self.emit(&tableau, &HashMap::new(), self.tbox_axioms(), dir)}+ /// Certify that a class is UNSATISFIABLE, which is the answer `emit` cannot+ /// certify and never could.+ ///+ /// `certify_class_satisfiable` hands over a model. There is no model to hand+ /// over here, so what is handed over is a closed tableau, and the checker+ /// that reads it is `oo-dlrefute` rather than `oo-dlmodel`. The two verdicts+ /// are different sentences and the two files must never be confused.+ ///+ /// The search that writes the tableau is NOT this reasoner. It is the small+ /// independent one in `crate::dl_refute`, over the certified rules only,+ /// because blocking and merging are completeness devices a refutation does+ /// not need and the certified calculus deliberately lacks. So this can fail+ /// to certify an unsatisfiability this reasoner decided, and when it does,+ /// the reasoner's answer is unchanged and uncertified, exactly as before.+ pub fn certify_class_unsatisfiable(+ &self,+ class_iri: &str,+ dir: &Path,+ ) -> anyhow::Result<crate::dl_refute::RefuteOutcome> {+ 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.phase_deadline());+ match tableau.decide(&concept) {+ Verdict::Unsatisfiable => {}+ Verdict::Unknown => {+ return Ok(crate::dl_refute::RefuteOutcome::NotFound(+ "the run was undetermined, so there is no negative answer to certify"+ .to_string(),+ ))+ }+ Verdict::Satisfiable => {+ return Ok(crate::dl_refute::RefuteOutcome::NotFound(+ "the class is satisfiable; certify the model instead".to_string(),+ ))+ }+ }+ let mut axioms = self.tbox_axioms();+ axioms.push(DlAxiom::NonEmpty(concept));+ let mut interner = self.interner.clone();+ crate::dl_refute::certify_unsatisfiable(+ &axioms,+ &mut interner,+ dir,+ crate::dl_refute::DEFAULT_BUDGET,+ )+ }++ /// Certify that the TBox is INCONSISTENT. The mirror of+ /// `certify_tbox_consistent`, and the same caveats apply.+ pub fn certify_tbox_inconsistent(+ &self,+ dir: &Path,+ ) -> anyhow::Result<crate::dl_refute::RefuteOutcome> {+ let mut tableau = Tableau::with_deadline(Arc::clone(&self.tbox), self.phase_deadline());+ match tableau.decide(&Concept::Top) {+ Verdict::Unsatisfiable => {}+ Verdict::Unknown => {+ return Ok(crate::dl_refute::RefuteOutcome::NotFound(+ "the run was undetermined".to_string(),+ ))+ }+ Verdict::Satisfiable => {+ return Ok(crate::dl_refute::RefuteOutcome::NotFound(+ "the TBox is consistent; certify the model instead".to_string(),+ ))+ }+ }+ let mut axioms = self.tbox_axioms();+ axioms.push(DlAxiom::NonEmpty(Concept::Top));+ let mut interner = self.interner.clone();+ crate::dl_refute::certify_unsatisfiable(+ &axioms,+ &mut interner,+ dir,+ crate::dl_refute::DEFAULT_BUDGET,+ )+ }++ /// Certify that the ABox is INCONSISTENT with the TBox.+ pub fn certify_abox_inconsistent(+ &self,+ dir: &Path,+ ) -> anyhow::Result<crate::dl_refute::RefuteOutcome> {+ let (mut tableau, _, _) = self.build_abox_tableau(Self::global_deadline());+ if tableau.expand(0) {+ return Ok(crate::dl_refute::RefuteOutcome::NotFound(+ "the ABox is consistent; certify the model instead".to_string(),+ ));+ }+ if tableau.budget.exhausted {+ return Ok(crate::dl_refute::RefuteOutcome::NotFound(+ "the run was undetermined".to_string(),+ ));+ }+ let mut interner = self.interner.clone();+ crate::dl_refute::certify_unsatisfiable(+ &self.abox_axioms(),+ &mut interner,+ dir,+ crate::dl_refute::DEFAULT_BUDGET,+ )+ }+/// Certify that the ABox is consistent with the TBox.pub fn certify_abox_consistent(&self, dir: &Path) -> anyhow::Result<ModelOutcome> {// Same three-part test as `check_abox`, and it has to be the same or thediff --git a/tests/dl_refutation_certificate_test.rs b/tests/dl_refutation_certificate_test.rsnew file mode 100644index 00000000..dae39656--- /dev/null+++ b/tests/dl_refutation_certificate_test.rs@@ -0,0 +1,424 @@+//! Refutation certificates for the SHIQ tableaux reasoner, end to end.+//!+//! `tests/dl_model_certificate_test.rs` closes the loop for the POSITIVE+//! answers: a class the reasoner calls satisfiable comes with a model, and+//! `Dl.satisfiable_of_checkModel` says an accepted model really is one. The+//! negative answers had nothing. `oo-dlmodel`'s own header used to say so, and+//! said that certifying them "needs a closed tableau with its blocking+//! argument". Half of that was right. A closed tableau is what it needs;+//! blocking is a COMPLETENESS device, for making a search for a model+//! terminate, and a refutation never needs one.+//!+//! So the negative answers now carry a derivation instead of a structure, and+//! `Dl.unsatisfiable_of_check` says an accepted derivation means the axiom set+//! has no model of ANY size. These tests close that loop.+//!+//! 1. The reasoner emits and the checker accepts, once for each shape of+//! derivation the calculus can build: a flat clash, a bound clash that+//! needs no witnesses, the ≥ rule inventing witnesses that a later bound+//! then refutes, and a disjunction, which is the only rule that makes the+//! certificate a tree rather than a list.+//! 2. The checker can say no, and each way is exercised on its own. A step+//! citing an axiom nobody asserted, a witness reusing a name the branch+//! already carries, and a file whose tree does not consume it. A gate that+//! cannot fail is decoration.+//! 3. The emitter declines rather than inventing. A satisfiable class gets+//! no certificate, and an inconsistency that needs a rule the calculus+//! lacks gets no certificate AND is told which rule.+//!+//! The checker needs a Lean toolchain (`lake`) AND the `oo-dlrefute` 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;+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 {+ 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.+ Command::new("lake")+ .arg("--version")+ .current_dir(lean_dir())+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+}++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-dlrefute")+ .current_dir(lean_dir())+ .output()+ .expect("run lake build oo-dlrefute");+ let text = format!(+ "{}{}",+ String::from_utf8_lossy(&out.stdout),+ String::from_utf8_lossy(&out.stderr)+ );+ if !out.status.success() {+ if text.contains("unknown target") || text.contains("no such target") {+ return Err(format!(+ "the `oo-dlrefute` target in lean/lakefile.toml. Add:\n\+ \n\+ [[lean_exe]]\nname = \"oo-dlrefute\"\nroot = \"DlRefuteMain\"\n\+ \n\+ lake said: {text}"+ ));+ }+ panic!("lake build oo-dlrefute failed:\n{text}");+ }+ let exe = lean_dir()+ .join(".lake")+ .join("build")+ .join("bin")+ .join("oo-dlrefute");+ 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 refutation-certificate tests need both, and check nothing without them",+ ),+ }+}++fn checker() -> &'static Path {+ build().as_ref().expect("checked by skip()").as_path()+}++/// Run `oo-dlrefute` over a directory. Returns (exit code, stdout + stderr).+fn check_dir(dir: &Path) -> (i32, String) {+ let out = Command::new(checker())+ .arg(dir.join("axioms.tsv"))+ .arg(dir.join("refutation.cert"))+ .output()+ .expect("run oo-dlrefute");+ (+ out.status.code().unwrap_or(-1),+ 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-dlrefute-{}-{}", name, std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+}++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#> .+"#;++/// Emit a refutation for `class` and return the directory, failing loudly if the+/// emitter declined. Every caller here uses an ontology whose inconsistency is+/// inside the certified fragment, so a decline is a defect rather than the+/// documented refusal.+fn refutation(name: &str, tbox: &str, class: &str) -> PathBuf {+ let dir = scratch(name);+ let store = Arc::new(GraphStore::new());+ store.load_turtle(&format!("{PREFIXES}{tbox}"), None).unwrap_or_else(|e| panic!("{e}"));+ let reasoner = DlReasoner::from_graph(&store).unwrap();+ let outcome = reasoner.certify_class_unsatisfiable(class, &dir).unwrap();+ assert!(+ outcome.is_certified(),+ "the emitter declined a class whose inconsistency is inside the certified \+ fragment: {}",+ outcome.describe()+ );+ dir+}++fn cert_text(dir: &Path) -> String {+ std::fs::read_to_string(dir.join("refutation.cert")).unwrap()+}++// ── 1. The reasoner emits and the checker accepts ───────────────────────++/// Two disjoint superclasses. The smallest thing a TBox can get wrong, and the+/// derivation is a straight line: name a member, lift it to each superclass,+/// clash on the disjointness.+const DISJOINT_TBOX: &str = r#"+ :A a owl:Class . :B a owl:Class .+ :A owl:disjointWith :B .+ :Impossible a owl:Class ; rdfs:subClassOf :A , :B .+"#;++#[test]+fn a_disjointness_contradiction_is_certified_and_the_checker_accepts_it() {+ if skip() {+ return;+ }+ let dir = refutation("disjoint", DISJOINT_TBOX, "<http://ex.org/Impossible>");+ let (code, out) = check_dir(&dir);+ assert_eq!(code, 0, "the checker rejected a certificate the emitter wrote: {out}");+ assert!(out.contains("\"verdict\":\"unsatisfiable\""), "{out}");+ assert!(+ out.contains("Dl.unsatisfiable_of_check"),+ "the verdict must name the theorem it rests on: {out}"+ );+}++/// `≥2 R.⊤` against `≤1 R.⊤`. The bound clash needs NO witnesses on the branch,+/// so this closes without the ≥ rule ever running, and the certificate is four+/// steps rather than the seven the witness route costs.+const BOUND_TBOX: &str = r#"+ :sib a owl:ObjectProperty .+ :Twins a owl:Class ; rdfs:subClassOf+ [ a owl:Restriction ; owl:onProperty :sib ; owl:minCardinality 2 ] ,+ [ a owl:Restriction ; owl:onProperty :sib ; owl:maxCardinality 1 ] .+"#;++#[test]+fn a_bound_clash_closes_without_inventing_any_witnesses() {+ if skip() {+ return;+ }+ let dir = refutation("bound", BOUND_TBOX, "<http://ex.org/Twins>");+ let text = cert_text(&dir);+ assert!(+ text.contains("minmax "),+ "the two bounds contradict each other directly and the certificate should say so: {text}"+ );+ assert!(+ !text.contains("\nmin ") && !text.contains(" min "),+ "no witness should have been invented for a clash that needs none: {text}"+ );+ let (code, out) = check_dir(&dir);+ assert_eq!(code, 0, "{out}");+}++/// `≥2 R.C` against `≤1 R.D` with `C ⊑ D`. The bounds do NOT contradict each+/// other directly, because they are about different fillers. The refutation has+/// to invent two witnesses, lift each through the subsumption, and only then+/// find them violating the bound. This is the derivation the ≥ rule exists for,+/// and it is the one usually said to need merging. It does not: the bound enters+/// as a clash rather than as a rule.+const WITNESS_TBOX: &str = r#"+ :r a owl:ObjectProperty .+ :C a owl:Class . :D a owl:Class .+ :C rdfs:subClassOf :D .+ :Bad a owl:Class ; rdfs:subClassOf+ [ a owl:Restriction ; owl:onProperty :r ; owl:minQualifiedCardinality 2 ;+ owl:onClass :C ] ,+ [ a owl:Restriction ; owl:onProperty :r ; owl:maxQualifiedCardinality 1 ;+ owl:onClass :D ] .+"#;++#[test]+fn the_at_least_rule_invents_witnesses_that_a_later_bound_refutes() {+ if skip() {+ return;+ }+ let dir = refutation("witness", WITNESS_TBOX, "<http://ex.org/Bad>");+ let text = cert_text(&dir);+ assert!(+ text.contains("min ") && text.contains("maxclash "),+ "this one cannot be closed by the bound clash and must run the ≥ rule: {text}"+ );+ // Two distinct witnesses, or the cardinality clash would be counting one+ // individual twice. The `Nodup` side condition is what the checker enforces;+ // this pins that the emitter actually supplies two.+ let min_line = text+ .lines()+ .find(|l| l.trim_start().starts_with("min "))+ .expect("a ≥ step");+ let fields: Vec<&str> = min_line.split_whitespace().collect();+ assert_eq!(fields[3], "2", "the witness count is written before the names: {min_line}");+ assert_ne!(fields[4], fields[5], "the two witnesses must be different names: {min_line}");+ let (code, out) = check_dir(&dir);+ assert_eq!(code, 0, "{out}");+}++/// A disjunction under two disjointness axioms. Both branches have to close, and+/// this is the only rule that makes the certificate a tree.+const TREE_TBOX: &str = r#"+ :A a owl:Class . :B a owl:Class . :N a owl:Class .+ :A owl:disjointWith :N . :B owl:disjointWith :N .+ :Bad a owl:Class ; rdfs:subClassOf [ a owl:Class ; owl:unionOf ( :A :B ) ] , :N .+"#;++#[test]+fn a_disjunction_makes_a_tree_and_both_leaves_must_close() {+ if skip() {+ return;+ }+ let dir = refutation("tree", TREE_TBOX, "<http://ex.org/Bad>");+ let text = cert_text(&dir);+ assert!(text.contains("or "), "a disjunction should appear: {text}");+ assert_eq!(+ text.matches("disjoint ").count(),+ 2,+ "one leaf per branch, and a tableau with one closed branch is not closed: {text}"+ );+ let (code, out) = check_dir(&dir);+ assert_eq!(code, 0, "{out}");+}++// ── 2. The checker can say no ───────────────────────────────────────────++/// A subsumption step citing an axiom nobody asserted. This is the laundering+/// move: a derivation that reads correctly, resting on a premise off the books.+#[test]+fn a_step_citing_an_axiom_the_ontology_lacks_is_rejected() {+ if skip() {+ return;+ }+ let dir = refutation("forge-axiom", DISJOINT_TBOX, "<http://ex.org/Impossible>");+ let forged = cert_text(&dir).replace("<http://ex.org/B>", "<http://ex.org/Invented>");+ std::fs::write(dir.join("refutation.cert"), forged).unwrap();+ let (code, out) = check_dir(&dir);+ assert_eq!(code, 1, "a forged premise must be rejected: {out}");+ assert!(+ out.contains("\"ok\":false"),+ "and the rejection must be legible: {out}"+ );+}++/// A witness reusing a name the branch already constrains. Freshness is the+/// whole of the ∃ and ≥ rules' soundness.+#[test]+fn a_witness_that_reuses_a_branch_name_is_rejected() {+ if skip() {+ return;+ }+ let dir = refutation("forge-fresh", WITNESS_TBOX, "<http://ex.org/Bad>");+ let text = cert_text(&dir);+ let min_line = text+ .lines()+ .find(|l| l.trim_start().starts_with("min "))+ .expect("a ≥ step");+ let fields: Vec<&str> = min_line.split_whitespace().collect();+ // Replace the second witness with the individual the ≥ step is about, which+ // is on the branch already.+ let (subject, second) = (fields[1], fields[5]);+ let forged = text.replace(second, subject);+ std::fs::write(dir.join("refutation.cert"), forged).unwrap();+ let (code, out) = check_dir(&dir);+ assert_eq!(code, 1, "a stale witness must be rejected: {out}");+}++/// A file the tree does not consume. A producer that truncated its derivation,+/// or wrote a second one, must not read as having finished the first.+#[test]+fn a_file_with_tokens_left_over_is_a_parse_error_not_a_verdict() {+ if skip() {+ return;+ }+ let dir = refutation("forge-trailing", DISJOINT_TBOX, "<http://ex.org/Impossible>");+ let mut text = cert_text(&dir);+ text.push_str("\nbot leftover\n");+ std::fs::write(dir.join("refutation.cert"), text).unwrap();+ let (code, out) = check_dir(&dir);+ assert_eq!(+ code, 2,+ "\"I could not read the file\" and \"this is not a refutation\" are different \+ answers and the exit codes must keep them apart: {out}"+ );+}++// ── 3. The emitter declines rather than inventing ───────────────────────++#[test]+fn a_satisfiable_class_gets_no_certificate_and_no_files() {+ if skip() {+ return;+ }+ let dir = scratch("satisfiable");+ let store = Arc::new(GraphStore::new());+ store+ .load_turtle(&format!(+ "{PREFIXES}:A a owl:Class . :Fine a owl:Class ; rdfs:subClassOf :A ."+ ), None)+ .unwrap();+ let reasoner = DlReasoner::from_graph(&store).unwrap();+ let outcome = reasoner+ .certify_class_unsatisfiable("<http://ex.org/Fine>", &dir)+ .unwrap();+ assert!(!outcome.is_certified(), "{}", outcome.describe());+ assert!(+ !dir.join("refutation.cert").exists(),+ "nothing should be written for an answer that was never negative"+ );+}++/// An inconsistency that lives entirely in transitivity, which the certified+/// calculus has no rule for. The emitter must decline AND say which rule it+/// lacked, because "no refutation exists" and "no refutation this calculus can+/// write" are different sentences.+#[test]+fn an_inconsistency_outside_the_calculus_is_declined_by_name() {+ if skip() {+ return;+ }+ let dir = scratch("trans");+ let store = Arc::new(GraphStore::new());+ store+ .load_turtle(&format!(+ "{PREFIXES}+ :r a owl:ObjectProperty , owl:TransitiveProperty .+ :C a owl:Class .+ :Bad a owl:Class ; rdfs:subClassOf+ [ a owl:Restriction ; owl:onProperty :r ; owl:someValuesFrom+ [ a owl:Restriction ; owl:onProperty :r ; owl:someValuesFrom :C ] ] ,+ [ a owl:Restriction ; owl:onProperty :r ; owl:allValuesFrom+ [ a owl:Class ; owl:complementOf :C ] ] .+ "+ ), None)+ .unwrap();+ let reasoner = DlReasoner::from_graph(&store).unwrap();+ let outcome = reasoner+ .certify_class_unsatisfiable("<http://ex.org/Bad>", &dir)+ .unwrap();+ assert!(!outcome.is_certified(), "{}", outcome.describe());+ assert!(+ outcome.describe().contains("trans"),+ "the decline has to name the rule it lacked: {}",+ outcome.describe()+ );+ assert!(+ !dir.join("refutation.cert").exists(),+ "and write nothing rather than something that will not check"+ );+}