Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
Make a rule into data, prove the checker once for every rule table, and refuse to call an assumption a fact
FABIOTESSf62683444c4a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 5ed5acb8..1e5e4f10 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -319,6 +319,15 @@ jobs:- uses: Swatinem/rust-cache@v2- name: Certify every shipped ontology through the proved checkerrun: OO_REQUIRE_FIXTURES=1 cargo test --test lean_certificate_test -- --nocapture+ - name: Check the generic Horn-rule layer, and that a user rule cannot earn the absolute verdict+ # The five legs here are not interchangeable. Four of them prove the+ # checker rejects a specific forgery; the fifth proves that a+ # certificate over rules the user supplied reports a DIFFERENT verdict+ # from one over the built-ins. That last one is the difference between+ # a verification layer and a device for laundering an assumption into a+ # fact, and it is the reason this job exists rather than being folded+ # into the line above.+ run: OO_REQUIRE_FIXTURES=1 cargo test --test lean_horn_certificate_test -- --nocapture# The official W3C SHACL test suite, as a ratchet.#diff --git a/docs/decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md b/docs/decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.mdnew file mode 100644index 00000000..2fa9b7f5--- /dev/null+++ b/docs/decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md@@ -0,0 +1,62 @@+# 0003 · A rule is data, and an assumption is not a fact++- **Status**: implemented · `lean/OOCert/Horn.lean` with `horn_certificate_sound` machine-checked ·+ `lean/OOCert/HornBuiltin.lean` discharges 19 of the engine's rules against the semantics, giving+ `entails_of_builtin_horn` · checker `oo-horn`, gated by `tests/lean_horn_certificate_test.rs` and+ a CI leg · **the Rust reasoner does not yet emit Horn certificates**, and+ `lean/OOCert/Mixed.lean` is deferred (see Not done)+- **Written**: 2026-09-14+- **Related**: decision 0002 (an inference carries a certificate); the adversarial-SHACL assurance+ laundering work, which named the failure this decision is built to avoid++## The problem++`checkStep` had one arm per rule and `Soundness.lean` one lemma per arm. That is fine for a fixed+set of twenty and impossible for rules a user writes, and rules a user writes are the entire+logic-programming family: RIF Core, Datalog, SWRL, and any domain rule table a customer has.+Extending the checker rule by rule would mean a Lean edit per customer.++## Decisions++1. **Rules become data.** A `RulePattern` is a body and a head over triple patterns with variables.+ A certificate step cites a rule by index into a supplied table and gives a binding. `checkHornStep`+ verifies the binding instantiates the body into known triples and the head into the claimed+ conclusion. One generic arm replaces the per-rule ones.+2. **One theorem covers every rule table at once.** `horn_certificate_sound` needs no case analysis+ over rules, because there is no per-rule structure left in the checker. Axioms are+ `propext`, `Classical.choice`, `Quot.sound`, identical to the existing theorem. The trust surface+ does not grow.+3. **The built-ins are a rule table like any other.** 19 of the engine's rules are Horn rules and are+ written out as data in `HornBuiltin.lean`, each with a one-line lemma deriving it from the+ semantic conditions. `cls-int1` and `cls-uni` are not Horn rules and stay as arms: their premise+ count is the length of an RDF list, which is data rather than fixed by the rule. That is not a gap+ in the generalisation, it is the exact boundary of the Horn family, and a user rule language will+ stop in the same place.+4. **The two verdicts never share a word.** A certificate over the built-ins yields `Entails`:+ true in every model of the asserted graph. A certificate over user rules yields `EntailsR`: true+ in every model that ALSO satisfies those rules. The rules are assumed and never checked, so a rule+ reading "every supplier is compliant" produces certificates that check green for ever. The checker+ prints `entailed` or `entailed_under_supplied_rules`, names a different theorem for each, and+ carries a digest of the table that was in force.+ `a_user_rule_never_earns_the_absolute_verdict` fails if that distinction is ever lost.+ Without it this layer is a machine for turning an assumption into a fact with a proof attached,+ which is the thing this project named and then had to find inside its own Lean layer once already.+5. **The digest identifies, it does not commit.** `String.hash` is not a cryptographic hash. It+ exists so two reports can be compared, not so one can be defended against someone who controls+ the rule file. Anyone needing that should hash the file.++## What this does not claim++The checker says a conclusion follows from the premises by the cited rule. It says nothing about+whether the rule is true, whether the rule set is consistent, or whether the asserted graph is+accurate. Under a user table the guarantee is conditional on assumptions the user wrote, and the+report says so in the verdict rather than in a footnote.++## Not done++- The Rust reasoner cannot yet evaluate a supplied rule table or emit a Horn certificate, so today+ the layer checks certificates rather than producing them. That is the next piece.+- `Mixed.lean`, which lets one certificate carry both built-in arms and Horn steps, needs+ `Soundness.lean` generalised from `Entails G` to `EntailsIn P`. The change is mechanical across+ about twenty cases and was deferred rather than rushed. Until it lands, a user-rule certificate+ cannot also cite `cls-int1` or `cls-uni`.diff --git a/docs/lean-certificates.md b/docs/lean-certificates.mdindex c98c3879..63a03004 100644--- a/docs/lean-certificates.md+++ b/docs/lean-certificates.md@@ -141,6 +141,41 @@ repository's RDF was never walked and was excluded without being named. Wideningsurfaced the literal-subject defect in `prp-symp`, `prp-inv1`, `prp-inv2` and `eq-sym`, which livedin `benchmark/`.+## User-written rules++The twenty built-in rules were twenty arms in the checker, which does not extend to rules you write.+`lean/OOCert/Horn.lean` makes a rule into data: a body and a head over triple patterns with+variables. A certificate step cites a rule by index into a table you supply and gives a binding, and+one theorem, `OOCert.horn_certificate_sound`, covers every rule table at once.++```bash+cd lean+lake build+lake exe oo-horn rules # the built-in table, as data+lake exe oo-horn check RULES.tsv ASSERTED.tsv HORN.tsv # check a certificate+```++**The verdict tells you what it is relative to, and you must read it.**++| table | verdict | theorem | means |+|---|---|---|---|+| exactly the built-ins | `entailed` | `OOCert.entails_of_builtin_horn` | true in every model of the asserted graph |+| anything else | `entailed_under_supplied_rules` | `OOCert.horn_certificate_sound` | true in every model that **also satisfies your rules** |++The second is weaker and the difference is not academic. A rule reading "every supplier is+compliant" makes certificates that check green for ever, because the certificate certifies the+inference and never the premises. The report carries a digest of the table that was in force so two+runs can be compared, and `tests/lean_horn_certificate_test.rs` fails if a user-rule run ever+reports the absolute verdict.++Nineteen of the engine's rules are Horn rules and appear in the built-in table. `cls-int1` and+`cls-uni` are not: their premise count is the length of an RDF list, which is data rather than fixed+by the rule, so they remain hardcoded arms. A user rule language stops at the same boundary.++The Rust reasoner does not yet evaluate a supplied rule table, so today this layer checks+certificates rather than producing them. See+[decision 0003](decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md).+## Known limitationsStated rather than discovered later.diff --git a/lean/HMain.lean b/lean/HMain.leannew file mode 100644index 00000000..f4fa7f69--- /dev/null+++ b/lean/HMain.lean@@ -0,0 +1,103 @@+import OOCert+import OOCert.HornParse++/-!+`oo-horn rules` prints the built-in rules as data+`oo-horn check RULES ASSERTED HORN` checks a Horn certificate++Exit 0 when every step checks, 1 when one does not, 2 on a read or parse error.++# The two verdicts, and why they must never share a word++A certificate over the BUILT-IN rules and a certificate over rules a user wrote+are checked by the same function and prove different things.++The built-ins are discharged against the semantics by `Builtin.asHorn_sound`, so+a certificate citing only them yields `OOCert.Entails`: true in every model of+the asserted graph. That is the same warrant `certificate_sound` gives.++A rule the user supplied is discharged by nobody. It is an ASSUMPTION the+certificate carries, so the result is `OOCert.EntailsR`: true in every model of+the asserted graph THAT ALSO SATISFIES THOSE RULES. A rule reading "every+supplier is compliant" produces certificates that check green for ever. The+certificate certifies the inference and never the premises.++Collapsing those two into one word is how a verified checker becomes a device+for laundering an assumption into a fact, so they are printed as different+verdicts (`entailed` against `entailed_under_supplied_rules`), they name+different theorems, and the relativised one carries a digest of the rule table+that was in force. `tests/lean_horn_certificate_test.rs` fails if a run over+user rules ever reports the absolute verdict.++The digest identifies a rule table; it is not a cryptographic commitment, and+`String.hash` is not a cryptographic hash. It exists so that two reports can be+compared, not so that one can be defended against an adversary who controls the+rule file. Anyone who needs that should hash the file itself.+-/+open OOCert++def readOrFail (path : String) : IO (Except UInt32 String) := do+ try+ return .ok (← IO.FS.readFile path)+ catch e =>+ IO.eprintln s!"cannot read {path}: {e}"+ return .error 2++/-- The canonical rendering of a rule table, used both to compare a supplied+table against the built-ins and to digest it. -/+def tableLines (R : List RulePattern) : List String := R.map HornParse.ruleStr++def tableDigest (R : List RulePattern) : UInt64 :=+ String.hash (String.intercalate "\n" (tableLines R))++def jsonStr (s : String) : String :=+ let escaped := s.foldl (fun acc c =>+ match c with+ | '"' => acc ++ "\\\""+ | '\\' => acc ++ "\\\\"+ | '\n' => acc ++ "\\n"+ | c => acc.push c) ""+ "\"" ++ escaped ++ "\""++def main (args : List String) : IO UInt32 := do+ match args with+ | ["rules"] =>+ for r in Builtin.asHorn do+ IO.println (HornParse.ruleStr r)+ return 0+ | ["check", rPath, gPath, dPath] =>+ let rTxt ← match ← readOrFail rPath with | .ok s => pure s | .error c => return c+ let gTxt ← match ← readOrFail gPath with | .ok s => pure s | .error c => return c+ let dTxt ← match ← readOrFail dPath with | .ok s => pure s | .error c => return c+ match HornParse.parseRules rTxt, Parse.parseTriples gTxt, HornParse.parseHornSteps dTxt with+ | .ok R, .ok G, .ok steps =>+ if checkHornCert G R steps then+ -- Which warrant did this run earn? Exactly the built-in table earns the+ -- absolute one, because that is the table `Builtin.asHorn_sound`+ -- discharges. Anything else, including the built-ins plus one extra+ -- rule, earns the relativised one.+ let builtin := tableLines R == tableLines Builtin.asHorn+ let verdict := if builtin then "entailed" else "entailed_under_supplied_rules"+ let thm :=+ if builtin then "OOCert.entails_of_builtin_horn" else "OOCert.horn_certificate_sound"+ let means :=+ if builtin then+ "every conclusion is true in every model of the asserted graph"+ else+ "every conclusion is true in every model of the asserted graph THAT ALSO SATISFIES \+ the supplied rules; the rules themselves are assumed, not checked"+ IO.println s!"\{\"ok\":true,\"verdict\":{jsonStr verdict},\"rules\":{R.length},\+ \"asserted\":{G.length},\"derivations\":{steps.length},\+ \"rules_digest\":\"{tableDigest R}\",\"builtin_rules_digest\":\"{tableDigest Builtin.asHorn}\",\+ \"theorem\":{jsonStr thm},\"means\":{jsonStr means}}"+ return 0+ else+ IO.println s!"\{\"ok\":false,\"rules\":{R.length},\"asserted\":{G.length},\+ \"derivations\":{steps.length},\"rules_digest\":\"{tableDigest R}\"}"+ return 1+ | .error e, _, _ => IO.eprintln e; return 2+ | _, .error e, _ => IO.eprintln e; return 2+ | _, _, .error e => IO.eprintln e; return 2+ | _ =>+ IO.eprintln "usage: oo-horn rules | oo-horn check RULES.tsv ASSERTED.tsv HORN.tsv"+ return 2diff --git a/lean/OOCert.lean b/lean/OOCert.leanindex a14d2019..1e9da8c0 100644--- a/lean/OOCert.lean+++ b/lean/OOCert.lean@@ -3,4 +3,7 @@ import OOCert.Semanticsimport OOCert.Rulesimport OOCert.Soundnessimport OOCert.Witness+import OOCert.Horn+import OOCert.HornBuiltin+import OOCert.HornWitnessimport OOCert.Parsediff --git a/lean/OOCert/Horn.lean b/lean/OOCert/Horn.leannew file mode 100644index 00000000..0c59ed65--- /dev/null+++ b/lean/OOCert/Horn.lean@@ -0,0 +1,304 @@+import OOCert.Rules+import OOCert.Witness++/-!+# User-supplied Horn rules, and one theorem for all of them++`Rules.lean` hardcodes twenty rules and `Soundness.lean` proves one lemma per+rule against a condition in `Semantics.lean`. That does not scale to rules the+user writes, which is what RIF Core, Datalog and SWRL are.++This file adds a second rule family to the certificate. A rule is a first-order+Horn sentence over triple patterns,++ forall x1..xn. B1 and ... and Bk -> H++and a certificate step cites a rule by its index in a rule set `R`, a+substitution, and the premises it used. No new semantic condition is added:+`SatRule I r` is defined from `Interp.sat`, which already exists. The rule is an+ASSUMPTION the certificate carries, not a fact about OWL vocabulary, and that is+what makes one theorem cover every rule at once.++## Two readings of "the interpretation satisfies the rule", and which one is used++`SatRuleFO` is the honest first-order reading: variables range over DOMAIN+ELEMENTS. `SatRule` is the term reading: variables range over TERMS, and the+rule is satisfied when every ground instance is. `SatRuleFO.to_SatRule` proves+the first implies the second (take the valuation `I.iota` composed with the+substitution).++The checker is proved sound against `SatRule`, the WEAKER hypothesis. That is+deliberate and it is the opposite of the usual trade: a weaker hypothesis admits+MORE interpretations, so "every such interpretation satisfies t" is a STRONGER+claim. `horn_certificate_sound_fo` then derives the first-order statement as a+corollary, so a user who means the first-order rule is covered a fortiori.++What the term reading costs is nothing on the soundness side and everything on+the side nobody is claiming: it gives no converse, and a countermodel to+`SatRule` is not automatically a countermodel to the first-order rule.++## Variables in predicate position++`Interp` has one ternary `iext` over the domain, so a property is a domain+element like any other. A variable may therefore stand in predicate position+and the language stays first-order. Eighteen of the twenty built-in rules,+`rdfs7` and `prp-trp` among them, are Horn rules of exactly this shape.+-/+namespace OOCert++abbrev Var := String++/-- A position in a triple pattern: a fixed term, or a variable. -/+inductive Pat+ | const : Term → Pat+ | var : Var → Pat+deriving DecidableEq, Repr++/-- A triple pattern. Any of the three positions may be a variable. -/+structure AtomPat where+ s : Pat+ p : Pat+ o : Pat+deriving DecidableEq, Repr++/-- `forall vars. body -> head`, with the quantifier left implicit: every+variable occurring anywhere in the rule is universally quantified. -/+structure RulePattern where+ name : String+ body : List AtomPat+ head : AtomPat+deriving Repr++/-- A substitution is total. Totality is free here and removes a whole class of+"unbound variable" failure: the semantic side quantifies over every total+substitution, so a junk value for a variable the rule never mentions changes+nothing. -/+abbrev Subst := Var → Term++def Pat.inst (sigma : Subst) : Pat → Term+ | .const c => c+ | .var v => sigma v++def AtomPat.inst (sigma : Subst) (a : AtomPat) : Triple :=+ ⟨a.s.inst sigma, a.p.inst sigma, a.o.inst sigma⟩++/-! ## The two satisfaction relations -/++/-- Term reading: every ground instance of the rule holds. -/+def SatRule (I : Interp) (r : RulePattern) : Prop :=+ ∀ sigma : Subst,+ (∀ a ∈ r.body, I.sat (AtomPat.inst sigma a)) → I.sat (AtomPat.inst sigma r.head)++def Pat.denote (I : Interp) (v : Var → I.D) : Pat → I.D+ | .const c => I.ι c+ | .var x => v x++def AtomPat.holds (I : Interp) (v : Var → I.D) (a : AtomPat) : Prop :=+ I.iext (a.p.denote I v) (a.s.denote I v) (a.o.denote I v)++/-- First-order reading: variables range over domain elements. -/+def SatRuleFO (I : Interp) (r : RulePattern) : Prop :=+ ∀ v : Var → I.D, (∀ a ∈ r.body, a.holds I v) → r.head.holds I v++theorem denote_inst (I : Interp) (sigma : Subst) (q : Pat) :+ q.denote I (fun x => I.ι (sigma x)) = I.ι (q.inst sigma) := by+ cases q <;> rfl++theorem holds_inst (I : Interp) (sigma : Subst) (a : AtomPat) :+ a.holds I (fun x => I.ι (sigma x)) ↔ I.sat (AtomPat.inst sigma a) := by+ unfold AtomPat.holds Interp.sat AtomPat.inst+ simp only [denote_inst]++/-- The first-order reading implies the term reading. This is the whole reason+the checker may be proved against the term reading and still speak about+genuine first-order rules. -/+theorem SatRuleFO.to_SatRule {I : Interp} {r : RulePattern}+ (h : SatRuleFO I r) : SatRule I r := by+ intro sigma hb+ refine (holds_inst I sigma r.head).mp (h (fun x => I.ι (sigma x)) ?_)+ intro a ha+ exact (holds_inst I sigma a).mpr (hb a ha)++/-! ## Entailment relative to a rule set -/++/-- `G, R ⊨ t`: every interpretation that models `G` and satisfies every rule of+`R` satisfies `t`. Note that `Model I G` still carries the RDF semantic+conditions, so this is entailment over the RDF-conditioned model class, not pure+first-order entailment from `G ∪ R`. Pure first-order entailment implies it, not+the other way round. -/+def ModelR (G : List Triple) (R : List RulePattern) (I : Interp) : Prop :=+ Model I G ∧ ∀ r ∈ R, SatRule I r++def EntailsR (G : List Triple) (R : List RulePattern) (t : Triple) : Prop :=+ EntailsIn (ModelR G R) t++theorem EntailsR.of_entails {G : List Triple} {R : List RulePattern} {t : Triple}+ (h : Entails G t) : EntailsR G R t := fun I hI => h I hI.1++theorem EntailsR.of_mem {G : List Triple} {R : List RulePattern} {t : Triple}+ (h : t ∈ G) : EntailsR G R t := fun _ hI => hI.1.facts t h++/-! ## The checker -/++/-- Indexing written out rather than borrowed, so the membership lemma below is+local and the file does not move with the standard library. -/+def nth? {α : Type} : List α → Nat → Option α+ | [], _ => none+ | a :: _, 0 => some a+ | _ :: as, n + 1 => nth? as n++theorem nth?_mem {α : Type} {l : List α} :+ ∀ {n : Nat} {a : α}, nth? l n = some a → a ∈ l := by+ induction l with+ | nil => intro n a h; cases n <;> simp [nth?] at h+ | cons b bs ih =>+ intro n a h+ cases n with+ | zero =>+ simp only [nth?, Option.some.injEq] at h+ subst h+ exact List.Mem.head bs+ | succ m => exact List.Mem.tail _ (ih h)++/-- A step that cites a user rule. `binds` is the substitution the engine used,+written out; `premises` are the triples it matched, in the rule's body order. -/+structure HornStep where+ rule : Nat+ binds : List (Var × Term)+ premises : List Triple+ conclusion : Triple+deriving Repr++/-- A cited binding list read as a total substitution. A variable with no+binding maps to its own name, which is junk and will fail the premise check;+soundness does not depend on that, because the semantic side quantifies over+every total substitution including this one. -/+def substOf (l : List (Var × Term)) : Subst := fun v => (List.lookup v l).getD v++/-- Check one Horn step. As with the built-in rules, premise ORDER is part of+the contract: the premise list must be the body instantiated, in order. A+certificate with the right triples in the wrong order is rejected, which is a+false alarm and never a false pass. -/+def checkHornStep (R : List RulePattern) (k : Triple → Bool) (st : HornStep) : Bool :=+ match nth? R st.rule with+ | none => false+ | some r =>+ decide (st.premises = r.body.map (AtomPat.inst (substOf st.binds))) &&+ st.premises.all k &&+ decide (st.conclusion = AtomPat.inst (substOf st.binds) r.head)++/-- THE THEOREM, one step. No case analysis on the rule: there is nothing to+case on. -/+theorem checkHornStep_sound {G : List Triple} {R : List RulePattern} {k : Triple → Bool}+ {st : HornStep} (hk : ∀ t, k t = true → EntailsR G R t)+ (h : checkHornStep R k st = true) : EntailsR G R st.conclusion := by+ unfold checkHornStep at h+ revert h+ cases hr : nth? R st.rule with+ | none => intro h; simp at h+ | some r =>+ intro h+ simp only [Bool.and_eq_true, decide_eq_true_eq] at h+ obtain ⟨⟨hprem, hall⟩, hconc⟩ := h+ intro I hI+ obtain ⟨M, hR⟩ := hI+ have hrmem : r ∈ R := nth?_mem hr+ have hbody : ∀ a ∈ r.body, I.sat (AtomPat.inst (substOf st.binds) a) := by+ intro a ha+ have hmem : AtomPat.inst (substOf st.binds) a ∈ st.premises := by+ rw [hprem]+ exact List.mem_map_of_mem ha+ exact hk _ (List.all_eq_true.mp hall _ hmem) I ⟨M, hR⟩+ rw [hconc]+ exact hR r hrmem (substOf st.binds) hbody++/-! ## Certificates++The same discipline `checkAll` uses: steps are checked in order, and a premise+counts as known when it is asserted in `G` or was concluded by an EARLIER step.+Nothing else changes, and in particular no step may cite itself. -/++def checkHornAll (inG : Triple → Bool) (R : List RulePattern) :+ List HornStep → Std.HashSet Triple → Bool+ | [], _ => true+ | st :: rest, derived =>+ checkHornStep R (fun t => inG t || derived.contains t) st &&+ checkHornAll inG R rest (derived.insert st.conclusion)++/-- The Horn checker. `G` is the asserted graph, `R` the rule set the+certificate is relative to, `steps` the certificate. -/+def checkHornCert (G : List Triple) (R : List RulePattern) (steps : List HornStep) : Bool :=+ let gset := Std.HashSet.ofList G+ checkHornAll (fun t => gset.contains t) R steps ∅++theorem checkHornAll_sound {G : List Triple} {R : List RulePattern} {inG : Triple → Bool}+ (hG : ∀ t, inG t = true → t ∈ G) :+ ∀ (steps : List HornStep) (derived : Std.HashSet Triple),+ (∀ t, derived.contains t = true → EntailsR G R t) →+ checkHornAll inG R steps derived = true →+ ∀ st ∈ steps, EntailsR G R st.conclusion := by+ intro steps+ induction steps with+ | nil => intro _ _ _ st hst; simp at hst+ | cons st rest ih =>+ intro derived hD h st' hst'+ simp only [checkHornAll, Bool.and_eq_true] at h+ obtain ⟨h1, h2⟩ := h+ have hk : ∀ t, (inG t || derived.contains t) = true → EntailsR G R t := by+ intro t ht+ simp only [Bool.or_eq_true] at ht+ rcases ht with hx | hx+ · exact EntailsR.of_mem (hG t hx)+ · exact hD t hx+ have hst : EntailsR G R st.conclusion := checkHornStep_sound hk h1+ have hD' : ∀ t, (derived.insert st.conclusion).contains t = true → EntailsR G R t := by+ intro t ht+ rw [Std.HashSet.contains_insert] at ht+ simp only [Bool.or_eq_true, beq_iff_eq] at ht+ rcases ht with rfl | ht+ · exact hst+ · exact hD t ht+ rcases List.mem_cons.mp hst' with rfl | hmem+ · exact hst+ · exact ih _ hD' h2 st' hmem++/-- **The generic theorem.** One statement, every user-supplied Horn rule at+once. There is no per-rule lemma and no per-rule arm: the rule set is a+parameter, and the rule it cites is discharged by the hypothesis the certificate+carries. -/+theorem horn_certificate_sound (G : List Triple) (R : List RulePattern) (steps : List HornStep)+ (h : checkHornCert G R steps = true) : ∀ st ∈ steps, EntailsR G R st.conclusion := by+ unfold checkHornCert at h+ refine checkHornAll_sound (G := G) (R := R)+ (inG := fun t => (Std.HashSet.ofList G).contains t) ?_ steps ∅ ?_ h+ · intro t ht+ rw [Std.HashSet.contains_ofList] at ht+ simpa using ht+ · intro t ht+ simp at ht++/-- The same theorem stated for the honest first-order reading of the rules,+which is what a user who writes RIF Core or SWRL means. It is a corollary and+not a separate proof, because `SatRuleFO` implies `SatRule`. -/+theorem horn_certificate_sound_fo (G : List Triple) (R : List RulePattern) (steps : List HornStep)+ (h : checkHornCert G R steps = true) :+ ∀ st ∈ steps, ∀ I : Interp, Model I G → (∀ r ∈ R, SatRuleFO I r) → I.sat st.conclusion := by+ intro st hst I M hR+ exact horn_certificate_sound G R steps h st hst I ⟨M, fun r hr => (hR r hr).to_SatRule⟩+++/-! The axiom tripwire, as `Soundness.lean` has one. A `sorry` or a+`native_decide` anywhere under these theorems fails the build here. -/+/-- info: 'OOCert.SatRuleFO.to_SatRule' depends on axioms: [propext] -/+#guard_msgs in+#print axioms SatRuleFO.to_SatRule++/-- info: 'OOCert.horn_certificate_sound' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms horn_certificate_sound++/-- info: 'OOCert.horn_certificate_sound_fo' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms horn_certificate_sound_fo++end OOCertdiff --git a/lean/OOCert/HornBuiltin.lean b/lean/OOCert/HornBuiltin.leannew file mode 100644index 00000000..deb764d3--- /dev/null+++ b/lean/OOCert/HornBuiltin.lean@@ -0,0 +1,297 @@+import OOCert.Horn++/-!+# The hardcoded arms, as data++The question this file settles: is the generic Horn theorem a SECOND rule+family bolted on beside the twenty arms, or does it SUBSUME them?++Nineteen of the engine's rules are Horn rules over triple patterns, written out below+as values of `RulePattern`. For each, one lemma says the semantic conditions in+`Semantics.lean` imply the term-level rule. Every one of those lemmas is a+single `exact` against the matching field of `Conditions`, because there is no+premise-list destructuring left to do: the checker did it.++`entails_of_horn` is then the payoff. A certificate that cites only rules with+such a lemma yields the ORIGINAL `Entails G t`, the same warrant+`certificate_sound` gives, with no per-rule arm in the checker and no per-rule+lemma about premise lists.++## The two that are not Horn rules, and why++`cls-int1` and `cls-uni` read an RDF list off the graph. Their premise count is+not fixed by the rule: it is the length of the list, which is data. A+`RulePattern` has a finite body, so expressing `cls-int1` needs either one rule+per list length, which is infinitely many rules, or an atom that matches a+chain, which is outside Horn logic over triple patterns. They stay hardcoded.+That is not a defect of the generalisation; it is the exact boundary of the+Horn family, and it is where a user-written rule language will also stop.+-/+namespace OOCert+namespace Builtin++def rdfs2 : RulePattern :=+ { name := "rdfs2"+ body := [⟨.var "s", .var "p", .var "o"⟩, ⟨.var "p", .const V.domain, .var "c"⟩]+ head := ⟨.var "s", .const V.type, .var "c"⟩ }++def rdfs3 : RulePattern :=+ { name := "rdfs3"+ body := [⟨.var "s", .var "p", .var "o"⟩, ⟨.var "p", .const V.range, .var "c"⟩]+ head := ⟨.var "o", .const V.type, .var "c"⟩ }++def rdfs5 : RulePattern :=+ { name := "rdfs5"+ body := [⟨.var "a", .const V.subPropertyOf, .var "b"⟩,+ ⟨.var "b", .const V.subPropertyOf, .var "c"⟩]+ head := ⟨.var "a", .const V.subPropertyOf, .var "c"⟩ }++def rdfs7 : RulePattern :=+ { name := "rdfs7"+ body := [⟨.var "s", .var "p", .var "o"⟩,+ ⟨.var "p", .const V.subPropertyOf, .var "q"⟩]+ head := ⟨.var "s", .var "q", .var "o"⟩ }++def rdfs9 : RulePattern :=+ { name := "rdfs9"+ body := [⟨.var "x", .const V.type, .var "a"⟩,+ ⟨.var "a", .const V.subClassOf, .var "b"⟩]+ head := ⟨.var "x", .const V.type, .var "b"⟩ }++def rdfs11 : RulePattern :=+ { name := "rdfs11"+ body := [⟨.var "a", .const V.subClassOf, .var "b"⟩,+ ⟨.var "b", .const V.subClassOf, .var "c"⟩]+ head := ⟨.var "a", .const V.subClassOf, .var "c"⟩ }++def prpTrp : RulePattern :=+ { name := "prp-trp"+ body := [⟨.var "p", .const V.type, .const V.transitiveProperty⟩,+ ⟨.var "x", .var "p", .var "y"⟩,+ ⟨.var "y", .var "p", .var "z"⟩]+ head := ⟨.var "x", .var "p", .var "z"⟩ }++def prpSymp : RulePattern :=+ { name := "prp-symp"+ body := [⟨.var "p", .const V.type, .const V.symmetricProperty⟩,+ ⟨.var "x", .var "p", .var "y"⟩]+ head := ⟨.var "y", .var "p", .var "x"⟩ }++def prpInv1 : RulePattern :=+ { name := "prp-inv1"+ body := [⟨.var "p", .const V.inverseOf, .var "q"⟩, ⟨.var "x", .var "p", .var "y"⟩]+ head := ⟨.var "y", .var "q", .var "x"⟩ }++def prpInv2 : RulePattern :=+ { name := "prp-inv2"+ body := [⟨.var "p", .const V.inverseOf, .var "q"⟩, ⟨.var "x", .var "q", .var "y"⟩]+ head := ⟨.var "y", .var "p", .var "x"⟩ }++def eqSym : RulePattern :=+ { name := "eq-sym"+ body := [⟨.var "a", .const V.sameAs, .var "b"⟩]+ head := ⟨.var "b", .const V.sameAs, .var "a"⟩ }++def scmEqc1 : RulePattern :=+ { name := "scm-eqc1"+ body := [⟨.var "a", .const V.equivalentClass, .var "b"⟩]+ head := ⟨.var "a", .const V.subClassOf, .var "b"⟩ }++/-- The second conclusion of W3C `scm-eqc1`, which licenses two. It is emitted+under that rule's own id, because `scm-eqc2` names a different W3C rule+concluding in the opposite direction. -/+def scmEqc1b : RulePattern :=+ { name := "scm-eqc1"+ body := [⟨.var "a", .const V.equivalentClass, .var "b"⟩]+ head := ⟨.var "b", .const V.subClassOf, .var "a"⟩ }++def scmEqp1 : RulePattern :=+ { name := "scm-eqp1"+ body := [⟨.var "a", .const V.equivalentProperty, .var "b"⟩]+ head := ⟨.var "a", .const V.subPropertyOf, .var "b"⟩ }++/-- The second conclusion of W3C `scm-eqp1`. See `scmEqc1b`. -/+def scmEqp1b : RulePattern :=+ { name := "scm-eqp1"+ body := [⟨.var "a", .const V.equivalentProperty, .var "b"⟩]+ head := ⟨.var "b", .const V.subPropertyOf, .var "a"⟩ }++def clsSvf1 : RulePattern :=+ { name := "cls-svf1"+ body := [⟨.var "r", .const V.onProperty, .var "p"⟩,+ ⟨.var "r", .const V.someValuesFrom, .var "c"⟩,+ ⟨.var "x", .var "p", .var "y"⟩,+ ⟨.var "y", .const V.type, .var "c"⟩]+ head := ⟨.var "x", .const V.type, .var "r"⟩ }++def clsAvf : RulePattern :=+ { name := "cls-avf"+ body := [⟨.var "r", .const V.onProperty, .var "p"⟩,+ ⟨.var "r", .const V.allValuesFrom, .var "c"⟩,+ ⟨.var "x", .const V.type, .var "r"⟩,+ ⟨.var "x", .var "p", .var "y"⟩]+ head := ⟨.var "y", .const V.type, .var "c"⟩ }++def clsHv1 : RulePattern :=+ { name := "cls-hv1"+ body := [⟨.var "r", .const V.onProperty, .var "p"⟩,+ ⟨.var "r", .const V.hasValue, .var "v"⟩,+ ⟨.var "x", .const V.type, .var "r"⟩]+ head := ⟨.var "x", .var "p", .var "v"⟩ }++def clsHv2 : RulePattern :=+ { name := "cls-hv2"+ body := [⟨.var "r", .const V.onProperty, .var "p"⟩,+ ⟨.var "r", .const V.hasValue, .var "v"⟩,+ ⟨.var "x", .var "p", .var "v"⟩]+ head := ⟨.var "x", .const V.type, .var "r"⟩ }++/-! ## Each is a consequence of the semantic conditions++One `exact` each. Compare `Soundness.lean`, where the same eighteen facts cost+a `rcases` over the premise list, a `simp only` to strip the decidability+wrapper, an `obtain` over the conjunction, and then the `exact`. -/++theorem rdfs2_sound {I : Interp} (C : Conditions I) : SatRule I rdfs2 := fun s hb =>+ C.dom _ _ (hb ⟨.var "p", .const V.domain, .var "c"⟩ (by simp [rdfs2])) _ _+ (hb ⟨.var "s", .var "p", .var "o"⟩ (by simp [rdfs2]))++theorem rdfs3_sound {I : Interp} (C : Conditions I) : SatRule I rdfs3 := fun s hb =>+ C.rng _ _ (hb ⟨.var "p", .const V.range, .var "c"⟩ (by simp [rdfs3])) _ _+ (hb ⟨.var "s", .var "p", .var "o"⟩ (by simp [rdfs3]))++theorem rdfs5_sound {I : Interp} (C : Conditions I) : SatRule I rdfs5 := fun s hb =>+ C.sp_trans _ _ _ (hb ⟨.var "a", .const V.subPropertyOf, .var "b"⟩ (by simp [rdfs5]))+ (hb ⟨.var "b", .const V.subPropertyOf, .var "c"⟩ (by simp [rdfs5]))++theorem rdfs7_sound {I : Interp} (C : Conditions I) : SatRule I rdfs7 := fun s hb =>+ C.sp_sub _ _ (hb ⟨.var "p", .const V.subPropertyOf, .var "q"⟩ (by simp [rdfs7])) _ _+ (hb ⟨.var "s", .var "p", .var "o"⟩ (by simp [rdfs7]))++theorem rdfs9_sound {I : Interp} (C : Conditions I) : SatRule I rdfs9 := fun s hb =>+ C.sc_sub _ _ (hb ⟨.var "a", .const V.subClassOf, .var "b"⟩ (by simp [rdfs9])) _+ (hb ⟨.var "x", .const V.type, .var "a"⟩ (by simp [rdfs9]))++theorem rdfs11_sound {I : Interp} (C : Conditions I) : SatRule I rdfs11 := fun s hb =>+ C.sc_trans _ _ _ (hb ⟨.var "a", .const V.subClassOf, .var "b"⟩ (by simp [rdfs11]))+ (hb ⟨.var "b", .const V.subClassOf, .var "c"⟩ (by simp [rdfs11]))++theorem prpTrp_sound {I : Interp} (C : Conditions I) : SatRule I prpTrp := fun s hb =>+ C.trp _ (hb ⟨.var "p", .const V.type, .const V.transitiveProperty⟩ (by simp [prpTrp])) _ _ _+ (hb ⟨.var "x", .var "p", .var "y"⟩ (by simp [prpTrp]))+ (hb ⟨.var "y", .var "p", .var "z"⟩ (by simp [prpTrp]))++theorem prpSymp_sound {I : Interp} (C : Conditions I) : SatRule I prpSymp := fun s hb =>+ C.symp _ (hb ⟨.var "p", .const V.type, .const V.symmetricProperty⟩ (by simp [prpSymp])) _ _+ (hb ⟨.var "x", .var "p", .var "y"⟩ (by simp [prpSymp]))++theorem prpInv1_sound {I : Interp} (C : Conditions I) : SatRule I prpInv1 := fun s hb =>+ (C.inv _ _ (hb ⟨.var "p", .const V.inverseOf, .var "q"⟩ (by simp [prpInv1])) _ _).mp+ (hb ⟨.var "x", .var "p", .var "y"⟩ (by simp [prpInv1]))++theorem prpInv2_sound {I : Interp} (C : Conditions I) : SatRule I prpInv2 := fun s hb =>+ (C.inv _ _ (hb ⟨.var "p", .const V.inverseOf, .var "q"⟩ (by simp [prpInv2])) _ _).mpr+ (hb ⟨.var "x", .var "q", .var "y"⟩ (by simp [prpInv2]))++theorem eqSym_sound {I : Interp} (C : Conditions I) : SatRule I eqSym := by+ intro s hb+ have h1 : I.iext (I.ι V.sameAs) (I.ι (s "a")) (I.ι (s "b")) :=+ hb ⟨.var "a", .const V.sameAs, .var "b"⟩ (by simp [eqSym])+ have e : I.ι (s "a") = I.ι (s "b") := C.same _ _ h1+ show I.iext (I.ι V.sameAs) (I.ι (s "b")) (I.ι (s "a"))+ rw [← e]+ rw [← e] at h1+ exact h1++theorem scmEqc1_sound {I : Interp} (C : Conditions I) : SatRule I scmEqc1 := fun s hb =>+ (C.eqc _ _ (hb ⟨.var "a", .const V.equivalentClass, .var "b"⟩ (by simp [scmEqc1]))).1++theorem scmEqc1b_sound {I : Interp} (C : Conditions I) : SatRule I scmEqc1b := fun s hb =>+ (C.eqc _ _ (hb ⟨.var "a", .const V.equivalentClass, .var "b"⟩ (by simp [scmEqc1b]))).2++theorem scmEqp1_sound {I : Interp} (C : Conditions I) : SatRule I scmEqp1 := fun s hb =>+ (C.eqp _ _ (hb ⟨.var "a", .const V.equivalentProperty, .var "b"⟩ (by simp [scmEqp1]))).1++theorem scmEqp1b_sound {I : Interp} (C : Conditions I) : SatRule I scmEqp1b := fun s hb =>+ (C.eqp _ _ (hb ⟨.var "a", .const V.equivalentProperty, .var "b"⟩ (by simp [scmEqp1b]))).2++theorem clsSvf1_sound {I : Interp} (C : Conditions I) : SatRule I clsSvf1 := fun s hb =>+ C.svf _ _ _ (hb ⟨.var "r", .const V.onProperty, .var "p"⟩ (by simp [clsSvf1]))+ (hb ⟨.var "r", .const V.someValuesFrom, .var "c"⟩ (by simp [clsSvf1])) _ _+ (hb ⟨.var "x", .var "p", .var "y"⟩ (by simp [clsSvf1]))+ (hb ⟨.var "y", .const V.type, .var "c"⟩ (by simp [clsSvf1]))++theorem clsAvf_sound {I : Interp} (C : Conditions I) : SatRule I clsAvf := fun s hb =>+ C.avf _ _ _ (hb ⟨.var "r", .const V.onProperty, .var "p"⟩ (by simp [clsAvf]))+ (hb ⟨.var "r", .const V.allValuesFrom, .var "c"⟩ (by simp [clsAvf])) _ _+ (hb ⟨.var "x", .const V.type, .var "r"⟩ (by simp [clsAvf]))+ (hb ⟨.var "x", .var "p", .var "y"⟩ (by simp [clsAvf]))++theorem clsHv1_sound {I : Interp} (C : Conditions I) : SatRule I clsHv1 := fun s hb =>+ (C.hv _ _ _ (hb ⟨.var "r", .const V.onProperty, .var "p"⟩ (by simp [clsHv1]))+ (hb ⟨.var "r", .const V.hasValue, .var "v"⟩ (by simp [clsHv1])) _).mp+ (hb ⟨.var "x", .const V.type, .var "r"⟩ (by simp [clsHv1]))++theorem clsHv2_sound {I : Interp} (C : Conditions I) : SatRule I clsHv2 := fun s hb =>+ (C.hv _ _ _ (hb ⟨.var "r", .const V.onProperty, .var "p"⟩ (by simp [clsHv2]))+ (hb ⟨.var "r", .const V.hasValue, .var "v"⟩ (by simp [clsHv2])) _).mpr+ (hb ⟨.var "x", .var "p", .var "v"⟩ (by simp [clsHv2]))++/-- The built-in rules that are Horn rules, as a rule set. Nineteen of the+engine's rules qualify; `cls-int1` and `cls-uni` do not, for the reason given+at the top of this file. -/+def asHorn : List RulePattern :=+ [rdfs2, rdfs3, rdfs5, rdfs7, rdfs9, rdfs11,+ prpTrp, prpSymp, prpInv1, prpInv2, eqSym,+ scmEqc1, scmEqc1b, scmEqp1, scmEqp1b, clsSvf1, clsAvf, clsHv1, clsHv2]++theorem asHorn_sound (I : Interp) (C : Conditions I) : ∀ r ∈ asHorn, SatRule I r := by+ intro r hr+ simp only [asHorn, List.mem_cons, List.not_mem_nil, or_false] at hr+ rcases hr with rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl+ · exact rdfs2_sound C+ · exact rdfs3_sound C+ · exact rdfs5_sound C+ · exact rdfs7_sound C+ · exact rdfs9_sound C+ · exact rdfs11_sound C+ · exact prpTrp_sound C+ · exact prpSymp_sound C+ · exact prpInv1_sound C+ · exact prpInv2_sound C+ · exact eqSym_sound C+ · exact scmEqc1_sound C+ · exact scmEqc1b_sound C+ · exact scmEqp1_sound C+ · exact scmEqp1b_sound C+ · exact clsSvf1_sound C+ · exact clsAvf_sound C+ · exact clsHv1_sound C+ · exact clsHv2_sound C++end Builtin++/-- If every rule in `R` follows from the semantic conditions, a Horn+certificate over `R` delivers the plain `Entails G t` of `Semantics.lean`: the+same warrant `certificate_sound` gives, with the rules moved out of the checker+and into data. -/+theorem entails_of_horn (G : List Triple) (R : List RulePattern)+ (hR : ∀ r ∈ R, ∀ I : Interp, Conditions I → SatRule I r)+ (steps : List HornStep) (h : checkHornCert G R steps = true) :+ ∀ st ∈ steps, Entails G st.conclusion := by+ intro st hst I M+ exact horn_certificate_sound G R steps h st hst I ⟨M, fun r hr => hR r hr I M.conds⟩++/-- Specialised to the built-ins. A certificate written against this rule set is+checked by code that knows nothing about RDFS or OWL, and still yields the+original entailment. -/+theorem entails_of_builtin_horn (G : List Triple) (steps : List HornStep)+ (h : checkHornCert G Builtin.asHorn steps = true) :+ ∀ st ∈ steps, Entails G st.conclusion :=+ entails_of_horn G Builtin.asHorn (fun r hr I C => Builtin.asHorn_sound I C r hr) steps h++/-- info: 'OOCert.entails_of_builtin_horn' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms entails_of_builtin_horn++end OOCertdiff --git a/lean/OOCert/HornParse.lean b/lean/OOCert/HornParse.leannew file mode 100644index 00000000..92ed6bf1--- /dev/null+++ b/lean/OOCert/HornParse.lean@@ -0,0 +1,83 @@+import OOCert.Horn+import OOCert.HornBuiltin+import OOCert.Parse++/-!+# A file format for rule sets and Horn certificates++Not part of any proof. A parse error is a rejected certificate, never an+accepted one, exactly as `Parse.lean` says of the built-in format.++* `rules.tsv`: `name TAB bodyLength TAB (s TAB p TAB o)* TAB hs TAB hp TAB ho`.+ A field beginning with `?` is a variable; anything else is a term in its+ N-Triples spelling. N-Triples terms begin with `<`, `_:` or `"`, so the+ encoding is unambiguous.+* `horn.tsv`: `ruleIndex TAB bindCount TAB (var TAB term)* TAB cs TAB cp TAB co+ TAB (ps TAB pp TAB po)*`.+-/+namespace OOCert.HornParse++def patOf (s : String) : Pat :=+ if s.startsWith "?" then .var (s.drop 1).toString else .const s++def patStr : Pat → String+ | .const c => c+ | .var v => "?" ++ v++def ruleStr (r : RulePattern) : String :=+ String.intercalate "\t"+ ([r.name, toString r.body.length] +++ (r.body.map (fun a => [patStr a.s, patStr a.p, patStr a.o])).flatten +++ [patStr r.head.s, patStr r.head.p, patStr r.head.o])++def groupAtoms : List String → Option (List AtomPat)+ | [] => some []+ | s :: p :: o :: rest => (groupAtoms rest).map (⟨patOf s, patOf p, patOf o⟩ :: ·)+ | _ => none++def groupPairs : List String → Option (List (Var × Term))+ | [] => some []+ | v :: t :: rest => (groupPairs rest).map ((v, t) :: ·)+ | _ => none++def parseRules (content : String) : Except String (List RulePattern) := do+ let mut out : Array RulePattern := #[]+ let mut n := 0+ for line in content.splitOn "\n" do+ n := n + 1+ if line.isEmpty then continue+ match line.splitOn "\t" with+ | name :: k :: rest =>+ match k.toNat? with+ | none => throw s!"rules line {n}: body length is not a number"+ | some m =>+ if rest.length ≠ 3 * m + 3 then+ throw s!"rules line {n}: expected {3 * m + 3} pattern fields, got {rest.length}"+ else+ match groupAtoms (rest.take (3 * m)), groupAtoms (rest.drop (3 * m)) with+ | some body, some [head] => out := out.push ⟨name, body, head⟩+ | _, _ => throw s!"rules line {n}: malformed patterns"+ | _ => throw s!"rules line {n}: expected name, body length, patterns"+ return out.toList++def parseHornSteps (content : String) : Except String (List HornStep) := do+ let mut out : Array HornStep := #[]+ let mut n := 0+ for line in content.splitOn "\n" do+ n := n + 1+ if line.isEmpty then continue+ match line.splitOn "\t" with+ | idx :: nb :: rest =>+ match idx.toNat?, nb.toNat? with+ | some i, some k =>+ match groupPairs (rest.take (2 * k)), rest.drop (2 * k) with+ | some binds, cs :: cp :: co :: prem =>+ match Parse.groupTriples prem with+ | some ps => out := out.push ⟨i, binds, ps, ⟨cs, cp, co⟩⟩+ | none => throw s!"horn line {n}: premises are not whole triples"+ | _, _ => throw s!"horn line {n}: malformed bindings or conclusion"+ | _, _ => throw s!"horn line {n}: rule index or bind count is not a number"+ | _ => throw s!"horn line {n}: expected index, bind count, bindings, conclusion"+ return out.toList++end OOCert.HornParsediff --git a/lean/OOCert/HornWitness.lean b/lean/OOCert/HornWitness.leannew file mode 100644index 00000000..3c079025--- /dev/null+++ b/lean/OOCert/HornWitness.lean@@ -0,0 +1,153 @@+import OOCert.Horn++/-!+# What the Horn layer is worth++`horn_certificate_sound` is worthless on its own for the same two reasons+`Witness.lean` lists: if nothing satisfied a rule set the theorem would be+vacuous, and if `EntailsR` held of everything it would say nothing. Both are+closed here by construction. A third section shows the gate can fail, and a+fourth shows that eighteen of the twenty hardcoded rules are instances of the+generic theorem, so the generalisation subsumes the existing checker rather+than sitting beside it.+-/+namespace OOCert++/-! ## The rule layer is not vacuous -/++/-- The saturated interpretation satisfies every rule whatsoever, so for any+graph and any rule set the model class `EntailsR` quantifies over is non-empty+and `EntailsR` is not the "anything follows" of an inconsistent premise set. -/+theorem saturated_sat_rule (r : RulePattern) : SatRule saturated r := fun _ _ => trivial++theorem entailsR_not_vacuous (G : List Triple) (R : List RulePattern) :+ ∃ I : Interp, Model I G ∧ ∀ r ∈ R, SatRule I r :=+ ⟨saturated, saturated_is_a_model G, fun r _ => saturated_sat_rule r⟩++/-! ## A worked user rule -/++def uA : Term := "<u:a>"+def uB : Term := "<u:b>"+def uC : Term := "<u:c>"+def uP : Term := "<u:p>"+def uGp : Term := "<u:gp>"++/-- `p(x,y) and p(y,z) -> gp(x,z)`. Nothing about it is built in; it is data. -/+def gpRule : RulePattern :=+ { name := "grandparent"+ body := [⟨.var "x", .const uP, .var "y"⟩, ⟨.var "y", .const uP, .var "z"⟩]+ head := ⟨.var "x", .const uGp, .var "z"⟩ }++def demoR : List RulePattern := [gpRule]+def demoG : List Triple := [⟨uA, uP, uB⟩, ⟨uB, uP, uC⟩]++def demoStep : HornStep :=+ { rule := 0+ binds := [("x", uA), ("y", uB), ("z", uC)]+ premises := [⟨uA, uP, uB⟩, ⟨uB, uP, uC⟩]+ conclusion := ⟨uA, uGp, uC⟩ }++theorem demo_step_accepted :+ checkHornStep demoR (fun t => decide (t ∈ demoG)) demoStep = true := by decide++/-- The payoff, for a rule the checker has never heard of. -/+theorem demo_conclusion_entailed : EntailsR demoG demoR ⟨uA, uGp, uC⟩ :=+ checkHornStep_sound (G := demoG) (R := demoR) (k := fun t => decide (t ∈ demoG))+ (fun _ ht => EntailsR.of_mem (of_decide_eq_true ht)) demo_step_accepted++/-! ## The gate can fail++Four ways to be wrong, each rejected. Without these the acceptance above would+be evidence of nothing. -/++def badConclusion : HornStep := { demoStep with conclusion := ⟨uA, uGp, uB⟩ }+def badOrder : HornStep := { demoStep with premises := [⟨uB, uP, uC⟩, ⟨uA, uP, uB⟩] }+def badIndex : HornStep := { demoStep with rule := 7 }+/-- The substitution is applied consistently and the premises are the instantiated+body, but the second premise is not in the graph. -/+def badUnknown : HornStep :=+ { rule := 0+ binds := [("x", uA), ("y", uB), ("z", uA)]+ premises := [⟨uA, uP, uB⟩, ⟨uB, uP, uA⟩]+ conclusion := ⟨uA, uGp, uA⟩ }++theorem rejects_wrong_conclusion :+ checkHornStep demoR (fun t => decide (t ∈ demoG)) badConclusion = false := by decide+theorem rejects_scrambled_premise_order :+ checkHornStep demoR (fun t => decide (t ∈ demoG)) badOrder = false := by decide+theorem rejects_unknown_rule_index :+ checkHornStep demoR (fun t => decide (t ∈ demoG)) badIndex = false := by decide+theorem rejects_unknown_premise :+ checkHornStep demoR (fun t => decide (t ∈ demoG)) badUnknown = false := by decide++/-! ## The rule layer does not derive everything++`demoH` is `demoG` closed under the grandparent rule. Its Herbrand+interpretation models `demoG`, satisfies the rule, and refutes `a gp b`. -/++def demoH : List Triple := ⟨uA, uGp, uC⟩ :: demoG++/-- The closure check, as a decidable statement over a three-triple list. -/+private theorem demoH_gp_closed :+ ∀ t ∈ demoH, ∀ u ∈ demoH, (t.p = uP ∧ u.p = uP ∧ u.s = t.o) →+ (⟨t.s, uGp, u.o⟩ : Triple) ∈ demoH := by decide++theorem demoH_sat_rule : SatRule (herbrand demoH) gpRule := by+ intro sigma hb+ have h1 := hb ⟨.var "x", .const uP, .var "y"⟩ (by simp [gpRule])+ have h2 := hb ⟨.var "y", .const uP, .var "z"⟩ (by simp [gpRule])+ exact demoH_gp_closed ⟨sigma "x", uP, sigma "y"⟩ h1 ⟨sigma "y", uP, sigma "z"⟩ h2+ ⟨rfl, rfl, rfl⟩++theorem demoH_is_a_model : Model (herbrand demoH) demoG where+ conds :=+ { sc_sub := fun a b hab => absurd hab (not_mem_pred demoH V.subClassOf (by decide) a b)+ sc_trans := fun a b _ hab => absurd hab (not_mem_pred demoH V.subClassOf (by decide) a b)+ sp_sub := fun a b hab => absurd hab (not_mem_pred demoH V.subPropertyOf (by decide) a b)+ sp_trans := fun a b _ hab =>+ absurd hab (not_mem_pred demoH V.subPropertyOf (by decide) a b)+ dom := fun p c hpc => absurd hpc (not_mem_pred demoH V.domain (by decide) p c)+ rng := fun p c hpc => absurd hpc (not_mem_pred demoH V.range (by decide) p c)+ trp := fun p hp => absurd hp (not_typed demoH V.transitiveProperty (by decide) p)+ symp := fun p hp => absurd hp (not_typed demoH V.symmetricProperty (by decide) p)+ inv := fun p q hpq => absurd hpq (not_mem_pred demoH V.inverseOf (by decide) p q)+ same := fun a b hab => absurd hab (not_mem_pred demoH V.sameAs (by decide) a b)+ eqc := fun a b hab => absurd hab (not_mem_pred demoH V.equivalentClass (by decide) a b)+ eqp := fun a b hab =>+ absurd hab (not_mem_pred demoH V.equivalentProperty (by decide) a b)+ svf := fun r p _ hop => absurd hop (not_mem_pred demoH V.onProperty (by decide) r p)+ avf := fun r p _ hop => absurd hop (not_mem_pred demoH V.onProperty (by decide) r p)+ hv := fun r p _ hop => absurd hop (not_mem_pred demoH V.onProperty (by decide) r p) }+ facts := fun t ht => List.mem_cons_of_mem _ ht+ int := by+ intro c l _ hc+ exact absurd hc (not_mem_pred demoG V.intersectionOf (by decide) c l)+ uni := by+ intro c l _ hc+ exact absurd hc (not_mem_pred demoG V.unionOf (by decide) c l)++/-- Adding a user rule does not collapse entailment: `a gp b` is still not a+consequence, so the Horn layer derives less than everything. -/+theorem demo_not_everything_entailed : ¬ EntailsR demoG demoR ⟨uA, uGp, uB⟩ := by+ intro h+ have hrules : ∀ r ∈ demoR, SatRule (herbrand demoH) r := by+ intro r hr+ have : r = gpRule := List.mem_singleton.mp hr+ subst this+ exact demoH_sat_rule+ have hs := h (herbrand demoH) ⟨demoH_is_a_model, hrules⟩+ exact absurd hs (by decide : (⟨uA, uGp, uB⟩ : Triple) ∉ demoH)++/-- info: 'OOCert.entailsR_not_vacuous' does not depend on any axioms -/+#guard_msgs in+#print axioms entailsR_not_vacuous++/-- info: 'OOCert.demo_conclusion_entailed' depends on axioms: [propext, Quot.sound] -/+#guard_msgs in+#print axioms demo_conclusion_entailed++/-- info: 'OOCert.demo_not_everything_entailed' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms demo_not_everything_entailed++end OOCertdiff --git a/lean/OOCert/Semantics.lean b/lean/OOCert/Semantics.leanindex b47264fa..eef5f57b 100644--- a/lean/OOCert/Semantics.lean+++ b/lean/OOCert/Semantics.lean@@ -129,8 +129,15 @@ structure Model (I : Interp) (G : List Triple) : Prop whereuni : ∀ c l ms, (⟨c, V.unionOf, l⟩ : Triple) ∈ G → Chain G l ms →∀ x m, m ∈ ms → I.cext (I.ι m) x → I.cext (I.ι c) x+/-- Entailment relative to an arbitrary class of interpretations. The soundness+proof never needs more than "every interpretation in this class models `G`", so+stating it this way lets one proof serve the built-in rules and any further+assumption a certificate chooses to carry, `OOCert.EntailsR` for user-written+Horn rules among them. -/+def EntailsIn (P : Interp → Prop) (t : Triple) : Prop := ∀ I : Interp, P I → I.sat t+/-- `G ⊨ t`: every model of `G` satisfies `t`. -/-def Entails (G : List Triple) (t : Triple) : Prop := ∀ I : Interp, Model I G → I.sat t+def Entails (G : List Triple) (t : Triple) : Prop := EntailsIn (fun I => Model I G) ttheorem Entails.of_mem {G : List Triple} {t : Triple} (h : t ∈ G) : Entails G t :=fun _ M => M.facts t hdiff --git a/lean/lakefile.toml b/lean/lakefile.tomlindex 33518c4a..2388535e 100644--- a/lean/lakefile.toml+++ b/lean/lakefile.toml@@ -1,6 +1,6 @@name = "oocert"version = "0.1.0"-defaultTargets = ["OOCert", "oo-cert"]+defaultTargets = ["OOCert", "oo-cert", "oo-horn"]# Core Lean only. No Mathlib, no external packages: the checker's trust surface# is the Lean kernel plus what is written in this directory, and it should stay@@ -12,3 +12,7 @@ name = "OOCert"[[lean_exe]]name = "oo-cert"root = "Main"++[[lean_exe]]+name = "oo-horn"+root = "HMain"diff --git a/tests/fixtures/horn/asserted.tsv b/tests/fixtures/horn/asserted.tsvnew file mode 100644index 00000000..388a220d--- /dev/null+++ b/tests/fixtures/horn/asserted.tsv@@ -0,0 +1,2 @@+<http://ex.org/a> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/A>+<http://ex.org/A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/B>diff --git a/tests/fixtures/horn/bad_binding.tsv b/tests/fixtures/horn/bad_binding.tsvnew file mode 100644index 00000000..36189185--- /dev/null+++ b/tests/fixtures/horn/bad_binding.tsv@@ -0,0 +1 @@+4 3 x <http://ex.org/a> a <http://ex.org/WRONG> b <http://ex.org/B> <http://ex.org/a> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/B> <http://ex.org/a> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/A> <http://ex.org/A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/B>diff --git a/tests/fixtures/horn/bad_conclusion.tsv b/tests/fixtures/horn/bad_conclusion.tsvnew file mode 100644index 00000000..3bbdd7b5--- /dev/null+++ b/tests/fixtures/horn/bad_conclusion.tsv@@ -0,0 +1 @@+4 3 x <http://ex.org/a> a <http://ex.org/A> b <http://ex.org/Z> <http://ex.org/a> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/B> <http://ex.org/a> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/A> <http://ex.org/A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/B>diff --git a/tests/fixtures/horn/bad_index.tsv b/tests/fixtures/horn/bad_index.tsvnew file mode 100644index 00000000..6a5fd202--- /dev/null+++ b/tests/fixtures/horn/bad_index.tsv@@ -0,0 +1 @@+99 3 x <http://ex.org/a> a <http://ex.org/A> b <http://ex.org/B> <http://ex.org/a> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/B> <http://ex.org/a> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/A> <http://ex.org/A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/B>diff --git a/tests/fixtures/horn/bad_premise.tsv b/tests/fixtures/horn/bad_premise.tsvnew file mode 100644index 00000000..61cda2d0--- /dev/null+++ b/tests/fixtures/horn/bad_premise.tsv@@ -0,0 +1 @@+4 3 x <http://ex.org/ghost> a <http://ex.org/A> b <http://ex.org/B> <http://ex.org/ghost> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/B> <http://ex.org/ghost> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/A> <http://ex.org/A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/B>diff --git a/tests/fixtures/horn/bad_self.tsv b/tests/fixtures/horn/bad_self.tsvnew file mode 100644index 00000000..ffd22cc3--- /dev/null+++ b/tests/fixtures/horn/bad_self.tsv@@ -0,0 +1 @@+4 3 x <http://ex.org/a> a <http://ex.org/A> b <http://ex.org/B> <http://ex.org/a> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/B> <http://ex.org/a> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/B> <http://ex.org/A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/B>diff --git a/tests/fixtures/horn/builtin_rules.tsv b/tests/fixtures/horn/builtin_rules.tsvnew file mode 100644index 00000000..69233461--- /dev/null+++ b/tests/fixtures/horn/builtin_rules.tsv@@ -0,0 +1,19 @@+rdfs2 2 ?s ?p ?o ?p <http://www.w3.org/2000/01/rdf-schema#domain> ?c ?s <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?c+rdfs3 2 ?s ?p ?o ?p <http://www.w3.org/2000/01/rdf-schema#range> ?c ?o <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?c+rdfs5 2 ?a <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?b ?b <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?c ?a <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?c+rdfs7 2 ?s ?p ?o ?p <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?q ?s ?q ?o+rdfs9 2 ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?a ?a <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?b ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?b+rdfs11 2 ?a <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?b ?b <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c ?a <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c+prp-trp 3 ?p <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#TransitiveProperty> ?x ?p ?y ?y ?p ?z ?x ?p ?z+prp-symp 2 ?p <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#SymmetricProperty> ?x ?p ?y ?y ?p ?x+prp-inv1 2 ?p <http://www.w3.org/2002/07/owl#inverseOf> ?q ?x ?p ?y ?y ?q ?x+prp-inv2 2 ?p <http://www.w3.org/2002/07/owl#inverseOf> ?q ?x ?q ?y ?y ?p ?x+eq-sym 1 ?a <http://www.w3.org/2002/07/owl#sameAs> ?b ?b <http://www.w3.org/2002/07/owl#sameAs> ?a+scm-eqc1 1 ?a <http://www.w3.org/2002/07/owl#equivalentClass> ?b ?a <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?b+scm-eqc1 1 ?a <http://www.w3.org/2002/07/owl#equivalentClass> ?b ?b <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?a+scm-eqp1 1 ?a <http://www.w3.org/2002/07/owl#equivalentProperty> ?b ?a <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?b+scm-eqp1 1 ?a <http://www.w3.org/2002/07/owl#equivalentProperty> ?b ?b <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?a+cls-svf1 4 ?r <http://www.w3.org/2002/07/owl#onProperty> ?p ?r <http://www.w3.org/2002/07/owl#someValuesFrom> ?c ?x ?p ?y ?y <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?c ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?r+cls-avf 4 ?r <http://www.w3.org/2002/07/owl#onProperty> ?p ?r <http://www.w3.org/2002/07/owl#allValuesFrom> ?c ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?r ?x ?p ?y ?y <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?c+cls-hv1 3 ?r <http://www.w3.org/2002/07/owl#onProperty> ?p ?r <http://www.w3.org/2002/07/owl#hasValue> ?v ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?r ?x ?p ?v+cls-hv2 3 ?r <http://www.w3.org/2002/07/owl#onProperty> ?p ?r <http://www.w3.org/2002/07/owl#hasValue> ?v ?x ?p ?v ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?rdiff --git a/tests/fixtures/horn/good.tsv b/tests/fixtures/horn/good.tsvnew file mode 100644index 00000000..e73ccd68--- /dev/null+++ b/tests/fixtures/horn/good.tsv@@ -0,0 +1 @@+4 3 x <http://ex.org/a> a <http://ex.org/A> b <http://ex.org/B> <http://ex.org/a> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/B> <http://ex.org/a> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/A> <http://ex.org/A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/B>diff --git a/tests/fixtures/horn/short_rules.tsv b/tests/fixtures/horn/short_rules.tsvnew file mode 100644index 00000000..3498eda6--- /dev/null+++ b/tests/fixtures/horn/short_rules.tsv@@ -0,0 +1,3 @@+rdfs2 2 ?s ?p ?o ?p <http://www.w3.org/2000/01/rdf-schema#domain> ?c ?s <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?c+rdfs3 2 ?s ?p ?o ?p <http://www.w3.org/2000/01/rdf-schema#range> ?c ?o <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?c+rdfs5 2 ?a <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?b ?b <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?c ?a <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?cdiff --git a/tests/fixtures/horn/user_rules.tsv b/tests/fixtures/horn/user_rules.tsvnew file mode 100644index 00000000..ed4ab1f5--- /dev/null+++ b/tests/fixtures/horn/user_rules.tsv@@ -0,0 +1,20 @@+rdfs2 2 ?s ?p ?o ?p <http://www.w3.org/2000/01/rdf-schema#domain> ?c ?s <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?c+rdfs3 2 ?s ?p ?o ?p <http://www.w3.org/2000/01/rdf-schema#range> ?c ?o <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?c+rdfs5 2 ?a <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?b ?b <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?c ?a <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?c+rdfs7 2 ?s ?p ?o ?p <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?q ?s ?q ?o+rdfs9 2 ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?a ?a <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?b ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?b+rdfs11 2 ?a <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?b ?b <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c ?a <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?c+prp-trp 3 ?p <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#TransitiveProperty> ?x ?p ?y ?y ?p ?z ?x ?p ?z+prp-symp 2 ?p <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#SymmetricProperty> ?x ?p ?y ?y ?p ?x+prp-inv1 2 ?p <http://www.w3.org/2002/07/owl#inverseOf> ?q ?x ?p ?y ?y ?q ?x+prp-inv2 2 ?p <http://www.w3.org/2002/07/owl#inverseOf> ?q ?x ?q ?y ?y ?p ?x+eq-sym 1 ?a <http://www.w3.org/2002/07/owl#sameAs> ?b ?b <http://www.w3.org/2002/07/owl#sameAs> ?a+scm-eqc1 1 ?a <http://www.w3.org/2002/07/owl#equivalentClass> ?b ?a <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?b+scm-eqc1 1 ?a <http://www.w3.org/2002/07/owl#equivalentClass> ?b ?b <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?a+scm-eqp1 1 ?a <http://www.w3.org/2002/07/owl#equivalentProperty> ?b ?a <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?b+scm-eqp1 1 ?a <http://www.w3.org/2002/07/owl#equivalentProperty> ?b ?b <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?a+cls-svf1 4 ?r <http://www.w3.org/2002/07/owl#onProperty> ?p ?r <http://www.w3.org/2002/07/owl#someValuesFrom> ?c ?x ?p ?y ?y <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?c ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?r+cls-avf 4 ?r <http://www.w3.org/2002/07/owl#onProperty> ?p ?r <http://www.w3.org/2002/07/owl#allValuesFrom> ?c ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?r ?x ?p ?y ?y <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?c+cls-hv1 3 ?r <http://www.w3.org/2002/07/owl#onProperty> ?p ?r <http://www.w3.org/2002/07/owl#hasValue> ?v ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?r ?x ?p ?v+cls-hv2 3 ?r <http://www.w3.org/2002/07/owl#onProperty> ?p ?r <http://www.w3.org/2002/07/owl#hasValue> ?v ?x ?p ?v ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?r+every-supplier-is-compliant 1 ?s <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Supplier> ?s <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Compliant>diff --git a/tests/lean_horn_certificate_test.rs b/tests/lean_horn_certificate_test.rsnew file mode 100644index 00000000..e696d4fa--- /dev/null+++ b/tests/lean_horn_certificate_test.rs@@ -0,0 +1,219 @@+//! The generic Horn-rule certificate layer.+//!+//! The checker in `lean/OOCert/Rules.lean` has one arm per built-in rule, which+//! does not scale to rules a user writes, and rules a user writes are the whole+//! logic-programming family: RIF Core, Datalog, SWRL. `lean/OOCert/Horn.lean`+//! replaces the per-rule arms with a single generic one. A certificate cites a+//! rule by index into a supplied table, gives a binding, and the checker+//! verifies that the binding instantiates the rule's body into known triples+//! and its head into the claimed conclusion. `OOCert.horn_certificate_sound` is+//! proved once, for every rule table at once.+//!+//! # The distinction these tests exist to protect+//!+//! Two runs of the same checker prove different things.+//!+//! Over the BUILT-IN table, `Builtin.asHorn_sound` discharges every rule against+//! the semantics, so the result is absolute entailment: true in every model of+//! the asserted graph. `OOCert.entails_of_builtin_horn`.+//!+//! Over a table the user supplied, nothing discharges the rules. They are+//! assumptions the certificate carries, so the result is relative: true in every+//! model of the graph that ALSO satisfies those rules.+//! `OOCert.horn_certificate_sound`. A rule reading "every supplier is compliant"+//! makes certificates that check green for ever, and the certificate certifies+//! the inference, never the premises.+//!+//! Collapsing those into one verdict turns a verified checker into a device for+//! laundering an assumption into a fact. `a_user_rule_never_earns_the_absolute_verdict`+//! is the test that fails if that ever happens.++mod common;++use std::path::{Path, PathBuf};+use std::process::Command;+use std::sync::OnceLock;++fn repo() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+}++fn lean_dir() -> PathBuf {+ repo().join("lean")+}++fn fixture(name: &str) -> PathBuf {+ repo().join("tests").join("fixtures").join("horn").join(name)+}++fn lake_available() -> bool {+ // `.current_dir(lean_dir())`: elan resolves the toolchain from the working+ // directory, and the crate root has no `lean-toolchain` in its ancestry.+ Command::new("lake")+ .arg("--version")+ .current_dir(lean_dir())+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+}++fn skip() -> bool {+ common::skip_unless(+ lake_available(),+ "lake (the Lean 4 build tool)",+ "install elan from https://github.com/leanprover/elan; lean/lean-toolchain pins the version",+ )+}++/// Build once per test binary. The proofs are part of the build, so a failure+/// here is a failure and never a skip.+fn checker() -> &'static Path {+ static BUILT: OnceLock<PathBuf> = OnceLock::new();+ BUILT.get_or_init(|| {+ let out = Command::new("lake")+ .arg("build")+ .current_dir(lean_dir())+ .output()+ .expect("run lake build");+ assert!(+ out.status.success(),+ "lake build failed:\n{}\n{}",+ String::from_utf8_lossy(&out.stdout),+ String::from_utf8_lossy(&out.stderr)+ );+ let exe = lean_dir().join(".lake").join("build").join("bin").join("oo-horn");+ assert!(exe.exists(), "checker binary missing at {}", exe.display());+ exe+ })+}++/// Returns (exit code, stdout).+fn check(rules: &str, asserted: &str, cert: &str) -> (i32, String) {+ let out = Command::new(checker())+ .arg("check")+ .arg(fixture(rules))+ .arg(fixture(asserted))+ .arg(fixture(cert))+ .output()+ .expect("run oo-horn");+ (out.status.code().unwrap_or(-1), String::from_utf8_lossy(&out.stdout).to_string())+}++fn field<'a>(json: &'a str, key: &str) -> &'a str {+ let pat = format!("\"{key}\":\"");+ let start = json.find(&pat).unwrap_or_else(|| panic!("no {key} in {json}")) + pat.len();+ let rest = &json[start..];+ &rest[..rest.find('"').expect("unterminated")]+}++#[test]+fn the_built_in_table_earns_the_absolute_verdict() {+ if skip() {+ return;+ }+ let (code, out) = check("builtin_rules.tsv", "asserted.tsv", "good.tsv");+ assert_eq!(code, 0, "{out}");+ assert_eq!(field(&out, "verdict"), "entailed", "{out}");+ assert_eq!(field(&out, "theorem"), "OOCert.entails_of_builtin_horn", "{out}");+ assert_eq!(+ field(&out, "rules_digest"),+ field(&out, "builtin_rules_digest"),+ "the table that earns the absolute verdict must BE the built-in table: {out}"+ );+}++#[test]+fn a_user_rule_never_earns_the_absolute_verdict() {+ // The laundering guard. `user_rules.tsv` is the built-in table plus one+ // invented rule asserting that every supplier is compliant. The same+ // certificate still checks, because the inference is still valid, and the+ // verdict must say what it is relative to.+ if skip() {+ return;+ }+ let (code, out) = check("user_rules.tsv", "asserted.tsv", "good.tsv");+ assert_eq!(code, 0, "{out}");+ assert_ne!(+ field(&out, "verdict"),+ "entailed",+ "a run over user-supplied rules must NOT report absolute entailment: {out}"+ );+ assert_eq!(field(&out, "verdict"), "entailed_under_supplied_rules", "{out}");+ assert_eq!(field(&out, "theorem"), "OOCert.horn_certificate_sound", "{out}");+ assert_ne!(+ field(&out, "rules_digest"),+ field(&out, "builtin_rules_digest"),+ "the digest must show the table differed from the built-ins: {out}"+ );+ assert!(+ field(&out, "means").contains("assumed, not checked"),+ "the report must say the rules are assumed: {out}"+ );+}++#[test]+fn every_forgery_is_rejected() {+ if skip() {+ return;+ }+ // Each one is a different way to lie, and each must be caught on its own.+ let forgeries = [+ ("bad_conclusion.tsv", "the conclusion is not the rule's head under the binding"),+ ("bad_index.tsv", "the cited rule index is outside the table"),+ ("bad_premise.tsv", "a premise is neither asserted nor derived earlier"),+ ("bad_self.tsv", "the step cites its own conclusion as a premise"),+ ("bad_binding.tsv", "the binding does not instantiate the body"),+ ];+ for (name, why) in forgeries {+ let (code, out) = check("builtin_rules.tsv", "asserted.tsv", name);+ assert_eq!(code, 1, "{name} must be rejected because {why}: {out}");+ }+ // And a table too short to contain the cited rule.+ let (code, out) = check("short_rules.tsv", "asserted.tsv", "good.tsv");+ assert_eq!(code, 1, "a rule table missing the cited rule must be rejected: {out}");+}++#[test]+fn an_unreadable_file_is_exit_two_not_a_rejection() {+ if skip() {+ return;+ }+ let out = Command::new(checker())+ .arg("check")+ .arg("/nonexistent/rules.tsv")+ .arg("/nonexistent/asserted.tsv")+ .arg("/nonexistent/horn.tsv")+ .output()+ .expect("run oo-horn");+ assert_eq!(+ out.status.code(),+ Some(2),+ "exit 1 means a step was rejected; an unreadable file must not look like that"+ );+}++#[test]+fn the_built_in_rules_are_emitted_as_data() {+ if skip() {+ return;+ }+ let out = Command::new(checker()).arg("rules").output().expect("run oo-horn rules");+ assert!(out.status.success());+ let text = String::from_utf8_lossy(&out.stdout);+ let lines: Vec<&str> = text.lines().filter(|l| !l.is_empty()).collect();+ assert_eq!(+ lines.len(),+ 19,+ "nineteen of the engine's rules are Horn rules; cls-int1 and cls-uni read an RDF list off \+ the graph, so their premise count is data rather than fixed by the rule, and they stay as \+ hardcoded arms. If this number changed, say which rule moved and why."+ );+ // The table printed here is the one the absolute verdict is pinned to, so it+ // must match the committed fixture byte for byte.+ let committed = std::fs::read_to_string(fixture("builtin_rules.tsv")).unwrap();+ assert_eq!(+ text.trim_end(),+ committed.trim_end(),+ "the committed rule table has drifted from the one the checker computes"+ );+}