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
A verified first-order resolution calculus in core Lean (#224)
Fabio Rovaia43c0e6ecbed
diff --git a/lean/Fo.lean b/lean/Fo.leannew file mode 100644index 00000000..f014a5be--- /dev/null+++ b/lean/Fo.lean@@ -0,0 +1,5 @@+import Fo.Term+import Fo.Clause+import Fo.Resolve+import Fo.Check+import Fo.Demodiff --git a/lean/Fo/Check.lean b/lean/Fo/Check.leannew file mode 100644index 00000000..537e2afa--- /dev/null+++ b/lean/Fo/Check.lean@@ -0,0 +1,222 @@+import Fo.Resolve++/-!+ The certificate, the checker, and `Fo.unsat_of_check`.++ A refutation is a list of steps. Each names its premises by identifier,+ supplies the substitutions and remainders it used, and states the clause it+ concludes. The checker replays each step and adds the stated conclusion to+ the set it carries. Reaching the empty clause means the original set has no+ model, over any carrier.+-/++namespace Fo++/-- A substitution given as a finite table. A variable the table does not+mention maps to itself. -/+def ofList (tbl : List (Nat × Term)) : Subst := fun n =>+ match tbl.find? (fun p => p.1 == n) with+ | some p => p.2+ | none => .var n++/-- One step of a refutation. -/+inductive Step where+ | resolve (ci : Nat) (lc : Lit) (σc : List (Nat × Term)) (restc : Clause)+ (dj : Nat) (ld : Lit) (σd : List (Nat × Term)) (restd : Clause)+ | factor (ci : Nat) (la : Lit) (lb : Lit) (σ : List (Nat × Term)) (rest : Clause)+ deriving Repr++structure Line where+ id : Nat+ concl : Clause+ step : Step+ deriving Repr++abbrev Refutation := List Line++def lookup (F : Formula) (i : Nat) : Option Clause :=+ match F with+ | [] => none+ | p :: rest => if p.1 = i then some p.2 else lookup rest i++theorem lookup_mem {F : Formula} {i : Nat} {c : Clause}+ (h : lookup F i = some c) : (i, c) ∈ F := by+ induction F with+ | nil => simp [lookup] at h+ | cons p rest ih =>+ unfold lookup at h+ by_cases hp : p.1 = i+ · rw [if_pos hp] at h+ have : p.2 = c := by simpa using h+ subst this; subst hp; simp+ · rw [if_neg hp] at h+ exact List.mem_cons_of_mem _ (ih h)++/-- Every literal of `a` is in `b`.++Used as `subsumes licensed stated`: everything the RULE gives must appear in+the conclusion the step STATES, and not the other way round. A stated+conclusion may carry extra literals, which only makes it weaker; it may never+DROP one, because dropping a literal claims more than the rule licensed. The+empty clause is the case that matters: stating it forces the licensed clause+to be empty too. -/+def subsumes (a b : Clause) : Bool := a.all (fun x => b.any (Lit.beq x))++theorem mem_of_subsumes {a b : Clause} (h : subsumes a b = true) {x : Lit}+ (hx : x ∈ a) : x ∈ b := by+ obtain ⟨y, hy, hxy⟩ := List.any_eq_true.mp (List.all_eq_true.mp h x hx)+ exact Lit.eq_of_beq hxy ▸ hy++theorem sat_of_subsumes {α : Type} {M : Struct α} {a b : Clause}+ (h : subsumes a b = true) (ha : Sat M a) : Sat M b := by+ intro ρ+ obtain ⟨l, hl, hv⟩ := ha ρ+ exact ⟨l, mem_of_subsumes h hl, hv⟩++/-! ## The two conditions++Split out from `checkStep` so each is a chain of `if`s over ordinary values,+with no `match` in it. The soundness proofs are then three `by_cases` and+nothing about what a multi-scrutinee match binds. -/++def checkResolve (c d : Clause) (lc ld : Lit) (σc σd : Subst)+ (restc restd : Clause) : Option Clause :=+ if coveredBy c lc restc then+ if coveredBy d ld restd then+ if Lit.beq (applyL σc lc) (Lit.neg (applyL σd ld)) then+ some (applyC σc restc ++ applyC σd restd)+ else none+ else none+ else none++def checkFactor (c : Clause) (la lb : Lit) (σ : Subst) (rest : Clause) : Option Clause :=+ if coveredBy c la rest then+ if rest.any (Lit.beq lb) then+ if Lit.beq (applyL σ la) (applyL σ lb) then+ some (applyC σ rest)+ else none+ else none+ else none++theorem checkResolve_sound {α : Type} {M : Struct α} {c d : Clause} {lc ld : Lit}+ {σc σd : Subst} {restc restd out : Clause}+ (hc : Sat M c) (hd : Sat M d)+ (h : checkResolve c d lc ld σc σd restc restd = some out) : Sat M out := by+ unfold checkResolve at h+ by_cases h1 : coveredBy c lc restc = true+ · rw [if_pos h1] at h+ by_cases h2 : coveredBy d ld restd = true+ · rw [if_pos h2] at h+ by_cases h3 : Lit.beq (applyL σc lc) (Lit.neg (applyL σd ld)) = true+ · rw [if_pos h3] at h+ have hout := (Option.some.inj h).symm+ subst hout+ exact resolve_sound hc hd h1 h2 (Lit.eq_of_beq h3)+ · rw [if_neg h3] at h; simp at h+ · rw [if_neg h2] at h; simp at h+ · rw [if_neg h1] at h; simp at h++theorem checkFactor_sound {α : Type} {M : Struct α} {c : Clause} {la lb : Lit}+ {σ : Subst} {rest out : Clause}+ (hc : Sat M c) (h : checkFactor c la lb σ rest = some out) : Sat M out := by+ unfold checkFactor at h+ by_cases h1 : coveredBy c la rest = true+ · rw [if_pos h1] at h+ by_cases h2 : rest.any (Lit.beq lb) = true+ · rw [if_pos h2] at h+ by_cases h3 : Lit.beq (applyL σ la) (applyL σ lb) = true+ · rw [if_pos h3] at h+ have hout := (Option.some.inj h).symm+ subst hout+ obtain ⟨y, hy, hxy⟩ := List.any_eq_true.mp h2+ exact factor_sound hc h1 (Lit.eq_of_beq hxy ▸ hy) (Lit.eq_of_beq h3)+ · rw [if_neg h3] at h; simp at h+ · rw [if_neg h2] at h; simp at h+ · rw [if_neg h1] at h; simp at h++/-- Check one step, returning the clause the rule licenses, or `none`. -/+def checkStep (F : Formula) : Step → Option Clause+ | .resolve ci lc σc restc dj ld σd restd =>+ match lookup F ci with+ | none => none+ | some c =>+ match lookup F dj with+ | none => none+ | some d => checkResolve c d lc ld (ofList σc) (ofList σd) restc restd+ | .factor ci la lb σ rest =>+ match lookup F ci with+ | none => none+ | some c => checkFactor c la lb (ofList σ) rest++theorem checkStep_sound {α : Type} {M : Struct α} {F : Formula} {st : Step}+ {out : Clause} (hm : Models M F) (h : checkStep F st = some out) : Sat M out := by+ cases st with+ | resolve ci lc σc restc dj ld σd restd =>+ simp only [checkStep] at h+ cases hc : lookup F ci with+ | none => rw [hc] at h; simp at h+ | some c =>+ rw [hc] at h+ cases hd : lookup F dj with+ | none => rw [hd] at h; simp at h+ | some d =>+ rw [hd] at h+ exact checkResolve_sound (hm (ci, c) (lookup_mem hc))+ (hm (dj, d) (lookup_mem hd)) h+ | factor ci la lb σ rest =>+ simp only [checkStep] at h+ cases hc : lookup F ci with+ | none => rw [hc] at h; simp at h+ | some c => rw [hc] at h; exact checkFactor_sound (hm (ci, c) (lookup_mem hc)) h++/-- Replay a refutation. Accepts exactly when a line states the empty clause,+having checked every line up to it. -/+def check (F : Formula) : Refutation → Bool+ | [] => false+ | ln :: rest =>+ match checkStep F ln.step with+ | none => false+ | some licensed =>+ if subsumes licensed ln.concl then+ if ln.concl.isEmpty then true+ else check ((ln.id, ln.concl) :: F) rest+ else false++theorem check_sound : ∀ (p : Refutation) {α : Type} (F : Formula) (M : Struct α),+ Models M F → check F p = true → False := by+ intro p+ induction p with+ | nil => intro α F M _ h; simp [check] at h+ | cons ln rest ih =>+ intro α F M hm h+ unfold check at h+ cases hstep : checkStep F ln.step with+ | none => rw [hstep] at h; simp at h+ | some licensed =>+ rw [hstep] at h+ simp only at h+ have hlic : Sat M licensed := checkStep_sound hm hstep+ by_cases hsub : subsumes licensed ln.concl = true+ · rw [if_pos hsub] at h+ have hcon : Sat M ln.concl := sat_of_subsumes hsub hlic+ by_cases he : ln.concl.isEmpty = true+ · have hnil : ln.concl = [] := by+ cases hc : ln.concl with+ | nil => rfl+ | cons a as => rw [hc] at he; simp at he+ obtain ⟨l, hl, _⟩ := hnil ▸ hcon (fun _ => M.elem)+ exact absurd hl (by simp)+ · rw [if_neg he] at h+ refine ih ((ln.id, ln.concl) :: F) M ?_ h+ intro q hq+ rcases List.mem_cons.mp hq with heq | hin+ · subst heq; exact hcon+ · exact hm q hin+ · rw [if_neg hsub] at h; simp at h++/-- **The theorem.** A refutation this checker accepts is a proof that the+clause set it was handed has no model, over any carrier. -/+theorem unsat_of_check {F : Formula} {p : Refutation} (h : check F p = true) :+ Unsat F := fun _ M hm => check_sound p F M hm h++end Fodiff --git a/lean/Fo/Clause.lean b/lean/Fo/Clause.leannew file mode 100644index 00000000..dc778bdb--- /dev/null+++ b/lean/Fo/Clause.lean@@ -0,0 +1,118 @@+import Fo.Term++/-!+ Literals, clauses, and what it means for a structure to satisfy a clause set.++ A clause is a list of literals read as a DISJUNCTION, with its variables+ UNIVERSALLY quantified. That second half is what makes instantiation free:+ a model of a clause is a model of every instance of it, which is the whole+ reason a resolution step may apply a substitution to its parents without+ asking anyone's permission.+-/++namespace Fo++/-- An atom: a predicate symbol applied to arguments. -/+structure Atom where+ pred : Nat+ args : List Term+ deriving Repr, Inhabited++def Atom.beq (a b : Atom) : Bool := a.pred == b.pred && Term.beqs a.args b.args++instance : BEq Atom := ⟨Atom.beq⟩++theorem Atom.eq_of_beq {a b : Atom} (h : Atom.beq a b = true) : a = b := by+ simp only [Atom.beq, Bool.and_eq_true, beq_iff_eq] at h+ cases a; cases b+ simp only [Atom.mk.injEq]+ exact ⟨h.1, Term.eqs_of_beqs h.2⟩++/-- A literal: an atom and a polarity. Same choice as the propositional+checker, and for the same reason: a polarity kept in a field is a polarity no+proof has to recover from an encoding. -/+structure Lit where+ pos : Bool+ atom : Atom+ deriving Repr, Inhabited++def Lit.neg (l : Lit) : Lit := ⟨!l.pos, l.atom⟩++def Lit.beq (a b : Lit) : Bool := a.pos == b.pos && Atom.beq a.atom b.atom++instance : BEq Lit := ⟨Lit.beq⟩++theorem Lit.eq_of_beq {a b : Lit} (h : Lit.beq a b = true) : a = b := by+ simp only [Lit.beq, Bool.and_eq_true, beq_iff_eq] at h+ cases a; cases b+ simp only [Lit.mk.injEq]+ exact ⟨h.1, Atom.eq_of_beq h.2⟩++/-- A clause: a disjunction of literals, variables universally quantified. -/+abbrev Clause := List Lit++/-- A clause set. Indexed, because a certificate names its premises. -/+abbrev Formula := List (Nat × Clause)++def applyA (σ : Subst) (a : Atom) : Atom := ⟨a.pred, applyTs σ a.args⟩+def applyL (σ : Subst) (l : Lit) : Lit := ⟨l.pos, applyA σ l.atom⟩+def applyC (σ : Subst) (c : Clause) : Clause := c.map (applyL σ)++/-! ## Semantics -/++def holdsA {α : Type} (M : Struct α) (ρ : Env α) (a : Atom) : Prop :=+ M.rel a.pred (evalTs M ρ a.args)++def holdsL {α : Type} (M : Struct α) (ρ : Env α) (l : Lit) : Prop :=+ if l.pos then holdsA M ρ l.atom else ¬ holdsA M ρ l.atom++/-- A clause holds under ONE environment when some literal does. -/+def holdsC {α : Type} (M : Struct α) (ρ : Env α) (c : Clause) : Prop :=+ ∃ l, l ∈ c ∧ holdsL M ρ l++/-- A model satisfies a clause when it holds under EVERY environment: the+variables are universally quantified. -/+def Sat {α : Type} (M : Struct α) (c : Clause) : Prop :=+ ∀ ρ : Env α, holdsC M ρ c++def Models {α : Type} (M : Struct α) (F : Formula) : Prop :=+ ∀ p, p ∈ F → Sat M p.2++/-- No structure, over any carrier, satisfies every clause. -/+def Unsat (F : Formula) : Prop :=+ ∀ (α : Type) (M : Struct α), ¬ Models M F++/-! ## Instantiation is free++The three lemmas that let a resolution step substitute into its parents. Each+is the substitution lemma of `Fo.Term` carried up one level. -/++theorem holdsA_applyA {α : Type} (M : Struct α) (ρ : Env α) (σ : Subst) (a : Atom) :+ holdsA M ρ (applyA σ a) ↔ holdsA M (fun n => evalT M ρ (σ n)) a := by+ simp only [holdsA, applyA]+ rw [evalTs_applyTs]++theorem holdsL_applyL {α : Type} (M : Struct α) (ρ : Env α) (σ : Subst) (l : Lit) :+ holdsL M ρ (applyL σ l) ↔ holdsL M (fun n => evalT M ρ (σ n)) l := by+ obtain ⟨pos, atom⟩ := l+ simp only [holdsL, applyL]+ cases pos <;> simp [holdsA_applyA]++/-- A literal and its negation never hold together. -/+theorem holdsL_neg {α : Type} (M : Struct α) (ρ : Env α) (l : Lit) :+ holdsL M ρ l.neg ↔ ¬ holdsL M ρ l := by+ obtain ⟨pos, atom⟩ := l+ cases pos+ · show holdsA M ρ atom ↔ ¬ ¬ holdsA M ρ atom+ exact ⟨fun h hn => hn h, fun h => Classical.byContradiction h⟩+ · show ¬ holdsA M ρ atom ↔ ¬ holdsA M ρ atom+ exact Iff.rfl++/-- **A model of a clause is a model of every instance of it.** -/+theorem sat_applyC {α : Type} {M : Struct α} {c : Clause} (h : Sat M c) (σ : Subst) :+ Sat M (applyC σ c) := by+ intro ρ+ obtain ⟨l, hl, hv⟩ := h (fun n => evalT M ρ (σ n))+ exact ⟨applyL σ l, List.mem_map_of_mem hl, (holdsL_applyL M ρ σ l).mpr hv⟩++end Fodiff --git a/lean/Fo/Demo.lean b/lean/Fo/Demo.leannew file mode 100644index 00000000..ff07c4c8--- /dev/null+++ b/lean/Fo/Demo.lean@@ -0,0 +1,104 @@+import Fo.Check++/-!+ The calculus, run.++ The worked example is the one every textbook opens with, and it is here+ because it is the smallest refutation that actually NEEDS unification:++ ∀x. P(x) → Q(x) ¬P(x) ∨ Q(x)+ P(a) P(a)+ ¬Q(a) ¬Q(a)++ Resolving the first two requires instantiating `x` to `a`, which is the step+ a propositional checker cannot take and the reason this development exists.+-/++namespace Fo++-- Symbols: variable 0 is `x`, function 0 is the constant `a`, predicate 0 is+-- `P` and predicate 1 is `Q`.+def x : Term := .var 0+def a : Term := .app 0 []+def P (t : Term) : Atom := ⟨0, [t]⟩+def Q (t : Term) : Atom := ⟨1, [t]⟩++def notPx : Lit := ⟨false, P x⟩+def Qx : Lit := ⟨true, Q x⟩+def Pa : Lit := ⟨true, P a⟩+def notQa : Lit := ⟨false, Q a⟩+def Qa : Lit := ⟨true, Q a⟩++def F : Formula := [(1, [notPx, Qx]), (2, [Pa]), (3, [notQa])]++/-- `x ↦ a`, the substitution the first step needs. -/+def xa : List (Nat × Term) := [(0, a)]++def refutation : Refutation :=+ [ -- Resolve `¬P(x) ∨ Q(x)` with `P(a)`, instantiating x to a, giving `Q(a)`.+ ⟨4, [Qa], .resolve 1 notPx xa [Qx] 2 Pa [] []⟩,+ -- Resolve `Q(a)` with `¬Q(a)`, giving the empty clause.+ ⟨5, [], .resolve 4 Qa [] [] 3 notQa [] []⟩ ]++/-- info: true -/+#guard_msgs in #eval check F refutation++/-- The clause set has no model, over any carrier. -/+theorem F_unsat : Unsat F := unsat_of_check (p := refutation) (by native_decide)++/-! ## Forgeries++Six ways to be refused, one per way a step can be wrong. -/++-- The substitution is missing, so `¬P(x)` and `P(a)` are not complementary:+-- `x` and `a` are different terms and the checker compares terms.+/-- info: false -/+#guard_msgs in #eval check F [⟨4, [Qa], .resolve 1 notPx [] [Qx] 2 Pa [] []⟩, ⟨5, [], .resolve 4 Qa [] [] 3 notQa [] []⟩]++-- Substituting the WRONG way: `a ↦ x` does not unify these either.+/-- info: false -/+#guard_msgs in #eval check F [⟨4, [Qa], .resolve 1 notPx [(1, x)] [Qx] 2 Pa [] []⟩]++-- Resolving two literals of the SAME polarity. `Q(a)` against `Q(a)` is not a+-- resolution step however well the terms match.+/-- info: false -/+#guard_msgs in #eval check F [⟨4, [Qa], .resolve 1 notPx xa [Qx] 2 Pa [] []⟩, ⟨5, [], .resolve 4 Qa [] [] 4 Qa [] []⟩]++-- The remainder does not cover the parent: `Q(x)` is dropped from clause 1+-- without being resolved away, so the conclusion claims more than the step did.+/-- info: false -/+#guard_msgs in #eval check F [⟨4, [], .resolve 1 notPx xa [] 2 Pa [] []⟩]++-- Naming a clause that is not there.+/-- info: false -/+#guard_msgs in #eval check F [⟨9, [], .resolve 99 notPx xa [Qx] 2 Pa [] []⟩]++-- A prefix of a refutation is not a refutation: the step checks, and it is+-- not the empty clause.+/-- info: false -/+#guard_msgs in #eval check F [⟨4, [Qa], .resolve 1 notPx xa [Qx] 2 Pa [] []⟩]++/-! ## And the claim behind the forgeries -/++/-- A structure in which `P` and `Q` hold of everything. It satisfies+`P(a)` and `¬P(x) ∨ Q(x)`, so those two alone cannot be refuted. -/+def allTrue : Struct Unit := ⟨fun _ _ => (), fun _ _ => True, ()⟩++/-- **A satisfiable clause set cannot be refuted, by any proof at all.**++Not an example: a theorem over every `Refutation`, which is what separates+"this forgery was caught" from "no forgery can succeed". -/+theorem no_refutation_of_a_satisfiable_set (prf : Refutation) :+ check [(1, [notPx, Qx]), (2, [Pa])] prf = false := by+ cases h : check [(1, [notPx, Qx]), (2, [Pa])] prf with+ | false => rfl+ | true =>+ refine absurd (unsat_of_check h Unit allTrue ?_) (by simp)+ intro q hq ρ+ rcases List.mem_cons.mp hq with heq | hin+ · subst heq; exact ⟨Qx, by simp, trivial⟩+ · have : q = (2, [Pa]) := by simpa using hin+ subst this+ exact ⟨Pa, by simp, trivial⟩++end Fodiff --git a/lean/Fo/Resolve.lean b/lean/Fo/Resolve.leannew file mode 100644index 00000000..1fec6640--- /dev/null+++ b/lean/Fo/Resolve.lean@@ -0,0 +1,89 @@+import Fo.Clause++/-!+ The resolution rule, and the only theorem that matters about it.++ ## The shape of a step++ A step names two parent clauses, one literal in each, a substitution FOR EACH+ PARENT SEPARATELY, and the remainder of each parent. Two substitutions rather+ than one is what removes the need to standardise variables apart: each parent+ is instantiated on its own, so neither has to be renamed away from the other+ first. A clause is universally quantified, so any instance of it holds in any+ model of it, and `sat_applyC` is exactly that sentence.++ ## What the checker asks, and what it does not++ One question: are the two chosen literals, after their own substitutions, the+ same atom with opposite polarity? That is an equality on terms.++ No unifier is computed here and no theorem about most-generality is stated.+ Decision 0005 names "a verified first-order calculus with unification" as the+ missing piece; the unification half of that is avoidable, because a checker+ does not need an algorithm that FINDS a most general unifier. It needs to+ confirm that a substitution it was HANDED makes two literals complementary.+ Resolving on a unifier that is not most general is still sound; it just+ proves less, and proving less is the prover's problem.++ ## Covering, rather than deletion++ The remainder is supplied by the certificate and CHECKED by covering: every+ literal of the parent must be the resolved one or be in the remainder. Not+ the other way round, and not an exact deletion. Soundness needs no more: if a+ model satisfies the parent then some literal of it is true, and covering says+ that literal is accounted for. A remainder carrying extra literals only makes+ the conclusion weaker, which cannot make a refutation unsound.+-/++namespace Fo++/-- Every literal of `c` is `l`, or is in `rest`. -/+def coveredBy (c : Clause) (l : Lit) (rest : Clause) : Bool :=+ c.all (fun x => Lit.beq x l || rest.any (Lit.beq x))++theorem covered_cases {c : Clause} {l : Lit} {rest : Clause} {x : Lit}+ (h : coveredBy c l rest = true) (hx : x ∈ c) : x = l ∨ x ∈ rest := by+ have := List.all_eq_true.mp h x hx+ rcases Bool.or_eq_true _ _ |>.mp this with h1 | h2+ · exact Or.inl (Lit.eq_of_beq h1)+ · obtain ⟨y, hy, hxy⟩ := List.any_eq_true.mp h2+ exact Or.inr (Lit.eq_of_beq hxy ▸ hy)++/-- **Resolution is sound.** -/+theorem resolve_sound {α : Type} {M : Struct α} {c d restc restd : Clause}+ {σc σd : Subst} {lc ld : Lit}+ (hc : Sat M c) (hd : Sat M d)+ (hcv : coveredBy c lc restc = true) (hdv : coveredBy d ld restd = true)+ (hcomp : applyL σc lc = Lit.neg (applyL σd ld)) :+ Sat M (applyC σc restc ++ applyC σd restd) := by+ intro ρ+ obtain ⟨la, hla, hva⟩ := sat_applyC hc σc ρ+ obtain ⟨lb, hlb, hvb⟩ := sat_applyC hd σd ρ+ obtain ⟨la0, hla0, rfl⟩ := List.mem_map.mp hla+ obtain ⟨lb0, hlb0, rfl⟩ := List.mem_map.mp hlb+ rcases covered_cases hcv hla0 with rfl | hrest+ · rcases covered_cases hdv hlb0 with rfl | hrest2+ · -- Both resolved literals true at once, and they are complementary.+ rw [hcomp] at hva+ exact absurd hvb ((holdsL_neg M ρ (applyL σd lb0)).mp hva)+ · exact ⟨applyL σd lb0,+ List.mem_append.mpr (Or.inr (List.mem_map_of_mem hrest2)), hvb⟩+ · exact ⟨applyL σc la0,+ List.mem_append.mpr (Or.inl (List.mem_map_of_mem hrest)), hva⟩++/-- **Factoring is sound.** Two literals a substitution makes equal collapse to+one, and the clause still holds. -/+theorem factor_sound {α : Type} {M : Struct α} {c rest : Clause} {σ : Subst}+ {la lb : Lit} (h : Sat M c)+ (hcv : coveredBy c la rest = true) (hlb : lb ∈ rest)+ (heq : applyL σ la = applyL σ lb) :+ Sat M (applyC σ rest) := by+ intro ρ+ obtain ⟨l0, hl0, hv⟩ := sat_applyC h σ ρ+ obtain ⟨l1, hl1, rfl⟩ := List.mem_map.mp hl0+ rcases covered_cases hcv hl1 with rfl | hrest+ · rw [heq] at hv+ exact ⟨applyL σ lb, List.mem_map_of_mem hlb, hv⟩+ · exact ⟨applyL σ l1, List.mem_map_of_mem hrest, hv⟩++end Fodiff --git a/lean/Fo/Term.lean b/lean/Fo/Term.leannew file mode 100644index 00000000..0effd345--- /dev/null+++ b/lean/Fo/Term.lean@@ -0,0 +1,141 @@+/-+ First-order terms, substitution, and the one lemma everything rests on.++ ## The design decision that makes this tractable++ Decision 0005 says checking a superposition proof "needs a verified+ first-order calculus with unification that does not exist in core Lean". The+ unification half of that is avoidable, and avoiding it is what brings the+ work inside reach.++ A checker does not need an algorithm that FINDS a most general unifier. It+ needs to confirm that a substitution it was HANDED makes two literals+ complementary, and that is a decidable equality on terms. The prover searches;+ the certificate carries the substitution it used; the checker applies it and+ compares. Most-generality is a property of a good search, not a premise of+ soundness: resolving on a non-most-general unifier is still sound, it just+ proves less.++ So there is no `mgu` in this development, and no theorem about one. There is+ `applySubst`, `==`, and the substitution lemma below.+-/++namespace Fo++/-- A first-order term. Function symbols and variables are numbered; arity is+not tracked, because a structure interprets a symbol at whatever list of+arguments it is given and nothing here needs arity to be well formed. -/+inductive Term where+ | var (n : Nat)+ | app (f : Nat) (args : List Term)+ deriving Repr, Inhabited++/-! ## Equality++Written out rather than derived: `Term` is a nested inductive, through+`List Term`, and the `DecidableEq` handler does not reach through the list. The+checker needs a Bool, and soundness needs `beq_eq` below, so both are here. -/++mutual+def Term.beq : Term → Term → Bool+ | .var a, .var b => a == b+ | .app f as, .app g bs => f == g && Term.beqs as bs+ | _, _ => false++def Term.beqs : List Term → List Term → Bool+ | [], [] => true+ | a :: as, b :: bs => Term.beq a b && Term.beqs as bs+ | _, _ => false+end++instance : BEq Term := ⟨Term.beq⟩++mutual+theorem Term.eq_of_beq : ∀ {a b : Term}, Term.beq a b = true → a = b+ | .var _, .var _, h => by simp [Term.beq] at h; simp [h]+ | .app _ as, .app _ bs, h => by+ simp only [Term.beq, Bool.and_eq_true, beq_iff_eq] at h+ rw [h.1, Term.eqs_of_beqs h.2]+ | .var _, .app _ _, h => by simp [Term.beq] at h+ | .app _ _, .var _, h => by simp [Term.beq] at h++theorem Term.eqs_of_beqs : ∀ {as bs : List Term}, Term.beqs as bs = true → as = bs+ | [], [], _ => rfl+ | a :: as, b :: bs, h => by+ simp only [Term.beqs, Bool.and_eq_true] at h+ rw [Term.eq_of_beq h.1, Term.eqs_of_beqs h.2]+ | [], _ :: _, h => by simp [Term.beqs] at h+ | _ :: _, [], h => by simp [Term.beqs] at h+end++/-- A substitution: a total map from variable numbers to terms. Total rather+than finite, so composing two of them needs no bookkeeping; a certificate+supplies a finite table and `ofList` turns it into one of these. -/+abbrev Subst := Nat → Term++def idSubst : Subst := Term.var++mutual+/-- Apply a substitution throughout a term. -/+def applyT (σ : Subst) : Term → Term+ | .var n => σ n+ | .app f args => .app f (applyTs σ args)++def applyTs (σ : Subst) : List Term → List Term+ | [] => []+ | t :: ts => applyT σ t :: applyTs σ ts+end++/-- A first-order structure over a carrier.++`fn` and `rel` are total on lists of arguments. A partial, arity-respecting+version would be more faithful to a textbook and would put an arity side+condition in the middle of every proof below; nothing here needs one, because+the syntax and the semantics agree on how many arguments a symbol was given. -/+structure Struct (α : Type) where+ fn : Nat → List α → α+ rel : Nat → List α → Prop+ /-- The domain is NON-EMPTY, which standard first-order semantics requires+ and which is not a technicality here. `Sat M c` quantifies over every+ environment, and over an empty carrier there are no environments, so the+ EMPTY CLAUSE would be vacuously satisfied and every refutation would prove+ nothing. Carrying a witness in the structure is the cheapest way to say what+ a first-order model is. -/+ elem : α++/-- An assignment of a carrier element to every variable. -/+abbrev Env (α : Type) := Nat → α++mutual+def evalT {α : Type} (M : Struct α) (ρ : Env α) : Term → α+ | .var n => ρ n+ | .app f args => M.fn f (evalTs M ρ args)++def evalTs {α : Type} (M : Struct α) (ρ : Env α) : List Term → List α+ | [] => []+ | t :: ts => evalT M ρ t :: evalTs M ρ ts+end++/-! ## The substitution lemma++Evaluating a substituted term is evaluating the original term in the+environment the substitution describes. Everything in `Fo/Resolve.lean` is this+lemma plus case analysis. -/++mutual+theorem evalT_applyT {α : Type} (M : Struct α) (ρ : Env α) (σ : Subst) :+ ∀ t : Term, evalT M ρ (applyT σ t) = evalT M (fun n => evalT M ρ (σ n)) t+ | .var n => by simp [applyT, evalT]+ | .app f args => by+ simp only [applyT, evalT]+ rw [evalTs_applyTs M ρ σ args]++theorem evalTs_applyTs {α : Type} (M : Struct α) (ρ : Env α) (σ : Subst) :+ ∀ ts : List Term, evalTs M ρ (applyTs σ ts) = evalTs M (fun n => evalT M ρ (σ n)) ts+ | [] => by simp [applyTs, evalTs]+ | t :: ts => by+ simp only [applyTs, evalTs]+ rw [evalT_applyT M ρ σ t, evalTs_applyTs M ρ σ ts]+end++end Fodiff --git a/lean/FoMain.lean b/lean/FoMain.leannew file mode 100644index 00000000..818f53cc--- /dev/null+++ b/lean/FoMain.lean@@ -0,0 +1,173 @@+import Fo++/-!+`oo-fores REFUTATION.cert`++Reads a clause set and a resolution refutation, replays it, and prints one JSON+object.++Exit codes, matching the convention the other checkers here use:++* `0` the refutation checks, so **the clause set has no model, over any+ carrier, finite or infinite**. The statement is `Fo.unsat_of_check`.+* `1` the refutation does not check. A statement about the CERTIFICATE and not+ about the clause set: a prover can fail to find a refutation that exists, and+ this exit code never means the set is satisfiable.+* `2` the file could not be read or parsed. No verdict either way.++## What exit 0 does not say++* Nothing about the prover. A checked refutation is checked; the search that+ found it is untrusted, which is why it is worth checking.+* Nothing about whether the clause set is your problem. Clausification and+ Skolemisation happen before this file and are not certified by it. A proof of+ the wrong clause set is a proof of the wrong clause set.++## The format++Tab separated. Terms are `vN` for a variable and `fN` or `fN[t,t]` for a+function. A literal is `+pN[t,t]` or `-pN[t,t]`. A clause is literals separated+by spaces, and the empty clause is the empty field. A substitution is+`N=t;N=t`.++ c <id> <clause>+ r <id> <concl> <ci> <lc> <σc> <restc> <dj> <ld> <σd> <restd>+ f <id> <concl> <ci> <la> <lb> <σ> <rest>+-/++open Fo++/-- Split on a character, dropping empty pieces. -/+def splitDrop (s : String) (c : Char) : List String :=+ (s.splitOn (String.singleton c)).filter (· ≠ "")++mutual+/-- `vN`, `fN`, or `fN[t,t,...]`. Returns the term and the rest of the input. -/+partial def parseTerm (s : List Char) : Option (Term × List Char) :=+ match s with+ | 'v' :: rest =>+ let (ds, rest') := rest.span Char.isDigit+ if ds.isEmpty then none else some (.var (String.mk ds).toNat!, rest')+ | 'f' :: rest =>+ let (ds, rest') := rest.span Char.isDigit+ if ds.isEmpty then none else+ let f := (String.mk ds).toNat!+ match rest' with+ | '[' :: inner =>+ match parseArgs inner with+ | some (args, rest'') => some (.app f args, rest'')+ | none => none+ | _ => some (.app f [], rest')+ | _ => none++partial def parseArgs (s : List Char) : Option (List Term × List Char) :=+ match s with+ | ']' :: rest => some ([], rest)+ | _ =>+ match parseTerm s with+ | none => none+ | some (t, rest) =>+ match rest with+ | ',' :: more =>+ match parseArgs more with+ | some (ts, rest') => some (t :: ts, rest')+ | none => none+ | ']' :: more => some ([t], more)+ | _ => none+end++def parseLit (s : String) : Option Lit :=+ match s.toList with+ | sign :: 'p' :: rest =>+ if sign != '+' && sign != '-' then none else+ let (ds, rest') := rest.span Char.isDigit+ if ds.isEmpty then none else+ let p := (String.mk ds).toNat!+ let args : Option (List Term) :=+ match rest' with+ | '[' :: inner => (parseArgs inner).map Prod.fst+ | [] => some []+ | _ => none+ args.map (fun ts => ⟨sign == '+', ⟨p, ts⟩⟩)+ | _ => none++def parseClause (s : String) : Option Clause :=+ (splitDrop s ' ').foldl (fun acc tok =>+ match acc, parseLit tok with+ | some ls, some l => some (ls ++ [l])+ | _, _ => none) (some [])++def parseSubst (s : String) : Option (List (Nat × Term)) :=+ (splitDrop s ';').foldl (fun acc tok =>+ match acc, tok.splitOn "=" with+ | some ps, [n, t] =>+ match n.toNat?, parseTerm t.toList with+ | some k, some (tm, []) => some (ps ++ [(k, tm)])+ | _, _ => none+ | _, _ => none) (some [])++structure Parsed where+ clauses : Formula+ lines : Refutation++def parseFile (text : String) : Option Parsed := do+ let mut cs : Formula := []+ let mut ls : Refutation := []+ for line in text.splitOn "\n" do+ let fs := line.splitOn "\t"+ match fs with+ | [] => pure ()+ | kind :: rest =>+ if kind == "" || kind.startsWith "#" then pure ()+ else if kind == "c" then+ match rest with+ | [i, cl] =>+ let n ← i.trim.toNat?+ let c ← parseClause cl+ cs := cs ++ [(n, c)]+ | _ => failure+ else if kind == "r" then+ match rest with+ | [i, concl, ci, lc, sc, rc, dj, ld, sd, rd] =>+ let n ← i.trim.toNat?+ ls := ls ++ [⟨n, ← parseClause concl, .resolve+ (← ci.trim.toNat?) (← parseLit lc.trim) (← parseSubst sc) (← parseClause rc)+ (← dj.trim.toNat?) (← parseLit ld.trim) (← parseSubst sd) (← parseClause rd)⟩]+ | _ => failure+ else if kind == "f" then+ match rest with+ | [i, concl, ci, la, lb, sg, rst] =>+ let n ← i.trim.toNat?+ ls := ls ++ [⟨n, ← parseClause concl, .factor+ (← ci.trim.toNat?) (← parseLit la.trim) (← parseLit lb.trim)+ (← parseSubst sg) (← parseClause rst)⟩]+ | _ => failure+ else failure+ some ⟨cs, ls⟩++def main (args : List String) : IO UInt32 := do+ match args with+ | [path] =>+ let text ← try IO.FS.readFile path catch _ =>+ IO.println s!"\{\"ok\":false,\"error\":\"could not read {path}\"}"+ return 2+ match parseFile text with+ | none =>+ IO.println s!"\{\"ok\":false,\"error\":\"could not parse {path}\"}"+ return 2+ | some p =>+ if check p.clauses p.lines then+ IO.println s!"\{\"ok\":true,\"verdict\":\"unsatisfiable\",\+ \"clauses\":{p.clauses.length},\"steps\":{p.lines.length},\+ \"theorem\":\"Fo.unsat_of_check\",\+ \"means\":\"this clause set has no model, over any carrier\"}"+ return 0+ else+ IO.println s!"\{\"ok\":false,\"verdict\":\"not_checked\",\+ \"clauses\":{p.clauses.length},\"steps\":{p.lines.length},\+ \"means\":\"the refutation did not check. This says nothing about \+whether the clause set is satisfiable\"}"+ return 1+ | _ =>+ IO.println "usage: oo-fores REFUTATION.cert"+ return 2diff --git a/lean/lakefile.toml b/lean/lakefile.tomlindex de50bd91..f90037e3 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", "oo-dlrefute", "Fol", "oo-folmodel", "Institution"]+defaultTargets = ["OOCert", "oo-cert", "oo-horn", "Shacl", "oo-shacl", "oo-refute", "Dl", "oo-dlmodel", "oo-dlrefute", "Fol", "oo-folmodel", "Institution", "Fo", "oo-fores"]# 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@@ -84,3 +84,23 @@ root = "FolMain"# file.[[lean_lib]]name = "Institution"++# First-order resolution, checked.+#+# Decision 0005 says a superposition proof cannot be certified here because it+# "needs a verified first-order calculus with unification that does not exist+# in core Lean". The unification half of that is avoidable: a checker does not+# need an algorithm that FINDS a most general unifier, it needs to confirm that+# a substitution it was HANDED makes two literals complementary, which is an+# equality on terms. The prover searches, the certificate carries the+# substitution, the checker applies it and compares.+#+# Separate from `Fol`, which certifies SATISFIABILITY by exhibiting a finite+# model. This certifies UNSATISFIABILITY by exhibiting a refutation, and the+# two are different sentences.+[[lean_lib]]+name = "Fo"++[[lean_exe]]+name = "oo-fores"+root = "FoMain"diff --git a/tests/lean_fo_resolution_test.rs b/tests/lean_fo_resolution_test.rsnew file mode 100644index 00000000..811f093f--- /dev/null+++ b/tests/lean_fo_resolution_test.rs@@ -0,0 +1,104 @@+//! `oo-fores` end to end.+//!+//! Decision 0005 names the missing piece: certifying a superposition proof+//! "needs a verified first-order calculus with unification that does not exist+//! in core Lean". This is that calculus, minus the unification, which turns out+//! not to be needed: a checker does not have to FIND a most general unifier, it+//! has to confirm that a substitution it was handed makes two literals+//! complementary, and that is an equality on terms.++use std::path::PathBuf;+use std::process::Command;+use std::sync::atomic::{AtomicU64, Ordering};++static NEXT: AtomicU64 = AtomicU64::new(0);++fn checker() -> Option<PathBuf> {+ if let Ok(p) = std::env::var("OO_FORES") {+ let p = PathBuf::from(p);+ return p.exists().then_some(p);+ }+ let built = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lean/.lake/build/bin/oo-fores");+ built.exists().then_some(built)+}++struct Run {+ code: i32,+ out: String,+}++fn run(cert: &str) -> Option<Run> {+ let bin = checker()?;+ // One directory per call. These run in parallel and a shared path makes+ // two tests read each other's certificate.+ let dir = std::env::temp_dir().join(format!(+ "oo-fores-{}-{}",+ std::process::id(),+ NEXT.fetch_add(1, Ordering::Relaxed)+ ));+ std::fs::create_dir_all(&dir).unwrap();+ let f = dir.join("r.cert");+ std::fs::write(&f, cert).unwrap();+ let o = Command::new(bin).arg(&f).output().expect("oo-fores runs");+ let _ = std::fs::remove_dir_all(&dir);+ Some(Run {+ code: o.status.code().unwrap_or(-1),+ out: String::from_utf8_lossy(&o.stdout).into_owned(),+ })+}++/// `¬P(x) ∨ Q(x)`, `P(a)`, `¬Q(a)`. The smallest refutation that needs a+/// substitution: resolving the first two instantiates `x` to `a`.+const CLAUSES: &str = "c\t1\t-p0[v0] +p1[v0]\nc\t2\t+p0[f0]\nc\t3\t-p1[f0]\n";+const STEPS: &str = "r\t4\t+p1[f0]\t1\t-p0[v0]\t0=f0\t+p1[v0]\t2\t+p0[f0]\t\t\n\+ r\t5\t\t4\t+p1[f0]\t\t\t3\t-p1[f0]\t\t\n";++#[test]+fn a_checked_refutation_exits_zero_and_names_its_theorem() {+ let Some(r) = run(&format!("{CLAUSES}{STEPS}")) else { return };+ assert_eq!(r.code, 0, "{}", r.out);+ assert!(r.out.contains(r#""theorem":"Fo.unsat_of_check""#), "{}", r.out);+}++#[test]+fn without_the_substitution_the_literals_do_not_resolve() {+ // `¬P(x)` and `P(a)` are complementary only after `x ↦ a`. Drop it and the+ // checker compares `x` with `a` and refuses.+ let bad = "r\t4\t+p1[f0]\t1\t-p0[v0]\t\t+p1[v0]\t2\t+p0[f0]\t\t\n";+ let Some(r) = run(&format!("{CLAUSES}{bad}")) else { return };+ assert_eq!(r.code, 1, "{}", r.out);+ assert!(!r.out.contains("theorem"), "a refusal must name no theorem: {}", r.out);+}++#[test]+fn a_remainder_that_drops_a_literal_is_refused() {+ // Clause 1 is `¬P(x) ∨ Q(x)`. Resolving away `¬P(x)` leaves `Q(x)`, and a+ // step claiming the empty remainder is claiming more than it proved.+ let bad = "r\t4\t\t1\t-p0[v0]\t0=f0\t\t2\t+p0[f0]\t\t\n";+ let Some(r) = run(&format!("{CLAUSES}{bad}")) else { return };+ assert_eq!(r.code, 1, "{}", r.out);+}++#[test]+fn a_prefix_of_a_refutation_is_not_a_refutation() {+ let one = "r\t4\t+p1[f0]\t1\t-p0[v0]\t0=f0\t+p1[v0]\t2\t+p0[f0]\t\t\n";+ let Some(r) = run(&format!("{CLAUSES}{one}")) else { return };+ assert_eq!(r.code, 1, "every step checking is not the same as proving: {}", r.out);+}++#[test]+fn a_satisfiable_clause_set_cannot_be_refuted() {+ // `¬P(x) ∨ Q(x)` and `P(a)` alone have a model, so no step reaches the+ // empty clause.+ let sat = "c\t1\t-p0[v0] +p1[v0]\nc\t2\t+p0[f0]\n";+ let step = "r\t3\t\t1\t-p0[v0]\t0=f0\t\t2\t+p0[f0]\t\t\n";+ let Some(r) = run(&format!("{sat}{step}")) else { return };+ assert_eq!(r.code, 1, "{}", r.out);+}++#[test]+fn an_unparsable_certificate_is_exit_two_and_not_a_verdict() {+ let Some(r) = run("c\t1\tthis is not a literal\n") else { return };+ assert_eq!(r.code, 2, "a parse failure must be exit 2, not a verdict: {}", r.out);+ assert!(!r.out.contains("verdict"), "{}", r.out);+}