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
Mechanise SHACL Core in Lean, land the mixed certificate, and let the engine emit Horn certificates
FABIOTESS41ee6cea9775
diff --git a/lean/OOCert.lean b/lean/OOCert.leanindex 1e9da8c0..749e2410 100644--- a/lean/OOCert.lean+++ b/lean/OOCert.lean@@ -6,4 +6,5 @@ import OOCert.Witnessimport OOCert.Hornimport OOCert.HornBuiltinimport OOCert.HornWitness+import OOCert.Mixedimport OOCert.Parsediff --git a/lean/OOCert/Mixed.lean b/lean/OOCert/Mixed.leannew file mode 100644index 00000000..37d2d78f--- /dev/null+++ b/lean/OOCert/Mixed.lean@@ -0,0 +1,626 @@+import OOCert.Soundness+import OOCert.Witness+import OOCert.Horn+import OOCert.HornBuiltin+import OOCert.HornWitness++/-!+# One certificate, both rule families++A certificate used to be either all built-in arms (`Rules.lean`, proved by+`certificate_sound`) or all citations of a user-supplied Horn rule (`Horn.lean`,+proved by `horn_certificate_sound`). A user who wrote one rule of their own could+not also cite `cls-int1` or `cls-uni`, and those two are never going to become+Horn rules: their premise count is the length of an RDF list, which is data+rather than something the rule fixes. `HornBuiltin.lean` says so at its top and+means it.++`MStep` is the union of the two step kinds and `mixed_certificate_sound` covers+both in one induction. The twenty arms are reused unchanged. The only thing that+had to give was the entailment relation in `Soundness.lean`, which is now+parametric in the class of interpretations the certificate is relative to+(`EntailsIn P`). A model of `G` that also satisfies `R` is in particular a model+of `G`, so every one of the per-rule cases applies at `P := ModelR G R` without+being touched.++## Which guarantee a mixed certificate earns++Two, and they are not the same one.++`mixed_certificate_sound` gives `EntailsR G R`: true in every model of the+asserted graph that also satisfies the supplied rules. The rules are an+assumption the certificate carries and nothing here checks them. A rule reading+"every supplier is compliant" makes certificates that check green for ever.++`mixed_certificate_sound_of_discharged` gives the absolute `Entails G`, and it+asks for the one thing that makes the difference: a proof, for every rule in the+table, that the semantic conditions already imply it.+`mixed_certificate_sound_builtin` is that theorem applied to the nineteen+built-in rules, which `Builtin.asHorn_sound` discharges, and+`mixed_certificate_sound_no_rules` is the empty table, which has nothing to+discharge.++The difference is not academic, and the witness section below proves that rather+than asserting it. `mix_conclusion_entailed` and `mix_not_absolutely_entailed`+are about the same triple of the same accepted certificate: it follows under the+supplied rule, and without that rule it does not follow, because there is a model+of the asserted graph that refutes it. Printing the absolute verdict for that run+would be a false statement about a machine-checked fact.++`absolute_verdict_is_earned` is the last theorem in the file and the reason the+report functions are here rather than in a binary. It says that whenever the+verdict function prints the absolute word, the absolute theorem applies to that+run. The verdict cannot launder an assumption into a fact, and that is a proof+rather than a review comment. See+`docs/decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md`.+-/+namespace OOCert++/-! ## The checker -/++/-- A step of a mixed certificate: a built-in rule with its hardcoded arm, or a+citation of a rule from the supplied table. -/+inductive MStep+ | builtin : Step → MStep+ | horn : HornStep → MStep+deriving Repr++def MStep.conclusion : MStep → Triple+ | .builtin st => st.conclusion+ | .horn st => st.conclusion++/-- Check one step of either kind.++The built-in arm is handed `inG` and `derived` separately rather than their+disjunction, and that is not tidiness. `cls-int1` and `cls-uni` read their RDF+list off the ASSERTED graph, because `Model` reads it off the asserted graph, so+`checkStep` tests the constructor triple and every chain triple with `inG`+alone. Passing `fun t => inG t || derived t` for both jobs would let a+certificate build a list out of its own earlier conclusions.+`rejects_a_list_that_was_not_asserted` below pins that, with `derived` answering+true to every triple in the language. -/+def checkMStep (inG derived : Triple → Bool) (R : List RulePattern) : MStep → Bool+ | .builtin st => checkStep inG derived st+ | .horn st => checkHornStep R (fun t => inG t || derived t) st++/-- Steps in order, each seeing only the conclusions of the ones before it. The+discipline `checkAll` and `checkHornAll` already use, and in particular no step+may cite itself. -/+def checkAllM (inG : Triple → Bool) (R : List RulePattern) :+ List MStep → Std.HashSet Triple → Bool+ | [], _ => true+ | st :: rest, derived =>+ checkMStep inG (fun t => derived.contains t) R st &&+ checkAllM inG R rest (derived.insert st.conclusion)++/-- The mixed checker. `G` is the asserted graph, `R` the rule table the+certificate is relative to, `steps` the certificate. -/+def checkCertM (G : List Triple) (R : List RulePattern) (steps : List MStep) : Bool :=+ let gset := Std.HashSet.ofList G+ checkAllM (fun t => gset.contains t) R steps ∅++/-! ## Soundness -/++/-- One step, either kind. The built-in case is `checkStep_sound` instantiated at+`P := ModelR G R`, which is the whole content of the generalisation; the Horn+case is `checkHornStep_sound` with the two sources of a known premise spliced+back together. -/+theorem checkMStep_sound {G : List Triple} {R : List RulePattern}+ {inG derived : Triple → Bool} {st : MStep}+ (hG : ∀ t, inG t = true → t ∈ G)+ (hD : ∀ t, derived t = true → EntailsR G R t)+ (h : checkMStep inG derived R st = true) : EntailsR G R st.conclusion := by+ cases st with+ | builtin b =>+ exact checkStep_sound (P := ModelR G R) (fun _ hI => hI.1) hG hD h+ | horn hs =>+ refine checkHornStep_sound ?_ h+ 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++theorem checkAllM_sound {G : List Triple} {R : List RulePattern} {inG : Triple → Bool}+ (hG : ∀ t, inG t = true → t ∈ G) :+ ∀ (steps : List MStep) (derived : Std.HashSet Triple),+ (∀ t, derived.contains t = true → EntailsR G R t) →+ checkAllM 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 [checkAllM, Bool.and_eq_true] at h+ obtain ⟨h1, h2⟩ := h+ have hst : EntailsR G R st.conclusion := checkMStep_sound hG hD 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 theorem for a mixed certificate.** One induction, both step kinds. The+guarantee is RELATIVE to `R`: every conclusion is true in every model of `G` that+also satisfies the supplied rules. It says nothing about whether those rules are+true, and nothing about whether the rule set is consistent. -/+theorem mixed_certificate_sound (G : List Triple) (R : List RulePattern) (steps : List MStep)+ (h : checkCertM G R steps = true) : ∀ st ∈ steps, EntailsR G R st.conclusion := by+ unfold checkCertM at h+ refine checkAllM_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 absolute guarantee, and the price of it: a proof for EVERY rule in the+table that the semantic conditions already imply it. Nothing else upgrades a+relative verdict to an absolute one. -/+theorem mixed_certificate_sound_of_discharged (G : List Triple) (R : List RulePattern)+ (hR : ∀ r ∈ R, ∀ I : Interp, Conditions I → SatRule I r)+ (steps : List MStep) (h : checkCertM G R steps = true) :+ ∀ st ∈ steps, Entails G st.conclusion := by+ intro st hst I M+ exact mixed_certificate_sound G R steps h st hst I ⟨M, fun r hr => hR r hr I M.conds⟩++/-- The empty table has nothing to discharge, so a mixed certificate over it is+the old built-in certificate and the old warrant comes back unchanged. Nothing+was lost in the generalisation. -/+theorem mixed_certificate_sound_no_rules (G : List Triple) (steps : List MStep)+ (h : checkCertM G [] steps = true) : ∀ st ∈ steps, Entails G st.conclusion :=+ mixed_certificate_sound_of_discharged G [] (by intro r hr; simp at hr) steps h++/-- The built-in table, discharged by `Builtin.asHorn_sound`. A certificate may+mix the nineteen built-in rules cited as data with the two hardcoded arms+`cls-int1` and `cls-uni` and still earn the absolute verdict. -/+theorem mixed_certificate_sound_builtin (G : List Triple) (steps : List MStep)+ (h : checkCertM G Builtin.asHorn steps = true) :+ ∀ st ∈ steps, Entails G st.conclusion :=+ mixed_certificate_sound_of_discharged G Builtin.asHorn+ (fun r hr I C => Builtin.asHorn_sound I C r hr) steps h++/-! ## A worked mixed certificate++Two steps that could not have shared a certificate before this file existed. The+first is `cls-int1`, a hardcoded arm, because its premise count is the length of+an RDF list. The second cites a rule the checker has never heard of, and its only+premise is the first step's conclusion.++The rule is decision 0003's own example, "every supplier is compliant", because+the point of the section is what such a rule does and does not buy. -/++def mAcme : Term := "<u:acme>"+def mVendor : Term := "<u:Vendor>"+def mApproved : Term := "<u:Approved>"+def mSupplier : Term := "<u:Supplier>"+def mStatus : Term := "<u:status>"+def mCompliant : Term := "<u:Compliant>"+def mL0 : Term := "_:l0"+def mL1 : Term := "_:l1"++/-- `Supplier ≡ Vendor ⊓ Approved` as an RDF list, and an acme that is both. -/+def mixG : List Triple :=+ [ ⟨mSupplier, V.intersectionOf, mL0⟩,+ ⟨mL0, V.first, mVendor⟩, ⟨mL0, V.rest, mL1⟩,+ ⟨mL1, V.first, mApproved⟩, ⟨mL1, V.rest, V.nil⟩,+ ⟨mAcme, V.type, mVendor⟩, ⟨mAcme, V.type, mApproved⟩ ]++/-- The assumption. Nothing in this file or any other proves it, and that is the+whole subject of decision 0003. -/+def complianceRule : RulePattern :=+ { name := "every-supplier-is-compliant"+ body := [⟨.var "s", .const V.type, .const mSupplier⟩]+ head := ⟨.var "s", .const mStatus, .const mCompliant⟩ }++def mixR : List RulePattern := [complianceRule]++def mixIntStep : Step :=+ { rule := .clsInt1+ premises :=+ [⟨mSupplier, V.intersectionOf, mL0⟩,+ ⟨mL0, V.first, mVendor⟩, ⟨mL0, V.rest, mL1⟩,+ ⟨mL1, V.first, mApproved⟩, ⟨mL1, V.rest, V.nil⟩,+ ⟨mAcme, V.type, mVendor⟩, ⟨mAcme, V.type, mApproved⟩]+ conclusion := ⟨mAcme, V.type, mSupplier⟩ }++def mixHornStep : HornStep :=+ { rule := 0+ binds := [("s", mAcme)]+ premises := [⟨mAcme, V.type, mSupplier⟩]+ conclusion := ⟨mAcme, mStatus, mCompliant⟩ }++def mixSteps : List MStep := [.builtin mixIntStep, .horn mixHornStep]++/-! The two facts are stated per step rather than through `checkCertM`, because+`checkCertM` carries its derived set in a `Std.HashSet` and `Triple`'s hash runs+through `String.hash`, which is opaque to the kernel. `decide` therefore cannot+evaluate it, and `native_decide` is not available here: it would add+`Lean.ofReduceBool` to the trust surface. `checkCertM` itself is exercised at+run time, by `tests/lean_mixed_certificate_test.rs`. -/++def mixInG : Triple → Bool := fun t => decide (t ∈ mixG)+/-- What the second step may treat as derived: the first step's conclusion, and+nothing else. -/+def mixAfterFirst : Triple → Bool := fun t => decide (t = (⟨mAcme, V.type, mSupplier⟩ : Triple))++theorem mix_builtin_step_accepted :+ checkMStep mixInG (fun _ => false) mixR (.builtin mixIntStep) = true := by decide++theorem mix_horn_step_accepted :+ checkMStep mixInG mixAfterFirst mixR (.horn mixHornStep) = true := by decide++theorem mix_type_entailed : EntailsR mixG mixR ⟨mAcme, V.type, mSupplier⟩ :=+ checkMStep_sound (G := mixG) (R := mixR)+ (fun _ ht => of_decide_eq_true ht)+ (fun _ ht => by simp at ht)+ mix_builtin_step_accepted++/-- The payoff. A conclusion reached through a hardcoded arm and a user rule in+one certificate. -/+theorem mix_conclusion_entailed : EntailsR mixG mixR ⟨mAcme, mStatus, mCompliant⟩ :=+ checkMStep_sound (G := mixG) (R := mixR)+ (fun _ ht => of_decide_eq_true ht)+ (fun t ht => by+ have he : t = (⟨mAcme, V.type, mSupplier⟩ : Triple) := of_decide_eq_true ht+ subst he+ exact mix_type_entailed)+ mix_horn_step_accepted++/-! ## The gate can fail++Six ways to be wrong, two of them about the built-in step and four about the+step citing a rule, each rejected on its own. Without these the acceptance above+would be evidence of nothing. -/++def mixForgedIntConclusion : Step := { mixIntStep with conclusion := ⟨mAcme, V.type, mVendor⟩ }++/-- A shorter list, so that being merely `Approved` would suffice. The chain+triples are not in `mixG`. -/+def mixForgedIntChain : Step :=+ { rule := .clsInt1+ premises :=+ [⟨mSupplier, V.intersectionOf, mL0⟩,+ ⟨mL0, V.first, mApproved⟩, ⟨mL0, V.rest, V.nil⟩,+ ⟨mAcme, V.type, mApproved⟩]+ conclusion := ⟨mAcme, V.type, mSupplier⟩ }++def mixForgedHornConclusion : HornStep :=+ { mixHornStep with conclusion := ⟨mAcme, mStatus, mSupplier⟩ }+def mixForgedHornIndex : HornStep := { mixHornStep with rule := 1 }+def mixForgedHornBinding : HornStep := { mixHornStep with binds := [("s", mVendor)] }++theorem rejects_a_forged_builtin_conclusion :+ checkMStep mixInG mixAfterFirst mixR (.builtin mixForgedIntConclusion) = false := by decide++/-- `derived` answers true to every triple there is, and the step is still+rejected, because a list must be asserted. -/+theorem rejects_a_list_that_was_not_asserted :+ checkMStep mixInG (fun _ => true) mixR (.builtin mixForgedIntChain) = false := by decide++theorem rejects_a_forged_horn_conclusion :+ checkMStep mixInG mixAfterFirst mixR (.horn mixForgedHornConclusion) = false := by decide++theorem rejects_an_unknown_rule_index :+ checkMStep mixInG mixAfterFirst mixR (.horn mixForgedHornIndex) = false := by decide++theorem rejects_a_binding_that_does_not_instantiate_the_body :+ checkMStep mixInG mixAfterFirst mixR (.horn mixForgedHornBinding) = false := by decide++/-- Order is part of the contract across the two kinds as well as within one:+the Horn step's only premise is the built-in step's conclusion, so before that+step has run it is neither asserted nor derived. -/+theorem rejects_a_horn_step_before_the_builtin_step_it_needs :+ checkMStep mixInG (fun _ => false) mixR (.horn mixHornStep) = false := by decide++/-! ## What the relative guarantee is worth, and what it is not++Three facts about the certificate just accepted. The model class it quantifies+over is not empty, so the guarantee is not the vacuous one of an inconsistent+premise set. It does not hold of everything, so it is not the trivial relation.+And the conclusion it licenses is NOT a consequence of the asserted graph alone,+which is the machine-checked form of the thing decision 0003 refuses to let a+report blur. -/++/-- `saturated` models any graph and satisfies any rule, so the model class is+non-empty for this graph and this table. -/+theorem mix_rules_are_satisfiable : ∃ I : Interp, Model I mixG ∧ ∀ r ∈ mixR, SatRule I r :=+ entailsR_not_vacuous mixG mixR++/-- Inversion for `Chain`, which `Semantics.lean` declares without one because+nothing needed it until a witness graph carried a list. It belongs beside the+inductive and would be welcome there. -/+private theorem chain_uncons {G : List Triple} {l : Term} {ms : List Term} (h : Chain G l ms) :+ (l = V.nil ∧ ms = []) ∨+ ∃ m l' ms', ms = m :: ms' ∧ (⟨l, V.first, m⟩ : Triple) ∈ G ∧+ (⟨l, V.rest, l'⟩ : Triple) ∈ G ∧ Chain G l' ms' := by+ cases h with+ | nil => exact Or.inl ⟨rfl, rfl⟩+ | cons h1 h2 hr => exact Or.inr ⟨_, _, _, rfl, h1, h2, hr⟩++/-! The list `mixG` carries is read off it by these five decidable facts, which+say that each node has exactly one `rdf:first` and one `rdf:rest`, that nothing+hangs off `rdf:nil`, and that `Supplier` is the only intersection. -/++private theorem mix_l0_first : ∀ t ∈ mixG, t.s = mL0 → t.p = V.first → t.o = mVendor := by decide+private theorem mix_l0_rest : ∀ t ∈ mixG, t.s = mL0 → t.p = V.rest → t.o = mL1 := by decide+private theorem mix_l1_first : ∀ t ∈ mixG, t.s = mL1 → t.p = V.first → t.o = mApproved := by decide+private theorem mix_l1_rest : ∀ t ∈ mixG, t.s = mL1 → t.p = V.rest → t.o = V.nil := by decide+private theorem mix_no_nil_subject : ∀ t ∈ mixG, t.s ≠ V.nil := by decide+private theorem mix_only_int : ∀ t ∈ mixG, t.p = V.intersectionOf →+ t.s = mSupplier ∧ t.o = mL0 := by decide++private theorem mix_chain_nil : ∀ ms, Chain mixG V.nil ms → ms = [] := by+ intro ms h+ rcases chain_uncons h with ⟨_, rfl⟩ | ⟨_, _, _, _, h1, _, _⟩+ · rfl+ · exact absurd rfl (mix_no_nil_subject _ h1)++private theorem mix_chain_l1 : ∀ ms, Chain mixG mL1 ms → ms = [mApproved] := by+ intro ms h+ rcases chain_uncons h with ⟨hn, _⟩ | ⟨m, l', ms', rfl, h1, h2, hr⟩+ · exact absurd hn (by decide)+ · have hm : m = mApproved := mix_l1_first _ h1 rfl rfl+ have hl : l' = V.nil := mix_l1_rest _ h2 rfl rfl+ subst hm; subst hl+ rw [mix_chain_nil _ hr]++private theorem mix_chain_l0 : ∀ ms, Chain mixG mL0 ms → ms = [mVendor, mApproved] := by+ intro ms h+ rcases chain_uncons h with ⟨hn, _⟩ | ⟨m, l', ms', rfl, h1, h2, hr⟩+ · exact absurd hn (by decide)+ · have hm : m = mVendor := mix_l0_first _ h1 rfl rfl+ have hl : l' = mL1 := mix_l0_rest _ h2 rfl rfl+ subst hm; subst hl+ rw [mix_chain_l1 _ hr]++/-- `mixG` plus the one triple the semantics does force, `acme rdf:type Supplier`,+and nothing else. In particular no `u:status`. -/+def mixH : List Triple := ⟨mAcme, V.type, mSupplier⟩ :: mixG++private theorem mixH_int_closed : ∀ t ∈ mixH, ∀ u ∈ mixH,+ (t.p = V.type ∧ t.o = mVendor ∧ u.p = V.type ∧ u.o = mApproved ∧ u.s = t.s) →+ (⟨t.s, V.type, mSupplier⟩ : Triple) ∈ mixH := by decide++theorem mixH_is_a_model : Model (herbrand mixH) mixG where+ conds :=+ { sc_sub := fun a b hab => absurd hab (not_mem_pred mixH V.subClassOf (by decide) a b)+ sc_trans := fun a b _ hab => absurd hab (not_mem_pred mixH V.subClassOf (by decide) a b)+ sp_sub := fun a b hab => absurd hab (not_mem_pred mixH V.subPropertyOf (by decide) a b)+ sp_trans := fun a b _ hab =>+ absurd hab (not_mem_pred mixH V.subPropertyOf (by decide) a b)+ dom := fun p c hpc => absurd hpc (not_mem_pred mixH V.domain (by decide) p c)+ rng := fun p c hpc => absurd hpc (not_mem_pred mixH V.range (by decide) p c)+ trp := fun p hp => absurd hp (not_typed mixH V.transitiveProperty (by decide) p)+ symp := fun p hp => absurd hp (not_typed mixH V.symmetricProperty (by decide) p)+ inv := fun p q hpq => absurd hpq (not_mem_pred mixH V.inverseOf (by decide) p q)+ same := fun a b hab => absurd hab (not_mem_pred mixH V.sameAs (by decide) a b)+ eqc := fun a b hab => absurd hab (not_mem_pred mixH V.equivalentClass (by decide) a b)+ eqp := fun a b hab =>+ absurd hab (not_mem_pred mixH V.equivalentProperty (by decide) a b)+ svf := fun r p _ hop => absurd hop (not_mem_pred mixH V.onProperty (by decide) r p)+ avf := fun r p _ hop => absurd hop (not_mem_pred mixH V.onProperty (by decide) r p)+ hv := fun r p _ hop => absurd hop (not_mem_pred mixH V.onProperty (by decide) r p) }+ facts := fun t ht => List.mem_cons_of_mem _ ht+ int := by+ intro c l ms hc hchain x hx+ obtain ⟨rfl, rfl⟩ := mix_only_int _ hc rfl+ have hms := mix_chain_l0 ms hchain+ subst hms+ exact mixH_int_closed _ (hx mVendor (by simp)) _ (hx mApproved (by simp))+ ⟨rfl, rfl, rfl, rfl, rfl⟩+ uni := by+ intro c l _ hc+ exact absurd hc (not_mem_pred mixG V.unionOf (by decide) c l)++/-- **The distinction, machine-checked.** The certificate above was accepted and+its conclusion is entailed under the supplied rule. It is NOT entailed by the+asserted graph: `mixH` is a model of that graph in which acme has no status at+all. A run over this table may therefore report `entailed_under_supplied_rules`+and may never report `entailed`. -/+theorem mix_not_absolutely_entailed : ¬ Entails mixG ⟨mAcme, mStatus, mCompliant⟩ := fun h =>+ absurd (h (herbrand mixH) mixH_is_a_model)+ (by decide : (⟨mAcme, mStatus, mCompliant⟩ : Triple) ∉ mixH)++/-- `mixG` closed under the supplied rule as well. -/+def mixH2 : List Triple := ⟨mAcme, mStatus, mCompliant⟩ :: mixH++private theorem mixH2_int_closed : ∀ t ∈ mixH2, ∀ u ∈ mixH2,+ (t.p = V.type ∧ t.o = mVendor ∧ u.p = V.type ∧ u.o = mApproved ∧ u.s = t.s) →+ (⟨t.s, V.type, mSupplier⟩ : Triple) ∈ mixH2 := by decide++private theorem mixH2_rule_closed : ∀ t ∈ mixH2, t.p = V.type → t.o = mSupplier →+ (⟨t.s, mStatus, mCompliant⟩ : Triple) ∈ mixH2 := by decide++theorem mixH2_is_a_model : Model (herbrand mixH2) mixG where+ conds :=+ { sc_sub := fun a b hab => absurd hab (not_mem_pred mixH2 V.subClassOf (by decide) a b)+ sc_trans := fun a b _ hab => absurd hab (not_mem_pred mixH2 V.subClassOf (by decide) a b)+ sp_sub := fun a b hab => absurd hab (not_mem_pred mixH2 V.subPropertyOf (by decide) a b)+ sp_trans := fun a b _ hab =>+ absurd hab (not_mem_pred mixH2 V.subPropertyOf (by decide) a b)+ dom := fun p c hpc => absurd hpc (not_mem_pred mixH2 V.domain (by decide) p c)+ rng := fun p c hpc => absurd hpc (not_mem_pred mixH2 V.range (by decide) p c)+ trp := fun p hp => absurd hp (not_typed mixH2 V.transitiveProperty (by decide) p)+ symp := fun p hp => absurd hp (not_typed mixH2 V.symmetricProperty (by decide) p)+ inv := fun p q hpq => absurd hpq (not_mem_pred mixH2 V.inverseOf (by decide) p q)+ same := fun a b hab => absurd hab (not_mem_pred mixH2 V.sameAs (by decide) a b)+ eqc := fun a b hab => absurd hab (not_mem_pred mixH2 V.equivalentClass (by decide) a b)+ eqp := fun a b hab =>+ absurd hab (not_mem_pred mixH2 V.equivalentProperty (by decide) a b)+ svf := fun r p _ hop => absurd hop (not_mem_pred mixH2 V.onProperty (by decide) r p)+ avf := fun r p _ hop => absurd hop (not_mem_pred mixH2 V.onProperty (by decide) r p)+ hv := fun r p _ hop => absurd hop (not_mem_pred mixH2 V.onProperty (by decide) r p) }+ facts := fun t ht => List.mem_cons_of_mem _ (List.mem_cons_of_mem _ ht)+ int := by+ intro c l ms hc hchain x hx+ obtain ⟨rfl, rfl⟩ := mix_only_int _ hc rfl+ have hms := mix_chain_l0 ms hchain+ subst hms+ exact mixH2_int_closed _ (hx mVendor (by simp)) _ (hx mApproved (by simp))+ ⟨rfl, rfl, rfl, rfl, rfl⟩+ uni := by+ intro c l _ hc+ exact absurd hc (not_mem_pred mixG V.unionOf (by decide) c l)++theorem mixH2_sat_rule : SatRule (herbrand mixH2) complianceRule := by+ intro sigma hb+ have h1 : (⟨sigma "s", V.type, mSupplier⟩ : Triple) ∈ mixH2 :=+ hb ⟨.var "s", .const V.type, .const mSupplier⟩ (by simp [complianceRule])+ exact mixH2_rule_closed ⟨sigma "s", V.type, mSupplier⟩ h1 rfl rfl++/-- Adding the rule does not collapse entailment into "everything follows".+`Vendor` is not a `Supplier`, so nothing makes it compliant. -/+theorem mix_relative_is_not_everything :+ ¬ EntailsR mixG mixR ⟨mVendor, mStatus, mCompliant⟩ := by+ intro h+ have hrules : ∀ r ∈ mixR, SatRule (herbrand mixH2) r := by+ intro r hr+ have hre : r = complianceRule := List.mem_singleton.mp hr+ subst hre+ exact mixH2_sat_rule+ exact absurd (h (herbrand mixH2) ⟨mixH2_is_a_model, hrules⟩)+ (by decide : (⟨mVendor, mStatus, mCompliant⟩ : Triple) ∉ mixH2)++/-! ## The report, and why it cannot launder++A run has to say which of the two guarantees it earned, and decision 0003 puts+that in the verdict rather than in a footnote. These three functions are the+report surface. They are not plumbing that a reviewer has to trust:+`absolute_verdict_is_earned` proves that the absolute word is printed only for a+table the absolute theorem covers. -/++/-- Structural equality of rules. `RulePattern` does not derive `DecidableEq`,+and `Horn.lean` is not this file's to change, so it is written out. Comparing+the rules themselves rather than their rendered form is what makes+`sameTable_eq` provable, and `sameTable_eq` is what makes the verdict theorem+possible. -/+def sameRule (a b : RulePattern) : Bool :=+ a.name == b.name && a.body == b.body && a.head == b.head++def sameTable : List RulePattern → List RulePattern → Bool+ | [], [] => true+ | a :: as, b :: bs => sameRule a b && sameTable as bs+ | _, _ => false++theorem sameRule_eq {a b : RulePattern} (h : sameRule a b = true) : a = b := by+ unfold sameRule at h+ simp only [Bool.and_eq_true, beq_iff_eq] at h+ obtain ⟨⟨h1, h2⟩, h3⟩ := h+ cases a; cases b+ simp_all++theorem sameTable_eq : ∀ {A B : List RulePattern}, sameTable A B = true → A = B+ | [], [], _ => rfl+ | [], _ :: _, h => by simp [sameTable] at h+ | _ :: _, [], h => by simp [sameTable] at h+ | _ :: _, _ :: _, h => by+ simp only [sameTable, Bool.and_eq_true] at h+ rw [sameRule_eq h.1, sameTable_eq h.2]++/-- Which of the three theorems a run over this table earned. -/+inductive Warrant+ | noRules | builtin | supplied+deriving DecidableEq, Repr++def warrantOf : List RulePattern → Warrant+ | [] => .noRules+ | r :: rs => if sameTable (r :: rs) Builtin.asHorn then .builtin else .supplied++theorem warrantOf_noRules : ∀ {R : List RulePattern}, warrantOf R = .noRules → R = []+ | [], _ => rfl+ | _ :: _, h => by+ simp only [warrantOf] at h+ split at h <;> exact absurd h (by decide)++theorem warrantOf_builtin : ∀ {R : List RulePattern},+ warrantOf R = .builtin → R = Builtin.asHorn+ | [], h => by simp only [warrantOf] at h; exact absurd h (by decide)+ | _ :: _, h => by+ simp only [warrantOf] at h+ split at h+ · rename_i hs; exact sameTable_eq hs+ · exact absurd h (by decide)++/-- The two verdicts never share a word. -/+def Warrant.verdict : Warrant → String+ | .noRules | .builtin => "entailed"+ | .supplied => "entailed_under_supplied_rules"++def Warrant.theoremName : Warrant → String+ | .noRules => "OOCert.mixed_certificate_sound_no_rules"+ | .builtin => "OOCert.mixed_certificate_sound_builtin"+ | .supplied => "OOCert.mixed_certificate_sound"++/-- What the run is conditional on, in the report itself. -/+def Warrant.means : Warrant → String+ | .noRules =>+ "every conclusion is true in every model of the asserted graph; this certificate cited \+ no rule table, so there is nothing it is conditional on"+ | .builtin =>+ "every conclusion is true in every model of the asserted graph"+ | .supplied =>+ "every conclusion is true in every model of the asserted graph THAT ALSO SATISFIES the \+ supplied rules; the rules themselves are assumed, not checked"++/-- **The verdict cannot launder an assumption into a fact.** Whenever the report+prints the absolute word for an accepted certificate, the absolute theorem+applies to that run. The relative case is the one this rules out, and+`mix_not_absolutely_entailed` shows it is a case that really arises. -/+theorem absolute_verdict_is_earned (G : List Triple) (R : List RulePattern) (steps : List MStep)+ (hv : (warrantOf R).verdict = "entailed")+ (h : checkCertM G R steps = true) : ∀ st ∈ steps, Entails G st.conclusion := by+ cases hw : warrantOf R with+ | noRules =>+ rw [warrantOf_noRules hw] at h+ exact mixed_certificate_sound_no_rules G steps h+ | builtin =>+ rw [warrantOf_builtin hw] at h+ exact mixed_certificate_sound_builtin G steps h+ | supplied =>+ rw [hw] at hv+ exact absurd hv (by decide)++/-- The table the worked certificate cites is not the built-in one, so it earns+the relative verdict. Read with `mix_not_absolutely_entailed`, that is the whole+of decision 0003 in two lines. -/+theorem mix_earns_only_the_relative_verdict :+ (warrantOf mixR).verdict = "entailed_under_supplied_rules" := by decide++/-! ## Axioms, pinned++As `Soundness.lean`, `Horn.lean` and `Witness.lean` pin theirs. A `sorry`, or a+`native_decide` anywhere under these, fails the build here. -/++/-- info: 'OOCert.mixed_certificate_sound' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms mixed_certificate_sound++/-- info: 'OOCert.mixed_certificate_sound_builtin' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms mixed_certificate_sound_builtin++/-- info: 'OOCert.absolute_verdict_is_earned' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms absolute_verdict_is_earned++/-- info: 'OOCert.mix_conclusion_entailed' depends on axioms: [propext, Quot.sound] -/+#guard_msgs in+#print axioms mix_conclusion_entailed++/-- info: 'OOCert.mix_not_absolutely_entailed' depends on axioms: [propext] -/+#guard_msgs in+#print axioms mix_not_absolutely_entailed++/-- info: 'OOCert.mix_relative_is_not_everything' depends on axioms: [propext] -/+#guard_msgs in+#print axioms mix_relative_is_not_everything++end OOCertdiff --git a/lean/OOCert/Soundness.lean b/lean/OOCert/Soundness.leanindex e361a1d8..4d150ab6 100644--- a/lean/OOCert/Soundness.lean+++ b/lean/OOCert/Soundness.lean@@ -20,13 +20,29 @@ What the theorem does not say, so that nobody reads more into it:the caller's contract: the engine's run is trusted only when the checkersays yes.+## Why the two lemmas are parametric++`checkStep_sound` and `checkAll_sound` do not mention `Entails G`. They are+stated over `EntailsIn P` for an arbitrary class of interpretations `P`, with+one extra hypothesis saying that every interpretation in that class models `G`.+`certificate_sound` recovers the original statement by taking `P` to be+"is a model of `G`", which makes that hypothesis the identity, and nothing else+about it changed: the statement and the axiom footprint are what they were.++The parameter is what lets `Mixed.lean` put a built-in step and a step citing a+user-supplied Horn rule in one certificate. Such a certificate is relative to+those rules, so its entailment relation quantifies over models of `G` that also+satisfy them, and that is a smaller class. Every per-rule case below reads its+condition off `Model I G`, which such an interpretation still is, so all twenty+cases are reused with no change to what any of them proves.+The `#guard_msgs` at the end pins the axioms the theorem depends on. If a`sorry` ever enters this file, or a `native_decide`, the build fails there.-/namespace OOCertsection-variable {G : List Triple}+variable {G : List Triple} {P : Interp → Prop}theorem allTyped_sound {x : Term} {k : Triple → Bool} :∀ {ms : List Term} {ps : List Triple}, allTyped x k ms ps = true →@@ -97,14 +113,15 @@ theorem takeChain_sound {inG : Triple → Bool} (hG : ∀ t, inG t = true → t· simp at htheorem checkStep_sound {inG derived : Triple → Bool} {st : Step}+ (hP : ∀ I, P I → Model I G)(hG : ∀ t, inG t = true → t ∈ G)- (hD : ∀ t, derived t = true → Entails G t)- (h : checkStep inG derived st = true) : Entails G st.conclusion := by- have hk : ∀ t, (inG t || derived t) = true → Entails G t := by+ (hD : ∀ t, derived t = true → EntailsIn P t)+ (h : checkStep inG derived st = true) : EntailsIn P st.conclusion := by+ have hk : ∀ t, (inG t || derived t) = true → EntailsIn P t := byintro t htsimp only [Bool.or_eq_true] at htrcases ht with h1 | h1- · exact Entails.of_mem (hG t h1)+ · exact fun I hPI => (hP I hPI).facts _ (hG t h1)· exact hD t h1obtain ⟨rule, premises, conclusion⟩ := stunfold checkStep at h@@ -114,68 +131,79 @@ theorem checkStep_sound {inG derived : Triple → Bool} {st : Step}rcases premises with _ | ⟨⟨s, p, o⟩, _ | ⟨⟨p', d, c⟩, _ | _⟩⟩ <;>simp only [decide_eq_true_eq, Bool.false_eq_true] at hobtain ⟨rfl, rfl, h1, h2, rfl⟩ := h- intro I M- exact M.conds.dom _ _ (hk _ h2 I M) _ _ (hk _ h1 I M)+ intro I hPI+ have M : Model I G := hP I hPI+ exact M.conds.dom _ _ (hk _ h2 I hPI) _ _ (hk _ h1 I hPI)case rdfs3 =>rcases premises with _ | ⟨⟨s, p, o⟩, _ | ⟨⟨p', r, c⟩, _ | _⟩⟩ <;>simp only [decide_eq_true_eq, Bool.false_eq_true] at hobtain ⟨rfl, rfl, h1, h2, rfl⟩ := h- intro I M- exact M.conds.rng _ _ (hk _ h2 I M) _ _ (hk _ h1 I M)+ intro I hPI+ have M : Model I G := hP I hPI+ exact M.conds.rng _ _ (hk _ h2 I hPI) _ _ (hk _ h1 I hPI)case rdfs5 =>rcases premises with _ | ⟨⟨a, sp1, b⟩, _ | ⟨⟨b', sp2, c⟩, _ | _⟩⟩ <;>simp only [decide_eq_true_eq, Bool.false_eq_true] at hobtain ⟨rfl, rfl, rfl, h1, h2, rfl⟩ := h- intro I M- exact M.conds.sp_trans _ _ _ (hk _ h1 I M) (hk _ h2 I M)+ intro I hPI+ have M : Model I G := hP I hPI+ exact M.conds.sp_trans _ _ _ (hk _ h1 I hPI) (hk _ h2 I hPI)case rdfs7 =>rcases premises with _ | ⟨⟨s, p, o⟩, _ | ⟨⟨p', sp, q⟩, _ | _⟩⟩ <;>simp only [decide_eq_true_eq, Bool.false_eq_true] at hobtain ⟨rfl, rfl, h1, h2, rfl⟩ := h- intro I M- exact M.conds.sp_sub _ _ (hk _ h2 I M) _ _ (hk _ h1 I M)+ intro I hPI+ have M : Model I G := hP I hPI+ exact M.conds.sp_sub _ _ (hk _ h2 I hPI) _ _ (hk _ h1 I hPI)case rdfs9 =>rcases premises with _ | ⟨⟨x, t, a⟩, _ | ⟨⟨a', sc, b⟩, _ | _⟩⟩ <;>simp only [decide_eq_true_eq, Bool.false_eq_true] at hobtain ⟨rfl, rfl, rfl, h1, h2, rfl⟩ := h- intro I M- exact M.conds.sc_sub _ _ (hk _ h2 I M) _ (hk _ h1 I M)+ intro I hPI+ have M : Model I G := hP I hPI+ exact M.conds.sc_sub _ _ (hk _ h2 I hPI) _ (hk _ h1 I hPI)case rdfs11 =>rcases premises with _ | ⟨⟨a, sc1, b⟩, _ | ⟨⟨b', sc2, c⟩, _ | _⟩⟩ <;>simp only [decide_eq_true_eq, Bool.false_eq_true] at hobtain ⟨rfl, rfl, rfl, h1, h2, rfl⟩ := h- intro I M- exact M.conds.sc_trans _ _ _ (hk _ h1 I M) (hk _ h2 I M)+ intro I hPI+ have M : Model I G := hP I hPI+ exact M.conds.sc_trans _ _ _ (hk _ h1 I hPI) (hk _ h2 I hPI)case prpTrp =>rcases premises with _ | ⟨⟨p, t, tp⟩, _ | ⟨⟨x, p1, y⟩, _ | ⟨⟨y', p2, z⟩, _ | _⟩⟩⟩ <;>simp only [decide_eq_true_eq, Bool.false_eq_true] at hobtain ⟨rfl, rfl, rfl, rfl, rfl, h1, h2, h3, rfl⟩ := h- intro I M- exact M.conds.trp _ (hk _ h1 I M) _ _ _ (hk _ h2 I M) (hk _ h3 I M)+ intro I hPI+ have M : Model I G := hP I hPI+ exact M.conds.trp _ (hk _ h1 I hPI) _ _ _ (hk _ h2 I hPI) (hk _ h3 I hPI)case prpSymp =>rcases premises with _ | ⟨⟨p, t, sy⟩, _ | ⟨⟨x, p1, y⟩, _ | _⟩⟩ <;>simp only [decide_eq_true_eq, Bool.false_eq_true] at hobtain ⟨rfl, rfl, rfl, h1, h2, rfl⟩ := h- intro I M- exact M.conds.symp _ (hk _ h1 I M) _ _ (hk _ h2 I M)+ intro I hPI+ have M : Model I G := hP I hPI+ exact M.conds.symp _ (hk _ h1 I hPI) _ _ (hk _ h2 I hPI)case prpInv1 =>rcases premises with _ | ⟨⟨p, io, q⟩, _ | ⟨⟨x, p1, y⟩, _ | _⟩⟩ <;>simp only [decide_eq_true_eq, Bool.false_eq_true] at hobtain ⟨rfl, rfl, h1, h2, rfl⟩ := h- intro I M- exact (M.conds.inv _ _ (hk _ h1 I M) _ _).mp (hk _ h2 I M)+ intro I hPI+ have M : Model I G := hP I hPI+ exact (M.conds.inv _ _ (hk _ h1 I hPI) _ _).mp (hk _ h2 I hPI)case prpInv2 =>rcases premises with _ | ⟨⟨p, io, q⟩, _ | ⟨⟨x, q1, y⟩, _ | _⟩⟩ <;>simp only [decide_eq_true_eq, Bool.false_eq_true] at hobtain ⟨rfl, rfl, h1, h2, rfl⟩ := h- intro I M- exact (M.conds.inv _ _ (hk _ h1 I M) _ _).mpr (hk _ h2 I M)+ intro I hPI+ have M : Model I G := hP I hPI+ exact (M.conds.inv _ _ (hk _ h1 I hPI) _ _).mpr (hk _ h2 I hPI)case eqSym =>rcases premises with _ | ⟨⟨a, sa, b⟩, _ | _⟩ <;>simp only [decide_eq_true_eq, Bool.false_eq_true] at hobtain ⟨rfl, h1, rfl⟩ := h- intro I M- have s : I.iext (I.ι V.sameAs) (I.ι a) (I.ι b) := hk _ h1 I M+ intro I hPI+ have M : Model I G := hP I hPI+ have s : I.iext (I.ι V.sameAs) (I.ι a) (I.ι b) := hk _ h1 I hPIhave e := M.conds.same _ _ sshow I.iext (I.ι V.sameAs) (I.ι b) (I.ι a)rw [← e]@@ -185,46 +213,52 @@ theorem checkStep_sound {inG derived : Triple → Bool} {st : Step}rcases premises with _ | ⟨⟨a, e, b⟩, _ | _⟩ <;>simp only [decide_eq_true_eq, Bool.false_eq_true] at hobtain ⟨rfl, h1, hc⟩ := h- intro I M+ intro I hPI+ have M : Model I G := hP I hPIrcases hc with rfl | rfl- · exact (M.conds.eqc _ _ (hk _ h1 I M)).1- · exact (M.conds.eqc _ _ (hk _ h1 I M)).2+ · exact (M.conds.eqc _ _ (hk _ h1 I hPI)).1+ · exact (M.conds.eqc _ _ (hk _ h1 I hPI)).2case scmEqp1 =>rcases premises with _ | ⟨⟨a, e, b⟩, _ | _⟩ <;>simp only [decide_eq_true_eq, Bool.false_eq_true] at hobtain ⟨rfl, h1, hc⟩ := h- intro I M+ intro I hPI+ have M : Model I G := hP I hPIrcases hc with rfl | rfl- · exact (M.conds.eqp _ _ (hk _ h1 I M)).1- · exact (M.conds.eqp _ _ (hk _ h1 I M)).2+ · exact (M.conds.eqp _ _ (hk _ h1 I hPI)).1+ · exact (M.conds.eqp _ _ (hk _ h1 I hPI)).2case clsSvf1 =>rcases premises with_ | ⟨⟨r, op, p⟩, _ | ⟨⟨r', sv, c⟩, _ | ⟨⟨x, p1, y⟩, _ | ⟨⟨y', t, c'⟩, _ | _⟩⟩⟩⟩ <;>simp only [decide_eq_true_eq, Bool.false_eq_true] at hobtain ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, h1, h2, h3, h4, rfl⟩ := h- intro I M- exact M.conds.svf _ _ _ (hk _ h1 I M) (hk _ h2 I M) _ _ (hk _ h3 I M) (hk _ h4 I M)+ intro I hPI+ have M : Model I G := hP I hPI+ exact M.conds.svf _ _ _ (hk _ h1 I hPI) (hk _ h2 I hPI) _ _ (hk _ h3 I hPI) (hk _ h4 I hPI)case clsAvf =>rcases premises with_ | ⟨⟨r, op, p⟩, _ | ⟨⟨r', av, c⟩, _ | ⟨⟨x, t, r''⟩, _ | ⟨⟨x', p1, y⟩, _ | _⟩⟩⟩⟩ <;>simp only [decide_eq_true_eq, Bool.false_eq_true] at hobtain ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, h1, h2, h3, h4, rfl⟩ := h- intro I M- exact M.conds.avf _ _ _ (hk _ h1 I M) (hk _ h2 I M) _ _ (hk _ h3 I M) (hk _ h4 I M)+ intro I hPI+ have M : Model I G := hP I hPI+ exact M.conds.avf _ _ _ (hk _ h1 I hPI) (hk _ h2 I hPI) _ _ (hk _ h3 I hPI) (hk _ h4 I hPI)case clsHv1 =>rcases premises with_ | ⟨⟨r, op, p⟩, _ | ⟨⟨r', hv, v⟩, _ | ⟨⟨x, t, r''⟩, _ | _⟩⟩⟩ <;>simp only [decide_eq_true_eq, Bool.false_eq_true] at hobtain ⟨rfl, rfl, rfl, rfl, rfl, h1, h2, h3, rfl⟩ := h- intro I M- exact (M.conds.hv _ _ _ (hk _ h1 I M) (hk _ h2 I M) _).mp (hk _ h3 I M)+ intro I hPI+ have M : Model I G := hP I hPI+ exact (M.conds.hv _ _ _ (hk _ h1 I hPI) (hk _ h2 I hPI) _).mp (hk _ h3 I hPI)case clsHv2 =>rcases premises with_ | ⟨⟨r, op, p⟩, _ | ⟨⟨r', hv, v⟩, _ | ⟨⟨x, p1, v'⟩, _ | _⟩⟩⟩ <;>simp only [decide_eq_true_eq, Bool.false_eq_true] at hobtain ⟨rfl, rfl, rfl, rfl, rfl, h1, h2, h3, rfl⟩ := h- intro I M- exact (M.conds.hv _ _ _ (hk _ h1 I M) (hk _ h2 I M) _).mpr (hk _ h3 I M)+ intro I hPI+ have M : Model I G := hP I hPI+ exact (M.conds.hv _ _ _ (hk _ h1 I hPI) (hk _ h2 I hPI) _).mpr (hk _ h3 I hPI)case clsInt1 =>rcases premises with _ | ⟨⟨c, io, l⟩, ps⟩· simp at h@@ -242,9 +276,10 @@ theorem checkStep_sound {inG derived : Triple → Bool} {st : Step}obtain ⟨hall, hp, ho⟩ := hmhave hC : Chain G l ms :=takeChain_sound hG ps.length ps (Nat.le_refl _) l ms q hchain- intro I M+ intro I hPI+ have M : Model I G := hP I hPIhave hx : ∀ m ∈ ms, I.cext (I.ι m) (I.ι conclusion.s) :=- fun m hm => hk _ (allTyped_sound hall m hm) I M+ fun m hm => hk _ (allTyped_sound hall m hm) I hPIhave hc := M.int c l ms (hG _ hin) hC (I.ι conclusion.s) hxshow I.iext (I.ι conclusion.p) (I.ι conclusion.s) (I.ι conclusion.o)rw [hp, ho]@@ -267,14 +302,16 @@ theorem checkStep_sound {inG derived : Triple → Bool} {st : Step}obtain ⟨rfl, hmem, hkx, rfl⟩ := hmhave hC : Chain G l ms :=takeChain_sound hG ps.length ps (Nat.le_refl _) l ms _ hchain- intro I M- exact M.uni c l ms (hG _ hin) hC (I.ι x) m hmem (hk _ hkx I M)+ intro I hPI+ have M : Model I G := hP I hPI+ exact M.uni c l ms (hG _ hin) hC (I.ι x) m hmem (hk _ hkx I hPI)-theorem checkAll_sound {inG : Triple → Bool} (hG : ∀ t, inG t = true → t ∈ G) :+theorem checkAll_sound {inG : Triple → Bool} (hP : ∀ I, P I → Model I G)+ (hG : ∀ t, inG t = true → t ∈ G) :∀ (steps : List Step) (derived : Std.HashSet Triple),- (∀ t, derived.contains t = true → Entails G t) →+ (∀ t, derived.contains t = true → EntailsIn P t) →checkAll inG steps derived = true →- ∀ st ∈ steps, Entails G st.conclusion := by+ ∀ st ∈ steps, EntailsIn P st.conclusion := byintro stepsinduction steps with| nil =>@@ -284,8 +321,8 @@ theorem checkAll_sound {inG : Triple → Bool} (hG : ∀ t, inG t = true → tintro derived hD h st' hst'simp only [checkAll, Bool.and_eq_true] at hobtain ⟨h1, h2⟩ := h- have hst : Entails G st.conclusion := checkStep_sound hG hD h1- have hD' : ∀ t, (derived.insert st.conclusion).contains t = true → Entails G t := by+ have hst : EntailsIn P st.conclusion := checkStep_sound hP hG hD h1+ have hD' : ∀ t, (derived.insert st.conclusion).contains t = true → EntailsIn P t := byintro t htrw [Std.HashSet.contains_insert] at htsimp only [Bool.or_eq_true, beq_iff_eq] at ht@@ -302,8 +339,9 @@ endtheorem certificate_sound (G : List Triple) (steps : List Step)(h : checkCert G steps = true) : ∀ st ∈ steps, Entails G st.conclusion := byunfold checkCert at h- refine checkAll_sound (G := G) (inG := fun t => (Std.HashSet.ofList G).contains t)- ?_ steps ∅ ?_ h+ refine checkAll_sound (G := G) (P := fun I => Model I G)+ (inG := fun t => (Std.HashSet.ofList G).contains t)+ (fun _ hM => hM) ?_ steps ∅ ?_ h· intro t htrw [Std.HashSet.contains_ofList] at htsimpa using htdiff --git a/lean/Shacl/Agreement.lean b/lean/Shacl/Agreement.leannew file mode 100644index 00000000..c9e2908d--- /dev/null+++ b/lean/Shacl/Agreement.lean@@ -0,0 +1,392 @@+import Shacl.Eval++/-!+# The evaluator agrees with the specification++Two theorems, both from one induction over the shape.++`eval_conforms_iff` the evaluator reports no results exactly when the focus node+ conforms. Soundness AND completeness of the verdict, for every+ component covered.++`eval_results_licensed` every result the evaluator reports names a constraint and+ a node, and that node really does fail that constraint+ according to the specification. Soundness of the report and not+ only of the boolean.++Both are conditional on `eval` having returned `.ok`. When it refuses there is+nothing to be sound about, and the refusal is reported rather than rounded into a+verdict.++## What is NOT claimed++* Nothing here says the specification in `Spec.lean` IS the W3C Recommendation.+ That is a reading of prose and no proof can establish it. The measurement in+ `tests/shacl_core_verified_test.rs` is what tests that reading: it runs this+ specification against the Working Group's own suite and counts the+ disagreements.+* Nothing here says the compiler from RDF to `Shape` is correct. It is outside the+ theorem on purpose, it fails closed, and its refusals show up as undetermined.+* `sh:resultPath`, `sh:value` and `sh:resultSeverity` on a result are not covered by+ the licensing theorem. It pins `blamed` and `blamedNode`, which are what make a+ result true or false; the other fields are presentation.+* **Completeness is claimed for the VERDICT, not for the result list.** `sh:and`,+ `sh:or`, `sh:not` and `sh:node` each report ONE result for a whole failing+ subtree, which is what the Recommendation asks for, so "one result per failing+ atomic constraint" is neither claimed nor true. What is claimed is that the report+ is empty exactly when the node conforms, which is the property a consumer of+ `sh:conforms` relies on.+-/+namespace Shacl++/-! ## Plumbing -/++theorem bind_ok_eq {α β} {x : Except Refusal α} {a : α} (h : x = .ok a)+ (g : α → Except Refusal β) : (x >>= g) = g a := by rw [h]; rfl++theorem bind_error_eq {α β} {x : Except Refusal α} {e : Refusal} (h : x = .error e)+ (g : α → Except Refusal β) : (x >>= g) = .error e := by rw [h]; rfl++/-- Everything `check` decides, in one place: the result list is empty exactly when+the decision was `true`, and when it is not empty it holds exactly the one result it+was given. -/+theorem check_spec {b : Bool} {r : Result} {rs : List Result} (h : check b r = .ok rs) :+ (rs = [] ↔ b = true) ∧ (∀ x ∈ rs, x = r) := by+ cases b with+ | true =>+ rw [check, if_pos rfl] at h+ injection h with h+ subst h+ exact ⟨Iff.intro (fun _ => rfl) (fun _ => rfl), by simp⟩+ | false =>+ rw [check] at h+ simp only [Bool.false_eq_true, if_false] at h+ injection h with h+ subst h+ refine ⟨Iff.intro (fun hn => absurd hn (by simp)) (fun hn => absurd hn (by simp)), ?_⟩+ intro x hx+ simpa using hx++/-- The shape every leaf constraint takes: a decision whose truth is exactly the+specification's condition, and, when it is false, one result blaming that very+constraint at that very node. Stating it once keeps eleven cases of the induction+below to three lines each, and keeps the licensing argument from being retyped+eleven times with a chance to drift. -/+theorem leafCase {G : Graph} {b : Bool} {r : Result} {rs : List Result} {s : Shape} {f : Term}+ (h : check b r = .ok rs) (hb : b = true ↔ Conf G s f)+ (hbl : r.blamed = s) (hbn : r.blamedNode = f) :+ (rs = [] ↔ Conf G s f) ∧ (∀ x ∈ rs, ¬ Conf G x.blamed x.blamedNode) := by+ obtain ⟨h1, h2⟩ := check_spec h+ have hiff : rs = [] ↔ Conf G s f := Iff.trans h1 hb+ refine ⟨hiff, ?_⟩+ intro x hx+ rw [h2 x hx, hbl, hbn]+ intro hc+ have hnil : rs = [] := hiff.mpr hc+ subst hnil+ exact absurd hx (by simp)++theorem liftValue_blamed (f : Term) (pa : Path) (v : Term) (r : Result) :+ (liftValue f pa v r).blamed = r.blamed := by+ rw [liftValue]; split <;> rfl++theorem liftValue_blamedNode (f : Term) (pa : Path) (v : Term) (r : Result) :+ (liftValue f pa v r).blamedNode = r.blamedNode := by+ rw [liftValue]; split <;> rfl++/-- `collect` returns one entry per input node, in order, each holding exactly what+the evaluator returned at that node. -/+theorem collect_ok {k : Term → Except Refusal (List Result)} :+ ∀ {l : List Term} {out : List (Term × List Result)}, collect k l = .ok out →+ out.map Prod.fst = l ∧ ∀ q ∈ out, k q.1 = .ok q.2+ | [], out, h => by+ rw [collect] at h; injection h with h; subst h; exact ⟨rfl, by simp⟩+ | v :: vs, out, h => by+ rw [collect] at h+ cases hk : k v with+ | error e => rw [bind_error_eq hk] at h; exact absurd h (by simp)+ | ok r =>+ rw [bind_ok_eq hk] at h+ cases hc : collect k vs with+ | error e => rw [bind_error_eq hc] at h; exact absurd h (by simp)+ | ok rest =>+ rw [bind_ok_eq hc] at h+ injection h with h+ subst h+ obtain ⟨h1, h2⟩ := collect_ok hc+ refine ⟨by simpa using h1, ?_⟩+ intro q hq+ rcases List.mem_cons.mp hq with rfl | hq+ · exact hk+ · exact h2 q hq++/-! ## The decision procedures, each matched to the proposition it decides -/++theorem nodup_valueNodes {G : Graph} {pa : Path} {f : Term} :+ (valueNodes G pa f).Nodup := by+ rw [valueNodes]; exact nodup_dedup _++/-- Counting the deduplicated value nodes decides "there are at least `n` distinct+value nodes". The backward direction is the pigeonhole: any duplicate-free list of+value nodes is a subset of the enumeration, so it cannot be longer. -/+theorem minCount_iff {G : Graph} {pa : Path} {f : Term} {n : Nat} :+ n ≤ (valueNodes G pa f).length ↔+ ∃ l : List Term, l.Nodup ∧ (∀ v ∈ l, IsValue G pa f v) ∧ n ≤ l.length := by+ constructor+ · intro h+ exact ⟨valueNodes G pa f, nodup_valueNodes, fun _ hv => mem_valueNodes.mp hv, h⟩+ · rintro ⟨l, hnd, hmem, hn⟩+ exact Nat.le_trans hn+ (List.Nodup.length_le_of_subset hnd (fun _ hv => mem_valueNodes.mpr (hmem _ hv)))++theorem maxCount_iff {G : Graph} {pa : Path} {f : Term} {n : Nat} :+ (valueNodes G pa f).length ≤ n ↔+ ∀ l : List Term, l.Nodup → (∀ v ∈ l, IsValue G pa f v) → l.length ≤ n := by+ constructor+ · intro h l hnd hmem+ exact Nat.le_trans+ (List.Nodup.length_le_of_subset hnd (fun _ hv => mem_valueNodes.mpr (hmem _ hv))) h+ · intro h+ exact h _ nodup_valueNodes (fun _ hv => mem_valueNodes.mp hv)++/-- The `sh:class` decision is exactly SHACL instancehood, given a closed+superclass set. Soundness comes from the iteration, completeness from the closure+check. -/+theorem klass_iff {G : Graph} {c f : Term} {S : List Term} (hcl : subClosure G c = some S) :+ (typesOf G f).any (fun t => S.contains t) = true ↔ IsInstance G c f := by+ rw [List.any_eq_true]+ constructor+ · rintro ⟨t, ht, hS⟩+ exact ⟨t, mem_typesOf.mp ht, subClosure_sound hcl t (List.contains_iff_mem.mp hS)⟩+ · rintro ⟨t, hG, hsc⟩+ exact ⟨t, mem_typesOf.mpr hG, List.contains_iff_mem.mpr (subClosure_complete hcl hsc)⟩++/-- `sh:datatype`, including the refusal. Stated for an arbitrary graph because the+constraint does not read the graph at all: it is a question about the term. -/+theorem evalDatatype_spec {G : Graph} {d src f : Term} {rs : List Result}+ (h : evalDatatype d src f = .ok rs) :+ (rs = [] ↔ Conf G (.datatype d) f) ∧ (∀ x ∈ rs, ¬ Conf G x.blamed x.blamedNode) := by+ rw [evalDatatype] at h+ cases hl : asLiteral f with+ | none =>+ simp only [hl] at h+ refine leafCase h ?_ rfl rfl+ constructor+ · intro hb; exact absurd hb (by simp)+ · rintro ⟨l, hl', -, -⟩+ rw [hl] at hl'+ exact absurd hl' (by simp)+ | some l =>+ simp only [hl] at h+ by_cases hd : l.dt = d+ · rw [if_pos hd] at h+ cases hx : lexOK l with+ | none => simp only [hx] at h; exact absurd h (by simp)+ | some b =>+ simp only [hx] at h+ refine leafCase h ?_ rfl rfl+ constructor+ · intro hb+ exact ⟨l, hl, hd, by rw [hx, hb]⟩+ · rintro ⟨l', hl', -, hok⟩+ rw [hl] at hl'+ injection hl' with e+ subst e+ exact Option.some.inj (hx.symm.trans hok)+ · rw [if_neg hd] at h+ refine leafCase h ?_ rfl rfl+ constructor+ · intro hb; exact absurd hb (by simp)+ · rintro ⟨l', hl', hdt, -⟩+ rw [hl] at hl'+ injection hl' with e+ subst e+ exact absurd hdt hd++/-! ## The two theorems -/++/-- Both halves at once, because the `forAll` case needs the verdict half of the+induction hypothesis and the licensing case needs the other. -/+theorem eval_agrees (G : Graph) (s : Shape) :+ ∀ (src f : Term) (rs : List Result), eval G s src f = .ok rs →+ (rs = [] ↔ Conf G s f) ∧ (∀ r ∈ rs, ¬ Conf G r.blamed r.blamedNode) := by+ induction s with+ | top =>+ intro src f rs h+ rw [eval] at h+ injection h with h+ subst h+ exact ⟨Iff.intro (fun _ => trivial) (fun _ => rfl), by simp⟩+ | bot =>+ intro src f rs h+ rw [eval] at h+ exact leafCase h (Iff.intro (fun hb => absurd hb (by simp)) (fun hc => hc.elim)) rfl rfl+ | klass c =>+ intro src f rs h+ rw [eval, evalKlass] at h+ cases hcl : subClosure G c with+ | none => simp only [hcl] at h; exact absurd h (by simp)+ | some S =>+ simp only [hcl] at h+ exact leafCase h (klass_iff hcl) rfl rfl+ | datatype d =>+ intro src f rs h+ rw [eval] at h+ exact evalDatatype_spec h+ | nodeKind k =>+ intro src f rs h+ rw [eval] at h+ exact leafCase h nodeKindOK_iff rfl rfl+ | hasValue v =>+ intro src f rs h+ rw [eval] at h+ exact leafCase h beq_iff_eq rfl rfl+ | inSet vs =>+ intro src f rs h+ rw [eval] at h+ exact leafCase h List.contains_iff_mem rfl rfl+ | minCount pa n =>+ intro src f rs h+ rw [eval] at h+ exact leafCase h (Iff.trans decide_eq_true_iff minCount_iff) rfl rfl+ | maxCount pa n =>+ intro src f rs h+ rw [eval] at h+ exact leafCase h (Iff.trans decide_eq_true_iff maxCount_iff) rfl rfl+ | hasValueOn pa v =>+ intro src f rs h+ rw [eval] at h+ exact leafCase h (Iff.trans List.contains_iff_mem mem_valueNodes) rfl rfl+ | named src' a ih =>+ intro src f rs h+ rw [eval] at h+ exact ih src' f rs h+ | both a b iha ihb =>+ intro src f rs h+ rw [eval] at h+ cases ha : eval G a src f with+ | error e => rw [bind_error_eq ha] at h; exact absurd h (by simp)+ | ok ra =>+ rw [bind_ok_eq ha] at h+ cases hb : eval G b src f with+ | error e => rw [bind_error_eq hb] at h; exact absurd h (by simp)+ | ok rb =>+ rw [bind_ok_eq hb] at h+ injection h with h+ subst h+ obtain ⟨ha1, ha2⟩ := iha src f ra ha+ obtain ⟨hb1, hb2⟩ := ihb src f rb hb+ refine ⟨?_, ?_⟩+ · rw [List.append_eq_nil_iff]+ exact and_congr ha1 hb1+ · intro r hr+ rcases List.mem_append.mp hr with hr | hr+ · exact ha2 r hr+ · exact hb2 r hr+ | andC a b iha ihb =>+ intro src f rs h+ rw [eval] at h+ cases ha : eval G a src f with+ | error e => rw [bind_error_eq ha] at h; exact absurd h (by simp)+ | ok ra =>+ rw [bind_ok_eq ha] at h+ cases hb : eval G b src f with+ | error e => rw [bind_error_eq hb] at h; exact absurd h (by simp)+ | ok rb =>+ rw [bind_ok_eq hb] at h+ obtain ⟨ha1, -⟩ := iha src f ra ha+ obtain ⟨hb1, -⟩ := ihb src f rb hb+ refine leafCase h ?_ rfl rfl+ rw [Bool.and_eq_true, List.isEmpty_iff, List.isEmpty_iff]+ exact and_congr ha1 hb1+ | orC a b iha ihb =>+ intro src f rs h+ rw [eval] at h+ cases ha : eval G a src f with+ | error e => rw [bind_error_eq ha] at h; exact absurd h (by simp)+ | ok ra =>+ rw [bind_ok_eq ha] at h+ cases hb : eval G b src f with+ | error e => rw [bind_error_eq hb] at h; exact absurd h (by simp)+ | ok rb =>+ rw [bind_ok_eq hb] at h+ obtain ⟨ha1, -⟩ := iha src f ra ha+ obtain ⟨hb1, -⟩ := ihb src f rb hb+ refine leafCase h ?_ rfl rfl+ rw [Bool.or_eq_true, List.isEmpty_iff, List.isEmpty_iff]+ exact or_congr ha1 hb1+ | notC a iha =>+ intro src f rs h+ rw [eval] at h+ cases ha : eval G a src f with+ | error e => rw [bind_error_eq ha] at h; exact absurd h (by simp)+ | ok ra =>+ rw [bind_ok_eq ha] at h+ obtain ⟨ha1, -⟩ := iha src f ra ha+ refine leafCase h ?_ rfl rfl+ rw [Bool.not_eq_true', List.isEmpty_eq_false_iff]+ exact not_congr ha1+ | nodeC a iha =>+ intro src f rs h+ rw [eval] at h+ cases ha : eval G a src f with+ | error e => rw [bind_error_eq ha] at h; exact absurd h (by simp)+ | ok ra =>+ rw [bind_ok_eq ha] at h+ obtain ⟨ha1, -⟩ := iha src f ra ha+ refine leafCase h ?_ rfl rfl+ rw [List.isEmpty_iff]+ exact ha1+ | forAll pa a iha =>+ intro src f rs h+ rw [eval] at h+ cases hc : collect (fun v => eval G a src v) (valueNodes G pa f) with+ | error e => rw [bind_error_eq hc] at h; exact absurd h (by simp)+ | ok out =>+ rw [bind_ok_eq hc] at h+ injection h with h+ subst h+ obtain ⟨hmap, hall⟩ := collect_ok hc+ refine ⟨?_, ?_⟩+ · rw [List.flatMap_eq_nil_iff]+ constructor+ · intro hnil v hv+ have hvn : v ∈ out.map Prod.fst := by+ rw [hmap]; exact mem_valueNodes.mpr hv+ obtain ⟨q, hq, hq1⟩ := List.mem_map.mp hvn+ obtain ⟨hq2, -⟩ := iha src q.1 q.2 (hall q hq)+ rw [← hq1]+ exact hq2.mp (List.map_eq_nil_iff.mp (hnil q hq))+ · intro hconf q hq+ rw [List.map_eq_nil_iff]+ obtain ⟨hq2, -⟩ := iha src q.1 q.2 (hall q hq)+ refine hq2.mpr (hconf q.1 ?_)+ apply mem_valueNodes.mp+ rw [← hmap]+ exact List.mem_map.mpr ⟨q, hq, rfl⟩+ · intro r hr+ obtain ⟨q, hq, hrq⟩ := List.mem_flatMap.mp hr+ obtain ⟨r₀, hr₀, hlift⟩ := List.mem_map.mp hrq+ obtain ⟨-, hq3⟩ := iha src q.1 q.2 (hall q hq)+ rw [← hlift, liftValue_blamed, liftValue_blamedNode]+ exact hq3 r₀ hr₀++/-- **Soundness and completeness of the verdict.** The evaluator reports no results+exactly when the specification says the focus node conforms. -/+theorem eval_conforms_iff {G : Graph} {s : Shape} {src f : Term} {rs : List Result}+ (h : eval G s src f = .ok rs) : rs = [] ↔ Conf G s f :=+ (eval_agrees G s src f rs h).1++/-- **Soundness of the report.** Every result the evaluator produces blames a node+that really does fail the constraint it is blamed for. -/+theorem eval_results_licensed {G : Graph} {s : Shape} {src f : Term} {rs : List Result}+ (h : eval G s src f = .ok rs) : ∀ r ∈ rs, ¬ Conf G r.blamed r.blamedNode :=+ (eval_agrees G s src f rs h).2++/-- The `sh:sourceShape` label cannot change a verdict. Cheap to state, and it is+the one structural property a reader would otherwise have to take on trust when+reading `eval`, which threads that label through every case. -/+theorem conf_named (G : Graph) (src : Term) (a : Shape) (f : Term) :+ Conf G (.named src a) f ↔ Conf G a f := Iff.rfl++end Shacldiff --git a/lean/Shacl/All.lean b/lean/Shacl/All.leannew file mode 100644index 00000000..662fba55--- /dev/null+++ b/lean/Shacl/All.lean@@ -0,0 +1,9 @@+import Shacl.Term+import Shacl.Shape+import Shacl.Spec+import Shacl.Eval+import Shacl.Agreement+import Shacl.Report+import Shacl.Witness+import Shacl.Parse+import Shacl.Compilediff --git a/lean/Shacl/Compile.lean b/lean/Shacl/Compile.leannew file mode 100644index 00000000..12009b8d--- /dev/null+++ b/lean/Shacl/Compile.lean@@ -0,0 +1,343 @@+import Shacl.Report++/-!+# Compiling a shapes graph into shapes++This module turns RDF into the `Shape` datatype the proved evaluator consumes. It+is NOT part of any theorem, and that is the design, not an omission: a compiler+from RDF into an abstract syntax is a parser, and the project's existing position on+parsers is that a parse error rejects rather than accepts.++## It fails closed, and that is the only reason it can be trusted at all++The dangerous failure for a validator is to ignore a constraint it does not+understand and report `conforms`. So:++* **Every `sh:` predicate on every shape the compiler walks must be known.** One it+ has not implemented is an error naming the predicate, not a silently dropped+ constraint. `ignoredParams` lists the handful that carry no conformance meaning,+ each with a reason.+* **A shapes graph that defines a constraint COMPONENT is refused outright.** A+ custom component introduces parameters in the user's own namespace, so the+ `sh:` check above cannot see them, and a shape using one would look empty. The+ guard is a scan for `sh:parameter`, `sh:validator`, `sh:nodeValidator`,+ `sh:propertyValidator`, `sh:sparql` and `rdf:type sh:ConstraintComponent`+ anywhere in the shapes graph.+* **Recursion is refused.** SHACL says it "does not define the semantics of+ recursive shape definitions". `Shape` is an inductive type, so a cyclic shapes+ graph exhausts the nesting budget and is reported as recursive.+* **A malformed shape is refused**, not guessed at: two `sh:path` values, a+ `sh:minCount` on a shape with no path, an RDF list that does not end at+ `rdf:nil`.++Every refusal comes out as `undetermined` in the report and in the conformance+measurement, which counts it separately from a pass and from a failure.++## What is deliberately ignored, and why it is safe here++`sh:message`, `sh:name`, `sh:description`, `sh:order`, `sh:group` and+`sh:defaultValue` carry no conformance meaning at all.++`sh:severity` does carry meaning, for `sh:resultSeverity` in the report. It is+ignored, so every result this validator produces is a violation with no severity+recorded. That is a real gap and it is named here rather than discovered: a report+consumer that acts on severity must not use this validator.+-/+namespace Shacl.Compile++open Shacl++/-! ## Vocabulary -/++namespace SH+def ns : String := "http://www.w3.org/ns/shacl#"+def iri (l : String) : Term := "<" ++ ns ++ l ++ ">"++def NodeShape : Term := iri "NodeShape"+def PropertyShape : Term := iri "PropertyShape"+def ConstraintComponent : Term := iri "ConstraintComponent"++def targetNode : Term := iri "targetNode"+def targetClass : Term := iri "targetClass"+def targetSubjectsOf : Term := iri "targetSubjectsOf"+def targetObjectsOf : Term := iri "targetObjectsOf"++def path : Term := iri "path"+def inversePath : Term := iri "inversePath"+def alternativePath : Term := iri "alternativePath"+def zeroOrMorePath : Term := iri "zeroOrMorePath"+def oneOrMorePath : Term := iri "oneOrMorePath"+def zeroOrOnePath : Term := iri "zeroOrOnePath"++def klass : Term := iri "class"+def datatype : Term := iri "datatype"+def nodeKind : Term := iri "nodeKind"+def minCount : Term := iri "minCount"+def maxCount : Term := iri "maxCount"+def hasValue : Term := iri "hasValue"+def inList : Term := iri "in"+def notC : Term := iri "not"+def andC : Term := iri "and"+def orC : Term := iri "or"+def nodeC : Term := iri "node"+def property : Term := iri "property"+def deactivated : Term := iri "deactivated"++def message : Term := iri "message"+def name : Term := iri "name"+def description : Term := iri "description"+def order : Term := iri "order"+def group : Term := iri "group"+def defaultValue : Term := iri "defaultValue"+def severity : Term := iri "severity"++def parameter : Term := iri "parameter"+def validator : Term := iri "validator"+def nodeValidator : Term := iri "nodeValidator"+def propertyValidator : Term := iri "propertyValidator"+def sparql : Term := iri "sparql"++def kIRI : Term := iri "IRI"+def kBlankNode : Term := iri "BlankNode"+def kLiteral : Term := iri "Literal"+def kBlankNodeOrIRI : Term := iri "BlankNodeOrIRI"+def kBlankNodeOrLiteral : Term := iri "BlankNodeOrLiteral"+def kIRIOrLiteral : Term := iri "IRIOrLiteral"++end SH++/-- Parameters with a conformance meaning that this development implements. -/+def knownParams : List Term :=+ [ SH.path, SH.klass, SH.datatype, SH.nodeKind, SH.minCount, SH.maxCount,+ SH.hasValue, SH.inList, SH.notC, SH.andC, SH.orC, SH.nodeC, SH.property,+ SH.deactivated, SH.targetNode, SH.targetClass, SH.targetSubjectsOf,+ SH.targetObjectsOf ]++/-- Parameters with no effect on the verdict or on the result fields this+validator reports. `sh:severity` is the one that is a real gap; see the module+header. -/+def ignoredParams : List Term :=+ [ SH.message, SH.name, SH.description, SH.order, SH.group, SH.defaultValue,+ SH.severity ]++def isShaclPred (p : Term) : Bool := p.startsWith ("<" ++ SH.ns)++/-! ## Reading the graph -/++def objectsOf (G : Graph) (s p : Term) : List Term :=+ (G.filter (fun t => t.s == s && t.p == p)).map Triple.o++def predsOf (G : Graph) (s : Term) : List Term :=+ dedup ((G.filter (fun t => t.s == s)).map Triple.p)++def hasTriple (G : Graph) (s p o : Term) : Bool :=+ G.any (fun t => t.s == s && t.p == p && t.o == o)++/-- An RDF list, or an error naming where it went wrong. -/+def readList (G : Graph) : Nat → Term → Except String (List Term)+ | 0, node => .error s!"RDF list at {node} is longer than the shapes graph, so it is cyclic"+ | fuel + 1, node =>+ if node == V.nil then .ok []+ else+ match objectsOf G node V.first, objectsOf G node V.rest with+ | [f], [r] => do+ let tl ← readList G fuel r+ .ok (f :: tl)+ | _, _ => .error s!"malformed RDF list at {node}: expected one rdf:first and one rdf:rest"++/-- The natural number a literal denotes, for `sh:minCount` and `sh:maxCount`. -/+def readNat (o : Term) : Except String Nat :=+ match asLiteral o with+ | some l =>+ if isDigits l.lex.toList then .ok (natOfDigits l.lex.toList)+ else .error s!"{o} is not a non-negative integer literal"+ | none => .error s!"{o} is not a literal, so it cannot be a count"++def readNodeKind (o : Term) : Except String NodeKind :=+ if o == SH.kIRI then .ok .iri+ else if o == SH.kBlankNode then .ok .blankNode+ else if o == SH.kLiteral then .ok .literal+ else if o == SH.kBlankNodeOrIRI then .ok .blankNodeOrIRI+ else if o == SH.kBlankNodeOrLiteral then .ok .blankNodeOrLiteral+ else if o == SH.kIRIOrLiteral then .ok .iriOrLiteral+ else .error s!"{o} is not one of the six sh:nodeKind values"++/-- The path forms present on a blank path node, named. -/+def pathForms (G : Graph) (node : Term) : List String :=+ (if (objectsOf G node SH.inversePath).isEmpty then [] else ["sh:inversePath"]) +++ (if (objectsOf G node SH.alternativePath).isEmpty then [] else ["sh:alternativePath"]) +++ (if (objectsOf G node SH.zeroOrMorePath).isEmpty then [] else ["sh:zeroOrMorePath"]) +++ (if (objectsOf G node SH.oneOrMorePath).isEmpty then [] else ["sh:oneOrMorePath"]) +++ (if (objectsOf G node SH.zeroOrOnePath).isEmpty then [] else ["sh:zeroOrOnePath"]) +++ (if (objectsOf G node V.first).isEmpty then [] else ["a sequence path"])++/-- A path, or an error naming the path form that was found. Only a predicate path+and `sh:inversePath` of a predicate are covered.++A node carrying TWO path forms is refused rather than read as either. SHACL+requires a well-formed path node to have exactly one form, and the suite's+`core/path/path-strange-001` is a node that is simultaneously a sequence path and+an inverse path. Reading it as the first form the code happens to check is how this+compiler produced its one wrong answer against the suite: it chose the inverse+reading and blamed the wrong node. Refusing an ill-formed shapes graph and saying+so is the answer that cannot be wrong. -/+def compilePath (G : Graph) (node : Term) : Except String Path :=+ if isIriSpelling node then .ok (.pred node)+ else+ match pathForms G node with+ | [] => .error s!"{node} is not a path this development understands"+ | ["sh:inversePath"] =>+ match objectsOf G node SH.inversePath with+ | [inner] =>+ if isIriSpelling inner then .ok (.inv inner)+ else .error "sh:inversePath of something other than a predicate is not implemented"+ | _ => .error "more than one sh:inversePath on a path node"+ | [one] => .error s!"{one} is not implemented"+ | many =>+ .error s!"the path node {node} carries more than one path form \+ ({String.intercalate ", " many}); SHACL allows exactly one, so this shapes graph is \+ ill formed and no reading of it is chosen"++def isDeactivated (G : Graph) (node : Term) : Bool :=+ (objectsOf G node SH.deactivated).any fun o =>+ match asLiteral o with+ | some l => l.lex == "true"+ | none => false++/-- Wrap a value-node constraint for the shape it sits on: on a property shape it+applies to every value node, on a node shape to the focus node itself. -/+def wrapV : Option Path → Shape → Shape+ | none, s => s+ | some pa, s => .forAll pa s++def foldAnd : List Shape → Shape+ | [] => .top+ | s :: rest => .andC s (foldAnd rest)++def foldOr : List Shape → Shape+ | [] => .bot+ | s :: rest => .orC s (foldOr rest)++/-- Compile one shape node. `fuel` bounds the nesting; one level of nesting always+consumes at least one triple of the shapes graph, so a budget of `|G| + 1`+exhausts only on a cycle. -/+def compileShape (G : Graph) : Nat → Term → Except String Shape+ | 0, node =>+ .error s!"shape nesting at {node} exceeds the size of the shapes graph, so the shapes \+ are recursive; SHACL does not define the semantics of recursive shapes"+ | fuel + 1, node => do+ for p in predsOf G node do+ if isShaclPred p && !(knownParams.contains p) && !(ignoredParams.contains p) then+ throw s!"{node}: the constraint parameter {p} is not implemented"+ if isDeactivated G node then+ return .top+ let pathOpt : Option Path ← (+ match objectsOf G node SH.path with+ | [] => pure none+ | [po] => do+ let pa ← compilePath G po+ pure (some pa)+ | _ => throw s!"{node}: more than one sh:path")+ let mut acc : Shape := .top+ for o in objectsOf G node SH.klass do+ acc := .both acc (wrapV pathOpt (.klass o))+ for o in objectsOf G node SH.datatype do+ acc := .both acc (wrapV pathOpt (.datatype o))+ for o in objectsOf G node SH.nodeKind do+ let k ← readNodeKind o+ acc := .both acc (wrapV pathOpt (.nodeKind k))+ for o in objectsOf G node SH.inList do+ let vs ← readList G (G.length + 1) o+ acc := .both acc (wrapV pathOpt (.inSet vs))+ for o in objectsOf G node SH.notC do+ let s ← compileShape G fuel o+ acc := .both acc (wrapV pathOpt (.notC s))+ for o in objectsOf G node SH.nodeC do+ let s ← compileShape G fuel o+ acc := .both acc (wrapV pathOpt (.nodeC s))+ for o in objectsOf G node SH.andC do+ let members ← readList G (G.length + 1) o+ let mut ss : List Shape := []+ for m in members do+ ss := ss ++ [← compileShape G fuel m]+ acc := .both acc (wrapV pathOpt (foldAnd ss))+ for o in objectsOf G node SH.orC do+ let members ← readList G (G.length + 1) o+ let mut ss : List Shape := []+ for m in members do+ ss := ss ++ [← compileShape G fuel m]+ acc := .both acc (wrapV pathOpt (foldOr ss))+ for o in objectsOf G node SH.property do+ let s ← compileShape G fuel o+ acc := .both acc (wrapV pathOpt s)+ for o in objectsOf G node SH.hasValue do+ match pathOpt with+ | none => acc := .both acc (.hasValue o)+ | some pa => acc := .both acc (.hasValueOn pa o)+ for o in objectsOf G node SH.minCount do+ let n ← readNat o+ match pathOpt with+ | none => throw s!"{node}: sh:minCount on a shape with no sh:path"+ | some pa => acc := .both acc (.minCount pa n)+ for o in objectsOf G node SH.maxCount do+ let n ← readNat o+ match pathOpt with+ | none => throw s!"{node}: sh:maxCount on a shape with no sh:path"+ | some pa => acc := .both acc (.maxCount pa n)+ return .named node acc++/-! ## Targets -/++def targetsOf (G : Graph) (node : Term) : List Target :=+ let explicit :=+ (objectsOf G node SH.targetNode).map Target.node +++ (objectsOf G node SH.targetClass).map Target.klass +++ (objectsOf G node SH.targetSubjectsOf).map Target.subjectsOf +++ (objectsOf G node SH.targetObjectsOf).map Target.objectsOf+ -- The implicit class target: a node that is both a shape and a class targets its+ -- own instances.+ let isShape :=+ hasTriple G node V.type SH.NodeShape || hasTriple G node V.type SH.PropertyShape+ if isShape && hasTriple G node V.type V.rdfsClass then+ explicit ++ [Target.klass node]+ else explicit++/-- Every node in the shapes graph that carries at least one target. -/+def targetedNodes (G : Graph) : List Term :=+ dedup ((G.filterMap fun t =>+ if t.p == SH.targetNode || t.p == SH.targetClass || t.p == SH.targetSubjectsOf+ || t.p == SH.targetObjectsOf then some t.s+ else if t.p == V.type && t.o == V.rdfsClass then+ if hasTriple G t.s V.type SH.NodeShape || hasTriple G t.s V.type SH.PropertyShape+ then some t.s else none+ else none))++/-- The global guard: a shapes graph that defines its own constraint components+introduces parameters outside the `sh:` namespace, so the per-shape check cannot+see them and a shape using one would look empty. Refuse the whole graph. -/+def extensionMechanism (G : Graph) : Option String :=+ let hit := G.find? fun t =>+ t.p == SH.parameter || t.p == SH.validator || t.p == SH.nodeValidator+ || t.p == SH.propertyValidator || t.p == SH.sparql+ || (t.p == V.type && t.o == SH.ConstraintComponent)+ match hit with+ | some t =>+ some s!"the shapes graph uses the SHACL extension mechanism ({t.p} on {t.s}); a \+ constraint component can declare parameters outside the sh: namespace, which this \+ compiler cannot detect, so the whole graph is refused rather than partly ignored"+ | none => none++/-- Compile a whole shapes graph into declarations, or refuse with a reason. -/+def compileShapes (G : Graph) : Except String (List ShapeDecl) := do+ match extensionMechanism G with+ | some why => throw why+ | none => pure ()+ let mut out : Array ShapeDecl := #[]+ for node in targetedNodes G do+ if isDeactivated G node then+ continue+ let s ← compileShape G (G.length + 1) node+ out := out.push { id := node, targets := targetsOf G node, shape := s }+ return out.toList++end Shacl.Compilediff --git a/lean/Shacl/Eval.lean b/lean/Shacl/Eval.leannew file mode 100644index 00000000..57c55bf3--- /dev/null+++ b/lean/Shacl/Eval.lean@@ -0,0 +1,469 @@+import Shacl.Spec++/-!+# The evaluator++An executable function from a graph, a shape and a focus node to either a list of+validation results or a refusal to answer. `Shacl/Agreement.lean` proves it agrees+with `Shacl/Spec.lean`.++## The third answer++`eval` returns `Except Refusal (List Result)`, and the error side is not a crash.+It is the evaluator declining to decide, in the two places where deciding would+mean guessing:++* a literal carries the datatype a `sh:datatype` constraint asks for, and this+ development does not know that datatype's lexical space, so it cannot say whether+ the literal is well formed;+* the `rdfs:subClassOf` closure did not reach a fixpoint inside the iteration+ budget, so the set of superclasses computed is not known to be complete.++Both are reported by name. A refusal propagates: one undecidable constraint makes+the whole run undetermined rather than letting the rest of the report imply a+verdict the undecided part could have overturned. The alternative, answering+`conforms` because the hard constraint was skipped, is the failure mode this+repository exists to catch.++The second refusal has never been observed to fire: `subIter` runs `|G| + 1`+rounds and the closure of a subclass graph with `|G|` edges settles in at most+`|G|`. It is a guard against an argument, not against a measurement, and the guard+is cheap enough to keep.++## Performance++Everything is lists and linear scans. The subclass closure is recomputed for each+`sh:class` constraint at each focus node. That is quadratic in the graph and fine+for the graphs a shapes test uses; it is not a validator for a large store, and+nothing here pretends otherwise.+-/+namespace Shacl++/-! ## Small list utilities -/++/-- Duplicate-free version of a list, keeping the last occurrence of each element.+`List.eraseDups` is in core but carries no `Nodup` lemma there, and the counting+constraints need one. -/+def dedup [DecidableEq α] : List α → List α+ | [] => []+ | a :: l =>+ let d := dedup l+ if a ∈ d then d else a :: d++theorem mem_dedup [DecidableEq α] {a : α} : ∀ {l : List α}, a ∈ dedup l ↔ a ∈ l+ | [] => by simp [dedup]+ | b :: l => by+ simp only [dedup]+ by_cases h : b ∈ dedup l+ · simp only [h, if_pos]+ constructor+ · intro ha; exact List.mem_cons_of_mem _ (mem_dedup.mp ha)+ · intro ha+ rcases List.mem_cons.mp ha with rfl | ha+ · exact h+ · exact mem_dedup.mpr ha+ · simp only [h, if_neg, not_false_iff]+ constructor+ · intro ha+ rcases List.mem_cons.mp ha with rfl | ha+ · exact List.mem_cons_self ..+ · exact List.mem_cons_of_mem _ (mem_dedup.mp ha)+ · intro ha+ rcases List.mem_cons.mp ha with rfl | ha+ · exact List.mem_cons_self ..+ · exact List.mem_cons_of_mem _ (mem_dedup.mpr ha)++theorem nodup_dedup [DecidableEq α] : ∀ (l : List α), (dedup l).Nodup+ | [] => by simp [dedup]+ | a :: l => by+ simp only [dedup]+ by_cases h : a ∈ dedup l+ · simp only [h, if_pos]; exact nodup_dedup l+ · simp only [h, if_neg, not_false_iff]+ exact List.nodup_cons.mpr ⟨h, nodup_dedup l⟩++/-! ## Reading the graph -/++/-- The value nodes of `f` along `pa`, without duplicates. -/+def valueNodes (G : Graph) (pa : Path) (f : Term) : List Term :=+ dedup ((G.filter (pa.sel f)).map pa.val)++theorem mem_valueNodes {G : Graph} {pa : Path} {f v : Term} :+ v ∈ valueNodes G pa f ↔ IsValue G pa f v := by+ rw [valueNodes, mem_dedup, List.mem_map]+ cases pa with+ | pred p =>+ constructor+ · rintro ⟨t, ht, hv⟩+ rw [List.mem_filter] at ht+ obtain ⟨hG, hsel⟩ := ht+ simp only [Path.sel, Bool.and_eq_true, beq_iff_eq] at hsel+ simp only [Path.val] at hv+ cases t+ simp_all [IsValue]+ · intro h+ refine ⟨⟨f, p, v⟩, ?_, rfl⟩+ rw [List.mem_filter]+ exact ⟨h, by simp [Path.sel]⟩+ | inv p =>+ constructor+ · rintro ⟨t, ht, hv⟩+ rw [List.mem_filter] at ht+ obtain ⟨hG, hsel⟩ := ht+ simp only [Path.sel, Bool.and_eq_true, beq_iff_eq] at hsel+ simp only [Path.val] at hv+ cases t+ simp_all [IsValue]+ · intro h+ refine ⟨⟨v, p, f⟩, ?_, rfl⟩+ rw [List.mem_filter]+ exact ⟨h, by simp [Path.sel]⟩++/-- Every `rdf:type` value of `x`. Duplicates are harmless here: only membership is+ever asked. -/+def typesOf (G : Graph) (x : Term) : List Term :=+ (G.filter (fun t => t.s == x && t.p == V.type)).map Triple.o++theorem mem_typesOf {G : Graph} {x t : Term} :+ t ∈ typesOf G x ↔ (⟨x, V.type, t⟩ : Triple) ∈ G := by+ rw [typesOf, List.mem_map]+ constructor+ · rintro ⟨u, hu, hv⟩+ rw [List.mem_filter] at hu+ obtain ⟨hG, hsel⟩ := hu+ simp only [Bool.and_eq_true, beq_iff_eq] at hsel+ cases u+ simp_all+ · intro h+ refine ⟨⟨x, V.type, t⟩, ?_, rfl⟩+ rw [List.mem_filter]+ exact ⟨h, by simp⟩++/-! ## The subclass closure++`subClosure G c` computes the set of classes that are `rdfs:subClassOf*` of `c`,+by iterating a one-step expansion and then CHECKING that the result is closed. The+check is what makes both halves of the agreement provable: soundness follows from+the iteration, completeness follows from closure alone by induction on the+`SubClassStar` derivation, and neither needs an argument about how many rounds are+enough. -/++/-- One round: every `x` with `x rdfs:subClassOf y` for a `y` already in `S`. -/+def subStep (G : Graph) (S : List Term) : List Term :=+ dedup (S ++ (G.filter (fun t => t.p == V.subClassOf && S.contains t.o)).map Triple.s)++/-- Iterate, stopping early once a round adds nothing. -/+def subIter (G : Graph) : Nat → List Term → List Term+ | 0, S => S+ | n + 1, S =>+ let S' := subStep G S+ if S'.length ≤ S.length then S else subIter G n S'++/-- Is `S` closed under the one-step expansion? Decidable, and the whole reason the+completeness half needs no counting argument. -/+def subClosed (G : Graph) (S : List Term) : Bool :=+ G.all (fun t => !(t.p == V.subClassOf) || !(S.contains t.o) || S.contains t.s)++/-- Hand back a set only if it is closed. Separated out so that `subClosure`'s+equation is a single application and the proofs below can `split` on the check+without first having to reduce a `let`. -/+def closeIf (G : Graph) (S : List Term) : Option (List Term) :=+ if subClosed G S then some S else none++/-- The superclass-closed set containing `c`, or `none` when the iteration budget+ran out before a closed set was reached. -/+def subClosure (G : Graph) (c : Term) : Option (List Term) :=+ closeIf G (subIter G (G.length + 1) [c])++theorem mem_subStep {G : Graph} {S : List Term} {x : Term} :+ x ∈ subStep G S ↔ (x ∈ S ∨ ∃ y, (⟨x, V.subClassOf, y⟩ : Triple) ∈ G ∧ y ∈ S) := by+ rw [subStep, mem_dedup, List.mem_append, List.mem_map]+ constructor+ · rintro (h | ⟨t, ht, hv⟩)+ · exact Or.inl h+ · rw [List.mem_filter] at ht+ obtain ⟨hG, hsel⟩ := ht+ simp only [Bool.and_eq_true, beq_iff_eq, List.contains_iff_mem] at hsel+ cases t+ simp_all+ exact Or.inr ⟨_, by simp_all, hsel.2⟩+ · rintro (h | ⟨y, hG, hy⟩)+ · exact Or.inl h+ · refine Or.inr ⟨⟨x, V.subClassOf, y⟩, ?_, rfl⟩+ rw [List.mem_filter]+ exact ⟨hG, by simp [hy]⟩++theorem subset_subStep {G : Graph} {S : List Term} : S ⊆ subStep G S :=+ fun _ h => mem_subStep.mpr (Or.inl h)++theorem subset_subIter {G : Graph} : ∀ (n : Nat) (S : List Term), S ⊆ subIter G n S+ | 0, _ => fun _ h => h+ | n + 1, S => by+ simp only [subIter]+ by_cases h : (subStep G S).length ≤ S.length+ · simp only [h, if_pos]; exact fun _ hx => hx+ · simp only [h, if_neg, not_false_iff]+ exact fun _ hx => subset_subIter n _ (subset_subStep hx)++/-- Everything the iteration produces really is a subclass of the seed. -/+theorem subIter_sound {G : Graph} (P : Term → Prop)+ (hstep : ∀ x y, (⟨x, V.subClassOf, y⟩ : Triple) ∈ G → P y → P x) :+ ∀ (n : Nat) (S : List Term), (∀ x ∈ S, P x) → ∀ x ∈ subIter G n S, P x+ | 0, _, h => h+ | n + 1, S, h => by+ simp only [subIter]+ by_cases hb : (subStep G S).length ≤ S.length+ · simp only [hb, if_pos]; exact h+ · simp only [hb, if_neg, not_false_iff]+ refine subIter_sound P hstep n _ ?_+ intro x hx+ rcases mem_subStep.mp hx with hx | ⟨y, hG, hy⟩+ · exact h x hx+ · exact hstep x y hG (h y hy)++/-- The closure test does what its name says: in a closed set, a subclass edge into+the set drags its subject in. This is the ONLY thing the completeness half needs,+which is why the iteration count never has to be justified. -/+theorem subClosed_step {G : Graph} {S : List Term} (h : subClosed G S = true) {a b : Term}+ (hG : (⟨a, V.subClassOf, b⟩ : Triple) ∈ G) (hb : b ∈ S) : a ∈ S := by+ rw [subClosed, List.all_eq_true] at h+ have hc : (!(V.subClassOf == V.subClassOf) || !(S.contains b) || S.contains a) = true :=+ h _ hG+ rw [beq_self_eq_true, Bool.not_true, Bool.false_or, List.contains_iff_mem.mpr hb,+ Bool.not_true, Bool.false_or] at hc+ exact List.contains_iff_mem.mp hc++/-- `subClosure` hands back exactly the iterate, and only when it is closed. -/+theorem subClosure_eq {G : Graph} {c : Term} {S : List Term}+ (h : subClosure G c = some S) :+ S = subIter G (G.length + 1) [c] ∧ subClosed G S = true := by+ rw [subClosure, closeIf] at h+ by_cases hc : subClosed G (subIter G (G.length + 1) [c]) = true+ · rw [if_pos hc] at h+ injection h with h+ exact ⟨h.symm, h ▸ hc⟩+ · rw [if_neg hc] at h+ exact absurd h (by simp)++theorem subClosure_sound {G : Graph} {c : Term} {S : List Term}+ (h : subClosure G c = some S) : ∀ x ∈ S, SubClassStar G x c := by+ obtain ⟨rfl, _⟩ := subClosure_eq h+ refine subIter_sound (fun x => SubClassStar G x c) (fun _ _ hG hy => .step hG hy) _ _ ?_+ intro x hx+ rw [List.mem_singleton] at hx+ subst hx+ exact .refl _++/-- In a closed set, membership follows the subclass chain downwards. Induction on+the derivation, with no reference to how the set was built. -/+theorem closed_star {G : Graph} {S : List Term} (hclosed : subClosed G S = true) :+ ∀ {x c : Term}, SubClassStar G x c → c ∈ S → x ∈ S := by+ intro x c hx+ induction hx with+ | refl _ => exact id+ | step hG _ ih => exact fun hc => subClosed_step hclosed hG (ih hc)++theorem subClosure_complete {G : Graph} {c : Term} {S : List Term}+ (h : subClosure G c = some S) : ∀ {x}, SubClassStar G x c → x ∈ S := by+ obtain ⟨hS, hclosed⟩ := subClosure_eq h+ have hseed : c ∈ S := by+ rw [hS]; exact subset_subIter _ _ (List.mem_singleton_self c)+ intro x hx+ exact closed_star hclosed hx hseed++/-! ## Results and refusals -/++/-- One validation result. `focus`, `path`, `value`, `source` and `component` are+the five fields the SHACL report vocabulary uses (`sh:focusNode`, `sh:resultPath`,+`sh:value`, `sh:sourceShape`, `sh:sourceConstraintComponent`).++`blamed` and `blamedNode` are not part of any report. They record WHICH constraint+failed and at WHICH node, so that "this result is justified" is a statement that+can be written down and proved: see `eval_results_licensed`. Without them the+soundness theorem could only be about the conformance boolean, and a validator that+reports the right boolean with the wrong results is not much of a validator. -/+structure Result where+ focus : Term+ path : Option Path+ value : Option Term+ source : Term+ component : Term+ blamed : Shape+ blamedNode : Term+deriving Repr++/-- Why the evaluator declined to answer. -/+inductive Refusal where+ /-- A `sh:datatype` constraint matched a literal whose datatype's lexical space+ this development does not know, so well-formedness is undecided. -/+ | unknownLexicalSpace (dt : Term) (lex : String)+ /-- The `rdfs:subClassOf` iteration did not reach a closed set in budget. -/+ | subclassClosureNotReached (c : Term)+deriving Repr++def Refusal.describe : Refusal → String+ | .unknownLexicalSpace dt lex =>+ s!"sh:datatype: the lexical space of {dt} is not implemented, so \"{lex}\" cannot be judged well formed"+ | .subclassClosureNotReached c =>+ s!"sh:class: the rdfs:subClassOf closure of {c} did not settle within the iteration budget"++/-- A result blaming the focus node itself. -/+def violation (src comp : Term) (s : Shape) (f : Term) : Result :=+ { focus := f, path := none, value := some f, source := src, component := comp,+ blamed := s, blamedNode := f }++/-- A result blaming a path rather than a single value: the set constraints+(`sh:minCount`, `sh:maxCount`, `sh:hasValue` on a property shape) are about the+value nodes as a whole, so they carry `sh:resultPath` and no `sh:value`. -/+def violationOn (src comp : Term) (s : Shape) (f : Term) (pa : Path) : Result :=+ { focus := f, path := some pa, value := none, source := src, component := comp,+ blamed := s, blamedNode := f }++/-- Decide a leaf constraint: no results when it holds, exactly one when it does not. -/+def check (b : Bool) (r : Result) : Except Refusal (List Result) :=+ if b then .ok [] else .ok [r]++/-- Re-aim a result produced at a value node so that it is reported against the+focus node, with the path and the value filled in.++Only results that do not already carry a path are re-aimed. A result that has one+came from a property shape nested inside this one and already names its own focus+node, which is the value node here; SHACL reports it unchanged. -/+def liftValue (f : Term) (pa : Path) (v : Term) (r : Result) : Result :=+ { r with focus := f, path := some pa, value := some v }++/-- Evaluate a shape at each of a list of nodes, keeping the pairing so the caller+can say which node produced which results. Any refusal aborts. -/+def collect (k : Term → Except Refusal (List Result)) :+ List Term → Except Refusal (List (Term × List Result))+ | [] => .ok []+ | v :: vs => do+ let r ← k v+ let rest ← collect k vs+ .ok ((v, r) :: rest)++/-! ## The leaf decisions, each paired with the proposition it decides -/++def nodeKindOK (k : NodeKind) (f : Term) : Bool :=+ match kindOf f with+ | some κ => k.admits κ+ | none => false++theorem nodeKindOK_iff {k : NodeKind} {f : Term} :+ nodeKindOK k f = true ↔ ∃ κ, kindOf f = some κ ∧ k.admits κ = true := by+ rw [nodeKindOK]+ cases h : kindOf f with+ | none => simp+ | some κ => simp++def evalKlass (G : Graph) (c src f : Term) : Except Refusal (List Result) :=+ match subClosure G c with+ | none => .error (.subclassClosureNotReached c)+ | some S => check ((typesOf G f).any (fun t => S.contains t)) (violation src C.klass (.klass c) f)++def evalDatatype (d src f : Term) : Except Refusal (List Result) :=+ match asLiteral f with+ | none => check false (violation src C.datatype (.datatype d) f)+ | some l =>+ if l.dt = d then+ match lexOK l with+ | none => .error (.unknownLexicalSpace l.dt l.lex)+ | some b => check b (violation src C.datatype (.datatype d) f)+ else check false (violation src C.datatype (.datatype d) f)++/-! ## The evaluator -/++def eval (G : Graph) : Shape → Term → Term → Except Refusal (List Result)+ | .top, _, _ => .ok []+ | .bot, src, f => check false (violation src C.bot .bot f)+ | .klass c, src, f => evalKlass G c src f+ | .datatype d, src, f => evalDatatype d src f+ | .nodeKind k, src, f => check (nodeKindOK k f) (violation src C.nodeKind (.nodeKind k) f)+ | .hasValue v, src, f => check (f == v) (violation src C.hasValue (.hasValue v) f)+ | .inSet vs, src, f => check (vs.contains f) (violation src C.inSet (.inSet vs) f)+ | .minCount pa n, src, f =>+ check (decide (n ≤ (valueNodes G pa f).length))+ (violationOn src C.minCount (.minCount pa n) f pa)+ | .maxCount pa n, src, f =>+ check (decide ((valueNodes G pa f).length ≤ n))+ (violationOn src C.maxCount (.maxCount pa n) f pa)+ | .hasValueOn pa v, src, f =>+ check ((valueNodes G pa f).contains v)+ (violationOn src C.hasValue (.hasValueOn pa v) f pa)+ | .named src' a, _, f => eval G a src' f+ | .both a b, src, f => do+ let ra ← eval G a src f+ let rb ← eval G b src f+ .ok (ra ++ rb)+ | .andC a b, src, f => do+ let ra ← eval G a src f+ let rb ← eval G b src f+ check (ra.isEmpty && rb.isEmpty) (violation src C.andC (.andC a b) f)+ | .orC a b, src, f => do+ let ra ← eval G a src f+ let rb ← eval G b src f+ check (ra.isEmpty || rb.isEmpty) (violation src C.orC (.orC a b) f)+ | .notC a, src, f => do+ let ra ← eval G a src f+ check (!ra.isEmpty) (violation src C.notC (.notC a) f)+ | .nodeC a, src, f => do+ let ra ← eval G a src f+ check ra.isEmpty (violation src C.nodeC (.nodeC a) f)+ | .forAll pa a, src, f => do+ let out ← collect (fun v => eval G a src v) (valueNodes G pa f)+ .ok (out.flatMap (fun q => q.2.map (liftValue f pa q.1)))++/-! ## Targets, and the whole report++A validator that evaluates the right shape at the wrong nodes is wrong, so the+target computation is inside the theorem too. -/++/-- The focus nodes one target declaration selects. `sh:targetClass` needs the same+subclass closure `sh:class` does, and refuses in the same way. -/+def focusNodes (G : Graph) : Target → Except Refusal (List Term)+ | .node n => .ok [n]+ | .klass c =>+ match subClosure G c with+ | none => .error (.subclassClosureNotReached c)+ | some S =>+ .ok (dedup ((G.filter (fun tr => tr.p == V.type && S.contains tr.o)).map Triple.s))+ | .subjectsOf p => .ok (dedup ((G.filter (fun tr => tr.p == p)).map Triple.s))+ | .objectsOf p => .ok (dedup ((G.filter (fun tr => tr.p == p)).map Triple.o))++/-- The union of several target declarations, without duplicates. A node named by+two declarations of one shape is validated once; SHACL's target is a set. -/+def focusList (G : Graph) : List Target → Except Refusal (List Term)+ | [] => .ok []+ | t :: ts => do+ let a ← focusNodes G t+ let b ← focusList G ts+ .ok (dedup (a ++ b))++/-- A shape with its identity and its targets, which is what a shapes graph+actually carries. -/+structure ShapeDecl where+ id : Term+ targets : List Target+ shape : Shape+deriving Repr++/-- Validate one declaration: every node any of its targets selects, against its+shape, reported under its own IRI. -/+def evalDecl (G : Graph) (d : ShapeDecl) : Except Refusal (List Result) := do+ let fs ← focusList G d.targets+ let out ← collect (fun f => eval G d.shape d.id f) fs+ .ok (out.flatMap (fun q => q.2))++/-- The whole report: every declaration in the shapes graph. -/+def validate (G : Graph) : List ShapeDecl → Except Refusal (List Result)+ | [] => .ok []+ | d :: ds => do+ let a ← evalDecl G d+ let b ← validate G ds+ .ok (a ++ b)++/-- What the report is about: `f` is targeted by `d`. -/+def Targeted (G : Graph) (d : ShapeDecl) (f : Term) : Prop :=+ ∃ t ∈ d.targets, IsFocus G t f++end Shacldiff --git a/lean/Shacl/Parse.lean b/lean/Shacl/Parse.leannew file mode 100644index 00000000..e82b02fb--- /dev/null+++ b/lean/Shacl/Parse.lean@@ -0,0 +1,104 @@+import Shacl.Term++/-!+# Reading N-Triples++Not part of any theorem. A parse error is a refusal, never a verdict, and+`ShaclMain.lean` exits with the code reserved for "a file could not be read".++N-Triples rather than Turtle because Turtle needs prefix resolution, base+resolution and a real grammar, and every one of those is a place to be subtly+wrong about which term a shape mentions. The bridge in+`tests/shacl_core_verified_test.rs` hands this module N-Triples produced by the+engine's own parser with an explicit base IRI, so relative IRIs are already+resolved and literals are already in one canonical spelling. That moves the hard+part of reading RDF out of this development and into a component that is measured+elsewhere, and it says so rather than pretending the whole path is verified.++What is accepted: one triple per line, terms separated by whitespace, a trailing+`.`, blank lines and `#` comments. Literals may carry `^^<datatype>` or `@lang`.+Escapes inside a literal are preserved exactly as written, never decoded, which is+the term model `Shacl/Term.lean` documents.+-/+namespace Shacl.Parse++def isWs (c : Char) : Bool := c == ' ' || c == '\t' || c == '\r' || c == '\n'++def skipWs : List Char → List Char+ | [] => []+ | c :: rest => if isWs c then skipWs rest else c :: rest++/-- Characters up to the first `stop`, and what follows it. -/+def takeUntil (stop : Char) : List Char → Option (List Char × List Char)+ | [] => none+ | c :: rest =>+ if c == stop then some ([], rest)+ else (takeUntil stop rest).map fun p => (c :: p.1, p.2)++def takeWhile (p : Char → Bool) : List Char → List Char × List Char+ | [] => ([], [])+ | c :: rest =>+ if p c then+ let (a, b) := takeWhile p rest+ (c :: a, b)+ else ([], c :: rest)++def isLangChar (c : Char) : Bool := c.isAlpha || c.isDigit || c == '-'++/-- Read one term and return it in the canonical N-Triples spelling this+development uses everywhere else. -/+def readTerm (cs : List Char) : Option (Term × List Char) :=+ match skipWs cs with+ | '<' :: rest =>+ match takeUntil '>' rest with+ | some (body, tail) => some (String.ofList ('<' :: body ++ ['>']), tail)+ | none => none+ | '_' :: ':' :: rest =>+ let (label, tail) := takeWhile (fun c => !isWs c && c != '.') rest+ if label.isEmpty then none else some (String.ofList ('_' :: ':' :: label), tail)+ | '"' :: rest =>+ match splitLex rest with+ | none => none+ | some (lex, tail) =>+ match tail with+ | '^' :: '^' :: '<' :: dtRest =>+ match takeUntil '>' dtRest with+ | some (dt, tail2) =>+ some (String.ofList ('"' :: lex ++ '"' :: '^' :: '^' :: '<' :: dt ++ ['>']), tail2)+ | none => none+ | '@' :: langRest =>+ let (tag, tail2) := takeWhile isLangChar langRest+ if tag.isEmpty then none+ else some (String.ofList ('"' :: lex ++ '"' :: '@' :: tag), tail2)+ | _ => some (String.ofList ('"' :: lex ++ ['"']), tail)+ | _ => none++def parseLine (n : Nat) (cs : List Char) : Except String (Option Triple) :=+ match skipWs cs with+ | [] => .ok none+ | '#' :: _ => .ok none+ | rest =>+ match readTerm rest with+ | none => .error s!"line {n}: could not read a subject"+ | some (s, r1) =>+ match readTerm r1 with+ | none => .error s!"line {n}: could not read a predicate"+ | some (p, r2) =>+ match readTerm r2 with+ | none => .error s!"line {n}: could not read an object"+ | some (o, r3) =>+ match skipWs r3 with+ | '.' :: _ => .ok (some ⟨s, p, o⟩)+ | _ => .error s!"line {n}: expected '.' after the object"++def parseNTriples (content : String) : Except String Graph := do+ let mut out : Array Triple := #[]+ let mut n := 0+ for line in content.splitOn "\n" do+ n := n + 1+ match ← parseLine n line.toList with+ | some t => out := out.push t+ | none => pure ()+ return out.toList++end Shacl.Parsediff --git a/lean/Shacl/Report.lean b/lean/Shacl/Report.leannew file mode 100644index 00000000..3f2c21a6--- /dev/null+++ b/lean/Shacl/Report.lean@@ -0,0 +1,219 @@+import Shacl.Agreement++/-!+# The whole report++`eval_conforms_iff` is about one focus node and one shape. A validator answers a+different question: given a data graph and a set of shape declarations with their+targets, does anything violate anything. That is what `validate` computes and what+`validate_spec` is about.++The target computation is inside the theorem deliberately. A validator that+evaluates the right shape at the wrong nodes is wrong in a way no amount of+correctness about `Conf` would catch, and `sh:targetClass` in particular reuses the+subclass closure, so it inherits the same refusal.+-/+namespace Shacl++theorem mem_focusNodes {G : Graph} {t : Target} {l : List Term} (h : focusNodes G t = .ok l)+ {x : Term} : x ∈ l ↔ IsFocus G t x := by+ cases t with+ | node n =>+ rw [focusNodes] at h+ injection h with h+ subst h+ exact Iff.trans List.mem_singleton (Iff.rfl : x = n ↔ IsFocus G (.node n) x)+ | klass c =>+ rw [focusNodes] at h+ cases hcl : subClosure G c with+ | none => simp only [hcl] at h; exact absurd h (by simp)+ | some S =>+ simp only [hcl] at h+ injection h with h+ subst h+ rw [mem_dedup, List.mem_map]+ constructor+ · rintro ⟨tr, htr, hs⟩+ rw [List.mem_filter] at htr+ obtain ⟨hG, hsel⟩ := htr+ simp only [Bool.and_eq_true, beq_iff_eq, List.contains_iff_mem] at hsel+ obtain ⟨hp, ho⟩ := hsel+ cases tr with+ | mk a b cc =>+ simp only at hp ho hs+ subst hp+ subst hs+ exact ⟨cc, hG, subClosure_sound hcl cc ho⟩+ · rintro ⟨ty, hG, hsc⟩+ refine ⟨⟨x, V.type, ty⟩, ?_, rfl⟩+ rw [List.mem_filter]+ refine ⟨hG, ?_⟩+ show ((V.type == V.type) && S.contains ty) = true+ rw [beq_self_eq_true, Bool.true_and]+ exact List.contains_iff_mem.mpr (subClosure_complete hcl hsc)+ | subjectsOf p =>+ rw [focusNodes] at h+ injection h with h+ subst h+ rw [mem_dedup, List.mem_map]+ constructor+ · rintro ⟨tr, htr, hs⟩+ rw [List.mem_filter] at htr+ obtain ⟨hG, hsel⟩ := htr+ simp only [beq_iff_eq] at hsel+ cases tr with+ | mk a b cc =>+ simp only at hsel hs+ subst hsel+ subst hs+ exact ⟨cc, hG⟩+ · rintro ⟨o, hG⟩+ exact ⟨⟨x, p, o⟩, by rw [List.mem_filter]; exact ⟨hG, by simp⟩, rfl⟩+ | objectsOf p =>+ rw [focusNodes] at h+ injection h with h+ subst h+ rw [mem_dedup, List.mem_map]+ constructor+ · rintro ⟨tr, htr, hs⟩+ rw [List.mem_filter] at htr+ obtain ⟨hG, hsel⟩ := htr+ simp only [beq_iff_eq] at hsel+ cases tr with+ | mk a b cc =>+ simp only at hsel hs+ subst hsel+ subst hs+ exact ⟨a, hG⟩+ · rintro ⟨s, hG⟩+ exact ⟨⟨s, p, x⟩, by rw [List.mem_filter]; exact ⟨hG, by simp⟩, rfl⟩++theorem mem_focusList {G : Graph} {x : Term} :+ ∀ {ts : List Target} {l : List Term}, focusList G ts = .ok l →+ (x ∈ l ↔ ∃ t ∈ ts, IsFocus G t x)+ | [], l, h => by+ rw [focusList] at h; injection h with h; subst h; simp+ | t :: ts, l, h => by+ rw [focusList] at h+ cases ha : focusNodes G t with+ | error e => rw [bind_error_eq ha] at h; exact absurd h (by simp)+ | ok a =>+ rw [bind_ok_eq ha] at h+ cases hb : focusList G ts with+ | error e => rw [bind_error_eq hb] at h; exact absurd h (by simp)+ | ok b =>+ rw [bind_ok_eq hb] at h+ injection h with h+ subst h+ rw [mem_dedup, List.mem_append, mem_focusNodes ha, mem_focusList hb]+ constructor+ · rintro (hx | ⟨u, hu, hx⟩)+ · exact ⟨t, List.mem_cons_self .., hx⟩+ · exact ⟨u, List.mem_cons_of_mem _ hu, hx⟩+ · rintro ⟨u, hu, hx⟩+ rcases List.mem_cons.mp hu with rfl | hu+ · exact Or.inl hx+ · exact Or.inr ⟨u, hu, hx⟩++theorem evalDecl_spec {G : Graph} {d : ShapeDecl} {rs : List Result}+ (h : evalDecl G d = .ok rs) :+ (rs = [] ↔ ∀ f, Targeted G d f → Conf G d.shape f) ∧+ (∀ r ∈ rs, ¬ Conf G r.blamed r.blamedNode) := by+ rw [evalDecl] at h+ cases hf : focusList G d.targets with+ | error e => rw [bind_error_eq hf] at h; exact absurd h (by simp)+ | ok fs =>+ rw [bind_ok_eq hf] at h+ cases hc : collect (fun f => eval G d.shape d.id f) fs with+ | error e => rw [bind_error_eq hc] at h; exact absurd h (by simp)+ | ok out =>+ rw [bind_ok_eq hc] at h+ injection h with h+ subst h+ obtain ⟨hmap, hall⟩ := collect_ok hc+ refine ⟨?_, ?_⟩+ · rw [List.flatMap_eq_nil_iff]+ constructor+ · intro hnil f hft+ have hfs : f ∈ fs := (mem_focusList hf).mpr hft+ rw [← hmap] at hfs+ obtain ⟨q, hq, hq1⟩ := List.mem_map.mp hfs+ rw [← hq1]+ exact (eval_conforms_iff (hall q hq)).mp (hnil q hq)+ · intro hconf q hq+ refine (eval_conforms_iff (hall q hq)).mpr (hconf q.1 ?_)+ refine (mem_focusList hf).mp ?_+ rw [← hmap]+ exact List.mem_map.mpr ⟨q, hq, rfl⟩+ · intro r hr+ obtain ⟨q, hq, hrq⟩ := List.mem_flatMap.mp hr+ exact eval_results_licensed (hall q hq) r hrq++/-- **The report is sound and complete.** `validate` returns an empty report exactly+when every node targeted by every declaration conforms to that declaration's shape,+and every result it does return blames a node that really fails the constraint it is+blamed for.++The hypothesis matters: this says nothing about a run that refused. A refusal is+reported as a refusal by `ShaclMain.lean`, never as `conforms`. -/+theorem validate_spec {G : Graph} :+ ∀ {ds : List ShapeDecl} {rs : List Result}, validate G ds = .ok rs →+ (rs = [] ↔ ∀ d ∈ ds, ∀ f, Targeted G d f → Conf G d.shape f) ∧+ (∀ r ∈ rs, ¬ Conf G r.blamed r.blamedNode)+ | [], rs, h => by+ rw [validate] at h+ injection h with h+ subst h+ exact ⟨Iff.intro (fun _ d hd => absurd hd (by simp)) (fun _ => rfl), by simp⟩+ | d :: ds, rs, h => by+ rw [validate] at h+ cases ha : evalDecl G d with+ | error e => rw [bind_error_eq ha] at h; exact absurd h (by simp)+ | ok a =>+ rw [bind_ok_eq ha] at h+ cases hb : validate G ds with+ | error e => rw [bind_error_eq hb] at h; exact absurd h (by simp)+ | ok b =>+ rw [bind_ok_eq hb] at h+ injection h with h+ subst h+ obtain ⟨ha1, ha2⟩ := evalDecl_spec ha+ obtain ⟨hb1, hb2⟩ := validate_spec hb+ refine ⟨?_, ?_⟩+ · rw [List.append_eq_nil_iff]+ constructor+ · rintro ⟨hna, hnb⟩ e he+ rcases List.mem_cons.mp he with rfl | he+ · exact ha1.mp hna+ · exact hb1.mp hnb e he+ · intro hall+ exact ⟨ha1.mpr (hall d (List.mem_cons_self ..)),+ hb1.mpr (fun e he => hall e (List.mem_cons_of_mem _ he))⟩+ · intro r hr+ rcases List.mem_append.mp hr with hr | hr+ · exact ha2 r hr+ · exact hb2 r hr++/-! ## Axioms, pinned++The same three the derivation checker in `lean/OOCert/` depends on. A `sorry` or a+`native_decide` anywhere under these theorems changes this list and fails the+build. -/++/-- info: 'Shacl.eval_conforms_iff' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms eval_conforms_iff++/-- info: 'Shacl.eval_results_licensed' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms eval_results_licensed++/-- info: 'Shacl.validate_spec' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms validate_spec++/-- info: 'Shacl.mem_focusNodes' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms mem_focusNodes++end Shacldiff --git a/lean/Shacl/Shape.lean b/lean/Shacl/Shape.leannew file mode 100644index 00000000..818560b0--- /dev/null+++ b/lean/Shacl/Shape.lean@@ -0,0 +1,142 @@+import Shacl.Term++/-!+# Shapes as a Lean datatype++A SHACL shapes graph is RDF. This module is the abstract syntax a shapes graph is+COMPILED into, and the compiler (`Shacl/Compile.lean`) is outside the theorem: it+either produces one of these shapes or refuses, and a refusal is a verdict of+"undetermined", never a pass. Everything downstream of this type is proved.++## Why an inductive type, and what that decides++SHACL shapes in RDF can refer to each other in a cycle. The Recommendation is+explicit that it "does not define the semantics of recursive shape definitions",+so there is nothing to be faithful to. Making `Shape` an inductive type settles the+question by construction: a cyclic shapes graph cannot be compiled into one, the+compiler refuses it, and the run is undetermined. That is the same answer the+Working Group gives, arrived at in a way a checker can act on.++## Transparent and opaque conjunction++SHACL has two conjunctions and they report differently, so they are two+constructors here.++* The constraints of one shape are conjoined and each reports its OWN validation+ result. That is `both`, and it produces the union of its two sides' results.+* `sh:and` conjoins shapes and reports ONE result, with+ `sh:AndConstraintComponent`, saying nothing about which conjunct failed. That is+ `andC`.++`sh:or`, `sh:not` and `sh:node` are opaque in the same way: one result each, and+the inner results are discarded. `sh:property` is transparent, which is why it has+no constructor of its own: a property shape compiles to `named PS (both ...)` and+its results surface at the parent unchanged, exactly as the Recommendation+describes.++## What `named` is for++`sh:sourceShape` on a validation result names the shape the constraint was written+on, which is not the shape being evaluated at that moment: a property shape's+constraints report the property shape, not the node shape that referenced it.+`named` carries that IRI down the tree. It has no effect on conformance, and+`Spec.lean` ignores it, which is the point: a shape's identity is bookkeeping for+the report and must not be able to change a verdict.+-/+namespace Shacl++/-- The two path forms this development covers.++`sh:path` in SHACL Core also has sequence, alternative, zero-or-more, one-or-more+and zero-or-one forms. They are not here. The compiler refuses a shapes graph that+uses one, so a test that needs them is undetermined rather than wrong. -/+inductive Path where+ | pred (p : Term)+ | inv (p : Term)+deriving DecidableEq, Repr++/-- Does this triple contribute a value node for focus node `f` along this path? -/+def Path.sel (pa : Path) (f : Term) (t : Triple) : Bool :=+ match pa with+ | .pred p => t.s == f && t.p == p+ | .inv p => t.p == p && t.o == f++/-- The value node a selected triple contributes. -/+def Path.val (pa : Path) (t : Triple) : Term :=+ match pa with+ | .pred _ => t.o+ | .inv _ => t.s++/-- The constraint components covered, plus the two units.++Constructors are named after the SHACL parameter they come from. `top` and `bot`+are the units of `andC` and `orC`; a compiler that folds a one-element `sh:or`+list needs `bot`, and nothing else produces it. -/+inductive Shape where+ /-- Conforms always. The unit of `andC`. -/+ | top+ /-- Conforms never. The unit of `orC`, and unreachable from a shapes graph whose+ `sh:or` lists are non-empty. -/+ | bot+ /-- `sh:class` -/+ | klass (c : Term)+ /-- `sh:datatype` -/+ | datatype (d : Term)+ /-- `sh:nodeKind` -/+ | nodeKind (k : NodeKind)+ /-- `sh:hasValue`, on a node shape: the focus node itself must be this term. -/+ | hasValue (v : Term)+ /-- `sh:in` -/+ | inSet (vs : List Term)+ /-- The implicit conjunction of one shape's constraints. Transparent: the+ results of both sides are reported. -/+ | both (a b : Shape)+ /-- `sh:and`. Opaque: one result. -/+ | andC (a b : Shape)+ /-- `sh:or`. Opaque: one result. -/+ | orC (a b : Shape)+ /-- `sh:not`. Opaque: one result. -/+ | notC (a : Shape)+ /-- `sh:node`. Opaque: one result, per the Recommendation, which says the nested+ shape's own results are not reported. -/+ | nodeC (a : Shape)+ /-- The value-node constraints of a property shape: every value node on the path+ must conform to the inner shape. -/+ | forAll (pa : Path) (a : Shape)+ /-- `sh:minCount` -/+ | minCount (pa : Path) (n : Nat)+ /-- `sh:maxCount` -/+ | maxCount (pa : Path) (n : Nat)+ /-- `sh:hasValue` on a property shape: SOME value node is this term. A set+ constraint, not a value-node constraint, which is why it is a separate+ constructor from `hasValue`. -/+ | hasValueOn (pa : Path) (v : Term)+ /-- Sets `sh:sourceShape` for everything underneath. No effect on conformance. -/+ | named (src : Term) (a : Shape)+deriving Repr, Inhabited++/-! ## The constraint component IRIs a result carries -/+namespace C++def klass : Term := "<http://www.w3.org/ns/shacl#ClassConstraintComponent>"+def datatype : Term := "<http://www.w3.org/ns/shacl#DatatypeConstraintComponent>"+def nodeKind : Term := "<http://www.w3.org/ns/shacl#NodeKindConstraintComponent>"+def hasValue : Term := "<http://www.w3.org/ns/shacl#HasValueConstraintComponent>"+def inSet : Term := "<http://www.w3.org/ns/shacl#InConstraintComponent>"+def andC : Term := "<http://www.w3.org/ns/shacl#AndConstraintComponent>"+def orC : Term := "<http://www.w3.org/ns/shacl#OrConstraintComponent>"+def notC : Term := "<http://www.w3.org/ns/shacl#NotConstraintComponent>"+def nodeC : Term := "<http://www.w3.org/ns/shacl#NodeConstraintComponent>"+def minCount : Term := "<http://www.w3.org/ns/shacl#MinCountConstraintComponent>"+def maxCount : Term := "<http://www.w3.org/ns/shacl#MaxCountConstraintComponent>"++/-- Not a SHACL IRI. `bot` has no counterpart in the Recommendation because it has+no counterpart in a shapes graph; it exists as the unit of `orC` and its result is+always discarded by the enclosing `orC`. Giving it a marker rather than borrowing+`sh:OrConstraintComponent` keeps a fabricated component out of any report that+somehow did escape. -/+def bot : Term := "<urn:x-oo-shacl-core:EmptyDisjunction>"++end C++end Shacldiff --git a/lean/Shacl/Spec.lean b/lean/Shacl/Spec.leannew file mode 100644index 00000000..796c9b58--- /dev/null+++ b/lean/Shacl/Spec.lean@@ -0,0 +1,106 @@+import Shacl.Shape++/-!+# The specification++What it means for a focus node to conform to a shape. Nothing in this file+computes anything: `Conf` is a `Prop`, the counting constraints quantify over+lists of value nodes rather than over any enumeration procedure, and the subclass+closure is an inductive relation rather than a fixpoint. `Shacl/Eval.lean` gives a+decision procedure and `Shacl/Agreement.lean` proves the two agree.++## Where this comes from++SHACL's normative validators are the prose ones in Appendix D of the+Recommendation. The document says of its own SPARQL definitions that they+"represent potential validators ... included for illustration purposes only and+have no formal status otherwise". So a direct reading of the prose is closer to the+normative text than a translation into SPARQL is, and it puts no SPARQL engine in+the trust path.++Each clause below is that prose, restated. The clauses that are NOT the prose are+called out where they occur, and there are two of them:++* `datatype` demands `lexOK l = some true`, so a literal whose datatype this+ development declines to judge (`lexOK = none`) does NOT conform. The evaluator+ refuses to answer in that case rather than reporting the violation this+ specification would license, which is the more conservative of the two.+* `klass` reads `rdfs:subClassOf*` off the data graph only. The Recommendation says+ the same, and an engine that reasons first will disagree with both.++## Why `Conf` ignores `named`++`named` carries the `sh:sourceShape` IRI for the report. A shape's identity must+not be able to change whether a node conforms, so the clause for it is a+pass-through. That is a property worth stating rather than assuming, and+`Agreement.lean` states it as `conf_named`.+-/+namespace Shacl++/-- `v` is a value node of `f` along `pa`. The whole of the path semantics covered,+in two lines. -/+def IsValue (G : Graph) : Path → Term → Term → Prop+ | .pred p, f, v => (⟨f, p, v⟩ : Triple) ∈ G+ | .inv p, f, v => (⟨v, p, f⟩ : Triple) ∈ G++/-- `rdfs:subClassOf*`, read off the data graph and nothing else. Reflexive and+transitive by construction. -/+inductive SubClassStar (G : Graph) : Term → Term → Prop+ | refl (a : Term) : SubClassStar G a a+ | step {a b c : Term} :+ (⟨a, V.subClassOf, b⟩ : Triple) ∈ G → SubClassStar G b c → SubClassStar G a c++/-- A SHACL instance of a class: a node with an `rdf:type` value that is a+subclass, reflexively and transitively, of the class. -/+def IsInstance (G : Graph) (c x : Term) : Prop :=+ ∃ t, (⟨x, V.type, t⟩ : Triple) ∈ G ∧ SubClassStar G t c++/-- **Conformance.** `Conf G s f` says focus node `f` conforms to shape `s` in+graph `G`.++The two counting clauses are the point of interest. `minCount` says there EXIST+that many distinct value nodes; `maxCount` says NO list of distinct value nodes is+longer than the bound. Both are statements about the set of value nodes with no+enumeration of it anywhere, which is what keeps this specification independent of+the evaluator that has to build one. -/+def Conf (G : Graph) : Shape → Term → Prop+ | .top, _ => True+ | .bot, _ => False+ | .klass c, f => IsInstance G c f+ | .datatype d, f => ∃ l, asLiteral f = some l ∧ l.dt = d ∧ lexOK l = some true+ | .nodeKind k, f => ∃ κ, kindOf f = some κ ∧ k.admits κ = true+ | .hasValue v, f => f = v+ | .inSet vs, f => f ∈ vs+ | .both a b, f => Conf G a f ∧ Conf G b f+ | .andC a b, f => Conf G a f ∧ Conf G b f+ | .orC a b, f => Conf G a f ∨ Conf G b f+ | .notC a, f => ¬ Conf G a f+ | .nodeC a, f => Conf G a f+ | .named _ a, f => Conf G a f+ | .forAll pa a, f => ∀ v, IsValue G pa f v → Conf G a v+ | .minCount pa n, f =>+ ∃ l : List Term, l.Nodup ∧ (∀ v ∈ l, IsValue G pa f v) ∧ n ≤ l.length+ | .maxCount pa n, f =>+ ∀ l : List Term, l.Nodup → (∀ v ∈ l, IsValue G pa f v) → l.length ≤ n+ | .hasValueOn pa v, f => IsValue G pa f v++/-! ## Targets++A target declaration selects focus nodes. These are `Prop`s for the same reason+`Conf` is: the executable computes a list and the agreement is proved. -/++/-- The focus nodes a target declaration selects. -/+inductive Target where+ | node (n : Term)+ | klass (c : Term)+ | subjectsOf (p : Term)+ | objectsOf (p : Term)+deriving DecidableEq, Repr++def IsFocus (G : Graph) : Target → Term → Prop+ | .node n, x => x = n+ | .klass c, x => IsInstance G c x+ | .subjectsOf p, x => ∃ o, (⟨x, p, o⟩ : Triple) ∈ G+ | .objectsOf p, x => ∃ s, (⟨s, p, x⟩ : Triple) ∈ G++end Shacldiff --git a/lean/Shacl/Term.lean b/lean/Shacl/Term.leannew file mode 100644index 00000000..768c9178--- /dev/null+++ b/lean/Shacl/Term.lean@@ -0,0 +1,240 @@+/-!+# Terms, triples, and the one place a SHACL checker must look inside a term++A term is kept in its N-Triples spelling: `<iri>`, `_:label`, or a literal with+its quotes and its datatype or language tag. Two terms are the same term when+their spellings are the same string. That is the convention `lean/OOCert/Triple.lean`+uses for the derivation checker, and the bridge in `ShaclMain.lean` reads the same+kind of file, so the two layers agree on what a term is.++`OOCert.Triple` is deliberately NOT imported here, for two reasons and the second+is the load-bearing one.++1. Build isolation. The two directories are developed independently and a broken+ edit in one should not take the other's proofs down with it.+2. **The discipline is different.** `OOCert/Triple.lean` says in its own header that+ "the checker never looks inside a term". A SHACL checker cannot honour that:+ `sh:datatype` and `sh:nodeKind` are questions ABOUT the spelling, and answering+ them means taking a literal apart. So this module does the one thing that one+ refuses to do, and it says so here rather than inheriting a promise it breaks.++## What this term model cannot express++Stated up front, because every limit below shows up as a wrong answer somewhere in+the W3C suite and it is better to name them than to discover them.++* **Two spellings of one value are two terms.** `"1"^^xsd:integer` and+ `"01"^^xsd:integer` denote the same integer and are distinct terms here, so+ `sh:hasValue`, `sh:in` and `sh:maxCount` count them separately. RDF itself is on+ this side of the line for term equality, but SHACL's comparison constraints+ (`sh:lessThan`, `sh:minInclusive`) are value-based and are therefore not+ implemented at all rather than implemented wrongly.+* **Escapes are not normalised.** `"aAb"` and `"aAb"` are one value and two+ terms. Nothing here unescapes a lexical form.+* **IRIs are not normalised.** No percent-decoding, no case folding of the scheme,+ no relative-IRI resolution. The bridge resolves relative IRIs before the term+ reaches Lean, so what arrives is already absolute; that resolution is outside+ the proof.+* **Blank node labels are constants.** Two graphs that are isomorphic but use+ different labels are different graphs here. SHACL conformance is not affected by+ blank node identity in the fragment covered, but a validation RESULT naming a+ blank node is only meaningful relative to the file it was read from.+* **Language tags are compared as written.** BCP 47 says `EN` and `en` are the same+ tag. Here they are two tags. Nothing in the covered fragment compares tags, so+ this costs nothing today; `sh:languageIn` is not implemented.+* **A lexical form's LENGTH is not the value's length.** `"a\\nb"` is a three-character+ value written with four characters, because nothing here decodes an escape. That is+ why `sh:minLength` and `sh:maxLength` are not implemented rather than implemented+ over the spelling: they would be right for every literal without an escape and+ silently wrong for the rest, which is the worst of the three options.+* **Lexical spaces are known for five datatypes and no more.** See `lexOK`.+-/+namespace Shacl++/-- A term in N-Triples spelling. -/+abbrev Term := String++structure Triple where+ s : Term+ p : Term+ o : Term+deriving DecidableEq, Repr, Inhabited++/-- A graph is a list of triples. Duplicates are allowed and are ignored by+everything that matters: membership is what the specification asks about, never+multiplicity. -/+abbrev Graph := List Triple++/-! ## Vocabulary, in N-Triples spelling -/+namespace V++def type : Term := "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>"+def subClassOf : Term := "<http://www.w3.org/2000/01/rdf-schema#subClassOf>"+def first : Term := "<http://www.w3.org/1999/02/22-rdf-syntax-ns#first>"+def rest : Term := "<http://www.w3.org/1999/02/22-rdf-syntax-ns#rest>"+def nil : Term := "<http://www.w3.org/1999/02/22-rdf-syntax-ns#nil>"+def rdfsClass : Term := "<http://www.w3.org/2000/01/rdf-schema#Class>"+def langString : Term := "<http://www.w3.org/1999/02/22-rdf-syntax-ns#langString>"+def xsdString : Term := "<http://www.w3.org/2001/XMLSchema#string>"+def xsdBoolean : Term := "<http://www.w3.org/2001/XMLSchema#boolean>"+def xsdInteger : Term := "<http://www.w3.org/2001/XMLSchema#integer>"+def xsdByte : Term := "<http://www.w3.org/2001/XMLSchema#byte>"++end V++/-! ## Taking a term apart -/++/-- The three RDF node kinds. A spelling that is none of them is classified by+`kindOf` as `none`, which satisfies no `sh:nodeKind` value. Refusing to classify a+spelling this module does not recognise is the conservative direction: it can cost+a false violation, never a false pass. -/+inductive Kind where+ | iri+ | blank+ | lit+deriving DecidableEq, Repr++/-! Every predicate below takes the term apart as a `List Char` rather than with+`String.startsWith` and friends. That is not a style preference. `String` operations+are indexed by UTF-8 byte positions, and the Lean KERNEL cannot reduce that+arithmetic on a string it did not receive as a literal, so a witness like+`Shacl/Witness.lean`'s would stop being provable by computation the moment a term+was taken apart and put back together. Working in `List Char` keeps every fact about+a concrete term decidable in the kernel, with no `native_decide` anywhere. -/++def isIriSpelling (t : Term) : Bool :=+ match t.toList with+ | '<' :: rest => !rest.isEmpty && rest.getLast? == some '>'+ | _ => false++def isBlankSpelling (t : Term) : Bool :=+ match t.toList with+ | '_' :: ':' :: rest => !rest.isEmpty+ | _ => false++/-- A literal taken apart. `lex` is the lexical form still in its N-Triples+escaping; `dt` is the datatype IRI in `<...>` spelling, filled in with+`xsd:string` for a plain literal and `rdf:langString` for a language-tagged one,+exactly as RDF 1.1 requires. -/+structure Lit where+ lex : String+ dt : Term+ lang : Option String+deriving DecidableEq, Repr++/-- Split the characters after an opening quote at the first UNESCAPED `"`,+returning the lexical form and whatever follows the closing quote. A backslash+consumes the next character whatever it is, which is the N-Triples escaping rule,+so `"a\"b"` has the four-character lexical form `a\"b` and not the one-character+form `a`. -/+def splitLex : List Char → Option (List Char × List Char)+ | [] => none+ | '\\' :: c :: rest => (splitLex rest).map fun p => ('\\' :: c :: p.1, p.2)+ | '"' :: rest => some ([], rest)+ | c :: rest => (splitLex rest).map fun p => (c :: p.1, p.2)++/-- Read a term as a literal, or refuse. -/+def asLiteral (t : Term) : Option Lit :=+ match t.toList with+ | '"' :: rest =>+ match splitLex rest with+ | none => none+ | some (lex, after) =>+ match after with+ | [] => some ⟨String.ofList lex, V.xsdString, none⟩+ | '@' :: tag =>+ if tag.isEmpty then none else some ⟨String.ofList lex, V.langString, some (String.ofList tag)⟩+ | '^' :: '^' :: iri =>+ let d := String.ofList iri+ if isIriSpelling d then some ⟨String.ofList lex, d, none⟩ else none+ | _ => none+ | _ => none++/-- The node kind of a term, or `none` when the spelling is not recognised. -/+def kindOf (t : Term) : Option Kind :=+ if isIriSpelling t then some .iri+ else if isBlankSpelling t then some .blank+ else if (asLiteral t).isSome then some .lit+ else none++/-- The six values `sh:nodeKind` can take. -/+inductive NodeKind where+ | iri+ | blankNode+ | literal+ | blankNodeOrIRI+ | blankNodeOrLiteral+ | iriOrLiteral+deriving DecidableEq, Repr++def NodeKind.admits : NodeKind → Kind → Bool+ | .iri, .iri => true+ | .blankNode, .blank => true+ | .literal, .lit => true+ | .blankNodeOrIRI, .blank => true+ | .blankNodeOrIRI, .iri => true+ | .blankNodeOrLiteral, .blank => true+ | .blankNodeOrLiteral, .lit => true+ | .iriOrLiteral, .iri => true+ | .iriOrLiteral, .lit => true+ | _, _ => false++/-! ## Lexical spaces, for the five datatypes this module is willing to judge -/++def isDigits (cs : List Char) : Bool := !cs.isEmpty && cs.all Char.isDigit++/-- The lexical space of `xsd:integer`: an optional sign then at least one digit.+Leading zeros are allowed, which is what the XSD specification says. -/+def isIntLex (s : String) : Bool :=+ match s.toList with+ | '-' :: rest => isDigits rest+ | '+' :: rest => isDigits rest+ | cs => isDigits cs++/-- The natural number a digit string denotes. Written over `List Char` for the+same kernel-reduction reason as the predicates above; `String.toNat?` folds over+byte positions and does not reduce. -/+def natOfDigits (cs : List Char) : Nat :=+ cs.foldl (fun n c => n * 10 + (c.toNat - 48)) 0++/-- The integer a lexical form denotes, when it is in `xsd:integer`'s lexical space. -/+def intValue (s : String) : Option Int :=+ match s.toList with+ | '-' :: rest => if isDigits rest then some (-(Int.ofNat (natOfDigits rest))) else none+ | '+' :: rest => if isDigits rest then some (Int.ofNat (natOfDigits rest)) else none+ | cs => if isDigits cs then some (Int.ofNat (natOfDigits cs)) else none++/-- **Is this literal well formed for its datatype?**++`some true` yes, `some false` no, `none` this module does not know the datatype's+lexical space and will not guess.++SHACL requires a value node to be a well-formed literal of the named datatype, not+merely a literal carrying the right datatype IRI, so this question cannot be+skipped. It can, however, be declined, and declining is what `none` is for: the+evaluator turns a `none` into a refusal to answer rather than into a verdict. That+is the whole difference between a validator that is quiet about what it does not+know and one that says `conforms` because it did not look.++The five it does know are `xsd:string` (every lexical form), `rdf:langString`+(every lexical form, given a tag), `xsd:boolean`, `xsd:integer` and `xsd:byte`.+Those are the datatypes the W3C core suite names in a `sh:datatype` constraint,+apart from `xsd:date` and `rdf:HTML`, which land in `none`.++The lexical form is still N-Triples-escaped when it gets here. For the five+datatypes above no well-formed value contains a character that needs escaping, so+the check is exact for them; it would not be for a datatype whose lexical space+includes quotes or newlines, which is one more reason the list is short. -/+def lexOK (l : Lit) : Option Bool :=+ if l.dt = V.xsdString then some true+ else if l.dt = V.langString then some l.lang.isSome+ else if l.dt = V.xsdBoolean then+ some (l.lex = "true" || l.lex = "false" || l.lex = "1" || l.lex = "0")+ else if l.dt = V.xsdInteger then some (isIntLex l.lex)+ else if l.dt = V.xsdByte then+ some (match intValue l.lex with+ | some v => -128 ≤ v && v ≤ 127+ | none => false)+ else none++end Shacldiff --git a/lean/Shacl/Witness.lean b/lean/Shacl/Witness.leannew file mode 100644index 00000000..c28236b9--- /dev/null+++ b/lean/Shacl/Witness.lean@@ -0,0 +1,238 @@+import Shacl.Report++/-!+# Witnesses: the specification says something, and it does not say everything++`eval_conforms_iff` and `validate_spec` are worth nothing on their own. If `Conf`+held of every focus node, "the evaluator reports nothing exactly when the node+conforms" would be a promise that the evaluator never reports anything, and the+theorem would still be true. If `Conf` held of none, the mirror image. This file+closes both by construction, the way `lean/OOCert/Witness.lean` does for the+derivation checker.++| theorem | says |+|---|---|+| `alice_conforms` | some node conforms to a real shape, proved from the specification by hand |+| `bob_does_not_conform` | some node does not, so `Conf` is not the trivial relation |+| `the_report_is_empty_when_everything_conforms` | `validate` can return nothing |+| `the_report_names_the_failing_node` | and it can return something, naming the right node and component |+| `duplicate_triples_are_counted_once` | `sh:maxCount` counts the SET of value nodes |+| `two_distinct_values_break_maxCount_one` | and it really does count them |+| `the_evaluator_refuses_rather_than_guessing` | the third answer is reachable, not decoration |++The two counting theorems are the ones worth reading. SHACL counts distinct value+nodes, so a triple asserted twice must not make a `sh:maxCount 1` fail. An engine+that counts SPARQL solutions rather than value nodes gets that wrong, and the+repository's own SHACL validator is documented as counting the other way+(`docs/lean-certificates.md`, "A SHACL report double-counts a node selected by two+target declarations"). Here it is settled in the specification and proved.+-/+namespace Shacl++/-! ## A small graph -/++def exAlice : Term := "<http://ex.org/alice>"+def exBob : Term := "<http://ex.org/bob>"+def exPerson : Term := "<http://ex.org/Person>"+def exAgent : Term := "<http://ex.org/Agent>"+def exName : Term := "<http://ex.org/name>"+def exKnows : Term := "<http://ex.org/knows>"+def exShape : Term := "<http://ex.org/AgentShape>"+def litAlice : Term := "\"Alice\""+def litBob : Term := "\"Bob\""++/-- Alice is a Person, Person is a subclass of Agent, Alice has a name, and Bob+knows Alice. Bob has no type and no name. -/+def gEx : Graph :=+ [ ⟨exAlice, V.type, exPerson⟩,+ ⟨exPerson, V.subClassOf, exAgent⟩,+ ⟨exAlice, exName, litAlice⟩,+ ⟨exBob, exKnows, exAlice⟩ ]++/-- An Agent with at least one name, every name a string. Written the way the+compiler writes it: the property shape's constraints wrapped in `named` so results+carry its IRI, the count constraint and the value-node constraint conjoined+transparently. -/+def sAgent : Shape :=+ .named exShape+ (.both (.klass exAgent)+ (.both (.minCount (.pred exName) 1)+ (.forAll (.pred exName) (.datatype V.xsdString))))++/-! ## Conformance holds somewhere, proved from the specification by hand++These three go through the definition of `Conf` and never touch `eval`. If the only+evidence that the specification says anything came from running the evaluator, a+reader would be entitled to suspect the two agree because they are the same+mistake. -/++theorem alice_is_an_agent : IsInstance gEx exAgent exAlice :=+ ⟨exPerson, by simp [gEx], .step (by simp [gEx]) (.refl _)⟩++theorem alice_has_a_name : Conf gEx (.minCount (.pred exName) 1) exAlice := by+ refine ⟨[litAlice], by simp, ?_, by simp⟩+ intro v hv+ rw [List.mem_singleton] at hv+ subst hv+ show (⟨exAlice, exName, litAlice⟩ : Triple) ∈ gEx+ simp [gEx]++theorem alices_names_are_strings :+ Conf gEx (.forAll (.pred exName) (.datatype V.xsdString)) exAlice := by+ intro v hv+ have hv' : (⟨exAlice, exName, v⟩ : Triple) ∈ gEx := hv+ simp only [gEx, List.mem_cons, List.not_mem_nil, or_false, Triple.mk.injEq] at hv'+ rcases hv' with ⟨-, h, -⟩ | ⟨h, -, -⟩ | ⟨-, -, h⟩ | ⟨-, h, -⟩+ · exact absurd h (by decide)+ · exact absurd h (by decide)+ · subst h+ exact ⟨⟨"Alice", V.xsdString, none⟩, by decide, rfl, by decide⟩+ · exact absurd h (by decide)++/-- **Conformance is not the empty relation.** -/+theorem alice_conforms : Conf gEx sAgent exAlice :=+ ⟨alice_is_an_agent, alice_has_a_name, alices_names_are_strings⟩++/-! ## And it fails somewhere -/++theorem bob_has_no_type (t : Term) : (⟨exBob, V.type, t⟩ : Triple) ∉ gEx := by+ intro h+ simp only [gEx, List.mem_cons, List.not_mem_nil, or_false, Triple.mk.injEq] at h+ rcases h with ⟨h, -, -⟩ | ⟨h, -, -⟩ | ⟨h, -, -⟩ | ⟨-, h, -⟩ <;> exact absurd h (by decide)++/-- **Conformance is not the total relation.** Bob has no `rdf:type` at all, so he+is an instance of nothing, so he is not an Agent. -/+theorem bob_does_not_conform : ¬ Conf gEx sAgent exBob := by+ rintro ⟨⟨t, ht, -⟩, -, -⟩+ exact bob_has_no_type t ht++/-! ## The report, end to end++`validate` is what a validator actually runs. These two runs are settled by kernel+computation (`rfl`), so they are executable facts rather than claims about the+code. -/++def declAgent : ShapeDecl :=+ { id := exShape, targets := [.node exAlice], shape := sAgent }++def declBoth : ShapeDecl :=+ { id := exShape, targets := [.node exAlice, .node exBob], shape := sAgent }++/-- Targeting only Alice, the report is empty. -/+theorem the_report_is_empty_when_everything_conforms :+ validate gEx [declAgent] = .ok [] := by rfl++/-- Targeting Bob as well, the report names Bob, blames `sh:class`, and blames+`sh:minCount`: two results, with the property shape's IRI as `sh:sourceShape` and+the right constraint components. Written out in full so that a change to any field+of a result breaks this proof rather than passing quietly. -/+theorem the_report_names_the_failing_node :+ validate gEx [declBoth] = .ok+ [ { focus := exBob, path := none, value := some exBob, source := exShape,+ component := C.klass, blamed := .klass exAgent, blamedNode := exBob },+ { focus := exBob, path := some (.pred exName), value := none, source := exShape,+ component := C.minCount, blamed := .minCount (.pred exName) 1,+ blamedNode := exBob } ] := by rfl++/-- The two are not independent: because the report above is non-empty,+`validate_spec` says some targeted node fails, and because the one before it is+empty, `validate_spec` says every targeted node conforms. Both directions of the+theorem are therefore exercised on real data. -/+theorem the_specification_agrees_with_both_runs :+ (∀ d ∈ [declAgent], ∀ f, Targeted gEx d f → Conf gEx d.shape f) ∧+ ¬ (∀ d ∈ [declBoth], ∀ f, Targeted gEx d f → Conf gEx d.shape f) := by+ refine ⟨(validate_spec the_report_is_empty_when_everything_conforms).1.mp rfl, ?_⟩+ intro hall+ have hnil := (validate_spec the_report_names_the_failing_node).1.mpr hall+ exact absurd hnil (by simp)++/-! ## Counting is about the set of value nodes -/++def gDup : Graph := [⟨exAlice, exName, litAlice⟩, ⟨exAlice, exName, litAlice⟩]+def gTwo : Graph := [⟨exAlice, exName, litAlice⟩, ⟨exAlice, exName, litBob⟩]++/-- One value asserted twice is one value node, so `sh:maxCount 1` holds. Proved+from the specification, which quantifies over duplicate-free lists of value nodes+and so cannot be fooled by a repeated triple. -/+theorem duplicate_triples_are_counted_once :+ Conf gDup (.maxCount (.pred exName) 1) exAlice := by+ intro l hnd hmem+ have hsub : l ⊆ [litAlice] := by+ intro v hv+ have hv' : (⟨exAlice, exName, v⟩ : Triple) ∈ gDup := hmem v hv+ simp only [gDup, List.mem_cons, List.not_mem_nil, or_false, Triple.mk.injEq] at hv'+ rcases hv' with ⟨-, -, h⟩ | ⟨-, -, h⟩ <;> (subst h; simp)+ simpa using List.Nodup.length_le_of_subset hnd hsub++/-- Two distinct values are two value nodes, so the same constraint fails. Without+this the theorem above would be consistent with a specification that counts+nothing. -/+theorem two_distinct_values_break_maxCount_one :+ ¬ Conf gTwo (.maxCount (.pred exName) 1) exAlice := by+ intro h+ have hle := h [litAlice, litBob] (by decide) ?_+ · exact absurd hle (by decide)+ · intro v hv+ rcases List.mem_cons.mp hv with rfl | hv+ · show (⟨exAlice, exName, litAlice⟩ : Triple) ∈ gTwo; simp [gTwo]+ · rw [List.mem_singleton] at hv+ subst hv+ show (⟨exAlice, exName, litBob⟩ : Triple) ∈ gTwo; simp [gTwo]++/-! ## The third answer is reachable++A refusal that never fires is decoration. This one fires on the first `xsd:date`+literal it meets, and `tests/shacl_core_verified_test.rs` counts how often that+happens across the W3C suite. -/++def xsdDate : Term := "<http://www.w3.org/2001/XMLSchema#date>"+def litDate : Term := "\"2026-09-14\"^^<http://www.w3.org/2001/XMLSchema#date>"++/-- The literal has the right datatype IRI, so the constraint turns on whether it is+a well-formed `xsd:date`, and `lexOK` does not know. The evaluator says so by name+instead of choosing an answer. -/+theorem the_evaluator_refuses_rather_than_guessing :+ eval [] (.datatype xsdDate) exShape litDate+ = .error (.unknownLexicalSpace xsdDate "2026-09-14") := by rfl++/-- The specification, meanwhile, treats an unjudgeable literal as non-conforming.+So the two possible behaviours at this point were "report a violation" and "report a+refusal", and the evaluator takes the weaker one. Neither is a false pass, which is+the property that matters. -/+theorem the_refused_literal_does_not_conform :+ ¬ Conf [] (.datatype xsdDate) litDate := by+ rintro ⟨l, hl, -, hok⟩+ have : l = ⟨"2026-09-14", xsdDate, none⟩ := by+ have : asLiteral litDate = some ⟨"2026-09-14", xsdDate, none⟩ := by decide+ rw [this] at hl+ exact (Option.some.inj hl).symm+ subst this+ exact absurd hok (by decide)++/-! ## Axioms, pinned -/++/-- info: 'Shacl.alice_conforms' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms alice_conforms++/-- info: 'Shacl.bob_does_not_conform' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms bob_does_not_conform++/-- info: 'Shacl.the_report_names_the_failing_node' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms the_report_names_the_failing_node++/-- info: 'Shacl.duplicate_triples_are_counted_once' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms duplicate_triples_are_counted_once++/-- info: 'Shacl.two_distinct_values_break_maxCount_one' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms two_distinct_values_break_maxCount_one++/-- info: 'Shacl.the_evaluator_refuses_rather_than_guessing' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms the_evaluator_refuses_rather_than_guessing++end Shacldiff --git a/lean/ShaclMain.lean b/lean/ShaclMain.leannew file mode 100644index 00000000..5f9eeb0f--- /dev/null+++ b/lean/ShaclMain.lean@@ -0,0 +1,108 @@+import Shacl.All++/-!+`oo-shacl validate DATA.nt SHAPES.nt`++Reads two N-Triples files, compiles the shapes graph, runs the verified evaluator,+and prints one JSON object.++Exit codes, chosen so that a harness cannot mistake one answer for another:++* `0` a verdict was reached. `"conforms"` is `true` or `false`.+* `2` a file could not be read or parsed. No verdict.+* `3` UNDETERMINED. The shapes graph uses something this development does not+ implement, or the evaluator declined to judge a literal. No verdict, and the+ reason is printed. This is the code that matters: it is the difference between+ "everything conforms" and "I did not check everything", and collapsing the two+ is the failure this whole layer exists to avoid.++The verdict and the results carry `"theorem": "Shacl.validate_spec"`, which is the+machine-checked statement they are covered by: the report is empty exactly when+every targeted node conforms to its shape under `Shacl/Spec.lean`, and every result+blames a node that really fails the constraint it is blamed for.++What that theorem does NOT cover, and what a reader must therefore not assume:++* that `Shacl/Spec.lean` is the W3C Recommendation. It is a reading of it, measured+ against the Working Group's suite by `tests/shacl_core_verified_test.rs`;+* that the compiler in `Shacl/Compile.lean` reads the shapes graph correctly. It is+ outside the theorem, and it refuses rather than guesses;+* that the N-Triples parser is correct. Also outside, and a parse error is exit 2;+* `sh:resultSeverity`. Never emitted; `sh:severity` in the shapes graph is ignored.+-/+open Shacl++def jsonStr (s : String) : String :=+ let escaped := s.foldl (fun acc c =>+ match c with+ | '"' => acc ++ "\\\""+ | '\\' => acc ++ "\\\\"+ | '\n' => acc ++ "\\n"+ | '\t' => acc ++ "\\t"+ | c => acc.push c) ""+ "\"" ++ escaped ++ "\""++def showPath : Path → String+ | .pred p => p+ | .inv p => "^" ++ p++def jsonOpt (o : Option String) : String :=+ match o with+ | none => "null"+ | some s => jsonStr s++def showResult (r : Result) : String :=+ "{\"focus\":" ++ jsonStr r.focus +++ ",\"path\":" ++ jsonOpt (r.path.map showPath) +++ ",\"value\":" ++ jsonOpt r.value +++ ",\"sourceShape\":" ++ jsonStr r.source +++ ",\"sourceConstraintComponent\":" ++ jsonStr r.component ++ "}"++def readOrFail (path : String) : IO (Except String String) := do+ try+ return .ok (← IO.FS.readFile path)+ catch e =>+ return .error s!"cannot read {path}: {e}"++def emitError (reason : String) : IO UInt32 := do+ IO.println ("{\"status\":\"error\",\"reason\":" ++ jsonStr reason ++ "}")+ return 2++def emitUndetermined (reason : String) : IO UInt32 := do+ IO.println ("{\"status\":\"undetermined\",\"reason\":" ++ jsonStr reason ++ "}")+ return 3++def run (dataPath shapesPath : String) : IO UInt32 := do+ let dataTxt ← match ← readOrFail dataPath with+ | .ok s => pure s+ | .error e => return ← emitError e+ let shapesTxt ← match ← readOrFail shapesPath with+ | .ok s => pure s+ | .error e => return ← emitError e+ let dataG ← match Parse.parseNTriples dataTxt with+ | .ok g => pure g+ | .error e => return ← emitError s!"data graph: {e}"+ let shapesG ← match Parse.parseNTriples shapesTxt with+ | .ok g => pure g+ | .error e => return ← emitError s!"shapes graph: {e}"+ let decls ← match Compile.compileShapes shapesG with+ | .ok d => pure d+ | .error e => return ← emitUndetermined s!"shapes graph not compiled: {e}"+ match validate dataG decls with+ | .error refusal =>+ emitUndetermined s!"the evaluator declined: {refusal.describe}"+ | .ok results =>+ let conforms := results.isEmpty+ IO.println ("{\"status\":\"verdict\",\"conforms\":" ++ (if conforms then "true" else "false") +++ ",\"shapes\":" ++ toString decls.length +++ ",\"data_triples\":" ++ toString dataG.length +++ ",\"results\":[" ++ String.intercalate "," (results.map showResult) ++ "]" +++ ",\"theorem\":\"Shacl.validate_spec\"}")+ return 0++def main (args : List String) : IO UInt32 := do+ match args with+ | ["validate", d, s] => run d s+ | _ =>+ IO.eprintln "usage: oo-shacl validate DATA.nt SHAPES.nt"+ return 2diff --git a/lean/lakefile.toml b/lean/lakefile.tomlindex 2388535e..b201b56a 100644--- a/lean/lakefile.toml+++ b/lean/lakefile.toml@@ -16,3 +16,15 @@ root = "Main"[[lean_exe]]name = "oo-horn"root = "HMain"++# SHACL Core, mechanised. Separate from `OOCert` on purpose: the derivation+# checker never looks inside a term and this one has to, so the two keep their+# own term modules and neither can break the other's build.+[[lean_lib]]+name = "Shacl"+roots = ["Shacl.All"]+globs = ["Shacl.+"]++[[lean_exe]]+name = "oo-shacl"+root = "ShaclMain"diff --git a/src/batch.rs b/src/batch.rsindex ab121362..a5cede8f 100644--- a/src/batch.rs+++ b/src/batch.rs@@ -239,12 +239,38 @@ impl BatchRunner {fn exec_reason(&self, args: &[String]) -> Value {use crate::reason::{InferenceTarget, Reasoner};let profile = Self::flag_value(args, "--profile")- .or_else(|| args.first().cloned())+ .or_else(|| args.first().filter(|a| !a.starts_with("--")).cloned()).unwrap_or("rdfs".to_string());let certificate = Self::flag_value(args, "--certificate");- let dir = certificate.as_deref().map(std::path::Path::new);- let result = Reasoner::run_full(&self.graph, &profile, true, InferenceTarget::DefaultGraph, dir)- .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));+ let rules = Self::flag_value(args, "--rules");+ // `--rules FILE` evaluates a SUPPLIED Horn table instead of a built-in+ // profile and writes a certificate `oo-horn check` can verify. It needs+ // somewhere to put that certificate: a run over rules nobody has+ // checked reports nothing about what it proved, so without the+ // certificate there would be nothing to check and the counts would+ // stand on the engine's word alone.+ let result = match (rules.as_deref(), certificate.as_deref()) {+ (Some(rules_path), Some(dir)) => Reasoner::run_horn(+ &self.graph,+ std::path::Path::new(rules_path),+ std::path::Path::new(dir),+ )+ .unwrap_or_else(|e| json!({"error": e.to_string()}).to_string()),+ (Some(_), None) => json!({+ "error": "reason --rules needs --certificate DIR. A run over a supplied rule \+ table states no verdict of its own: the certificate is the output, and \+ `lake exe oo-horn check` is what pronounces on it"+ })+ .to_string(),+ (None, cert) => Reasoner::run_full(+ &self.graph,+ &profile,+ true,+ InferenceTarget::DefaultGraph,+ cert.map(std::path::Path::new),+ )+ .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e)),+ };serde_json::from_str(&result).unwrap_or(json!({"raw": result}))}diff --git a/src/inputs.rs b/src/inputs.rsindex 634eda74..d0f12725 100644--- a/src/inputs.rs+++ b/src/inputs.rs@@ -268,6 +268,20 @@ pub struct OntoReasonInput {/// contains only entailed triples whatever this engine did. Not available/// for `owl-dl`.pub certificate_dir: Option<String>,+ /// Path to a SUPPLIED Horn rule table in the `rules.tsv` format the Lean+ /// checker reads (`name TAB bodyLength TAB (s TAB p TAB o)* TAB hs TAB hp+ /// TAB ho`, a field beginning with `?` being a variable). When given, the+ /// run evaluates THAT table to a fixpoint instead of a built-in profile,+ /// and writes `rules.tsv`, `asserted.tsv` and `horn.tsv` to+ /// `certificate_dir`, which is then required.+ ///+ /// Nothing is materialised, and the response states no verdict. A rule the+ /// user supplied is an assumption nobody has checked, so what a checked+ /// certificate establishes is truth in every model of the asserted graph+ /// that ALSO satisfies those rules. `lake exe oo-horn check` is what+ /// pronounces on that, and it distinguishes the built-in table from any+ /// other. See docs/decisions/0003.+ pub rules_file: Option<String>,}#[derive(Deserialize, JsonSchema)]diff --git a/src/main.rs b/src/main.rsindex ed505dca..25f5932c 100644--- a/src/main.rs+++ b/src/main.rs@@ -433,6 +433,15 @@ enum Commands {/// is a machine-checked theorem; see docs/lean-certificates.md.#[arg(long)]certificate: Option<String>,+ /// Evaluate a SUPPLIED Horn rule table instead of a built-in profile,+ /// in the `rules.tsv` format `oo-horn` reads (`oo-horn rules` prints+ /// the built-in table in it). Requires --certificate, because a run+ /// over rules nobody has checked reports nothing about what it proved:+ /// the certificate is the output, and `oo-horn check` is what+ /// pronounces on it. --profile is not run alongside it; the supplied+ /// table is the whole rule set for the run. Nothing is materialised.+ #[arg(long)]+ rules: Option<String>,},/// Full pipeline: ingest → SHACL → reasonExtend {@@ -624,12 +633,16 @@ impl Commands {Commands::Query { query } => cmd("query", vec![query.clone()]),Commands::Lint { input } => cmd("lint", vec![absolutize(input)]),Commands::Defects { input } => cmd("defects", vec![absolutize(input)]),- Commands::Reason { profile, certificate } => {+ Commands::Reason { profile, certificate, rules } => {let mut a = vec!["--profile".into(), profile.clone()];if let Some(c) = certificate {a.push("--certificate".into());a.push(absolutize(c));}+ if let Some(r) = rules {+ a.push("--rules".into());+ a.push(absolutize(r));+ }cmd("reason", a)}Commands::Shacl { shapes } => cmd("shacl", vec![absolutize(shapes)]),@@ -2312,12 +2325,36 @@ async fn async_main() -> anyhow::Result<()> {.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));output_result_checked(&result, cli.pretty);}- Commands::Reason { profile, certificate } => {+ Commands::Reason { profile, certificate, rules } => {use open_ontologies::reason::{InferenceTarget, Reasoner};let (_db, graph) = setup(&cli.data_dir)?;- let dir = certificate.as_deref().map(std::path::Path::new);- let result = Reasoner::run_full(&graph, &profile, true, InferenceTarget::DefaultGraph, dir)- .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));+ let result = match (rules.as_deref(), certificate.as_deref()) {+ // A supplied table and somewhere to put the certificate.+ (Some(rules_path), Some(dir)) => Reasoner::run_horn(+ &graph,+ std::path::Path::new(rules_path),+ std::path::Path::new(dir),+ )+ .unwrap_or_else(|e| serde_json::json!({"error": e.to_string()}).to_string()),+ // A supplied table and nowhere to put the certificate. The run+ // would report counts nothing can check, over rules nobody has+ // checked. Refuse rather than let the engine become a second+ // place that pronounces.+ (Some(_), None) => serde_json::json!({+ "error": "reason --rules needs --certificate DIR. A run over a supplied rule \+ table states no verdict of its own: the certificate is the output, \+ and `lake exe oo-horn check` is what pronounces on it"+ })+ .to_string(),+ (None, cert) => Reasoner::run_full(+ &graph,+ &profile,+ true,+ InferenceTarget::DefaultGraph,+ cert.map(std::path::Path::new),+ )+ .unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e)),+ };output_result_checked(&result, cli.pretty);}Commands::Extend {@@ -2833,7 +2870,7 @@ mod proxy_serialization_tests {Commands::Stats,Commands::Query { query: "SELECT ?s WHERE { ?s ?p ?o }".into() },Commands::Lint { input: "x.ttl".into() },- Commands::Reason { profile: "rdfs".into(), certificate: None },+ Commands::Reason { profile: "rdfs".into(), certificate: None, rules: None },Commands::Shacl { shapes: "s.ttl".into() },Commands::Status,Commands::Pull { url: "http://example.org".into(), sparql: false, query: None },diff --git a/src/reason.rs b/src/reason.rsindex bc696108..57f5cfc8 100644--- a/src/reason.rs+++ b/src/reason.rs@@ -774,3 +774,663 @@ impl Reasoner {Ok(result.to_string())}}++// ── User-supplied Horn rules ────────────────────────────────────────────────+//+// Everything above this line applies a rule set this file hardcodes. The+// checker in `lean/OOCert/Horn.lean` accepts a certificate over ANY rule table,+// proved once by `OOCert.horn_certificate_sound`, and until now nothing could+// produce one: the generic layer had a consumer and no producer, and a user+// with a rule table had nothing to hand it.+//+// What follows reads a rule table in the `rules.tsv` format+// `OOCert.HornParse.parseRules` accepts, evaluates it to a fixpoint over the+// loaded graph, and writes a certificate in the `horn.tsv` format+// `OOCert.HornParse.parseHornSteps` accepts.+//+// # This path states no verdict, and that is deliberate+//+// A certificate over the built-in table earns `entailed`: true in every model+// of the asserted graph, because `OOCert.Builtin.asHorn_sound` discharges those+// rules against the semantics. A certificate over a table a user wrote earns+// `entailed_under_supplied_rules`: true in every model of the graph THAT ALSO+// SATISFIES THOSE RULES. The rules are assumed and never checked, so a rule+// reading "every supplier is compliant" produces steps that check green for+// ever.+//+// `oo-horn` decides which of the two a run earned, by comparing the table it+// was given against the built-in one. This engine does not repeat that+// judgement in its own output and does not print either verdict word, because a+// second place where the two could be confused is exactly the hazard decision+// 0003 exists to prevent. What the engine reports is the table it used, a+// hash of it, and the command that pronounces.++/// One position of a triple pattern: a fixed term in its N-Triples spelling, or+/// a variable. Mirrors `OOCert.Pat`.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum Pat {+ Const(String),+ Var(String),+}++impl Pat {+ /// The `rules.tsv` spelling: `?x` for a variable, the term itself for a+ /// constant. Inverse of the parse below, and byte-identical to+ /// `OOCert.HornParse.patStr`.+ fn render(&self) -> String {+ match self {+ Pat::Const(c) => c.clone(),+ Pat::Var(v) => format!("?{v}"),+ }+ }+}++/// A triple pattern. Any of the three positions may be a variable, predicate+/// position included: `Interp` has one ternary extension, so a property is a+/// domain element like any other and the language stays first-order.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct AtomPat {+ pub s: Pat,+ pub p: Pat,+ pub o: Pat,+}++/// `forall vars. body -> head`, the quantifier left implicit. Mirrors+/// `OOCert.RulePattern`.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct RulePattern {+ pub name: String,+ pub body: Vec<AtomPat>,+ pub head: AtomPat,+}++impl RulePattern {+ fn atoms(&self) -> impl Iterator<Item = &AtomPat> {+ self.body.iter().chain(std::iter::once(&self.head))+ }+}++fn pat_vars<'a>(a: &'a AtomPat, out: &mut Vec<&'a str>) {+ for p in [&a.s, &a.p, &a.o] {+ if let Pat::Var(v) = p+ && !out.contains(&v.as_str())+ {+ out.push(v.as_str());+ }+ }+}++/// Parse one field of a rule table.+///+/// A field beginning with `?` is a variable, anything else a term, which is the+/// encoding `HornParse` documents: N-Triples terms begin with `<`, `_:` or `"`,+/// so nothing is ambiguous. This is stricter than `HornParse` on exactly one+/// point, and the strictness is the "reject rather than guess" direction: a+/// constant that is not in N-Triples spelling can never equal a term the store+/// holds, so a rule carrying one silently never fires. That is a typo, not a+/// rule, and it is refused rather than run.+fn parse_pat(field: &str, line: usize, which: &str) -> anyhow::Result<Pat> {+ if let Some(name) = field.strip_prefix('?') {+ if name.is_empty() {+ anyhow::bail!("rules line {line}: {which} is '?' with no variable name");+ }+ return Ok(Pat::Var(name.to_string()));+ }+ if field.starts_with('<') || field.starts_with("_:") || field.starts_with('"') {+ return Ok(Pat::Const(field.to_string()));+ }+ if field.is_empty() {+ anyhow::bail!("rules line {line}: {which} is empty");+ }+ anyhow::bail!(+ "rules line {line}: {which} is '{field}', which is neither a variable (?x) nor an \+ N-Triples term (<iri>, _:blank, or a quoted literal). The store spells every term in \+ N-Triples, so a constant in any other spelling would match nothing and the rule would \+ silently never fire"+ )+}++/// Read a rule table in the `rules.tsv` format `OOCert.HornParse.parseRules`+/// accepts: `name TAB bodyLength TAB (s TAB p TAB o)* TAB hs TAB hp TAB ho`.+///+/// Malformed input is an error naming the line and what was wrong, never a+/// guess. Two rejections go beyond what the Lean parser refuses, both because+/// this side has to PRODUCE bindings rather than check them:+///+/// * A head variable that does not occur in the body. The checker is right to+/// accept a certificate over such a rule, because `SatRule` quantifies over+/// every substitution, but the engine would have to invent a term to bind it+/// to. Refusing is the only honest option.+/// * A carriage return. `HornParse` splits on `\n` alone, so a CRLF file would+/// put a `\r` inside the last term of every line. Stripping it is a guess+/// about what the user meant; the error says to convert the file.+pub fn parse_rules(content: &str) -> anyhow::Result<Vec<RulePattern>> {+ let mut out: Vec<RulePattern> = Vec::new();+ for (i, line) in content.split('\n').enumerate() {+ let n = i + 1;+ if line.is_empty() {+ continue;+ }+ if line.contains('\r') {+ anyhow::bail!(+ "rules line {n}: the line contains a carriage return. The format is tab \+ separated with LF endings, and a CR would become part of a term; convert the \+ file rather than have it stripped silently"+ );+ }+ let fields: Vec<&str> = line.split('\t').collect();+ if fields.len() < 2 {+ anyhow::bail!(+ "rules line {n}: expected a name, a body length and then the patterns, got \+ {} tab-separated field(s)",+ fields.len()+ );+ }+ let name = fields[0];+ if name.is_empty() {+ anyhow::bail!("rules line {n}: the rule name is empty");+ }+ let len_field = fields[1];+ if len_field.is_empty() || !len_field.bytes().all(|b| b.is_ascii_digit()) {+ anyhow::bail!("rules line {n}: body length '{len_field}' is not a number");+ }+ let m: usize = len_field+ .parse()+ .map_err(|_| anyhow::anyhow!("rules line {n}: body length '{len_field}' is too large"))?;+ let rest = &fields[2..];+ let want = m+ .checked_mul(3)+ .and_then(|x| x.checked_add(3))+ .ok_or_else(|| anyhow::anyhow!("rules line {n}: body length '{len_field}' is too large"))?;+ if rest.len() != want {+ anyhow::bail!(+ "rules line {n}: a body of {m} atom(s) plus a head needs {want} pattern fields, \+ got {}",+ rest.len()+ );+ }+ let mut pats: Vec<Pat> = Vec::with_capacity(want);+ for (k, f) in rest.iter().enumerate() {+ let which = if k < 3 * m {+ format!("body atom {} position {}", k / 3 + 1, k % 3 + 1)+ } else {+ format!("head position {}", k - 3 * m + 1)+ };+ pats.push(parse_pat(f, n, &which)?);+ }+ let head = AtomPat {+ o: pats.pop().expect("head object"),+ p: pats.pop().expect("head predicate"),+ s: pats.pop().expect("head subject"),+ };+ let mut body: Vec<AtomPat> = Vec::with_capacity(m);+ let mut it = pats.into_iter();+ for _ in 0..m {+ let s = it.next().expect("body subject");+ let p = it.next().expect("body predicate");+ let o = it.next().expect("body object");+ body.push(AtomPat { s, p, o });+ }+ let rule = RulePattern { name: name.to_string(), body, head };++ let mut body_vars: Vec<&str> = Vec::new();+ for a in &rule.body {+ pat_vars(a, &mut body_vars);+ }+ let mut head_vars: Vec<&str> = Vec::new();+ pat_vars(&rule.head, &mut head_vars);+ for v in head_vars {+ if !body_vars.contains(&v) {+ anyhow::bail!(+ "rules line {n}: rule '{}' has head variable ?{v}, which does not occur in \+ the body. The engine has nothing to bind it to, so the table is refused \+ rather than run with a term invented for it",+ rule.name+ );+ }+ }+ out.push(rule);+ }+ Ok(out)+}++/// Render a rule table back to `rules.tsv`. Byte-identical to+/// `OOCert.HornParse.ruleStr` per line, so `oo-horn rules` and this agree and a+/// table read here and written back out digests to the same value it came in+/// with.+pub fn rules_tsv(rules: &[RulePattern]) -> String {+ let mut out = String::new();+ for r in rules {+ out.push_str(&r.name);+ out.push('\t');+ out.push_str(&r.body.len().to_string());+ for a in r.atoms() {+ for p in [&a.s, &a.p, &a.o] {+ out.push('\t');+ out.push_str(&p.render());+ }+ }+ out.push('\n');+ }+ out+}++/// A rule pattern position over interned ids, with variables resolved to a slot+/// in the rule's environment.+enum CPat {+ Const(u32),+ Var(usize),+}++struct CAtom {+ s: CPat,+ p: CPat,+ o: CPat,+}++struct CRule {+ vars: Vec<String>,+ body: Vec<CAtom>,+ head: CAtom,+}++/// One line of a Horn certificate: the rule index, the binding the engine used,+/// the premises it matched in the rule's body order, and what it concluded.+struct HornStepOut {+ rule: usize,+ binds: Vec<(String, u32)>,+ premises: Vec<Fact>,+ conclusion: Fact,+}++fn resolve_pat(p: &CPat, env: &[Option<u32>]) -> Option<u32> {+ match p {+ CPat::Const(id) => Some(*id),+ CPat::Var(i) => env[*i],+ }+}++/// Match one position against one term, binding a fresh variable and recording+/// the slot so the caller can undo it on backtracking.+fn unify_pat(p: &CPat, val: u32, env: &mut [Option<u32>], bound: &mut [usize; 3], nb: &mut usize) -> bool {+ match p {+ CPat::Const(id) => *id == val,+ CPat::Var(i) => match env[*i] {+ Some(existing) => existing == val,+ None => {+ env[*i] = Some(val);+ bound[*nb] = *i;+ *nb += 1;+ true+ }+ },+ }+}++/// Enumerate every way to match the body against the known facts, calling+/// `on_match` once per complete binding.+///+/// Plain backtracking, one atom at a time, left to right. An atom whose+/// predicate is already fixed (a constant, or a variable bound by an earlier+/// atom) is matched against the facts with that predicate; otherwise every fact+/// is a candidate. That is the whole optimisation, and it is not semi-naive+/// evaluation: each iteration re-derives what the last one did, and the+/// duplicate is dropped when its conclusion is found to be known. Correctness+/// first, as the task said. The cost is a constant factor per iteration on a+/// scan the loop does anyway, and `derived_triples` is unaffected.+fn match_body(+ atoms: &[CAtom],+ i: usize,+ env: &mut Vec<Option<u32>>,+ all: &[Fact],+ by_pred: &HashMap<u32, Vec<Fact>>,+ on_match: &mut dyn FnMut(&[Option<u32>]),+) {+ if i == atoms.len() {+ on_match(env);+ return;+ }+ let a = &atoms[i];+ let candidates: &[Fact] = match resolve_pat(&a.p, env) {+ Some(pid) => by_pred.get(&pid).map(Vec::as_slice).unwrap_or(&[]),+ None => all,+ };+ for &(s, p, o) in candidates {+ let mut bound = [0usize; 3];+ let mut nb = 0usize;+ let ok = unify_pat(&a.s, s, env, &mut bound, &mut nb)+ && unify_pat(&a.p, p, env, &mut bound, &mut nb)+ && unify_pat(&a.o, o, env, &mut bound, &mut nb);+ if ok {+ match_body(atoms, i + 1, env, all, by_pred, on_match);+ }+ for slot in bound.iter().take(nb) {+ env[*slot] = None;+ }+ }+}++fn inst_atom(a: &CAtom, env: &[Option<u32>]) -> Fact {+ const WHY: &str = "every variable of a matched rule is bound: the body is matched in full and \+ parse_rules refuses a head variable that does not occur in the body";+ (+ resolve_pat(&a.s, env).expect(WHY),+ resolve_pat(&a.p, env).expect(WHY),+ resolve_pat(&a.o, env).expect(WHY),+ )+}++impl Reasoner {+ /// Evaluate a SUPPLIED Horn rule table over the loaded graph and write a+ /// certificate `lean`'s `oo-horn` can check.+ ///+ /// Three files land in `certificate_dir`:+ ///+ /// * `rules.tsv`, the table as the engine parsed it. The checker is given+ /// this rather than the user's file, so what it checks and what the run+ /// used are the same table.+ /// * `asserted.tsv`, every triple the run started from.+ /// * `horn.tsv`, one line per derived triple:+ /// `ruleIndex TAB bindCount TAB (var TAB term)* TAB cs TAB cp TAB co TAB (ps TAB pp TAB po)*`.+ /// The binding is written out in full and the premises are the body+ /// instantiated, in the body's order, because that is what+ /// `OOCert.checkHornStep` demands: a binding that does not instantiate+ /// the body, or premises in the wrong order, is rejected.+ ///+ /// Steps are written in derivation order, and a step's premises are always+ /// facts that were known before the round that derived it, so every premise+ /// is asserted or concluded by an EARLIER line. That is the ordering+ /// `OOCert.checkHornAll` requires, and no step can cite itself.+ ///+ /// Nothing is materialised into the store. A conclusion under a supplied+ /// table holds only in models that satisfy that table, and writing it in+ /// beside the assertions would lose exactly the distinction decision 0003+ /// is about.+ pub fn run_horn(+ graph: &Arc<GraphStore>,+ rules_path: &std::path::Path,+ certificate_dir: &std::path::Path,+ ) -> anyhow::Result<String> {+ let rules_text = std::fs::read_to_string(rules_path)+ .map_err(|e| anyhow::anyhow!("cannot read rule table {}: {e}", rules_path.display()))?;+ let rules = parse_rules(&rules_text)+ .map_err(|e| anyhow::anyhow!("{} is not a rule table: {e}", rules_path.display()))?;+ if rules.is_empty() {+ anyhow::bail!(+ "{} holds no rules. An empty table derives nothing, so there is no certificate \+ to write",+ rules_path.display()+ );+ }++ let raw_triples = graph.all_triples()?;+ let mut interner = Interner::new();+ let mut facts: Vec<Fact> = Vec::with_capacity(raw_triples.len());+ for (s, p, o) in &raw_triples {+ facts.push((interner.intern(s), interner.intern(p), interner.intern(o)));+ }++ // Compile the table over the interner. A constant the graph never+ // mentions still gets an id; it simply matches nothing, which is what+ // it should do.+ let mut crules: Vec<CRule> = Vec::with_capacity(rules.len());+ for r in &rules {+ let mut vars: Vec<String> = Vec::new();+ for a in r.atoms() {+ for p in [&a.s, &a.p, &a.o] {+ if let Pat::Var(v) = p+ && !vars.iter().any(|x| x == v)+ {+ vars.push(v.clone());+ }+ }+ }+ let mut compile = |p: &Pat| match p {+ Pat::Const(c) => CPat::Const(interner.intern(c)),+ Pat::Var(v) => CPat::Var(vars.iter().position(|x| x == v).expect("var listed")),+ };+ let body: Vec<CAtom> = r+ .body+ .iter()+ .map(|a| CAtom { s: compile(&a.s), p: compile(&a.p), o: compile(&a.o) })+ .collect();+ let head = CAtom { s: compile(&r.head.s), p: compile(&r.head.p), o: compile(&r.head.o) };+ crules.push(CRule { vars, body, head });+ }++ // A rule whose head puts a literal in subject position, or anything but+ // an IRI in predicate position, produces something no RDF serialiser+ // can write. The built-in loop guards the first case for four of its+ // rules; here both are refused, the count is reported, and the+ // conclusion is not used as a premise for anything else. Deriving less+ // is the sound direction, but it means the emitted set is the fixpoint+ // of the table over WRITABLE triples, which is what+ // `skipped_unserialisable` in the response is there to say.+ let serialisable = |interner: &Interner, (s, p, _o): Fact| -> bool {+ !interner.resolve(s).starts_with('"') && interner.resolve(p).starts_with('<')+ };++ let mut known: HashSet<Fact> = facts.iter().copied().collect();+ let asserted_count = known.len();+ let mut steps: Vec<HornStepOut> = Vec::new();+ // Distinct conclusions refused for being unwritable. A set rather than+ // a counter because a refused conclusion is never added to `known`, so+ // every later round matches the same body again and re-derives it: a+ // counter would report attempts and grow with the iteration count,+ // which is not what a reader takes "skipped 2" to mean.+ let mut refused: HashSet<Fact> = HashSet::new();+ let mut skipped_samples: Vec<String> = Vec::new();+ let mut iterations = 0usize;+ let mut fixpoint = false;+ let max_iterations = crate::runtime::reasoner_max_iterations();++ while iterations < max_iterations {+ iterations += 1;++ // Sorted so the candidate order, and therefore the order of the+ // lines in `horn.tsv`, does not depend on hash iteration order.+ let mut all: Vec<Fact> = known.iter().copied().collect();+ all.sort_unstable();+ let mut by_pred: HashMap<u32, Vec<Fact>> = HashMap::new();+ for &f in &all {+ by_pred.entry(f.1).or_default().push(f);+ }++ let mut round: Vec<HornStepOut> = Vec::new();+ let mut pending: HashSet<Fact> = HashSet::new();+ for (ri, rule) in crules.iter().enumerate() {+ let mut env: Vec<Option<u32>> = vec![None; rule.vars.len()];+ let known_ref = &known;+ let interner_ref = &interner;+ let round_ref = &mut round;+ let pending_ref = &mut pending;+ let refused_ref = &mut refused;+ let samples_ref = &mut skipped_samples;+ match_body(&rule.body, 0, &mut env, &all, &by_pred, &mut |env| {+ let conclusion = inst_atom(&rule.head, env);+ if known_ref.contains(&conclusion) || pending_ref.contains(&conclusion) {+ return;+ }+ if !serialisable(interner_ref, conclusion) {+ if refused_ref.insert(conclusion) && samples_ref.len() < 3 {+ samples_ref.push(format!(+ "{} {} {}",+ interner_ref.resolve(conclusion.0),+ interner_ref.resolve(conclusion.1),+ interner_ref.resolve(conclusion.2)+ ));+ }+ return;+ }+ pending_ref.insert(conclusion);+ round_ref.push(HornStepOut {+ rule: ri,+ binds: rule+ .vars+ .iter()+ .enumerate()+ .map(|(i, v)| (v.clone(), env[i].expect("matched body binds every body variable")))+ .collect(),+ premises: rule.body.iter().map(|a| inst_atom(a, env)).collect(),+ conclusion,+ });+ });+ }++ if round.is_empty() {+ fixpoint = true;+ break;+ }+ for st in round {+ known.insert(st.conclusion);+ steps.push(st);+ }+ }++ // Write the three files.+ std::fs::create_dir_all(certificate_dir)?;+ let canonical_rules = rules_tsv(&rules);+ // The checker verifies the steps against the FILE, and the run+ // evaluated the table in memory. If the rendering lost or changed+ // anything the two would be different rule sets, and a step would be+ // checked against a rule nobody ran. Reading the file back and+ // comparing costs nothing and closes that gap; a mismatch is a bug in+ // this file, so it stops the run rather than writing a certificate+ // whose meaning is not the run's.+ match parse_rules(&canonical_rules) {+ Ok(reparsed) if reparsed == rules => {}+ Ok(_) => anyhow::bail!(+ "internal: the rule table this engine writes does not read back as the table it \+ evaluated, so the certificate would be checked against different rules. Refusing \+ to write it"+ ),+ Err(e) => anyhow::bail!(+ "internal: the rule table this engine writes does not parse ({e}), so the checker \+ could not read it. Refusing to write it"+ ),+ }+ std::fs::write(certificate_dir.join("rules.tsv"), &canonical_rules)?;++ let mut asserted = String::with_capacity(facts.len() * 96);+ for &(s, p, o) in &facts {+ asserted.push_str(interner.resolve(s));+ asserted.push('\t');+ asserted.push_str(interner.resolve(p));+ asserted.push('\t');+ asserted.push_str(interner.resolve(o));+ asserted.push('\n');+ }+ std::fs::write(certificate_dir.join("asserted.tsv"), asserted)?;++ let mut horn = String::with_capacity(steps.len() * 256);+ let mut by_rule: Vec<usize> = vec![0; rules.len()];+ for st in &steps {+ by_rule[st.rule] += 1;+ horn.push_str(&st.rule.to_string());+ horn.push('\t');+ horn.push_str(&st.binds.len().to_string());+ for (v, term) in &st.binds {+ horn.push('\t');+ horn.push_str(v);+ horn.push('\t');+ horn.push_str(interner.resolve(*term));+ }+ for &(s, p, o) in std::iter::once(&st.conclusion).chain(st.premises.iter()) {+ horn.push('\t');+ horn.push_str(interner.resolve(s));+ horn.push('\t');+ horn.push_str(interner.resolve(p));+ horn.push('\t');+ horn.push_str(interner.resolve(o));+ }+ horn.push('\n');+ }+ std::fs::write(certificate_dir.join("horn.tsv"), horn)?;++ let digest = {+ use sha2::{Digest, Sha256};+ format!("{:x}", Sha256::digest(canonical_rules.as_bytes()))+ };+ let per_rule: Vec<serde_json::Value> = rules+ .iter()+ .enumerate()+ .map(|(i, r)| {+ serde_json::json!({"index": i, "name": r.name, "derivations": by_rule[i]})+ })+ .collect();+ let sample: Vec<String> = steps+ .iter()+ .take(10)+ .map(|st| {+ format!(+ "{} {} {}",+ interner.resolve(st.conclusion.0),+ interner.resolve(st.conclusion.1),+ interner.resolve(st.conclusion.2)+ )+ })+ .collect();+ let dir = certificate_dir.display().to_string();++ let mut result = serde_json::json!({+ "mode": "horn",+ "rules_file": rules_path.display().to_string(),+ "rules": rules.len(),+ "asserted_triples": facts.len(),+ "distinct_asserted_triples": asserted_count,+ "derived_triples": steps.len(),+ "iterations": iterations,+ "fixpoint_reached": fixpoint,+ "skipped_unserialisable": refused.len(),+ "materialized": false,+ "why_not_materialized":+ "a conclusion drawn under a supplied rule table holds only in models that satisfy \+ that table, so it is not written into the store beside the assertions. The \+ certificate is the output of this run",+ "conditional_on":+ format!("the rules in {}, which this run ASSUMED and never checked. A certificate \+ is only as good as the table it cites: a rule saying every supplier is \+ compliant produces steps that check green for ever",+ rules_path.display()),+ "sample_derivations": sample,+ "certificate": {+ "dir": dir,+ "format": "oo-horn/1",+ "rules": rules.len(),+ "rules_tsv_sha256": digest,+ "asserted": facts.len(),+ "derivations": steps.len(),+ "by_rule": per_rule,+ "check_with": format!(+ "cd lean && lake exe oo-horn check {d}/rules.tsv {d}/asserted.tsv {d}/horn.tsv",+ d = certificate_dir.display()+ ),+ "pronounced_by":+ "lean/, through `oo-horn check`, which decides what this run earned by \+ comparing the table against the built-in one. This engine emits the \+ certificate and states no verdict of its own",+ }+ });+ if !fixpoint {+ // An iteration cap reached with work still to do is not a fixpoint,+ // and a count from such a run is a lower bound. Say it in the+ // result rather than let the caller read `derived_triples` as the+ // closure.+ result["incomplete"] = serde_json::json!(format!(+ "the run stopped at the {max_iterations}-iteration cap with rules still firing. \+ Every step in the certificate is still a step the checker can verify, but \+ derived_triples is a LOWER BOUND on the closure of this table, not the closure"+ ));+ }+ if !refused.is_empty() {+ result["skipped_examples"] = serde_json::json!(skipped_samples);+ result["skipped_reason"] = serde_json::json!(+ "the rule head instantiated to a triple no RDF serialiser can write (a literal in \+ subject position, or a non-IRI in predicate position). Such conclusions are \+ neither certified nor used as premises, so this run derives LESS than the table \+ licenses"+ );+ }+ Ok(result.to_string())+ }+}diff --git a/src/server.rs b/src/server.rsindex 3cf6041e..9dff0247 100644--- a/src/server.rs+++ b/src/server.rs@@ -1876,9 +1876,40 @@ impl OpenOntologiesServer {body.to_string()}- #[tool(name = "onto_reason", description = "Run inference over the loaded ontology. Profiles: 'rdfs' (subclass, domain/range), 'owl-rl' (+ transitive/symmetric/inverse, sameAs, equivalentClass), 'owl-rl-ext' (+ someValuesFrom, allValuesFrom, hasValue, intersectionOf, unionOf), 'owl-dl' (SHIQ tableaux: satisfiability, classification, qualified number restrictions with node merging, inverse/symmetric roles, functional properties, parallel agent-based classification, explanation traces, ABox reasoning. Nominals are not implemented: owl:oneOf is not read and owl:hasValue is approximated as an atomic concept, so an ontology that uses either returns undetermined classes rather than a classification. Datatype ranges are skipped). Materializes inferred triples. Set `inference_graph` to keep them in a separate graph, where nothing downstream can read an inference as an assertion and a Turtle/RDF-XML save cannot publish one.")]+ #[tool(name = "onto_reason", description = "Run inference over the loaded ontology. Profiles: 'rdfs' (subclass, domain/range), 'owl-rl' (+ transitive/symmetric/inverse, sameAs, equivalentClass), 'owl-rl-ext' (+ someValuesFrom, allValuesFrom, hasValue, intersectionOf, unionOf), 'owl-dl' (SHIQ tableaux: satisfiability, classification, qualified number restrictions with node merging, inverse/symmetric roles, functional properties, parallel agent-based classification, explanation traces, ABox reasoning. Nominals are not implemented: owl:oneOf is not read and owl:hasValue is approximated as an atomic concept, so an ontology that uses either returns undetermined classes rather than a classification. Datatype ranges are skipped). Materializes inferred triples. Set `inference_graph` to keep them in a separate graph, where nothing downstream can read an inference as an assertion and a Turtle/RDF-XML save cannot publish one. Pass `rules_file` to evaluate a SUPPLIED Horn rule table instead of a built-in profile: it needs `certificate_dir`, materialises nothing, and writes a certificate the proved-sound Lean checker verifies with `lake exe oo-horn check`. The verdict comes from that checker and not from here, because rules you supply are assumed and never checked: a conclusion then holds in every model of the asserted graph that ALSO satisfies your rules.")]async fn onto_reason(&self, Parameters(input): Parameters<OntoReasonInput>) -> String {use crate::reason::Reasoner;+ // A supplied Horn rule table takes a different path: it is evaluated+ // instead of a built-in profile, it materialises nothing, and the+ // response carries no verdict, because a rule the caller wrote is an+ // assumption and `oo-horn check` is what pronounces on a certificate+ // over it. Anything the caller asked for that this path cannot honour+ // is refused rather than ignored in silence.+ if let Some(rules_file) = input.rules_file.as_deref() {+ let Some(dir) = input.certificate_dir.as_deref() else {+ return serde_json::json!({+ "error": "rules_file needs certificate_dir. A run over a supplied rule table \+ states no verdict of its own: the certificate is the output, and \+ `lake exe oo-horn check` is what pronounces on it"+ })+ .to_string();+ };+ if input.materialize == Some(true) || input.inference_graph == Some(true) {+ return serde_json::json!({+ "error": "rules_file does not materialise. A conclusion drawn under a rule \+ table nobody has checked holds only in models that satisfy that \+ table, so it is not written into the store; drop materialize / \+ inference_graph to run it"+ })+ .to_string();+ }+ return Reasoner::run_horn(+ &self.graph,+ std::path::Path::new(rules_file),+ std::path::Path::new(dir),+ )+ .unwrap_or_else(Self::err_json);+ }let profile = input.profile.as_deref().unwrap_or("rdfs");let materialize = input.materialize.unwrap_or(true);let target = if input.inference_graph.unwrap_or(false) {diff --git a/tests/fixtures/shaclcore/baseline.json b/tests/fixtures/shaclcore/baseline.jsonnew file mode 100644index 00000000..e1a4d4ff--- /dev/null+++ b/tests/fixtures/shaclcore/baseline.json@@ -0,0 +1,134 @@+{+ "note": "W3C SHACL Core conformance of the VERIFIED evaluator in lean/Shacl/, ratcheted. PASS may not drop, FAIL may not rise, and no named PASS may regress. Regenerate with OO_SHACL_CORE_UPDATE_BASELINE=1 cargo test --test shacl_core_verified_test. UNDETERMINED is a refusal, not a pass; moving a test out of it lands as a PASS and the ratchet counts that.",+ "suite_commit": "94d8bc2bd4fc4fdc6f2964d1ec4a892329e05f06",+ "counts": {+ "total": 120,+ "pass": 46,+ "fail": 0,+ "undetermined": 74,+ "error": 0+ },+ "partial_compliance": 46,+ "outcomes": {+ "core/complex/personexample": "UNDETERMINED",+ "core/complex/shacl-shacl": "UNDETERMINED",+ "core/misc/deactivated-001": "PASS",+ "core/misc/deactivated-002": "PASS",+ "core/misc/message-001": "PASS",+ "core/misc/severity-001": "PASS",+ "core/misc/severity-002": "PASS",+ "core/node/and-001": "PASS",+ "core/node/and-002": "PASS",+ "core/node/class-001": "PASS",+ "core/node/class-002": "PASS",+ "core/node/class-003": "PASS",+ "core/node/closed-001": "UNDETERMINED",+ "core/node/closed-002": "UNDETERMINED",+ "core/node/datatype-001": "PASS",+ "core/node/datatype-002": "PASS",+ "core/node/disjoint-001": "UNDETERMINED",+ "core/node/equals-001": "UNDETERMINED",+ "core/node/hasValue-001": "PASS",+ "core/node/in-001": "PASS",+ "core/node/languageIn-001": "UNDETERMINED",+ "core/node/maxExclusive-001": "UNDETERMINED",+ "core/node/maxInclusive-001": "UNDETERMINED",+ "core/node/maxLength-001": "UNDETERMINED",+ "core/node/minExclusive-001": "UNDETERMINED",+ "core/node/minInclusive-001": "UNDETERMINED",+ "core/node/minInclusive-002": "UNDETERMINED",+ "core/node/minInclusive-003": "UNDETERMINED",+ "core/node/minLength-001": "UNDETERMINED",+ "core/node/node-001": "PASS",+ "core/node/nodeKind-001": "PASS",+ "core/node/not-001": "PASS",+ "core/node/not-002": "PASS",+ "core/node/or-001": "PASS",+ "core/node/pattern-001": "UNDETERMINED",+ "core/node/pattern-002": "UNDETERMINED",+ "core/node/qualified-001": "UNDETERMINED",+ "core/node/xone-001": "UNDETERMINED",+ "core/node/xone-duplicate": "UNDETERMINED",+ "core/path/path-alternative-001": "UNDETERMINED",+ "core/path/path-complex-001": "UNDETERMINED",+ "core/path/path-complex-002": "UNDETERMINED",+ "core/path/path-inverse-001": "PASS",+ "core/path/path-oneOrMore-001": "UNDETERMINED",+ "core/path/path-sequence-001": "UNDETERMINED",+ "core/path/path-sequence-002": "UNDETERMINED",+ "core/path/path-sequence-duplicate-001": "UNDETERMINED",+ "core/path/path-strange-001": "UNDETERMINED",+ "core/path/path-strange-002": "UNDETERMINED",+ "core/path/path-unused-001": "PASS",+ "core/path/path-zeroOrMore-001": "UNDETERMINED",+ "core/path/path-zeroOrOne-001": "UNDETERMINED",+ "core/property/and-001": "PASS",+ "core/property/class-001": "PASS",+ "core/property/datatype-001": "UNDETERMINED",+ "core/property/datatype-002": "PASS",+ "core/property/datatype-003": "PASS",+ "core/property/datatype-ill-formed": "PASS",+ "core/property/disjoint-001": "UNDETERMINED",+ "core/property/equals-001": "UNDETERMINED",+ "core/property/hasValue-001": "PASS",+ "core/property/in-001": "PASS",+ "core/property/languageIn-001": "UNDETERMINED",+ "core/property/lessThan-001": "UNDETERMINED",+ "core/property/lessThan-002": "UNDETERMINED",+ "core/property/lessThanOrEquals-001": "UNDETERMINED",+ "core/property/maxCount-001": "PASS",+ "core/property/maxCount-002": "PASS",+ "core/property/maxExclusive-001": "UNDETERMINED",+ "core/property/maxInclusive-001": "UNDETERMINED",+ "core/property/maxLength-001": "UNDETERMINED",+ "core/property/minCount-001": "PASS",+ "core/property/minCount-002": "PASS",+ "core/property/minExclusive-001": "UNDETERMINED",+ "core/property/minExclusive-002": "UNDETERMINED",+ "core/property/minLength-001": "UNDETERMINED",+ "core/property/node-001": "PASS",+ "core/property/node-002": "PASS",+ "core/property/nodeKind-001": "PASS",+ "core/property/not-001": "PASS",+ "core/property/or-001": "PASS",+ "core/property/or-datatypes-001": "UNDETERMINED",+ "core/property/pattern-001": "UNDETERMINED",+ "core/property/pattern-002": "UNDETERMINED",+ "core/property/property-001": "PASS",+ "core/property/qualifiedMinCountDisjoint-001": "UNDETERMINED",+ "core/property/qualifiedValueShape-001": "UNDETERMINED",+ "core/property/qualifiedValueShapesDisjoint-001": "UNDETERMINED",+ "core/property/uniqueLang-001": "UNDETERMINED",+ "core/property/uniqueLang-002": "UNDETERMINED",+ "core/targets/multipleTargets-001": "PASS",+ "core/targets/targetClass-001": "PASS",+ "core/targets/targetClassImplicit-001": "PASS",+ "core/targets/targetNode-001": "PASS",+ "core/targets/targetObjectsOf-001": "PASS",+ "core/targets/targetSubjectsOf-001": "PASS",+ "core/targets/targetSubjectsOf-002": "PASS",+ "core/validation-reports/shared": "PASS",+ "sparql/component/optional-001": "UNDETERMINED",+ "sparql/component/propertyValidator-select-001": "UNDETERMINED",+ "sparql/component/validator-001": "UNDETERMINED",+ "sparql/node/prefixes-001": "UNDETERMINED",+ "sparql/node/sparql-001": "UNDETERMINED",+ "sparql/node/sparql-002": "UNDETERMINED",+ "sparql/node/sparql-003": "UNDETERMINED",+ "sparql/pre-binding/pre-binding-001": "UNDETERMINED",+ "sparql/pre-binding/pre-binding-002": "UNDETERMINED",+ "sparql/pre-binding/pre-binding-003": "UNDETERMINED",+ "sparql/pre-binding/pre-binding-004": "UNDETERMINED",+ "sparql/pre-binding/pre-binding-005": "UNDETERMINED",+ "sparql/pre-binding/pre-binding-006": "UNDETERMINED",+ "sparql/pre-binding/pre-binding-007": "UNDETERMINED",+ "sparql/pre-binding/shapesGraph-001": "UNDETERMINED",+ "sparql/pre-binding/unsupported-sparql-001": "UNDETERMINED",+ "sparql/pre-binding/unsupported-sparql-002": "UNDETERMINED",+ "sparql/pre-binding/unsupported-sparql-003": "UNDETERMINED",+ "sparql/pre-binding/unsupported-sparql-004": "UNDETERMINED",+ "sparql/pre-binding/unsupported-sparql-005": "UNDETERMINED",+ "sparql/pre-binding/unsupported-sparql-006": "UNDETERMINED",+ "sparql/property/sparql-001": "UNDETERMINED"+ }+}\ No newline at end of filediff --git a/tests/fixtures/shaclcore/component-shapes.nt b/tests/fixtures/shaclcore/component-shapes.ntnew file mode 100644index 00000000..5c7fb3e2--- /dev/null+++ b/tests/fixtures/shaclcore/component-shapes.nt@@ -0,0 +1,7 @@+# A user-defined constraint component. Its parameter lives outside the sh: namespace,+# so the per-shape parameter check cannot see it: the whole graph must be refused.+<http://ex.org/MyComponent> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/ns/shacl#ConstraintComponent> .+<http://ex.org/MyComponent> <http://www.w3.org/ns/shacl#parameter> <http://ex.org/myParam> .+<http://ex.org/S> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/ns/shacl#NodeShape> .+<http://ex.org/S> <http://www.w3.org/ns/shacl#targetClass> <http://ex.org/Person> .+<http://ex.org/S> <http://ex.org/myParam> "anything" .diff --git a/tests/fixtures/shaclcore/conforming-data.nt b/tests/fixtures/shaclcore/conforming-data.ntnew file mode 100644index 00000000..151c5d71--- /dev/null+++ b/tests/fixtures/shaclcore/conforming-data.nt@@ -0,0 +1,2 @@+<http://ex.org/alice> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Person> .+<http://ex.org/alice> <http://ex.org/name> "Alice" .diff --git a/tests/fixtures/shaclcore/duplicate-data.nt b/tests/fixtures/shaclcore/duplicate-data.ntnew file mode 100644index 00000000..947b0b21--- /dev/null+++ b/tests/fixtures/shaclcore/duplicate-data.nt@@ -0,0 +1,5 @@+# The same triple twice. sh:maxCount counts value nodes, not statements, so this+# must still conform. A validator that counts SPARQL solutions gets it wrong.+<http://ex.org/alice> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Person> .+<http://ex.org/alice> <http://ex.org/name> "Alice" .+<http://ex.org/alice> <http://ex.org/name> "Alice" .diff --git a/tests/fixtures/shaclcore/malformed.nt b/tests/fixtures/shaclcore/malformed.ntnew file mode 100644index 00000000..f755a622--- /dev/null+++ b/tests/fixtures/shaclcore/malformed.nt@@ -0,0 +1 @@+<http://ex.org/alice> <http://ex.org/name> "Alice"diff --git a/tests/fixtures/shaclcore/ok-shapes.nt b/tests/fixtures/shaclcore/ok-shapes.ntnew file mode 100644index 00000000..765c8d2d--- /dev/null+++ b/tests/fixtures/shaclcore/ok-shapes.nt@@ -0,0 +1,8 @@+# A node shape with a class target and one property shape: exactly one name, a string.+<http://ex.org/S> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/ns/shacl#NodeShape> .+<http://ex.org/S> <http://www.w3.org/ns/shacl#targetClass> <http://ex.org/Person> .+<http://ex.org/S> <http://www.w3.org/ns/shacl#property> <http://ex.org/NameShape> .+<http://ex.org/NameShape> <http://www.w3.org/ns/shacl#path> <http://ex.org/name> .+<http://ex.org/NameShape> <http://www.w3.org/ns/shacl#minCount> "1"^^<http://www.w3.org/2001/XMLSchema#integer> .+<http://ex.org/NameShape> <http://www.w3.org/ns/shacl#maxCount> "1"^^<http://www.w3.org/2001/XMLSchema#integer> .+<http://ex.org/NameShape> <http://www.w3.org/ns/shacl#datatype> <http://www.w3.org/2001/XMLSchema#string> .diff --git a/tests/fixtures/shaclcore/recursive-shapes.nt b/tests/fixtures/shaclcore/recursive-shapes.ntnew file mode 100644index 00000000..bbc50687--- /dev/null+++ b/tests/fixtures/shaclcore/recursive-shapes.nt@@ -0,0 +1,6 @@+# A shape that reaches itself through sh:node. SHACL does not define the semantics+# of recursive shapes, so the compiler must refuse rather than pick one.+<http://ex.org/S> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/ns/shacl#NodeShape> .+<http://ex.org/S> <http://www.w3.org/ns/shacl#targetClass> <http://ex.org/Person> .+<http://ex.org/S> <http://www.w3.org/ns/shacl#node> <http://ex.org/T> .+<http://ex.org/T> <http://www.w3.org/ns/shacl#node> <http://ex.org/S> .diff --git a/tests/fixtures/shaclcore/unknown-datatype-data.nt b/tests/fixtures/shaclcore/unknown-datatype-data.ntnew file mode 100644index 00000000..4dec3bd1--- /dev/null+++ b/tests/fixtures/shaclcore/unknown-datatype-data.nt@@ -0,0 +1 @@+<http://ex.org/alice> <http://ex.org/born> "1999-01-31"^^<http://www.w3.org/2001/XMLSchema#date> .diff --git a/tests/fixtures/shaclcore/unknown-datatype-shapes.nt b/tests/fixtures/shaclcore/unknown-datatype-shapes.ntnew file mode 100644index 00000000..c91c034a--- /dev/null+++ b/tests/fixtures/shaclcore/unknown-datatype-shapes.nt@@ -0,0 +1,7 @@+# xsd:date: the datatype IRI matches, so the answer turns on well-formedness, and+# this development does not know xsd:date's lexical space. It must decline.+<http://ex.org/S> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/ns/shacl#NodeShape> .+<http://ex.org/S> <http://www.w3.org/ns/shacl#targetNode> <http://ex.org/alice> .+<http://ex.org/S> <http://www.w3.org/ns/shacl#property> <http://ex.org/BornShape> .+<http://ex.org/BornShape> <http://www.w3.org/ns/shacl#path> <http://ex.org/born> .+<http://ex.org/BornShape> <http://www.w3.org/ns/shacl#datatype> <http://www.w3.org/2001/XMLSchema#date> .diff --git a/tests/fixtures/shaclcore/unsupported-shapes.nt b/tests/fixtures/shaclcore/unsupported-shapes.ntnew file mode 100644index 00000000..bca03bb6--- /dev/null+++ b/tests/fixtures/shaclcore/unsupported-shapes.nt@@ -0,0 +1,6 @@+# sh:pattern is not implemented. The compiler must refuse and name it.+<http://ex.org/S> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/ns/shacl#NodeShape> .+<http://ex.org/S> <http://www.w3.org/ns/shacl#targetClass> <http://ex.org/Person> .+<http://ex.org/S> <http://www.w3.org/ns/shacl#property> <http://ex.org/NameShape> .+<http://ex.org/NameShape> <http://www.w3.org/ns/shacl#path> <http://ex.org/name> .+<http://ex.org/NameShape> <http://www.w3.org/ns/shacl#pattern> "^A" .diff --git a/tests/fixtures/shaclcore/violating-data.nt b/tests/fixtures/shaclcore/violating-data.ntnew file mode 100644index 00000000..5edbd27f--- /dev/null+++ b/tests/fixtures/shaclcore/violating-data.nt@@ -0,0 +1,4 @@+<http://ex.org/alice> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Person> .+<http://ex.org/bob> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/Person> .+<http://ex.org/bob> <http://ex.org/name> "Bob" .+<http://ex.org/bob> <http://ex.org/name> "Robert" .diff --git a/tests/lean_mixed_certificate_test.rs b/tests/lean_mixed_certificate_test.rsnew file mode 100644index 00000000..d3022747--- /dev/null+++ b/tests/lean_mixed_certificate_test.rs@@ -0,0 +1,436 @@+//! One certificate carrying both rule families.+//!+//! Until `lean/OOCert/Mixed.lean` landed, a certificate was either all built-in+//! arms (`OOCert.certificate_sound`) or all citations of a user-supplied Horn+//! rule (`OOCert.horn_certificate_sound`). That split is not cosmetic.+//! `cls-int1` and `cls-uni` read an RDF list off the graph, so their premise+//! count is the length of that list rather than something the rule fixes, and+//! they are never going to become Horn rules. A user with one rule of their own+//! therefore could not cite them at all.+//!+//! `OOCert.checkCertM` accepts both step kinds and `OOCert.mixed_certificate_sound`+//! covers both in one induction. The certificate exercised below is the smallest+//! one that needs the feature: a `cls-int1` step concludes that acme is a+//! `Supplier`, and a step citing a rule the checker has never heard of turns that+//! into a compliance claim.+//!+//! # The distinction these tests exist to protect+//!+//! A mixed certificate over a table the user supplied proves the RELATIVE+//! guarantee: every conclusion is true in every model of the asserted graph that+//! ALSO satisfies those rules. Nothing checks the rules. The rule used here is+//! decision 0003's own example, "every supplier is compliant", and+//! `OOCert.mix_not_absolutely_entailed` is a machine-checked proof that its+//! conclusion does NOT follow from the asserted graph alone: there is a model of+//! that graph in which acme has no status at all.+//!+//! So a run over this table must print `entailed_under_supplied_rules` and must+//! never print `entailed`. `a_user_rule_never_earns_the_absolute_verdict` is the+//! test that fails if it ever does, and `OOCert.absolute_verdict_is_earned` is+//! the theorem that says the report function cannot do it in the first place.+//!+//! # How these tests run Lean+//!+//! There is no `oo-mixed` binary. Adding one means editing `lean/lakefile.toml`,+//! which this change does not own, so each case is a small generated Lean file+//! run through `lake env lean --run`. It imports the same library `lake build`+//! proved and calls the same `checkCertM`. What it does NOT exercise is a file+//! format: there is no parser for a mixed certificate yet, and the certificates+//! below are Lean terms rather than TSV. That is a real gap, stated here rather+//! than left to be discovered.++mod common;++use std::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 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 built() -> bool {+ static BUILT: OnceLock<bool> = 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)+ );+ true+ })+}++const TYPE: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>";+const FIRST: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#first>";+const REST: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#rest>";+const NIL: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#nil>";+const SUBCLASS: &str = "<http://www.w3.org/2000/01/rdf-schema#subClassOf>";+const INTERSECTION: &str = "<http://www.w3.org/2002/07/owl#intersectionOf>";++const ACME: &str = "<u:acme>";+const VENDOR: &str = "<u:Vendor>";+const APPROVED: &str = "<u:Approved>";+const SUPPLIER: &str = "<u:Supplier>";+const TRADER: &str = "<u:Trader>";+const STATUS: &str = "<u:status>";+const COMPLIANT: &str = "<u:Compliant>";+const L0: &str = "_:l0";+const L1: &str = "_:l1";++/// A Lean string literal. Every term here is ASCII with no quote or backslash,+/// so Rust's debug spelling is also Lean's.+fn q(s: &str) -> String {+ format!("{s:?}")+}++fn triple(s: &str, p: &str, o: &str) -> String {+ format!("Triple.mk {} {} {}", q(s), q(p), q(o))+}++fn lean_list(items: &[String]) -> String {+ format!("[{}]", items.join(", "))+}++/// The asserted graph: `Supplier` is the intersection of `Vendor` and+/// `Approved`, acme is both, and acme is a `Trader` with `Trader` a subclass of+/// `Vendor` so that a built-in Horn rule has something to do as well.+fn asserted() -> String {+ lean_list(&[+ triple(SUPPLIER, INTERSECTION, L0),+ triple(L0, FIRST, VENDOR),+ triple(L0, REST, L1),+ triple(L1, FIRST, APPROVED),+ triple(L1, REST, NIL),+ triple(ACME, TYPE, VENDOR),+ triple(ACME, TYPE, APPROVED),+ triple(ACME, TYPE, TRADER),+ triple(TRADER, SUBCLASS, VENDOR),+ ])+}++/// "Every supplier is compliant." Nothing checks it, which is the point.+fn compliance_table() -> String {+ format!(+ "[RulePattern.mk \"every-supplier-is-compliant\" \+ [AtomPat.mk (Pat.var \"s\") (Pat.const {}) (Pat.const {})] \+ (AtomPat.mk (Pat.var \"s\") (Pat.const {}) (Pat.const {}))]",+ q(TYPE),+ q(SUPPLIER),+ q(STATUS),+ q(COMPLIANT)+ )+}++/// The `cls-int1` step: a hardcoded arm, because the premise count is the length+/// of the RDF list.+fn int_step(conclusion: &str) -> String {+ let premises = lean_list(&[+ triple(SUPPLIER, INTERSECTION, L0),+ triple(L0, FIRST, VENDOR),+ triple(L0, REST, L1),+ triple(L1, FIRST, APPROVED),+ triple(L1, REST, NIL),+ triple(ACME, TYPE, VENDOR),+ triple(ACME, TYPE, APPROVED),+ ]);+ format!(+ "MStep.builtin (Step.mk Rule.clsInt1 {premises} ({}))",+ triple(ACME, TYPE, conclusion)+ )+}++/// The step citing the supplied rule, taking the built-in step's conclusion as+/// its only premise.+fn horn_step(rule: usize, bind: &str, premise_subject: &str, conclusion: &str) -> String {+ format!(+ "MStep.horn (HornStep.mk {rule} [(\"s\", {})] [{}] ({}))",+ q(bind),+ triple(premise_subject, TYPE, SUPPLIER),+ conclusion+ )+}++fn compliance_conclusion(subject: &str) -> String {+ triple(subject, STATUS, COMPLIANT)+}++const DRIVER: &str = r#"import OOCert+open OOCert++def G : List Triple := __G__++def R : List RulePattern := __R__++def steps : List MStep := __STEPS__++def main : IO UInt32 := do+ let ok := checkCertM G R steps+ let w := warrantOf R+ let verdict := if ok then w.verdict else "rejected"+ IO.println ("ok\t" ++ toString ok)+ IO.println ("verdict\t" ++ verdict)+ IO.println ("theorem\t" ++ w.theoremName)+ IO.println ("means\t" ++ w.means)+ return (if ok then 0 else 1)+"#;++/// Returns (exit code, stdout). The Lean file is regenerated per case, so a+/// stale artifact cannot make a rejection look like an acceptance.+fn run(name: &str, rules: &str, graph: &str, steps: &[String]) -> (i32, String) {+ assert!(built());+ let dir = std::env::temp_dir().join(format!("oo-mixed-{}-{}", name, std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let src = DRIVER+ .replace("__G__", graph)+ .replace("__R__", rules)+ .replace("__STEPS__", &lean_list(steps));+ let path = dir.join("Driver.lean");+ std::fs::write(&path, src).unwrap();++ let out = Command::new("lake")+ .arg("env")+ .arg("lean")+ .arg("--run")+ .arg(&path)+ .current_dir(lean_dir())+ .output()+ .expect("run lake env lean --run");+ let text = format!(+ "{}{}",+ String::from_utf8_lossy(&out.stdout),+ String::from_utf8_lossy(&out.stderr)+ );+ // Lean exits 1 both for a rejected certificate and for a file that does not+ // elaborate. The two must never be confused, so an elaboration failure is a+ // panic rather than a rejection.+ assert!(+ !text.contains("error:"),+ "the generated Lean file did not elaborate, which is not the same as a rejected \+ certificate:\n{text}"+ );+ let _ = std::fs::remove_dir_all(&dir);+ (out.status.code().unwrap_or(-1), text)+}++fn field<'a>(out: &'a str, key: &str) -> &'a str {+ out.lines()+ .find_map(|l| l.strip_prefix(&format!("{key}\t")))+ .unwrap_or_else(|| panic!("no {key} line in {out}"))+}++/// The certificate that could not exist before `Mixed.lean`: a hardcoded arm+/// feeding a step that cites a rule the checker has never heard of.+fn good_mixed_steps() -> Vec<String> {+ vec![+ int_step(SUPPLIER),+ horn_step(0, ACME, ACME, &compliance_conclusion(ACME)),+ ]+}++#[test]+fn a_mixed_certificate_carries_both_step_kinds() {+ if skip() {+ return;+ }+ let (code, out) = run(+ "good",+ &compliance_table(),+ &asserted(),+ &good_mixed_steps(),+ );+ assert_eq!(code, 0, "the honest mixed certificate must be accepted: {out}");+ assert_eq!(field(&out, "ok"), "true", "{out}");+}++#[test]+fn a_user_rule_never_earns_the_absolute_verdict() {+ // The laundering guard. `OOCert.mix_not_absolutely_entailed` proves that the+ // conclusion of this very certificate is not entailed by the asserted graph,+ // so reporting `entailed` here would be a false statement about a+ // machine-checked fact.+ if skip() {+ return;+ }+ let (code, out) = run(+ "relative",+ &compliance_table(),+ &asserted(),+ &good_mixed_steps(),+ );+ 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.mixed_certificate_sound", "{out}");+ assert!(+ field(&out, "means").contains("assumed, not checked"),+ "the report must say the rules are assumed: {out}"+ );+}++#[test]+fn a_table_of_built_in_rules_earns_the_absolute_verdict() {+ // Index 4 of `Builtin.asHorn` is rdfs9. The certificate mixes it with the+ // `cls-int1` arm, which is exactly the combination `Mixed.lean` exists for,+ // and every rule in the table is discharged against the semantics by+ // `Builtin.asHorn_sound`, so this run earns `Entails`.+ if skip() {+ return;+ }+ let rdfs9 = format!(+ "MStep.horn (HornStep.mk 4 [(\"x\", {}), (\"a\", {}), (\"b\", {})] [{}, {}] ({}))",+ q(ACME),+ q(TRADER),+ q(VENDOR),+ triple(ACME, TYPE, TRADER),+ triple(TRADER, SUBCLASS, VENDOR),+ triple(ACME, TYPE, VENDOR)+ );+ let steps = vec![int_step(SUPPLIER), rdfs9];+ let (code, out) = run("builtin", "Builtin.asHorn", &asserted(), &steps);+ assert_eq!(code, 0, "{out}");+ assert_eq!(field(&out, "verdict"), "entailed", "{out}");+ assert_eq!(+ field(&out, "theorem"),+ "OOCert.mixed_certificate_sound_builtin",+ "{out}"+ );+}++#[test]+fn an_empty_table_is_the_old_certificate_unchanged() {+ if skip() {+ return;+ }+ let (code, out) = run("norules", "[]", &asserted(), &[int_step(SUPPLIER)]);+ assert_eq!(code, 0, "{out}");+ assert_eq!(field(&out, "verdict"), "entailed", "{out}");+ assert_eq!(+ field(&out, "theorem"),+ "OOCert.mixed_certificate_sound_no_rules",+ "{out}"+ );+}++#[test]+fn every_forgery_is_rejected() {+ if skip() {+ return;+ }+ // A list the graph does not carry: `Supplier` would become the intersection+ // of `Approved` alone, so being approved would be enough. The chain triples+ // are absent from the asserted graph.+ let forged_chain = {+ let premises = lean_list(&[+ triple(SUPPLIER, INTERSECTION, L0),+ triple(L0, FIRST, APPROVED),+ triple(L0, REST, NIL),+ triple(ACME, TYPE, APPROVED),+ ]);+ format!(+ "MStep.builtin (Step.mk Rule.clsInt1 {premises} ({}))",+ triple(ACME, TYPE, SUPPLIER)+ )+ };++ let forgeries: Vec<(&str, Vec<String>, &str)> = vec![+ (+ "builtin_conclusion",+ vec![int_step(VENDOR), horn_step(0, ACME, ACME, &compliance_conclusion(ACME))],+ "the built-in step concludes membership in a class that is not the intersection",+ ),+ (+ "unasserted_list",+ vec![forged_chain, horn_step(0, ACME, ACME, &compliance_conclusion(ACME))],+ "the RDF list the built-in step walks is not in the asserted graph",+ ),+ (+ "horn_conclusion",+ vec![+ int_step(SUPPLIER),+ horn_step(0, ACME, ACME, &triple(ACME, STATUS, SUPPLIER)),+ ],+ "the cited rule's head under that binding is not the claimed conclusion",+ ),+ (+ "horn_index",+ vec![+ int_step(SUPPLIER),+ horn_step(7, ACME, ACME, &compliance_conclusion(ACME)),+ ],+ "the cited rule index is outside the supplied table",+ ),+ (+ "horn_binding",+ vec![+ int_step(SUPPLIER),+ horn_step(0, VENDOR, ACME, &compliance_conclusion(ACME)),+ ],+ "the binding does not instantiate the rule's body into the cited premises",+ ),+ (+ "horn_premise",+ vec![+ int_step(SUPPLIER),+ horn_step(0, VENDOR, VENDOR, &compliance_conclusion(VENDOR)),+ ],+ "the premise is neither asserted nor concluded by an earlier step",+ ),+ (+ "out_of_order",+ vec![+ horn_step(0, ACME, ACME, &compliance_conclusion(ACME)),+ int_step(SUPPLIER),+ ],+ "the step that derives the Horn step's premise comes after it, and a step may only \+ use what earlier steps concluded",+ ),+ ];++ for (name, steps, why) in forgeries {+ let (code, out) = run(name, &compliance_table(), &asserted(), &steps);+ assert_eq!(code, 1, "{name} must be rejected because {why}: {out}");+ assert_eq!(field(&out, "ok"), "false", "{name}: {out}");+ assert_eq!(+ field(&out, "verdict"),+ "rejected",+ "{name}: a rejected certificate must not carry either entailment verdict: {out}"+ );+ }+}diff --git a/tests/reason_horn_emit_test.rs b/tests/reason_horn_emit_test.rsnew file mode 100644index 00000000..82f3145b--- /dev/null+++ b/tests/reason_horn_emit_test.rs@@ -0,0 +1,850 @@+//! The engine as a PRODUCER of Horn certificates.+//!+//! `lean/OOCert/Horn.lean` checks a certificate over any rule table, proved+//! once by `OOCert.horn_certificate_sound`. Until this file existed the layer+//! had a consumer and no producer: the engine could only certify its own+//! hardcoded rules, so a user with a rule table had nothing to hand the+//! checker.+//!+//! What is gated here:+//!+//! 1. A malformed rule table is refused with a reason, never guessed at.+//! 2. The table the engine writes back out is byte-identical to the one the+//! Lean side writes, pinned against the committed built-in table.+//! 3. The emitted certificate satisfies the contract `OOCert.checkHornAll`+//! imposes on ORDER: no step cites a premise that is neither asserted nor+//! concluded by an earlier line, so no step can cite itself.+//! 4. Evaluating the built-in table through the generic path derives+//! everything the hardcoded loop derives. A missing join would show here.+//! 5. `oo-horn` accepts what the engine emits, and rejects it once broken.+//! Five forgeries, five rejections; without them the acceptance would be+//! evidence of nothing.+//! 6. The engine states NO verdict. A certificate over the built-in table+//! earns `entailed` and one over a user table earns+//! `entailed_under_supplied_rules`, and `oo-horn` is the only thing that+//! decides which. An engine that also pronounced would be a second place+//! those two could be confused, which is the hazard decision 0003 exists+//! to prevent.++mod common;++use std::collections::BTreeSet;+use std::path::{Path, PathBuf};+use std::process::Command;+use std::sync::{Arc, OnceLock};++use open_ontologies::graph::GraphStore;+use open_ontologies::reason::{parse_rules, rules_tsv, InferenceTarget, Reasoner};++const PREFIXES: &str = r#"+ @prefix : <http://ex.org/> .+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+"#;++fn repo() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+}++fn lean_dir() -> PathBuf {+ repo().join("lean")+}++fn scratch(name: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("oo-horn-emit-{}-{}", name, std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+}++/// One line of a rule table, assembled so no test has to type a tab.+fn rule(name: &str, body: &[[&str; 3]], head: [&str; 3]) -> String {+ let mut parts: Vec<String> = vec![name.to_string(), body.len().to_string()];+ for atom in body.iter().chain(std::iter::once(&head)) {+ for f in atom {+ parts.push((*f).to_string());+ }+ }+ parts.join("\t") + "\n"+}++fn iri(local: &str) -> String {+ format!("<http://ex.org/{local}>")+}++/// Load the Turtle, evaluate the rule table over it, and return the parsed+/// response. The rule table is written beside the certificate so a failing test+/// leaves both on disk.+fn emit(ttl: &str, rules: &str, dir: &Path) -> serde_json::Value {+ let store = Arc::new(GraphStore::new());+ store.load_turtle(&format!("{PREFIXES}{ttl}"), None).unwrap();+ let rules_path = dir.join("input_rules.tsv");+ std::fs::write(&rules_path, rules).unwrap();+ let out = Reasoner::run_horn(&store, &rules_path, dir)+ .unwrap_or_else(|e| panic!("run_horn failed: {e}"));+ serde_json::from_str(&out).unwrap()+}++/// Every triple in a tab-separated file, read as (s, p, o) from the given+/// field offset.+fn triples_at(line: &str, offset: usize) -> Vec<(String, String, String)> {+ let f: Vec<&str> = line.split('\t').collect();+ let mut out = Vec::new();+ let mut i = offset;+ while i + 2 < f.len() {+ out.push((f[i].to_string(), f[i + 1].to_string(), f[i + 2].to_string()));+ i += 3;+ }+ out+}++/// Split one `horn.tsv` line into (rule index, bindings, conclusion, premises).+#[allow(clippy::type_complexity)]+fn parse_horn_line(+ line: &str,+) -> (usize, Vec<(String, String)>, (String, String, String), Vec<(String, String, String)>) {+ let f: Vec<&str> = line.split('\t').collect();+ let rule: usize = f[0].parse().expect("rule index");+ let nb: usize = f[1].parse().expect("bind count");+ let mut binds = Vec::new();+ for k in 0..nb {+ binds.push((f[2 + 2 * k].to_string(), f[3 + 2 * k].to_string()));+ }+ let rest = 2 + 2 * nb;+ let conclusion = (f[rest].to_string(), f[rest + 1].to_string(), f[rest + 2].to_string());+ let premises = triples_at(line, rest + 3);+ (rule, binds, conclusion, premises)+}++fn read_lines(path: &Path) -> Vec<String> {+ std::fs::read_to_string(path)+ .unwrap_or_else(|e| panic!("cannot read {}: {e}", path.display()))+ .lines()+ .filter(|l| !l.is_empty())+ .map(|l| l.to_string())+ .collect()+}++// ── 1. A malformed table is refused, with a reason ──────────────────────────++#[test]+fn a_malformed_rule_table_is_refused_with_a_reason() {+ // Each entry is a table that must not parse, and a fragment the error has+ // to contain. Guessing at any of them would mean running a rule the user+ // did not write.+ let cases: Vec<(&str, &str, &str)> = vec![+ (+ "a body of two atoms with only one atom's worth of fields",+ "r\t2\t?s\t?p\t?o\t?s\t<http://ex.org/q>\t?o\n",+ "pattern fields",+ ),+ ("a body length that is not a number", "r\ttwo\t?s\t?p\t?o\n", "not a number"),+ (+ "a head variable the body never binds",+ "r\t1\t?s\t<http://ex.org/p>\t?o\t?s\t<http://ex.org/q>\t?z\n",+ "does not occur in the body",+ ),+ (+ "a constant that is not an N-Triples term",+ "r\t1\t?s\tex:p\t?o\t?s\t<http://ex.org/q>\t?o\n",+ "neither a variable",+ ),+ (+ "a variable with no name",+ "r\t1\t?s\t<http://ex.org/p>\t?\t?s\t<http://ex.org/q>\t?s\n",+ "no variable name",+ ),+ ("a CRLF line ending", "r\t0\t?s\t?p\t?o\r\n", "carriage return"),+ ("a line with no body length at all", "justaname\n", "expected a name"),+ ("an empty rule name", "\t0\t<http://ex.org/a>\t<http://ex.org/b>\t<http://ex.org/c>\n", "name is empty"),+ ];+ for (what, table, fragment) in cases {+ match parse_rules(table) {+ Ok(rules) => panic!("{what} parsed into {} rule(s) instead of being refused", rules.len()),+ Err(e) => assert!(+ e.to_string().contains(fragment),+ "{what}: the error must say what was wrong; wanted a mention of '{fragment}', got '{e}'"+ ),+ }+ }+}++#[test]+fn a_well_formed_table_parses() {+ // The negative test above is worthless if nothing passes.+ let table = rule(+ "grandparent",+ &[["?x", &iri("p"), "?y"], ["?y", &iri("p"), "?z"]],+ ["?x", &iri("gp"), "?z"],+ );+ let rules = parse_rules(&table).expect("a well-formed table must parse");+ assert_eq!(rules.len(), 1);+ assert_eq!(rules[0].name, "grandparent");+ assert_eq!(rules[0].body.len(), 2);+}++// ── 2. The wire format is the Lean one ──────────────────────────────────────++#[test]+fn the_table_the_engine_writes_is_the_table_the_checker_reads() {+ // `tests/fixtures/horn/builtin_rules.tsv` is pinned byte for byte against+ // `oo-horn rules` by `lean_horn_certificate_test.rs`. Rendering it back out+ // through this engine and getting the same bytes is what makes the two+ // sides agree without a Lean toolchain in the loop.+ let committed = repo().join("tests").join("fixtures").join("horn").join("builtin_rules.tsv");+ if common::skip_unless(+ committed.exists(),+ "tests/fixtures/horn/builtin_rules.tsv",+ "it is committed; run `cd lean && lake exe oo-horn rules > tests/fixtures/horn/builtin_rules.tsv` to regenerate",+ ) {+ return;+ }+ let text = std::fs::read_to_string(&committed).unwrap();+ let rules = parse_rules(&text).expect("the committed built-in table must parse");+ // How many rules the built-in table holds is pinned by+ // `lean_horn_certificate_test.rs`, which owns that fixture. What matters+ // here is that this engine reads and writes the same bytes for it.+ assert!(!rules.is_empty(), "the built-in table must hold rules");+ assert_eq!(+ rules_tsv(&rules).trim_end(),+ text.trim_end(),+ "the engine's rendering of the built-in table has drifted from the committed one"+ );+}++// ── 3. Order: no step cites a premise it has not earned ─────────────────────++/// The `ancestor` rule table: recursive, so most steps cite an earlier step's+/// conclusion and the ordering contract is actually exercised.+fn ancestor_rules() -> String {+ rule("base", &[["?x", &iri("parent"), "?y"]], ["?x", &iri("anc"), "?y"])+ + &rule(+ "step",+ &[["?x", &iri("parent"), "?y"], ["?y", &iri("anc"), "?z"]],+ ["?x", &iri("anc"), "?z"],+ )+}++const CHAIN: &str = r#"+ :a :parent :b . :b :parent :c . :c :parent :d . :d :parent :e .+"#;++#[test]+fn a_recursive_table_reaches_its_fixpoint() {+ let dir = scratch("recursive");+ let r = emit(CHAIN, &ancestor_rules(), &dir);+ // Four parent edges over five nodes: the ancestor relation is every pair+ // (i, j) with i before j, which is 4 + 3 + 2 + 1 = 10.+ assert_eq!(r["derived_triples"], 10, "{r}");+ assert_eq!(r["fixpoint_reached"], true, "{r}");+ assert_eq!(r["skipped_unserialisable"], 0, "{r}");+ assert_eq!(read_lines(&dir.join("horn.tsv")).len(), 10, "one line per derived triple");+}++#[test]+fn no_step_cites_a_premise_that_is_not_already_known() {+ // This is `OOCert.checkHornAll`'s contract, checked here without Lean so a+ // break is caught by `cargo test` alone. A step whose premise is neither+ // asserted nor concluded EARLIER is rejected by the checker, and a step+ // citing its own conclusion is the special case that matters most.+ let dir = scratch("order");+ emit(CHAIN, &ancestor_rules(), &dir);+ let asserted: BTreeSet<(String, String, String)> = read_lines(&dir.join("asserted.tsv"))+ .iter()+ .map(|l| triples_at(l, 0).into_iter().next().expect("a triple per line"))+ .collect();+ // The chain is :a -> :b -> :c -> :d -> :e, so the distance of a derived+ // `anc` pair is fixed by its two ends. The engine emits round by round, and+ // round k derives exactly the distance-k pairs, so the distances down the+ // file never decrease. This is here because the premise check below can be+ // satisfied by luck: a certificate reordered by term happens to stay valid+ // when the term order agrees with the dependency order, and then a gate+ // that should have fired does not. Four subjects each have a distance-1+ // conclusion and three of them also have a longer one, so ANY grouping by+ // term forces a decrease.+ let node = |t: &str| "abcde".find(t.trim_start_matches("<http://ex.org/").trim_end_matches('>'));+ let mut previous_distance = 0usize;+ for (n, line) in read_lines(&dir.join("horn.tsv")).iter().enumerate() {+ let (_, _, (s, _, o), _) = parse_horn_line(line);+ let d = node(&o).expect("object on the chain") - node(&s).expect("subject on the chain");+ assert!(+ d >= previous_distance,+ "horn.tsv line {}: a distance-{d} conclusion after a distance-{previous_distance} one. \+ The engine emits in derivation rounds, so the file is not in the order it derived in",+ n + 1+ );+ previous_distance = d;+ }++ let mut known = asserted.clone();+ for (n, line) in read_lines(&dir.join("horn.tsv")).iter().enumerate() {+ let (_, _, conclusion, premises) = parse_horn_line(line);+ for p in &premises {+ assert!(+ known.contains(p),+ "horn.tsv line {}: premise {p:?} is neither asserted nor concluded by an earlier \+ line, so the checker would reject the step",+ n + 1+ );+ }+ assert!(+ !premises.contains(&conclusion),+ "horn.tsv line {}: the step cites its own conclusion as a premise",+ n + 1+ );+ known.insert(conclusion);+ }+}++#[test]+fn every_binding_instantiates_the_body_and_the_head() {+ // `OOCert.checkHornStep` rejects a binding that does not instantiate the+ // body into exactly the premises listed, in the body's order. Re-running+ // the substitution here catches an emitter that writes a partial binding.+ let dir = scratch("binding");+ emit(CHAIN, &ancestor_rules(), &dir);+ let rules = parse_rules(&std::fs::read_to_string(dir.join("rules.tsv")).unwrap()).unwrap();+ for (n, line) in read_lines(&dir.join("horn.tsv")).iter().enumerate() {+ let (ri, binds, conclusion, premises) = parse_horn_line(line);+ let r = rules.get(ri).unwrap_or_else(|| panic!("line {}: rule index {ri} is off the end", n + 1));+ let lookup = |pat: &open_ontologies::reason::Pat| -> String {+ match pat {+ open_ontologies::reason::Pat::Const(c) => c.clone(),+ open_ontologies::reason::Pat::Var(v) => binds+ .iter()+ .find(|(name, _)| name == v)+ .unwrap_or_else(|| panic!("line {}: variable ?{v} is unbound", n + 1))+ .1+ .clone(),+ }+ };+ let inst = |a: &open_ontologies::reason::AtomPat| (lookup(&a.s), lookup(&a.p), lookup(&a.o));+ assert_eq!(+ premises,+ r.body.iter().map(inst).collect::<Vec<_>>(),+ "line {}: the premises are not the body under the binding, in body order",+ n + 1+ );+ assert_eq!(conclusion, inst(&r.head), "line {}: the conclusion is not the head under the binding", n + 1);+ }+}++// ── 4. The generic path against the hardcoded one ───────────────────────────++/// One graph for every built-in rule that is a Horn rule. No `owl:intersectionOf`+/// or `owl:unionOf`: those two read an RDF list off the graph, so their premise+/// count is data rather than fixed by the rule and they are not in the Horn+/// table at all.+const EVERY_HORN_RULE: &str = r#"+ :A rdfs:subClassOf :B . :B rdfs:subClassOf :C . :a a :A .+ :p rdfs:domain :Dom ; rdfs:range :Rng . :s :p :o .+ :q rdfs:subPropertyOf :r . :r rdfs:subPropertyOf :t . :s2 :q :o2 .+ :anc a owl:TransitiveProperty . :x :anc :y . :y :anc :z .+ :near a owl:SymmetricProperty . :x2 :near :y2 .+ :parent owl:inverseOf :child . :m :parent :n . :u :child :v .+ :i owl:sameAs :j .+ :E owl:equivalentClass :F . :e a :E .+ :g owl:equivalentProperty :h . :s3 :g :o3 .+ :R owl:onProperty :pr ; owl:someValuesFrom :SV . :sv1 :pr :sv2 . :sv2 a :SV .+ :R2 owl:onProperty :pa ; owl:allValuesFrom :AV . :av1 a :R2 ; :pa :av2 .+ :R3 owl:onProperty :ph ; owl:hasValue :HV . :hv1 a :R3 . :hv2 :ph :HV .+"#;++fn builtin_table() -> Option<String> {+ let committed = repo().join("tests").join("fixtures").join("horn").join("builtin_rules.tsv");+ if common::skip_unless(+ committed.exists(),+ "tests/fixtures/horn/builtin_rules.tsv",+ "it is committed; run `cd lean && lake exe oo-horn rules > tests/fixtures/horn/builtin_rules.tsv` to regenerate",+ ) {+ return None;+ }+ Some(std::fs::read_to_string(committed).unwrap())+}++#[test]+fn the_generic_path_derives_everything_the_hardcoded_loop_derives() {+ let Some(table) = builtin_table() else { return };+ let dir = scratch("differential");++ // The hardcoded loop, with a certificate so its conclusions can be read off+ // the file rather than out of the store.+ let builtin_dir = dir.join("builtin");+ let store = Arc::new(GraphStore::new());+ store.load_turtle(&format!("{PREFIXES}{EVERY_HORN_RULE}"), None).unwrap();+ Reasoner::run_full(&store, "owl-rl-ext", false, InferenceTarget::DefaultGraph, Some(&builtin_dir))+ .unwrap();+ let hardcoded: BTreeSet<(String, String, String)> = read_lines(&builtin_dir.join("derivations.tsv"))+ .iter()+ .map(|l| triples_at(l, 1).into_iter().next().expect("a conclusion per line"))+ .collect();++ // The same rules as data, through the generic path.+ let horn_dir = dir.join("horn");+ std::fs::create_dir_all(&horn_dir).unwrap();+ let r = emit(EVERY_HORN_RULE, &table, &horn_dir);+ let generic: BTreeSet<(String, String, String)> = read_lines(&horn_dir.join("horn.tsv"))+ .iter()+ .map(|l| parse_horn_line(l).2)+ .collect();++ assert!(!hardcoded.is_empty(), "the hardcoded loop must derive something on this graph");+ let missing: Vec<_> = hardcoded.difference(&generic).collect();+ assert!(+ missing.is_empty(),+ "the generic path missed {} triple(s) the hardcoded loop derived, which means a join is \+ wrong: {missing:?}\n{r}",+ missing.len()+ );++ // Where the two differ, the generic path derives MORE, and only in one+ // place: the hardcoded loop carries inequality guards (`a != c` in rdfs11+ // and rdfs5, `x != z` in prp-trp) that suppress a reflexive conclusion.+ // Those conclusions are licensed by the rule as written in the Lean table,+ // so the generic path draws them. Deriving more here is not unsoundness,+ // it is the guard the hardcoded loop applies and the rule does not, and+ // every one of them must be reflexive.+ for extra in generic.difference(&hardcoded) {+ assert_eq!(+ extra.0, extra.2,+ "the generic path derived {extra:?}, which the hardcoded loop did not and which is \+ not one of the reflexive conclusions its inequality guards suppress"+ );+ }+}++// ── 5. The engine states no verdict ─────────────────────────────────────────++#[test]+fn the_engine_pronounces_on_nothing() {+ // Decision 0003, rule 5. `oo-horn` decides between `entailed` and+ // `entailed_under_supplied_rules` by comparing the table it was handed+ // against the built-in one. The engine must not print either word, in any+ // field, or there are two places a reader could take a verdict from.+ let dir = scratch("verdict");+ let r = emit(CHAIN, &ancestor_rules(), &dir);+ let text = r.to_string();+ for forbidden in ["entailed", "entails", "\"verdict\"", "proved", "proven"] {+ assert!(+ !text.contains(forbidden),+ "the response contains '{forbidden}'. The engine emits a certificate and the checker \+ pronounces; a verdict word here is a second place the two could be confused:\n{text}"+ );+ }+ assert!(+ text.contains("ASSUMED and never checked"),+ "the response must say what the run is conditional on, in the response and not a \+ footnote:\n{text}"+ );+ assert_eq!(r["materialized"], false, "{r}");+}++#[test]+fn nothing_reaches_the_store() {+ let store = Arc::new(GraphStore::new());+ store.load_turtle(&format!("{PREFIXES}{CHAIN}"), None).unwrap();+ let before = store.all_triples().unwrap().len();+ let dir = scratch("store");+ let rules_path = dir.join("rules_in.tsv");+ std::fs::write(&rules_path, ancestor_rules()).unwrap();+ let out = Reasoner::run_horn(&store, &rules_path, &dir).unwrap();+ let r: serde_json::Value = serde_json::from_str(&out).unwrap();+ assert!(r["derived_triples"].as_u64().unwrap() > 0, "the run must do work: {r}");+ assert_eq!(+ store.all_triples().unwrap().len(),+ before,+ "a conclusion under a supplied rule table holds only in models that satisfy that table, \+ so it must not be written into the store beside the assertions"+ );+}++#[test]+fn a_head_that_cannot_be_written_is_not_derived() {+ // `?s ?p ?o` with the head putting the object in subject position: with a+ // literal object the conclusion is a triple no RDF serialiser can write.+ // The hardcoded loop guards four of its own rules this way; the generic+ // path refuses both a literal subject and a non-IRI predicate, says how+ // many it refused, and never uses one as a premise.+ let dir = scratch("literal");+ let table = rule("flip", &[["?s", &iri("p"), "?o"]], ["?o", &iri("q"), "?s"]);+ let r = emit(r#" :a :p "hello" . :a :p :b . "#, &table, &dir);+ assert_eq!(r["derived_triples"], 1, "only the IRI-object triple may be flipped: {r}");+ assert_eq!(r["skipped_unserialisable"], 1, "{r}");+ let lines = read_lines(&dir.join("horn.tsv"));+ assert_eq!(lines.len(), 1);+ assert!(+ !lines[0].contains("\"hello\"\t"),+ "a literal must never appear in subject position in the certificate: {}",+ lines[0]+ );+}++#[test]+fn a_rule_with_no_body_asserts_its_head() {+ // The boundary of the format: a body of zero atoms. `checkHornStep` maps+ // the empty body to the empty premise list and instantiates the head under+ // a binding of nothing, so the step is well formed and the head must be+ // ground. The engine emits it with a bind count of 0 and no premises, and+ // derives it once rather than once per round.+ let dir = scratch("nobody");+ let table = rule("axiom", &[], [&iri("a"), &iri("b"), &iri("c")]);+ let r = emit(CHAIN, &table, &dir);+ assert_eq!(r["derived_triples"], 1, "{r}");+ assert_eq!(r["fixpoint_reached"], true, "{r}");+ let lines = read_lines(&dir.join("horn.tsv"));+ assert_eq!(lines.len(), 1);+ let (ri, binds, conclusion, premises) = parse_horn_line(&lines[0]);+ assert_eq!(ri, 0);+ assert!(binds.is_empty(), "a rule with no body binds nothing: {:?}", binds);+ assert!(premises.is_empty(), "a rule with no body cites no premises: {premises:?}");+ assert_eq!(conclusion, (iri("a"), iri("b"), iri("c")));+ if !skip_without_lake() {+ let (code, out) = check(&dir);+ assert_eq!(code, 0, "the checker must accept a zero-body step: {out}");+ }+}++#[test]+fn a_run_that_stopped_at_the_iteration_cap_says_so() {+ // The third answer. Evaluation is naive: the transitive closure of a chain+ // of n nodes needs n rounds, and the engine stops at+ // `runtime::reasoner_max_iterations()` (64 by default). A run that stopped+ // there has NOT reached the fixpoint, and reporting `derived_triples` as+ // though it had would be a count of the closure that is not the closure.+ // Every step it did write is still a step the checker verifies.+ let dir = scratch("cap");+ let mut ttl = String::new();+ for i in 0..80 {+ ttl.push_str(&format!(":n{i} :parent :n{}.\n", i + 1));+ }+ let r = emit(&ttl, &ancestor_rules(), &dir);+ assert_eq!(r["fixpoint_reached"], false, "80 hops cannot close in 64 rounds: {r}");+ assert!(+ r["incomplete"].as_str().unwrap_or_default().contains("LOWER BOUND"),+ "a run that stopped at the cap must say the count is a lower bound: {r}"+ );+ // 81 nodes closed would be 81*80/2 = 3240 pairs; the cap stops it short.+ assert!(r["derived_triples"].as_u64().unwrap() < 3240, "{r}");+ if !skip_without_lake() {+ let (code, out) = check(&dir);+ assert_eq!(code, 0, "a truncated run still emits steps the checker accepts: {out}");+ }+}++#[test]+fn a_missing_rule_table_is_named_in_the_error() {+ let store = Arc::new(GraphStore::new());+ let dir = scratch("missing");+ let err = Reasoner::run_horn(&store, &dir.join("nowhere.tsv"), &dir).unwrap_err();+ let text = err.to_string();+ assert!(text.contains("cannot read"), "{text}");+ assert!(text.contains("nowhere.tsv"), "the error must name the file it could not read: {text}");+}++#[test]+fn an_empty_table_is_refused() {+ let store = Arc::new(GraphStore::new());+ store.load_turtle(&format!("{PREFIXES}{CHAIN}"), None).unwrap();+ let dir = scratch("empty");+ let rules_path = dir.join("empty.tsv");+ std::fs::write(&rules_path, "\n\n").unwrap();+ let err = Reasoner::run_horn(&store, &rules_path, &dir).unwrap_err();+ assert!(err.to_string().contains("no rules"), "{err}");+}++// ── 6. The CLI and the batch command ────────────────────────────────────────++fn oo() -> Command {+ Command::new(env!("CARGO_BIN_EXE_open-ontologies"))+}++#[test]+fn the_batch_command_emits_a_certificate() {+ use std::io::Write;+ let dir = scratch("batch");+ let ttl = dir.join("chain.ttl");+ std::fs::write(&ttl, format!("{PREFIXES}{CHAIN}")).unwrap();+ let rules_path = dir.join("rules_in.tsv");+ std::fs::write(&rules_path, ancestor_rules()).unwrap();+ let cert = dir.join("cert");++ let mut child = oo()+ .args(["--no-connect", "--data-dir"])+ .arg(dir.join("store"))+ .args(["batch", "-"])+ .stdin(std::process::Stdio::piped())+ .stdout(std::process::Stdio::piped())+ .spawn()+ .unwrap();+ let script = format!(+ "load {}\nreason --rules {} --certificate {}\n",+ ttl.display(),+ rules_path.display(),+ cert.display()+ );+ child.stdin.take().unwrap().write_all(script.as_bytes()).unwrap();+ let out = child.wait_with_output().unwrap();+ let stdout = String::from_utf8_lossy(&out.stdout);+ assert!(out.status.success(), "batch failed: {stdout}");+ assert!(stdout.contains("\"mode\":\"horn\""), "the Horn path did not run: {stdout}");+ for f in ["rules.tsv", "asserted.tsv", "horn.tsv"] {+ assert!(cert.join(f).exists(), "{f} was not written: {stdout}");+ }+ assert_eq!(read_lines(&cert.join("horn.tsv")).len(), 10, "{stdout}");+}++#[test]+fn the_cli_refuses_a_rule_table_with_nowhere_to_put_the_certificate() {+ let dir = scratch("nodir");+ let rules_path = dir.join("rules_in.tsv");+ std::fs::write(&rules_path, ancestor_rules()).unwrap();+ let out = oo()+ .args(["--data-dir"])+ .arg(dir.join("store"))+ .args(["reason", "--rules"])+ .arg(&rules_path)+ .output()+ .unwrap();+ let stdout = String::from_utf8_lossy(&out.stdout);+ assert!(+ !out.status.success(),+ "a run with nowhere to put the certificate must fail, not report counts nothing can \+ check: {stdout}"+ );+ assert!(stdout.contains("needs --certificate"), "{stdout}");+}++#[test]+fn the_mcp_tool_accepts_a_rule_table_and_a_certificate_directory() {+ // What this pins is the wire name of the field, which a rename would+ // otherwise break in silence: an unknown key deserialises to None and the+ // tool would quietly run the built-in profile instead. It does NOT+ // exercise the dispatch inside `onto_reason`, because the tool methods are+ // private to the crate and nothing in tests/ can call one.+ let input: open_ontologies::inputs::OntoReasonInput = serde_json::from_value(+ serde_json::json!({"rules_file": "/tmp/r.tsv", "certificate_dir": "/tmp/c"}),+ )+ .expect("the MCP input must carry a rule table");+ assert_eq!(input.rules_file.as_deref(), Some("/tmp/r.tsv"));+ assert_eq!(input.certificate_dir.as_deref(), Some("/tmp/c"));+ assert_eq!(input.materialize, None, "an unset materialize must stay unset, not default to true here");+}++// ── 7. The round trip, against the real checker ─────────────────────────────++fn lake_available() -> bool {+ Command::new("lake")+ .arg("--version")+ .current_dir(lean_dir())+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+}++fn skip_without_lake() -> 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+ })+}++/// Run `oo-horn check` over a certificate directory. Returns (exit code, stdout).+fn check(dir: &Path) -> (i32, String) {+ let out = Command::new(checker())+ .arg("check")+ .arg(dir.join("rules.tsv"))+ .arg(dir.join("asserted.tsv"))+ .arg(dir.join("horn.tsv"))+ .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_checker_accepts_a_certificate_the_engine_emitted() {+ if skip_without_lake() {+ return;+ }+ let dir = scratch("accept");+ let r = emit(CHAIN, &ancestor_rules(), &dir);+ let (code, out) = check(&dir);+ assert_eq!(code, 0, "the checker rejected an honest certificate: {out}\n{r}");+ assert_eq!(+ field(&out, "verdict"),+ "entailed_under_supplied_rules",+ "a table the user wrote earns the relativised verdict and nothing stronger: {out}"+ );+ assert_eq!(field(&out, "theorem"), "OOCert.horn_certificate_sound", "{out}");+ assert!(field(&out, "means").contains("assumed, not checked"), "{out}");+ assert_eq!(+ out.matches("\"derivations\":10").count(),+ 1,+ "the checker must see the ten steps the engine wrote: {out}"+ );+}++#[test]+fn the_built_in_table_read_back_as_data_earns_the_absolute_verdict() {+ // The strongest form of the round trip. `oo-horn rules` prints the rule+ // table `OOCert.Builtin.asHorn_sound` discharges against the semantics; the+ // engine reads it as data, evaluates it, and the certificate it emits earns+ // `entailed`, not the relativised verdict. That is the generic path+ // agreeing with the machine-checked rules, and it only works if the+ // engine's rendering of the table is byte-identical to the Lean one.+ if skip_without_lake() {+ return;+ }+ let dir = scratch("absolute");+ let out = Command::new(checker()).arg("rules").output().expect("run oo-horn rules");+ assert!(out.status.success());+ let table = String::from_utf8_lossy(&out.stdout).to_string();++ let r = emit(EVERY_HORN_RULE, &table, &dir);+ assert!(r["derived_triples"].as_u64().unwrap() > 0, "the run must derive something: {r}");+ let (code, report) = check(&dir);+ assert_eq!(code, 0, "the checker rejected the built-in-table certificate: {report}\n{r}");+ assert_eq!(+ field(&report, "verdict"),+ "entailed",+ "the built-in table is the one table that earns the absolute verdict: {report}"+ );+ assert_eq!(field(&report, "theorem"), "OOCert.entails_of_builtin_horn", "{report}");+ assert_eq!(+ field(&report, "rules_digest"),+ field(&report, "builtin_rules_digest"),+ "the table the engine wrote back out must BE the built-in table: {report}"+ );+}++#[test]+fn every_forgery_of_an_emitted_certificate_is_rejected() {+ // A gate that cannot fail is decoration. Each forgery is a different way to+ // lie about a run, applied to a certificate the checker has just accepted.+ if skip_without_lake() {+ return;+ }+ let base = scratch("forgery");+ emit(CHAIN, &ancestor_rules(), &base);+ assert_eq!(check(&base).0, 0, "the honest certificate must pass first");++ let lines = read_lines(&base.join("horn.tsv"));+ // A recursive step: rule 1, two premises, the second of them derived.+ let victim = lines+ .iter()+ .position(|l| l.starts_with("1\t"))+ .expect("the recursive rule must have fired");++ let forge = |name: &str, mutate: &dyn Fn(&mut Vec<String>)| -> (i32, String) {+ let dir = base.parent().unwrap().join(format!("forgery-{name}"));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ for f in ["rules.tsv", "asserted.tsv"] {+ std::fs::copy(base.join(f), dir.join(f)).unwrap();+ }+ let mut out = lines.clone();+ mutate(&mut out);+ std::fs::write(dir.join("horn.tsv"), out.join("\n") + "\n").unwrap();+ check(&dir)+ };++ type Forgery = (&'static str, Box<dyn Fn(&mut Vec<String>)>);+ let forgeries: Vec<Forgery> = vec![+ (+ // The conclusion is not the head under the binding.+ "forged conclusion",+ Box::new(move |l: &mut Vec<String>| {+ l[victim] = l[victim].replace(&iri("anc"), &iri("owns"));+ }),+ ),+ (+ // The premises are the right triples in the wrong order. Premise+ // order is part of the contract, so this is a rejection.+ "scrambled premise order",+ Box::new(move |l: &mut Vec<String>| {+ let (ri, binds, c, mut prem) = parse_horn_line(&l[victim]);+ prem.reverse();+ let mut f = vec![ri.to_string(), binds.len().to_string()];+ for (v, t) in binds {+ f.push(v);+ f.push(t);+ }+ for t in std::iter::once(c).chain(prem) {+ f.push(t.0);+ f.push(t.1);+ f.push(t.2);+ }+ l[victim] = f.join("\t");+ }),+ ),+ (+ // A rule index off the end of the table.+ "unknown rule index",+ Box::new(move |l: &mut Vec<String>| {+ l[victim] = format!("9{}", &l[victim][1..]);+ }),+ ),+ (+ // The step that derived this step's premise is removed, so the+ // premise is cited before anything earns it.+ "premise cited before it is derived",+ Box::new(move |l: &mut Vec<String>| {+ l.remove(0);+ }),+ ),+ (+ // A binding dropped: the substitution no longer instantiates the+ // body into the premises listed.+ "incomplete binding",+ Box::new(move |l: &mut Vec<String>| {+ let (ri, binds, c, prem) = parse_horn_line(&l[victim]);+ let kept: Vec<_> = binds.into_iter().take(1).collect();+ let mut f = vec![ri.to_string(), kept.len().to_string()];+ for (v, t) in kept {+ f.push(v);+ f.push(t);+ }+ for t in std::iter::once(c).chain(prem) {+ f.push(t.0);+ f.push(t.1);+ f.push(t.2);+ }+ l[victim] = f.join("\t");+ }),+ ),+ ];++ for (what, mutate) in forgeries {+ let (code, out) = forge(&what.replace(' ', "-"), &*mutate);+ assert_eq!(code, 1, "a certificate with a {what} must be rejected: {out}");+ }+}diff --git a/tests/shacl_core_verified_test.rs b/tests/shacl_core_verified_test.rsnew file mode 100644index 00000000..8409ba94--- /dev/null+++ b/tests/shacl_core_verified_test.rs@@ -0,0 +1,1035 @@+//! The W3C SHACL test suite, run against the VERIFIED evaluator in `lean/Shacl/`.+//!+//! # What this measures, and why it exists+//!+//! `tests/w3c_shacl_conformance_test.rs` measures the Rust engine, which compiles+//! every SHACL constraint into a SPARQL query and hands it to Oxigraph. That path+//! cannot be verified without verifying SPARQL, and no verified SPARQL engine+//! exists. The usual conclusion is that a verified SHACL validator is therefore out+//! of reach.+//!+//! The hole in that argument is that SHACL Core does not need SPARQL. The+//! Recommendation says of its own SPARQL definitions that they "represent potential+//! validators ... included for illustration purposes only and have no formal status+//! otherwise"; the normative validators are the prose ones in Appendix D. So+//! `lean/Shacl/Spec.lean` states those conditions directly over a finite graph,+//! `lean/Shacl/Eval.lean` decides them, and `Shacl.validate_spec` proves the two+//! agree. There is no SPARQL engine anywhere in that path.+//!+//! This file is what stops that from being an admirable claim. It runs the verified+//! evaluator over the same 120 tests, under the same comparison, in the same four+//! buckets, and prints the number.+//!+//! # The number is allowed to be small, and it is+//!+//! The Lean development covers eleven constraint components, four target forms and+//! two path forms. Everything else is REFUSED by the compiler in+//! `lean/Shacl/Compile.lean`, which lands in UNDETERMINED. A low PASS count with a+//! zero FAIL count is the shape this should have: it means the coverage is narrow+//! and nothing inside it is wrong. A FAIL is the serious bucket, because a FAIL is+//! the verified evaluator giving an answer that disagrees with the Working Group.+//!+//! The Rust engine's own number, under its own harness at the same suite commit, is+//! PASS 36 / FAIL 24 / UNDETERMINED 60 of 120. That is the comparison to hold this+//! against, and it is not an apples-to-apples one: the Rust engine answers many more+//! tests and gets 24 of them wrong.+//!+//! # The comparison, which is the same one the other harness uses+//!+//! COMPARED: the `sh:conforms` verdict, and the SET of+//! `(focus node, sh:sourceShape, sh:sourceConstraintComponent)` triples.+//!+//! IGNORED, each for the same reason as in `w3c_shacl_conformance_test.rs`:+//! `sh:resultPath` and `sh:value` (blank-node path structures need graph+//! isomorphism), `sh:resultSeverity` (this validator never emits one and ignores+//! `sh:severity`; see `lean/Shacl/Compile.lean`), `sh:resultMessage`, multiplicity+//! (sets, not multisets), and blank node identity (canonicalised to `_:`).+//!+//! Keeping the lens identical is deliberate. Two numbers produced under two+//! different lenses cannot be compared, and the comparison is the point.+//!+//! # Buckets+//!+//! PASS verdict and result set both agree; or the test expects+//! `sht:Failure` and the bridge reported an error.+//! FAIL the evaluator answered and the answer is wrong.+//! UNDETERMINED exit 3: the compiler refused the shapes graph, or the evaluator+//! declined to judge a literal. Not a pass and not a failure. NOT+//! credit.+//! ERROR exit 2, or a graph that would not load or re-serialise.+//!+//! # The gate+//!+//! A committed baseline in `tests/fixtures/shaclcore/baseline.json`, ratcheted:+//! PASS may not drop, FAIL may not rise, and no named PASS may regress. Re-cut with+//! `OO_SHACL_CORE_UPDATE_BASELINE=1 cargo test --test shacl_core_verified_test`.+//!+//! `the_bridge_refuses_what_it_cannot_check` feeds the bridge four shapes graphs it+//! must refuse and three data graphs whose verdicts must differ, and requires the+//! exact exit code and a reason that names the thing refused. Its own docstring+//! records the run in which it was seen to fail.++mod common;++use open_ontologies::graph::GraphStore;+use oxigraph::io::{RdfFormat, RdfParser};+use oxigraph::sparql::{QueryResults, SparqlEvaluator};+use oxigraph::store::Store;+use serde::{Deserialize, Serialize};+use std::collections::{BTreeMap, BTreeSet, HashMap};+use std::io::Cursor;+use std::path::{Path, PathBuf};+use std::process::Command;+use std::sync::OnceLock;++/// The base every relative IRI in the suite resolves against. Identical to the+/// other harness: the resolved IRIs end up inside `sh:sourceShape` on both sides,+/// so a base that varied with the checkout would make the comparison+/// machine-dependent.+const SUITE_BASE: &str = "https://w3c.github.io/data-shapes/data-shapes-test-suite/tests/";++/// The upstream commit `tests/w3c-shacl/` was taken from.+const SUITE_COMMIT: &str = "94d8bc2bd4fc4fdc6f2964d1ec4a892329e05f06";++/// Entries reachable from the root manifest at `SUITE_COMMIT`. The same 120 the+/// other harness walks, so the denominators are the same number.+const EXPECTED_ENTRIES: usize = 120;++const PREFIXES: &str = r#"+PREFIX mf: <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#>+PREFIX sht: <http://www.w3.org/ns/shacl-test#>+PREFIX sh: <http://www.w3.org/ns/shacl#>+PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>+PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>+"#;++fn repo() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+}++fn lean_dir() -> PathBuf {+ repo().join("lean")+}++fn suite_root() -> PathBuf {+ repo().join("tests").join("w3c-shacl")+}++fn fixtures() -> PathBuf {+ repo().join("tests").join("fixtures").join("shaclcore")+}++fn baseline_path() -> PathBuf {+ fixtures().join("baseline.json")+}++/// `.current_dir(lean_dir())` is not cosmetic: elan resolves the toolchain from the+/// working directory's `lean-toolchain`, and the crate root has none in its+/// ancestry. See the same note in `tests/lean_certificate_test.rs`, which was+/// written after this exact probe reported lake as missing in CI.+fn lake_available() -> bool {+ 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() && suite_root().join("manifest.ttl").is_file(),+ "lake (the Lean 4 build tool) and the vendored W3C SHACL suite at tests/w3c-shacl/",+ "install elan from https://github.com/leanprover/elan; the suite is normally committed",+ )+}++/// Build the verified evaluator once per test binary.+///+/// `lake build oo-shacl` compiles `lean/Shacl/` in full, and compiling it IS+/// checking the proofs: a `sorry`, a `native_decide`, or an axiom list that no+/// longer matches the `#guard_msgs` pins fails here. So a green run of this file+/// entails a green proof check, and a failure is a failure rather than a skip.+///+/// The plain `lake build` used by `tests/lean_certificate_test.rs` does NOT build+/// this target: `lean/lakefile.toml` lists `defaultTargets = ["OOCert", "oo-cert",+/// "oo-horn"]` and this task was not permitted to edit that line. Naming the target+/// explicitly is the workaround, and the consequence is that a bare `lake build` in+/// `lean/` does not check these proofs. Adding `"Shacl"` and `"oo-shacl"` to+/// `defaultTargets` is the fix and is reported rather than made.+fn evaluator() -> &'static Path {+ static BUILT: OnceLock<PathBuf> = OnceLock::new();+ BUILT.get_or_init(|| {+ let out = Command::new("lake")+ .args(["build", "Shacl", "oo-shacl"])+ .current_dir(lean_dir())+ .output()+ .expect("run lake build Shacl oo-shacl");+ assert!(+ out.status.success(),+ "lake build Shacl oo-shacl failed. The proofs are part of this build, so this is a \+ proof failure, not a build inconvenience:\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-shacl");+ assert!(exe.exists(), "oo-shacl binary missing at {}", exe.display());+ exe+ })+}++fn scratch() -> &'static Path {+ static DIR: OnceLock<PathBuf> = OnceLock::new();+ DIR.get_or_init(|| {+ let dir = std::env::temp_dir().join(format!("oo-shacl-core-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+ })+}++// ─────────────────────────────────────────────────────────────────────────────+// Running the bridge+// ─────────────────────────────────────────────────────────────────────────────++#[derive(Debug, Clone)]+struct Verdict {+ code: i32,+ json: serde_json::Value,+ raw: String,+}++fn run_bridge(data: &Path, shapes: &Path) -> Verdict {+ let out = Command::new(evaluator())+ .arg("validate")+ .arg(data)+ .arg(shapes)+ .output()+ .expect("run oo-shacl");+ let raw = format!(+ "{}{}",+ String::from_utf8_lossy(&out.stdout),+ String::from_utf8_lossy(&out.stderr)+ );+ let json = serde_json::from_str(raw.lines().next().unwrap_or("")).unwrap_or(serde_json::Value::Null);+ Verdict { code: out.status.code().unwrap_or(-1), json, raw }+}++// ─────────────────────────────────────────────────────────────────────────────+// Manifest walk+// ─────────────────────────────────────────────────────────────────────────────++#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]+struct ResultKey {+ focus: String,+ shape: String,+ component: String,+}++impl std::fmt::Display for ResultKey {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "({}, {}, {})", short(&self.focus), short(&self.shape), short(&self.component))+ }+}++#[derive(Debug, Clone)]+enum Expectation {+ Failure,+ Report { conforms: bool, results: BTreeSet<ResultKey> },+}++#[derive(Debug, Clone)]+struct TestCase {+ name: String,+ data: PathBuf,+ shapes: PathBuf,+ expected: Expectation,+}++#[derive(Debug, Clone, PartialEq, Eq)]+enum Outcome {+ Pass,+ Fail(String),+ Undetermined(String),+ Error(String),+}++impl Outcome {+ fn bucket(&self) -> &'static str {+ match self {+ Outcome::Pass => "PASS",+ Outcome::Fail(_) => "FAIL",+ Outcome::Undetermined(_) => "UNDETERMINED",+ Outcome::Error(_) => "ERROR",+ }+ }+ fn detail(&self) -> &str {+ match self {+ Outcome::Pass => "",+ Outcome::Fail(d) | Outcome::Undetermined(d) | Outcome::Error(d) => d,+ }+ }+}++fn short(iri: &str) -> String {+ if iri.starts_with('"') || iri.starts_with("_:") || !iri.contains(['#', '/']) {+ return iri.to_string();+ }+ iri.rsplit(['#', '/']).next().unwrap_or(iri).to_string()+}++/// Canonical comparison form. IRIs lose their angle brackets, blank nodes collapse+/// to `_:`, literals are left as printed. Applied to both sides, so the two are+/// symmetric.+fn canon(term: &str) -> String {+ let t = term.trim();+ if t.starts_with("_:") {+ return "_:".to_string();+ }+ if let Some(inner) = t.strip_prefix('<').and_then(|s| s.strip_suffix('>')) {+ return inner.to_string();+ }+ t.to_string()+}++fn rows(store: &Store, query: &str) -> anyhow::Result<Vec<HashMap<String, String>>> {+ let mut out = Vec::new();+ if let QueryResults::Solutions(solutions) =+ SparqlEvaluator::new().parse_query(query)?.on_store(store).execute()?+ {+ let vars: Vec<String> =+ solutions.variables().iter().map(|v| v.as_str().to_string()).collect();+ for solution in solutions {+ let solution = solution?;+ let mut row = HashMap::new();+ for v in &vars {+ if let Some(t) = solution.get(v.as_str()) {+ row.insert(v.clone(), t.to_string());+ }+ }+ out.push(row);+ }+ }+ Ok(out)+}++fn cell(row: &HashMap<String, String>, var: &str) -> String {+ row.get(var).cloned().unwrap_or_else(|| "(none)".to_string())+}++fn rel(path: &Path) -> String {+ path.strip_prefix(suite_root())+ .unwrap_or(path)+ .components()+ .map(|c| c.as_os_str().to_string_lossy().to_string())+ .collect::<Vec<_>>()+ .join("/")+}++fn base_of(path: &Path) -> String {+ format!("{SUITE_BASE}{}", rel(path))+}++fn path_of(iri: &str) -> Option<PathBuf> {+ iri.strip_prefix(SUITE_BASE).map(|r| suite_root().join(r))+}++fn load_graph(path: &Path) -> anyhow::Result<Store> {+ let text = std::fs::read_to_string(path)?;+ let store = Store::new()?;+ let parser = RdfParser::from_format(RdfFormat::Turtle)+ .with_base_iri(base_of(path))?+ .for_reader(Cursor::new(text.as_bytes()));+ for quad in parser {+ store.insert(&quad?)?;+ }+ Ok(store)+}++fn collect_tests() -> anyhow::Result<Vec<TestCase>> {+ let mut seen: BTreeSet<PathBuf> = BTreeSet::new();+ let mut out: Vec<TestCase> = Vec::new();+ walk(&suite_root().join("manifest.ttl"), &mut seen, &mut out)?;+ out.sort_by(|a, b| a.name.cmp(&b.name));+ Ok(out)+}++fn walk(+ manifest: &Path,+ seen: &mut BTreeSet<PathBuf>,+ out: &mut Vec<TestCase>,+) -> anyhow::Result<()> {+ let canonical = std::fs::canonicalize(manifest).unwrap_or_else(|_| manifest.to_path_buf());+ if !seen.insert(canonical) {+ return Ok(());+ }+ let store = load_graph(manifest)?;++ let entries: Vec<String> = rows(+ &store,+ &format!(+ "{PREFIXES}+ SELECT ?e WHERE {{ ?m mf:entries/rdf:rest*/rdf:first ?e . ?e a sht:Validate . }}"+ ),+ )?+ .into_iter()+ .filter_map(|r| r.get("e").cloned())+ .collect();+ for entry in entries {+ out.push(read_entry(&store, manifest, &entry)?);+ }++ let mut includes: Vec<String> =+ rows(&store, &format!("{PREFIXES} SELECT ?i WHERE {{ ?m mf:include ?i }}"))?+ .into_iter()+ .filter_map(|r| r.get("i").map(|s| canon(s)))+ .collect();+ includes.sort();+ includes.dedup();+ for inc in includes {+ match path_of(&inc) {+ Some(p) if p.is_file() => walk(&p, seen, out)?,+ _ => anyhow::bail!("{}: mf:include leaves the vendored suite: {inc}", rel(manifest)),+ }+ }+ Ok(())+}++fn read_entry(store: &Store, manifest: &Path, entry: &str) -> anyhow::Result<TestCase> {+ let action = rows(+ store,+ &format!(+ "{PREFIXES}+ SELECT ?d ?s WHERE {{ {entry} mf:action ?a . ?a sht:dataGraph ?d ; sht:shapesGraph ?s . }}"+ ),+ )?;+ let Some(a) = action.first() else {+ anyhow::bail!("{}: entry {entry} has no mf:action naming both graphs", rel(manifest));+ };+ let data = path_of(&canon(&cell(a, "d")))+ .ok_or_else(|| anyhow::anyhow!("{}: sht:dataGraph outside the suite", rel(manifest)))?;+ let shapes = path_of(&canon(&cell(a, "s")))+ .ok_or_else(|| anyhow::anyhow!("{}: sht:shapesGraph outside the suite", rel(manifest)))?;++ let result_term = rows(store, &format!("{PREFIXES} SELECT ?r WHERE {{ {entry} mf:result ?r }}"))?+ .first()+ .map(|r| cell(r, "r"))+ .unwrap_or_else(|| "(none)".to_string());++ let expected = if canon(&result_term) == "http://www.w3.org/ns/shacl-test#Failure" {+ Expectation::Failure+ } else {+ let conforms = rows(+ store,+ &format!("{PREFIXES} SELECT ?c WHERE {{ {entry} mf:result ?r . ?r sh:conforms ?c }}"),+ )?+ .first()+ .map(|r| {+ let c = cell(r, "c");+ c.starts_with("\"true\"") || c == "true"+ })+ .ok_or_else(|| {+ anyhow::anyhow!(+ "{}: entry {entry} has neither sh:conforms nor sht:Failure",+ rel(manifest)+ )+ })?;++ let mut results = BTreeSet::new();+ for row in rows(+ store,+ &format!(+ "{PREFIXES}+ SELECT ?f ?sh ?c WHERE {{+ {entry} mf:result ?r . ?r sh:result ?res .+ OPTIONAL {{ ?res sh:focusNode ?f }}+ OPTIONAL {{ ?res sh:sourceShape ?sh }}+ OPTIONAL {{ ?res sh:sourceConstraintComponent ?c }}+ }}"+ ),+ )? {+ results.insert(ResultKey {+ focus: canon(&cell(&row, "f")),+ shape: canon(&cell(&row, "sh")),+ component: canon(&cell(&row, "c")),+ });+ }+ Expectation::Report { conforms, results }+ };++ let mut name = rel(manifest);+ name.truncate(name.len().saturating_sub(".ttl".len()));+ let local = short(&canon(entry));+ if !name.ends_with(&local) {+ name = format!("{name}::{local}");+ }+ Ok(TestCase { name, data, shapes, expected })+}++// ─────────────────────────────────────────────────────────────────────────────+// Running one test+// ─────────────────────────────────────────────────────────────────────────────++/// Turtle to N-Triples through the engine's own parser, with the file's IRI as+/// base. The Lean bridge reads N-Triples only, on purpose: prefix and base+/// resolution are exactly the kind of work that is easy to get subtly wrong, and+/// doing it here rather than in Lean keeps it out of the verified path AND makes+/// this harness resolve IRIs the same way the expected reports do.+///+/// This is the one part of the pipeline whose correctness is assumed rather than+/// proved or measured. A mis-resolved IRI would show up as a disagreement, not as a+/// false pass, because the expected side resolves through the same code.+fn to_ntriples(path: &Path) -> Result<String, String> {+ let store = GraphStore::new();+ let text = std::fs::read_to_string(path).map_err(|e| format!("unreadable: {e}"))?;+ store+ .load_turtle(&text, Some(&base_of(path)))+ .map_err(|e| format!("does not parse: {}", first_line(&e.to_string())))?;+ store.serialize("ntriples").map_err(|e| format!("will not re-serialise: {e}"))+}++/// The outcome of one test, plus how many targeted shapes the compiler found.+///+/// The shape count is not decoration. A test whose expected report is+/// `sh:conforms true` PASSES for free if the compiler found no targeted shape at+/// all, and counting those as credit is exactly the silent success this repository+/// exists to catch. They are counted separately and printed on their own line.+fn run_case(tc: &TestCase, idx: usize) -> (Outcome, Option<u64>) {+ let data_nt = match to_ntriples(&tc.data) {+ Ok(s) => s,+ Err(e) => return (Outcome::Error(format!("data graph {e}")), None),+ };+ let shapes_nt = match to_ntriples(&tc.shapes) {+ Ok(s) => s,+ Err(e) => return (Outcome::Error(format!("shapes graph {e}")), None),+ };+ let dp = scratch().join(format!("data-{idx}.nt"));+ let sp = scratch().join(format!("shapes-{idx}.nt"));+ if let Err(e) = std::fs::write(&dp, &data_nt) {+ return (Outcome::Error(format!("cannot write scratch data graph: {e}")), None);+ }+ if let Err(e) = std::fs::write(&sp, &shapes_nt) {+ return (Outcome::Error(format!("cannot write scratch shapes graph: {e}")), None);+ }++ let v = run_bridge(&dp, &sp);+ let shapes_found = v.json["shapes"].as_u64();+ let outcome = match v.code {+ 3 => {+ let reason = v.json["reason"].as_str().unwrap_or("unnamed").to_string();+ Outcome::Undetermined(first_line(&reason))+ }+ 2 => {+ let reason = v.json["reason"].as_str().unwrap_or(&v.raw).to_string();+ // The suite's rule: a test whose mf:result is sht:Failure passes if the+ // validation reported a failure. Exit 2 is that report.+ match tc.expected {+ Expectation::Failure => Outcome::Pass,+ _ => Outcome::Error(first_line(&reason)),+ }+ }+ 0 => compare_verdict(tc, &v),+ other => Outcome::Error(format!("unexpected exit code {other}: {}", first_line(&v.raw))),+ };+ (outcome, shapes_found)+}++/// Compare a produced verdict with the expected one, under the lens the module+/// header states.+fn compare_verdict(tc: &TestCase, v: &Verdict) -> Outcome {+ let Some(actual_conforms) = v.json["conforms"].as_bool() else {+ return Outcome::Error(format!("exit 0 without a conforms field: {}", v.raw));+ };+ let actual: BTreeSet<ResultKey> = v.json["results"]+ .as_array()+ .map(|rs| {+ rs.iter()+ .map(|r| ResultKey {+ focus: canon(r["focus"].as_str().unwrap_or("(none)")),+ shape: canon(r["sourceShape"].as_str().unwrap_or("(none)")),+ component: canon(r["sourceConstraintComponent"].as_str().unwrap_or("(none)")),+ })+ .collect()+ })+ .unwrap_or_default();+ match &tc.expected {+ Expectation::Failure => Outcome::Fail(format!(+ "verdict: the suite requires a reported failure for this shapes graph; the verified \+ evaluator returned conforms={actual_conforms}"+ )),+ Expectation::Report { conforms, results } => {+ if actual_conforms != *conforms {+ return Outcome::Fail(format!(+ "verdict: expected conforms={conforms}, got {actual_conforms} ({} expected \+ result(s), {} produced)",+ results.len(),+ actual.len()+ ));+ }+ if actual == *results {+ return Outcome::Pass;+ }+ let missing: Vec<String> = results.difference(&actual).map(|k| k.to_string()).collect();+ let extra: Vec<String> = actual.difference(results).map(|k| k.to_string()).collect();+ Outcome::Fail(format!(+ "results: verdict agrees (conforms={conforms}) but the result set differs; {} \+ missing {}, {} unexpected {}",+ missing.len(),+ preview(&missing),+ extra.len(),+ preview(&extra)+ ))+ }+ }+}++fn first_line(s: &str) -> String {+ s.lines().next().unwrap_or(s).to_string()+}++fn preview(items: &[String]) -> String {+ if items.is_empty() {+ return "[]".to_string();+ }+ let shown: Vec<&str> = items.iter().take(2).map(String::as_str).collect();+ if items.len() > 2 {+ format!("[{}, ...]", shown.join("; "))+ } else {+ format!("[{}]", shown.join("; "))+ }+}++/// The short reason a test was undetermined, clustered so that the next piece of+/// work is chosen by evidence. "not implemented: sh:pattern" is a different job+/// from "recursive shapes".+fn refusal_class(detail: &str) -> String {+ if let Some(i) = detail.find("the constraint parameter ") {+ let rest = &detail[i + "the constraint parameter ".len()..];+ let name = rest.split(' ').next().unwrap_or(rest);+ return format!("parameter not implemented: {}", short(&canon(name)));+ }+ if detail.contains("extension mechanism") {+ return "SHACL extension mechanism (sh:sparql / constraint component)".to_string();+ }+ if detail.contains("recursive") {+ return "recursive shapes".to_string();+ }+ if detail.contains("more than one path form") {+ return "path node with more than one path form (ill-formed shapes graph)".to_string();+ }+ if detail.contains("lexical space") {+ return "datatype lexical space not implemented".to_string();+ }+ if detail.contains("is not implemented") {+ let i = detail.rfind(": ").map(|i| i + 2).unwrap_or(0);+ return format!("path form: {}", &detail[i..]);+ }+ if detail.contains("malformed RDF list") {+ return "malformed RDF list".to_string();+ }+ first_line(detail)+}++// ─────────────────────────────────────────────────────────────────────────────+// The run+// ─────────────────────────────────────────────────────────────────────────────++struct Run {+ cases: Vec<TestCase>,+ outcomes: Vec<Outcome>,+ counts: Counts,+ /// Tests where the verdict agreed even if the result set did not. The suite+ /// calls this partial compliance.+ partial: usize,+ /// PASSes earned with no targeted shape compiled at all. Free credit, counted+ /// so it can be subtracted by anyone who reads the number.+ vacuous_passes: Vec<String>,+ /// PASSes where the expected report is NON-EMPTY, so the evaluator had to+ /// produce the right violations at the right nodes with the right components,+ /// not merely stay silent. The strongest number in this file.+ substantive_passes: usize,+ /// Tests expecting `sht:Failure`, and how many of them landed in each bucket.+ /// A refusal is not a reported failure and is not credited as one.+ failure_expected: usize,+ failure_undetermined: usize,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]+struct Counts {+ total: usize,+ pass: usize,+ fail: usize,+ undetermined: usize,+ error: usize,+}++#[derive(Debug, Serialize, Deserialize)]+struct Baseline {+ note: String,+ suite_commit: String,+ counts: Counts,+ partial_compliance: usize,+ outcomes: BTreeMap<String, String>,+}++fn run() -> &'static Run {+ static RUN: OnceLock<Run> = OnceLock::new();+ RUN.get_or_init(|| {+ let cases = collect_tests().expect("walk the vendored W3C SHACL manifests");+ let mut outcomes = Vec::with_capacity(cases.len());+ let mut counts = Counts { total: cases.len(), ..Default::default() };+ let mut partial = 0usize;+ let mut vacuous_passes = Vec::new();+ let mut substantive_passes = 0usize;+ let mut failure_expected = 0usize;+ let mut failure_undetermined = 0usize;+ for (i, tc) in cases.iter().enumerate() {+ let (o, shapes_found) = run_case(tc, i);+ match &o {+ Outcome::Pass => {+ counts.pass += 1;+ partial += 1;+ if shapes_found == Some(0) {+ vacuous_passes.push(tc.name.clone());+ }+ if let Expectation::Report { results, .. } = &tc.expected+ && !results.is_empty()+ {+ substantive_passes += 1;+ }+ }+ Outcome::Fail(d) => {+ counts.fail += 1;+ if d.starts_with("results:") {+ partial += 1;+ }+ }+ Outcome::Undetermined(_) => {+ counts.undetermined += 1;+ if matches!(tc.expected, Expectation::Failure) {+ failure_undetermined += 1;+ }+ }+ Outcome::Error(_) => counts.error += 1,+ }+ if matches!(tc.expected, Expectation::Failure) {+ failure_expected += 1;+ }+ outcomes.push(o);+ }+ Run {+ cases,+ outcomes,+ counts,+ partial,+ vacuous_passes,+ substantive_passes,+ failure_expected,+ failure_undetermined,+ }+ })+}++fn outcome_map(r: &Run) -> BTreeMap<String, String> {+ r.cases+ .iter()+ .zip(r.outcomes.iter())+ .map(|(c, o)| (c.name.clone(), o.bucket().to_string()))+ .collect()+}++fn ratchet_verdict(+ base: &Counts,+ base_outcomes: &BTreeMap<String, String>,+ now: &Counts,+ now_outcomes: &BTreeMap<String, String>,+) -> Vec<String> {+ let mut broken = Vec::new();+ if now.pass < base.pass {+ broken.push(format!("PASS dropped from {} to {}", base.pass, now.pass));+ }+ if now.fail > base.fail {+ broken.push(format!("FAIL rose from {} to {}", base.fail, now.fail));+ }+ let regressed: Vec<&str> = base_outcomes+ .iter()+ .filter(|(n, b)| {+ b.as_str() == "PASS" && now_outcomes.get(*n).map(String::as_str) != Some("PASS")+ })+ .map(|(n, _)| n.as_str())+ .collect();+ if !regressed.is_empty() {+ broken.push(format!(+ "{} test(s) that passed in the baseline no longer pass: {}",+ regressed.len(),+ regressed.join(", ")+ ));+ }+ broken+}++fn pct(n: usize, d: usize) -> f64 {+ if d == 0 { 0.0 } else { 100.0 * n as f64 / d as f64 }+}++// ─────────────────────────────────────────────────────────────────────────────+// Tests+// ─────────────────────────────────────────────────────────────────────────────++/// The bridge refuses what it cannot check, and says which thing it refused.+///+/// This gate has been seen to fail. Deleting the unknown-parameter check in+/// `lean/Shacl/Compile.lean` (replacing its condition with `false`) and running this+/// file produced:+///+/// ```text+/// test the_bridge_refuses_what_it_cannot_check ... FAILED+/// unsupported-shapes.nt: expected exit 3 (undetermined), got 0.+/// {"status":"verdict","conforms":true,"shapes":1,...,"results":[]}+/// test the_verified_evaluator_does_not_regress ... FAILED+/// FAIL rose from 0 to 36+/// ```+///+/// That is the failure mode this whole layer exists to catch: a validator reporting+/// `conforms` about constraints it never evaluated. Both gates caught it.+#[test]+fn the_bridge_refuses_what_it_cannot_check() {+ if skip() {+ return;+ }+ let f = fixtures();+ let shapes = f.join("ok-shapes.nt");++ // A verdict, both ways, on the same shapes graph. If these two agreed the+ // bridge would not be measuring anything.+ let good = run_bridge(&f.join("conforming-data.nt"), &shapes);+ assert_eq!(good.code, 0, "conforming fixture did not produce a verdict: {}", good.raw);+ assert_eq!(good.json["conforms"], serde_json::json!(true), "{}", good.raw);++ let bad = run_bridge(&f.join("violating-data.nt"), &shapes);+ assert_eq!(bad.code, 0, "violating fixture did not produce a verdict: {}", bad.raw);+ assert_eq!(bad.json["conforms"], serde_json::json!(false), "{}", bad.raw);+ let comps: BTreeSet<String> = bad.json["results"]+ .as_array()+ .expect("results array")+ .iter()+ .map(|r| short(&canon(r["sourceConstraintComponent"].as_str().unwrap_or(""))))+ .collect();+ assert!(+ comps.contains("MinCountConstraintComponent") && comps.contains("MaxCountConstraintComponent"),+ "expected both count components, got {comps:?} in {}",+ bad.raw+ );++ // sh:maxCount counts value nodes, not statements. The same triple twice is one+ // value node, so this must conform.+ let dup = run_bridge(&f.join("duplicate-data.nt"), &shapes);+ assert_eq!(dup.code, 0, "{}", dup.raw);+ assert_eq!(+ dup.json["conforms"],+ serde_json::json!(true),+ "a repeated triple is one value node, so sh:maxCount 1 must hold: {}",+ dup.raw+ );++ // Four refusals, each naming what it refused.+ let refusals: [(&str, &str, &str); 4] = [+ ("conforming-data.nt", "unsupported-shapes.nt", "shacl#pattern"),+ ("conforming-data.nt", "recursive-shapes.nt", "recursive"),+ ("conforming-data.nt", "component-shapes.nt", "extension mechanism"),+ ("unknown-datatype-data.nt", "unknown-datatype-shapes.nt", "lexical space"),+ ];+ for (data, shp, needle) in refusals {+ let v = run_bridge(&f.join(data), &f.join(shp));+ assert_eq!(+ v.code, 3,+ "{shp}: expected exit 3 (undetermined), got {}. A validator that answers here is \+ answering about constraints it did not evaluate.\n{}",+ v.code, v.raw+ );+ assert_eq!(v.json["status"], serde_json::json!("undetermined"), "{}", v.raw);+ let reason = v.json["reason"].as_str().unwrap_or("");+ assert!(+ reason.contains(needle),+ "{shp}: the refusal must name what was refused; expected {needle:?} in {reason:?}"+ );+ }++ // A file that is not N-Triples is exit 2, which is a different answer again.+ let broken = run_bridge(&f.join("malformed.nt"), &shapes);+ assert_eq!(broken.code, 2, "a parse failure must be exit 2, not a verdict: {}", broken.raw);+ assert_eq!(broken.json["status"], serde_json::json!("error"), "{}", broken.raw);+}++/// The suite is present and whole, so the denominator cannot shrink silently.+#[test]+fn the_vendored_suite_is_whole() {+ if skip() {+ return;+ }+ let r = run();+ assert!(+ r.cases.len() >= EXPECTED_ENTRIES,+ "the manifest walk found only {} sht:Validate entries; upstream {SUITE_COMMIT} carries \+ {EXPECTED_ENTRIES}. A shrunken suite makes the number below meaningless.",+ r.cases.len()+ );+ let names: BTreeSet<&str> = r.cases.iter().map(|c| c.name.as_str()).collect();+ assert_eq!(names.len(), r.cases.len(), "two entries share a baseline key");+}++/// The headline: what the verified evaluator scores, and where the rest went.+#[test]+fn the_verified_conformance_report() {+ if skip() {+ return;+ }+ let r = run();+ let c = r.counts;++ eprintln!("\n====== W3C SHACL Core, the VERIFIED evaluator (lean/Shacl/) ======");+ eprintln!("suite commit {SUITE_COMMIT}\n");+ eprintln!(" total {:>4}", c.total);+ eprintln!(" PASS {:>4} ({:.1}%)", c.pass, pct(c.pass, c.total));+ eprintln!(+ " FAIL {:>4} ({:.1}%) <- wrong answer from a proved evaluator, the serious bucket",+ c.fail,+ pct(c.fail, c.total)+ );+ eprintln!(+ " UNDETERMINED {:>4} ({:.1}%) <- exit 3, refused and said why. NOT credit.",+ c.undetermined,+ pct(c.undetermined, c.total)+ );+ eprintln!(" ERROR {:>4} ({:.1}%)", c.error, pct(c.error, c.total));+ eprintln!(+ "\n partial compliance (sh:conforms agrees, result set ignored): {} of {} ({:.1}%)",+ r.partial,+ c.total,+ pct(r.partial, c.total)+ );+ eprintln!(+ "\n of those passes, {} required the evaluator to produce the RIGHT violations at the\n \+ right nodes with the right constraint components, not merely the right silence.",+ r.substantive_passes+ );+ eprintln!(+ " {} were earned with no targeted shape compiled at all. That is the correct answer\n \+ when every shape in the graph is deactivated and free credit otherwise, so they are\n \+ named:",+ r.vacuous_passes.len()+ );+ for n in &r.vacuous_passes {+ eprintln!(" {n}");+ }+ eprintln!(+ " {} test(s) expect sht:Failure; {} of those were refused rather than failed, and a\n \+ refusal is NOT credited as a reported failure.",+ r.failure_expected, r.failure_undetermined+ );+ eprintln!(+ "\n for comparison, the SPARQL-backed Rust engine under its own harness at the same\n \+ suite commit: PASS 36 / FAIL 24 / UNDETERMINED 60. It answers more and is wrong more."+ );++ // Where the undetermined tests went, clustered, with one test named per+ // cluster so the next piece of work can be picked by evidence.+ let mut clusters: BTreeMap<String, (usize, String)> = BTreeMap::new();+ for (tc, o) in r.cases.iter().zip(r.outcomes.iter()) {+ if let Outcome::Undetermined(d) = o {+ let e = clusters.entry(refusal_class(d)).or_insert((0, tc.name.clone()));+ e.0 += 1;+ }+ }+ if !clusters.is_empty() {+ eprintln!("\n UNDETERMINED by reason, with one test named per reason:");+ let mut rows: Vec<(&String, &(usize, String))> = clusters.iter().collect();+ rows.sort_by(|a, b| b.1.0.cmp(&a.1.0).then(a.0.cmp(b.0)));+ for (why, (n, example)) in rows {+ eprintln!(" {n:>4} {why} e.g. {example}");+ }+ }++ // Every failure, by name. There should not be many and each one is a defect.+ let fails: Vec<(&TestCase, &Outcome)> = r+ .cases+ .iter()+ .zip(r.outcomes.iter())+ .filter(|(_, o)| matches!(o, Outcome::Fail(_)))+ .collect();+ if !fails.is_empty() {+ eprintln!("\n FAIL, every one:");+ for (tc, o) in &fails {+ eprintln!(" {}\n {}", tc.name, o.detail());+ }+ }+ let errs: Vec<(&TestCase, &Outcome)> = r+ .cases+ .iter()+ .zip(r.outcomes.iter())+ .filter(|(_, o)| matches!(o, Outcome::Error(_)))+ .collect();+ if !errs.is_empty() {+ eprintln!("\n ERROR, every one:");+ for (tc, o) in &errs {+ eprintln!(" {}\n {}", tc.name, o.detail());+ }+ }+ eprintln!();+}++/// The ratchet. PASS may not drop, FAIL may not rise, no named PASS may regress.+#[test]+fn the_verified_evaluator_does_not_regress() {+ if skip() {+ return;+ }+ let r = run();+ let now_outcomes = outcome_map(r);++ if std::env::var("OO_SHACL_CORE_UPDATE_BASELINE").as_deref() == Ok("1") {+ let baseline = Baseline {+ note: "W3C SHACL Core conformance of the VERIFIED evaluator in lean/Shacl/, \+ ratcheted. PASS may not drop, FAIL may not rise, and no named PASS may \+ regress. Regenerate with OO_SHACL_CORE_UPDATE_BASELINE=1 cargo test --test \+ shacl_core_verified_test. UNDETERMINED is a refusal, not a pass; moving a \+ test out of it lands as a PASS and the ratchet counts that."+ .to_string(),+ suite_commit: SUITE_COMMIT.to_string(),+ counts: r.counts,+ partial_compliance: r.partial,+ outcomes: now_outcomes.clone(),+ };+ std::fs::create_dir_all(fixtures()).unwrap();+ std::fs::write(baseline_path(), serde_json::to_string_pretty(&baseline).unwrap()).unwrap();+ eprintln!("baseline rewritten at {}", baseline_path().display());+ return;+ }++ let text = std::fs::read_to_string(baseline_path()).unwrap_or_else(|e| {+ panic!(+ "no baseline at {}: {e}. Cut one with OO_SHACL_CORE_UPDATE_BASELINE=1 cargo test \+ --test shacl_core_verified_test",+ baseline_path().display()+ )+ });+ let base: Baseline = serde_json::from_str(&text).expect("parse the committed baseline");+ assert_eq!(+ base.suite_commit, SUITE_COMMIT,+ "the baseline was cut against a different suite commit; a suite refresh and an \+ evaluator change must not be confusable in a diff"+ );++ let broken = ratchet_verdict(&base.counts, &base.outcomes, &r.counts, &now_outcomes);+ assert!(+ broken.is_empty(),+ "the verified SHACL evaluator regressed against {}:\n {}\n\nIf the change is \+ deliberate, re-cut the baseline and say why in the commit message.",+ baseline_path().display(),+ broken.join("\n ")+ );+ eprintln!(+ "ratchet ok: PASS {} (baseline {}), FAIL {} (baseline {})",+ r.counts.pass, base.counts.pass, r.counts.fail, base.counts.fail+ );+}