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
wip: binding-list well-formedness, interrupted by a session limit
FABIOTESS33c2928dddf0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4760aa06..93555ca9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,34 @@ All notable changes to Open Ontologies are documented here.## [Unreleased]+### Changed+- **A binding is data, and a certificate that admits two readings is refused.** Running the+ Lean checker in `lean/OOCert/Horn.lean` and the independent Isabelle/HOL one in `isabelle/`+ over 1,718 certificates found 47 rows where the two disagreed, always in the same direction+ and always from one cause: Isabelle validated the binding list as a data structure and Lean+ did not. Neither checker was unsound, because Lean's acceptances held in Lean's own theorem:+ `EntailsR` quantifies over every total substitution. So the defect was in the FORMAT, which+ said nothing about a repeated binding key or an incomplete binding. `checkHornStep` now+ requires the binding to have distinct keys and to cover every variable the cited rule+ mentions, body and head, and the divergence is 47 rows to 0: 349 accepted by both and 465+ unparseable on both are unchanged, and the 47 moved into rejected-by-both, 857 to 904. The+ corpus test now requires both kernels to refuse each of the 286 rows carrying a malformed+ binding, so the analysis that used to excuse a disagreement is a gate that can fail. The+ refusals are strictness with+ no soundness content: `horn_certificate_sound`, `horn_certificate_sound_fo` and+ `SatRuleFO.to_SatRule` are unchanged in statement and in axiom footprint, and what the checks+ buy is stated as `OOCert.wellFormed_determines_instantiation` instead. Every total+ substitution extending a well-formed binding instantiates the cited rule the same way, so the+ certificate has one meaning rather than one per checker. **A binding for a variable the rule+ never mentions is still accepted.** The Isabelle is untouched, because it was written from the+ W3C sources without reading the Lean and is worth nothing once it is edited to agree.+ `reason --rules` structurally cannot emit either refused shape, and+ `no_emitted_binding_is_one_the_format_now_refuses` checks that against the bytes. See+ [decision 0008](docs/decisions/0008-a-binding-is-data-and-evidence-admits-one-reading.md).+ This does NOT make a conclusion writable RDF: binding `z` to the bare term `z` is required and+ still accepted, and `the_refusal_costs_no_certificate_anybody_meant` pins that boundary rather+ than letting it be assumed away.+### Added- **The refutation checker has a producer.** `lean/OOCert/Refute.lean` haschecked refutations since it landed and nothing in `src/` could write one: adiff --git a/README.md b/README.mdindex 9c3b5bc4..ac91661e 100644--- a/README.md+++ b/README.md@@ -69,8 +69,12 @@ description-logic false cleans, each an inconsistent ontology reported consistenconfidence. A rule that could conclude a triple no serialiser can write, reachable from ordinaryOWL, which left the store non-deterministic: three runs of one input kept 40, 9 and 24 inferences.And two independently verified kernels disagreeing on 47 of 1,718 certificates, all in the safe-direction, tracing to a gap in the certificate format that neither proof could see. Every one of-those had passed every test that existed before.+direction, tracing to a gap in the certificate format that neither proof could see: the format did+not say what a repeated binding key meant, or what an incomplete binding meant, so each kernel+answered from whatever its lookup function happened to do. That gap is closed by+[decision 0008](docs/decisions/0008-a-binding-is-data-and-evidence-admits-one-reading.md), which+refuses both shapes, and the differential now reports zero divergent rows. Every one of those had+passed every test that existed before.## What is actually proveddiff --git a/docs/decisions/0008-a-binding-is-data-and-evidence-admits-one-reading.md b/docs/decisions/0008-a-binding-is-data-and-evidence-admits-one-reading.mdnew file mode 100644index 00000000..71930395--- /dev/null+++ b/docs/decisions/0008-a-binding-is-data-and-evidence-admits-one-reading.md@@ -0,0 +1,165 @@+# 0008 · A binding is data, and evidence admits one reading++- **Status**: implemented · `lean/OOCert/Horn.lean`, where `bindingWellFormed` is a conjunct of+ `checkHornStep`, and `wellFormed_determines_instantiation` is the theorem that says what it+ buys · `horn_certificate_sound`, `horn_certificate_sound_fo` and `SatRuleFO.to_SatRule` are+ unchanged in statement and in axiom footprint · `isabelle/OO_Check.thy` is UNTOUCHED, because+ it was written independently and that independence is the whole value · the refusal can fail+ in Lean+ (`rejects_duplicate_binding_key`, `rejects_binding_that_omits_a_rule_variable` in+ `HornWitness.lean`) and on the real bytes+ (`tests/cross_kernel_differential_test.rs::resolved_d1_*`, `::resolved_d2*`) · the producer is+ proved unable to emit either shape by+ `tests/reason_horn_emit_test.rs::no_emitted_binding_is_one_the_format_now_refuses`+- **Written**: 2026-09-14+- **Related**: decision 0003 (a rule is data, and an assumption is not a fact), whose format this+ amends; decision 0002 (an inference carries a certificate)+- **Not run in CI.** The differential needs Isabelle2025-2 and Poly/ML, which the workflow does not+ install, so `cargo test --test cross_kernel_differential_test` is a LOCAL gate and the 47-to-0+ number is reproduced by running it, not by a green badge. `lean_horn_certificate_test` and+ `reason_horn_emit_test` do run in CI and carry the Lean-side and producer-side halves.++## The problem++The repository carries two verified checkers for one Horn certificate format: the Lean in+`lean/OOCert/Horn.lean` and an independent Isabelle/HOL formalisation in `isabelle/`, written from+the W3C sources with the Lean deliberately unread. Run over 1,718 certificates they agreed on 1,671+and disagreed on 47, always in the same direction, with one root cause:++**Isabelle validates the binding list as a data structure and Lean did not.** Isabelle's+`check_step` requires `distinct (map fst b)` and `binding_covers b r` before it instantiates+anything. Lean's `substOf` was `fun v => (List.lookup v l).getD v`, which turns any binding list+into a total function with a silent default, and it was applied without the list being inspected+at all.++Neither checker was unsound, and saying so is not a softening. Lean's soundness theorem quantifies+over whatever total substitution it built, so every acceptance held in its own theorem; Isabelle's+extra rejections were false alarms, which is the harmless direction. **The defect was in the+FORMAT.** Nothing in `docs/lean-certificates.md` or decision 0003 said what a repeated binding key+meant or what an incomplete binding meant, so two readings of the same bytes were both defensible+and a certificate's validity depended on which verified checker read it.++Two files make it concrete.++`isabelle/fixtures-added/bad_dup_key.tsv` binds `x` twice, first to `<http://ex.org/a>`, which makes+the step check, and then to `<http://ex.org/zzz>`, which does not. Lean returned exit 0 and the+ABSOLUTE verdict `entailed`. Isabelle returned `binding_dup_key`. Which one was right turned on+`List.lookup` being first-wins: a tie-break inside a standard-library function standing in for a+rule about a file format, deciding whether a certificate is valid.++`isabelle/fixtures-differential/unsafehead_cert.tsv` cites the rule `?s <p> ?o -> ?s <q> ?z` over+one ordinary triple of IRIs, binds `s` and `o`, and omits `z`. Lean accepted a conclusion whose+object was the bare term `z`, which is not an IRI, not a blank node, not a literal and not+writable RDF, minted out of a variable's NAME in the rule file. Nobody wrote that term. The fuzzer+then found the same hole through a one-character typo (`?o` became a bare `?`, read by both parsers+as a variable whose name is the empty string), which is what settles the objection that the first+case was contrived.++## The decision++**A binding list is DATA before it is a substitution, and a malformed binding is refused rather than+repaired.** `checkHornStep` now requires, of the binding and the rule it cites:++1. **Distinct keys.** A repeated key is refused.+2. **Coverage.** Every variable the cited rule mentions, in the body AND in the head, has a binding.++Both refusals are strictness with no soundness content, and that is the point. What they buy is a+sentence a soundness theorem cannot say: the certificate means ONE thing.+`wellFormed_determines_instantiation` states it and the kernel checks it. Once the binding is well+formed for the cited rule, every total substitution that extends it instantiates that rule the same+way, so a checker carrying the binding as a partial map and one carrying it as a total function with+a default are reading the same certificate.++### Why refusing, rather than writing the permissive reading into the format++Both questions had a permissive answer available, and both were rejected on the same ground: the+permissive reading costs nothing to give up and buys a second meaning.++On the **repeated key**, the alternative was to make first-wins normative. One sentence would have+made the format determinate, so this is a real option and not a straw man. It is the wrong one.+First-wins is not "the natural implementation", because there is no such thing. Of the four+association-list primitives an implementer is most likely to reach for, two are first-wins+(`List.lookup` in Lean, `map_of` in Isabelle) and two are last-wins (`dict(pairs)` in Python,+`HashMap::from_iter` in Rust, both of which insert in order and let the later value win). A+normative first-wins rule would therefore be broken by half the primitives on that short list, and+broken SILENTLY, by accepting a certificate that means something else. `distinct` has no such+split: every language has it, and getting it wrong is loud. Against that, a duplicate key carries no+information a producer needs, since there is no certificate writable with one that is not writable+without one, so refusing costs exactly nothing.++On the **incomplete binding**, the argument is sharper, because on the question of ENTAILMENT the+permissive reading was right and Isabelle was the incomplete one. `EntailsR` quantifies over every+total substitution, so a step whose body instantiates into known triples under SOME total+substitution really does entail its conclusion. The refusal is therefore a deliberate choice of+well-formedness over completeness, and it is the right one for two reasons. First, the permissive+reading does not merely admit more certificates: it FABRICATES a term out of a variable's name and+puts it in the conclusion, so what the certificate says depends on a rule file's choice of+identifier. Second, and this is what makes the trade free, it loses no certificate anybody meant. A+step whose binding omits a variable can always be rewritten with that variable bound to the term the+conclusion already shows, and the rewritten step is accepted by both kernels.+`the_repair_is_accepted` in `HornWitness.lean` and+`the_refusal_costs_no_certificate_anybody_meant` in the differential are that claim, run.++### What is NOT refused++**A binding for a variable the cited rule never mentions is accepted.** It is never consulted, so it+cannot make a step mean two things, and there is no second reading to remove. Refusing it would be a+tidiness rule dressed as a determinacy one. Both kernels already agreed here+(`probe_extrabind`, exit 0 on both) and they still do.++## What this does not claim++**This decision does not make a conclusion writable RDF.** Binding `z` to the bare term `z` is now+required and still accepted, so a certificate can still conclude a triple no serialiser can write.+What changed is that the term must be WRITTEN by the certificate's author rather than minted by the+checker. Whether the format should additionally require every term to be well-formed N-Triples is a+separate question, it is not answered here, and `the_refusal_costs_no_certificate_anybody_meant`+exists partly so that the boundary is visible rather than assumed away.++It also does not add a theorem to `horn_certificate_sound`. That statement is unchanged, its proof+below the first line is unchanged, and the new conjunct is destructured and discarded. Adding a+check makes `checkHornStep = true` a STRONGER hypothesis, so the theorem cannot have been+weakened to accommodate it. The accounting runs the other way, and it is the accounting that+matters: a checker that refuses more is trivially easier to prove sound, so the evidence that this+one still accepts anything lives in `HornWitness.lean` and in the differential's floor of 20+mutually accepted certificates, not in the soundness theorem.++## What moved, and what deliberately did not++The **Lean moved**. The Isabelle was written from the specifications without reading it, and editing+it to agree would spend the only thing the second kernel is for. Where the two now differ is a new+finding and belongs in a report, not in a patch to whichever side is easier to change.++A property proved inside one formalisation is not a property of the format, and this is the case+that showed it. Isabelle's `coverage_implied` proves that removing its coverage check cannot change+its accept/reject bit. That is true of Isabelle, whose instantiation is partial, so a missing+binding kills the step anyway. It does not transfer: Lean's instantiation is total, so the same+check is load-bearing there and in the opposite direction.++## The numbers++Before, over 1,718 certificates (61 base, 1,291 mutated, 366 fuzzed, fuzz seed `0xd1ffed0001`):++ both accept: 349+ both reject: 857+ both exit 2: 465+ known divergence: 47+ unexplained: 0++After:++ both accept: 349+ both reject: 904+ both exit 2: 465+ divergent: 0+ malformed binding, refused by both (decision 0008): 286++The 47 moved into rejected-by-both and nowhere else: 857 plus 47 is 904, and the accepted and+unparseable counts did not move. The 286 is larger than 47 because most rows carrying a malformed+binding were already rejected by both kernels for some other reason; the gate runs on every row+rather than only on the ones that disagree, because a check that ran only on divergences could be+satisfied by silence.++## Since written++Nothing yet.diff --git a/docs/lean-certificates.md b/docs/lean-certificates.mdindex 4a576303..df0c264c 100644--- a/docs/lean-certificates.md+++ b/docs/lean-certificates.md@@ -299,6 +299,34 @@ Twenty-seven of the engine's rules are Horn rules and appear in the built-in tabrather than fixed by the rule. They remain hardcoded arms. A user rule language stops at the sameboundary.+### What a binding must look like++A step's binding is a list of `var TAB term` pairs and **it is data before it is a substitution**.+Two shapes are refused, on both checkers:++| shape | example | why |+|---|---|---|+| a key bound twice | `x <http://ex.org/a> x <http://ex.org/zzz>` | the variable's value would be decided by the tie-break inside whichever lookup function a checker uses: first-wins in Lean's `List.lookup` and Isabelle's `map_of`, last-wins in Python's `dict()` and Rust's `HashMap::from_iter` |+| a variable of the cited rule with no binding | binding `s`, `o` for the rule `?s <p> ?o -> ?s <q> ?z` | the checker would otherwise have to invent a value, and the only one available is the variable's NAME, so the conclusion would carry a term nobody wrote |++A binding for a variable the cited rule never mentions **is accepted**: it is never consulted, so it+cannot make a certificate mean two things.++Both refusals are strictness and neither carries soundness content. What they buy is that a+certificate has ONE meaning, which `OOCert.wellFormed_determines_instantiation` states and the Lean+kernel checks: once the binding is well formed for the cited rule, every total substitution that+extends it instantiates that rule the same way. The defect they close was found by running this+checker and the independent Isabelle/HOL one in `isabelle/` over 1,718 certificates: 47 rows+disagreed, all from this one cause. See+[decision 0008](decisions/0008-a-binding-is-data-and-evidence-admits-one-reading.md).++This does **not** make a conclusion writable RDF. Binding `z` to the bare term `z` is required and+still accepted, so a certificate can still conclude a triple no serialiser can write; what changed is+that the term must be written by the certificate's author rather than minted by the checker.+`reason --rules` cannot emit either refused shape, which+`tests/reason_horn_emit_test.rs::no_emitted_binding_is_one_the_format_now_refuses` checks against the+bytes rather than asserting.+`reason --rules TABLE --certificate DIR` evaluates a supplied table to a fixpoint over the loadedgraph and writes the three files `oo-horn check` reads. Nothing is materialised: a conclusion drawnunder a table nobody has checked holds only in models that satisfy that table, and writing it intodiff --git a/docs/reasoning-systems-inventory.md b/docs/reasoning-systems-inventory.mdindex 964fd3a5..87cd7b2d 100644--- a/docs/reasoning-systems-inventory.md+++ b/docs/reasoning-systems-inventory.md@@ -91,9 +91,13 @@ same direction, with none unexplained, and the cause was neither proof. Isabellebinding list as a data structure; Lean turned any binding list into a total function with asilent default. On a certificate that binds one variable twice, first to a value that makes thestep check and then to one that does not, Lean returned the absolute verdict and Isabelle-refused. The defect was in the FORMAT, which never said what a repeated key means, and only a-second implementation could have surfaced it. That gap is being closed by making the Lean refuse-the shape, not by editing the Isabelle, since its independence is the asset.+refused. The defect was in the FORMAT, which never said what a repeated key means or what an+incomplete binding means, and only a second implementation could have surfaced it.++That gap is now CLOSED. `docs/decisions/0008-a-binding-is-data-and-evidence-admits-one-reading.md`+refuses both shapes, the Lean moved and the Isabelle was not touched, and the same corpus now+reports zero divergent rows: 349 accepted by both, 904 rejected by both, 465 unparseable on both.+The 47 moved into rejected-by-both and nowhere else.The adversarial review of that comparison established four things about the Lean layer that theLean's own build could never have shown, and they are the current work rather than a footnote:diff --git a/isabelle/README.md b/isabelle/README.mdindex 7509fcf0..6e86ef9d 100644--- a/isabelle/README.md+++ b/isabelle/README.md@@ -66,42 +66,41 @@ repository ships, mutates and fuzzes them, and runs both kernels over the lot. Iloudly (`common::skip_unless`) when either proof assistant is missing, and`OO_REQUIRE_FIXTURES=1` turns that skip into a failure.-## What the differential found+## What the differential found, and what it changed-1,718 certificates: 61 base, 1,291 mutated, 366 fuzzed. Both kernels accept 349, reject-857, and refuse 465 as unparseable. **Forty-seven rows disagree, in two classes.** Nothing-was adjusted on either side to make them go away.+1,718 certificates: 61 base, 1,291 mutated, 366 fuzzed. **Forty-seven rows disagreed, in two+classes.** Nothing was adjusted on either side to make them go away; the FORMAT was changed+instead, and the divergence is now zero.-Both classes have ONE root cause: **Isabelle validates the binding list as a data-structure and Lean does not.** `check_step` requires `distinct (map fst b)` and-`binding_covers b r` before it instantiates anything; Lean's `substOf` is-`fun v => (List.lookup v l).getD v`, which turns any binding list into a total function-with a silent default and never inspects it.+Both classes had ONE root cause: **Isabelle validates the binding list as a data structure+and Lean did not.** `check_step` requires `distinct (map fst b)` and `binding_covers b r`+before it instantiates anything; Lean's `substOf` is `fun v => (List.lookup v l).getD v`,+which turns any binding list into a total function with a silent default and used to be+applied without the list being inspected at all.-| | certificate | Lean | Isabelle |+| | certificate | Lean, before | Isabelle ||---|---|---|---|-| **D1** duplicate binding key | `fixtures-added/bad_dup_key.tsv` | accepts, `entailed` | rejects, `binding_dup_key` |-| **D2a** binding omits a variable whose NAME is a term in the graph | `fixtures-differential/varname_unbound_cert.tsv` | accepts | rejects, `binding_incomplete` |-| **D2b** binding omits a variable the rule's HEAD needs | `fixtures-differential/unsafehead_cert.tsv` | accepts | rejects, `binding_incomplete` |-| **D2c** the same, **found by the fuzzer** in a rule file one character from a probe written for something else | `fixtures-differential/d2c_fuzzfound_*.tsv` | accepts | rejects, `binding_incomplete` |--Neither checker is unsound. Lean's acceptances are all sound in Lean's own theorem,-because `EntailsR` quantifies over every total substitution and the substitution Lean used-is a real one; Isabelle's rejections are false alarms, which is the harmless direction.-What the pair shows is that the FORMAT is underspecified in two places, and that a-certificate's validity therefore depends on which verified checker reads it.--D1's resolution rests on `List.lookup` being first-wins. That is a tie-break inside a-standard-library function standing in for a rule about a file format, and it decides+| **D1** duplicate binding key | `fixtures-added/bad_dup_key.tsv` | accepted, `entailed` | rejects, `binding_dup_key` |+| **D2a** binding omits a variable whose NAME is a term in the graph | `fixtures-differential/varname_unbound_cert.tsv` | accepted | rejects, `binding_incomplete` |+| **D2b** binding omits a variable the rule's HEAD needs | `fixtures-differential/unsafehead_cert.tsv` | accepted | rejects, `binding_incomplete` |+| **D2c** the same, **found by the fuzzer** in a rule file one character from a probe written for something else | `fixtures-differential/d2c_fuzzfound_*.tsv` | accepted | rejects, `binding_incomplete` |++Neither checker was unsound. Lean's acceptances were all sound in Lean's own theorem, because+`EntailsR` quantifies over every total substitution and the substitution Lean used is a real+one; Isabelle's rejections were false alarms, which is the harmless direction. What the pair+showed is that the FORMAT was underspecified in two places, and that a certificate's validity+therefore depended on which verified checker read it.++D1's resolution rested on `List.lookup` being first-wins. That is a tie-break inside a+standard-library function standing in for a rule about a file format, and it decidedwhether a certificate is valid. DECISION M25 in `OO_Check.thy` predicted exactly this and-named `map_of`'s first-wins behaviour as the reason not to rely on it; `substOf`'s-docstring on the Lean side discusses missing bindings only and says nothing about repeated-ones.+named `map_of`'s first-wins behaviour as the reason not to rely on it; `substOf`'s docstring+on the Lean side discussed missing bindings only and said nothing about repeated ones.D2b is the sharp one. The rule is `?s <p> ?o -> ?s <q> ?z`, the graph is one ordinary-triple of IRIs, and the certificate omits `z`. Lean accepts a conclusion whose object is-the bare term `z` — not an IRI, not a blank node, not a literal, not writable RDF — minted-out of a variable's NAME in the rule file. The engine refuses to evaluate such a rule+triple of IRIs, and the certificate omits `z`. Lean accepted a conclusion whose object is+the bare term `z`, which is not an IRI, not a blank node, not a literal and not writable RDF,+minted out of a variable's NAME in the rule file. The engine refuses to evaluate such a rule(`parse_rules` in `src/reason.rs` rejects "a head variable the body never binds"), butthat guard is in the PRODUCER, and the checker is the thing you point at a certificatesomeone else wrote.@@ -110,18 +109,43 @@ D2c is the one that settles the obvious objection to D2a, which is that nobody wgraph whose subject is spelled like a variable. Nobody designed D2c either: the seededfuzzer replaced one field of a probe's rule file, `?o` became a bare `?`, and both parsersread that as a variable whose NAME IS THE EMPTY STRING. The graph's object is an empty-field, so Lean's default sends the unbound variable `""` to the term `""` and the step-checks. The hole is reachable by a typo. This is also why the corpus test classifies a-divergence by its CAUSE rather than by the edit that produced it — a quarantine keyed on+field, so Lean's default sent the unbound variable `""` to the term `""` and the step+checked. The hole was reachable by a typo. This is also why the corpus test works from the+CAUSE of a divergence rather than from the edit that produced it: a quarantine keyed onthe edit would have hidden exactly this row.-D2 also falsifies, across the two checkers, something proved inside one of them.+D2 also falsified, across the two checkers, something proved inside one of them.`coverage_implied` says removing Isabelle's coverage check cannot change its accept/rejectbit, and that is true of Isabelle, whose instantiation is partial. It does not transfer:Lean's instantiation is total, so the same check is load-bearing there and in the oppositedirection. A property proved of one formalisation's checker is not a property of theformat.+### How it was closed, and which side moved++`docs/decisions/0008-a-binding-is-data-and-evidence-admits-one-reading.md` refuses both+shapes, and **the LEAN moved**. `bindingWellFormed` is now a conjunct of `checkHornStep`, so+Lean rejects a repeated key and an incomplete binding exactly where Isabelle already did, and+`OOCert.wellFormed_determines_instantiation` is the Lean-side theorem that a well-formed+binding leaves nothing for a checker's choice of representation to decide.++**Nothing under `isabelle/` was edited to produce that agreement**, and nothing should be.+These theories were written from the W3C sources without reading the Lean, and a formalisation+edited to agree with the one it is checking is worth nothing. If the two disagree again+somewhere else, that is a new finding and it belongs in a report before it belongs in a patch.++The corpus is now 349 accepted by both, 904 rejected by both, 465 unparseable on both, and+ZERO divergent. The 47 that diverged moved into the rejected column and nowhere else: 857 plus+47 is 904, and the accepted and unparseable counts did not move at all.++The analysis that used to excuse a disagreement is now a gate that can fail. 286 rows of the+corpus carry a binding malformed in one of the two ways, the 47 among them, and the corpus test+requires BOTH kernels to refuse every one. The other 239 were already rejected by both for some+other reason, which is why the gate is checked on every row rather than only on the ones that+disagree: a check that ran only on divergences could be satisfied by silence.++A binding for a variable the cited rule never mentions is still ACCEPTED on both sides+(`probe_extrabind`). It is never consulted, so there was no second reading to remove.### What agreement on the other 1,671 rows is evidence ofChecking a Horn certificate is purely syntactic. Neither kernel consults its semantics, sodiff --git a/lean/OOCert/Horn.lean b/lean/OOCert/Horn.leanindex 0c59ed65..1536f412 100644--- a/lean/OOCert/Horn.lean+++ b/lean/OOCert/Horn.lean@@ -169,26 +169,186 @@ structure HornStep whereconclusion : Triplederiving Repr-/-- A cited binding list read as a total substitution. A variable with no-binding maps to its own name, which is junk and will fail the premise check;-soundness does not depend on that, because the semantic side quantifies over-every total substitution including this one. -/+/-- A cited binding list read as a total substitution. The default for a+variable the list does not mention is the variable's own name, and it is+UNREACHABLE on any variable the cited rule mentions, because `checkHornStep`+refuses a binding that does not cover them: see `bindingWellFormed` and+`lookup_eq_substOf_of_covers`. The total form is kept because the semantic side+quantifies over total substitutions, not because any value it invents is+meaningful. -/def substOf (l : List (Var × Term)) : Subst := fun v => (List.lookup v l).getD v-/-- Check one Horn step. As with the built-in rules, premise ORDER is part of-the contract: the premise list must be the body instantiated, in order. A-certificate with the right triples in the wrong order is rejected, which is a-false alarm and never a false pass. -/+/-! ## The binding list as a data structure++Decision 0008. A binding list is DATA before it is a substitution, and a+certificate whose binding is malformed is refused rather than repaired.++Two shapes are refused, and both were found by running this checker and the+independent Isabelle/HOL one over 1,718 certificates and comparing:++* a REPEATED KEY, because the value of the variable would then be decided by+ the tie-break inside whatever lookup function a checker happens to use.+ `List.lookup` here is first-wins, while `dict()` and `HashMap::from_iter`+ elsewhere are last-wins, and a certificate whose meaning depends on that is+ not evidence of anything;+* an INCOMPLETE BINDING, because `substOf`'s default would otherwise mint a+ term out of a variable's NAME in the rule file and put it in the conclusion.++A binding for a variable the rule never mentions is NOT refused. It cannot make+a step mean two things, because it is never consulted, and refusing it would be+a tidiness rule rather than a determinacy one. -/++def Pat.varList : Pat → List Var+ | .const _ => []+ | .var v => [v]++/-- Every variable the pattern mentions, with repeats. Deduplicating would cost+a `DecidableEq` pass and buy nothing: every use is under `List.all` or a+membership, and neither can see a repeat. -/+def AtomPat.varList (a : AtomPat) : List Var :=+ a.s.varList ++ a.p.varList ++ a.o.varList++/-- Every variable the rule mentions, body AND head. The head matters: a rule+whose head carries a variable its body never binds is the sharp case, and it is+the one where the silent default fabricated a term. -/+def RulePattern.varList (r : RulePattern) : List Var :=+ (r.body.map AtomPat.varList).flatten ++ r.head.varList++/-- No key occurs twice. Written out rather than borrowed so that it is a+`Bool` the witness file can `decide`, and so this file does not move with the+standard library. -/+def keysDistinct : List (Var × Term) → Bool+ | [] => true+ | (v, _) :: rest => rest.all (fun p => p.1 != v) && keysDistinct rest++/-- Every variable the cited rule mentions has a binding. -/+def bindsCover (r : RulePattern) (l : List (Var × Term)) : Bool :=+ r.varList.all (fun v => (List.lookup v l).isSome)++/-- The binding list is well formed FOR THE CITED RULE. Not a property of the+list alone: coverage is relative to the rule, which is why this is checked after+the rule has been looked up and not at parse time. -/+def bindingWellFormed (r : RulePattern) (l : List (Var × Term)) : Bool :=+ keysDistinct l && bindsCover r l++/-- With distinct keys, `List.lookup`'s first-wins tie-break stops deciding+anything: the value is the one the certificate wrote. This is the whole content+of refusing a repeated key, and it is why the refusal is not a taste. -/+theorem lookup_eq_of_mem_of_keysDistinct :+ ∀ {l : List (Var × Term)}, keysDistinct l = true →+ ∀ {v : Var} {t : Term}, (v, t) ∈ l → List.lookup v l = some t := by+ intro l+ induction l with+ | nil => intro _ v t hm; simp at hm+ | cons p rest ih =>+ obtain ⟨w, u⟩ := p+ intro hd v t hm+ simp only [keysDistinct, Bool.and_eq_true] at hd+ obtain ⟨hne, hrest⟩ := hd+ rcases List.mem_cons.mp hm with heq | hmem+ · have hv : v = w := congrArg Prod.fst heq+ have ht : t = u := congrArg Prod.snd heq+ subst hv; subst ht+ simp [List.lookup]+ · have hvw : ¬ v = w := by+ intro h+ subst h+ have := List.all_eq_true.mp hne (v, t) hmem+ simp at this+ have hbeq : (v == w) = false := by+ cases hb : v == w with+ | false => rfl+ | true => exact absurd (eq_of_beq hb) hvw+ simp only [List.lookup, hbeq]+ exact ih hrest hmem++/-- On every variable the rule mentions, the total substitution's value is the+value the binding list actually supplies. The default is never reached, so+`substOf` and a PARTIAL lookup agree everywhere the checker looks. -/+theorem lookup_eq_substOf_of_covers {r : RulePattern} {l : List (Var × Term)}+ (h : bindsCover r l = true) {v : Var} (hv : v ∈ r.varList) :+ List.lookup v l = some (substOf l v) := by+ have hs := List.all_eq_true.mp h v hv+ unfold substOf+ cases hl : List.lookup v l with+ | none => rw [hl] at hs; simp at hs+ | some t => simp++theorem Pat.inst_congr {sigma tau : Subst} {q : Pat}+ (h : ∀ v ∈ q.varList, sigma v = tau v) : q.inst sigma = q.inst tau := by+ cases q with+ | const c => rfl+ | var x => exact h x (by simp [Pat.varList])++theorem AtomPat.inst_congr {sigma tau : Subst} {a : AtomPat}+ (h : ∀ v ∈ a.varList, sigma v = tau v) : a.inst sigma = a.inst tau := by+ unfold AtomPat.varList at h+ unfold AtomPat.inst+ rw [Pat.inst_congr (fun v hv => h v (by simp [List.mem_append, hv])),+ Pat.inst_congr (fun v hv => h v (by simp [List.mem_append, hv])),+ Pat.inst_congr (fun v hv => h v (by simp [List.mem_append, hv]))]++theorem mem_varList_of_mem_body {r : RulePattern} {a : AtomPat} (ha : a ∈ r.body)+ {v : Var} (hv : v ∈ a.varList) : v ∈ r.varList :=+ List.mem_append_left _ (List.mem_flatten.mpr ⟨a.varList, List.mem_map_of_mem ha, hv⟩)++theorem mem_varList_of_mem_head {r : RulePattern} {v : Var} (hv : v ∈ r.head.varList) :+ v ∈ r.varList :=+ List.mem_append_right _ hv++/-- **The format decision, as a theorem.** Once the binding list is well formed+for the cited rule, EVERY total substitution that extends it instantiates that+rule the same way. So a checker that carries the binding as a partial map and+one that carries it as a total function with a default are reading the same+certificate, and the certificate has one meaning rather than one per checker.+Nothing below depends on this: it is the statement the differential could not+make for itself. -/+theorem wellFormed_determines_instantiation {r : RulePattern} {l : List (Var × Term)}+ (h : bindingWellFormed r l = true) {sigma : Subst}+ (hext : ∀ v t, List.lookup v l = some t → sigma v = t) :+ r.body.map (AtomPat.inst sigma) = r.body.map (AtomPat.inst (substOf l)) ∧+ AtomPat.inst sigma r.head = AtomPat.inst (substOf l) r.head := by+ simp only [bindingWellFormed, Bool.and_eq_true] at h+ have agree : ∀ v ∈ r.varList, sigma v = substOf l v := fun v hv =>+ hext v _ (lookup_eq_substOf_of_covers h.2 hv)+ refine ⟨List.map_congr_left ?_, AtomPat.inst_congr ?_⟩+ · intro a ha+ exact AtomPat.inst_congr (fun v hv => agree v (mem_varList_of_mem_body ha hv))+ · intro v hv+ exact agree v (mem_varList_of_mem_head hv)++/-- Check one Horn step. Three things are contracted, not two.++The BINDING must be well formed for the cited rule (decision 0008): distinct+keys, and a binding for every variable the rule mentions.++The PREMISE ORDER is part of the contract: the premise list must be the body+instantiated, in order. A certificate with the right triples in the wrong order+is rejected, which is a false alarm and never a false pass.++Both refusals are strictness and neither carries soundness content. That is the+point. `checkHornStep_sound` holds with or without them, because `EntailsR`+quantifies over every total substitution; what they buy is that the certificate+means ONE thing, which is not something a soundness theorem can say. -/def checkHornStep (R : List RulePattern) (k : Triple → Bool) (st : HornStep) : Bool :=match nth? R st.rule with| none => false| some r =>+ bindingWellFormed r st.binds &&decide (st.premises = r.body.map (AtomPat.inst (substOf st.binds))) &&st.premises.all k &&decide (st.conclusion = AtomPat.inst (substOf st.binds) r.head)/-- THE THEOREM, one step. No case analysis on the rule: there is nothing to-case on. -/+case on.++The statement is unchanged by decision 0008, and so is the proof below the first+line: the well-formedness conjunct is destructured and DISCARDED. That is the+honest accounting. Adding a check makes `checkHornStep = true` a stronger+hypothesis, so this theorem cannot have been weakened to accommodate it, and the+new refusals earn their place somewhere a soundness theorem cannot look:+`wellFormed_determines_instantiation` above, and `HornWitness.lean` for the+evidence that the checker still accepts anything at all. -/theorem checkHornStep_sound {G : List Triple} {R : List RulePattern} {k : Triple → Bool}{st : HornStep} (hk : ∀ t, k t = true → EntailsR G R t)(h : checkHornStep R k st = true) : EntailsR G R st.conclusion := by@@ -199,7 +359,7 @@ theorem checkHornStep_sound {G : List Triple} {R : List RulePattern} {k : Triple| some r =>intro hsimp only [Bool.and_eq_true, decide_eq_true_eq] at h- obtain ⟨⟨hprem, hall⟩, hconc⟩ := h+ obtain ⟨⟨⟨_hwf, hprem⟩, hall⟩, hconc⟩ := hintro I hIobtain ⟨M, hR⟩ := hIhave hrmem : r ∈ R := nth?_mem hr@@ -293,6 +453,14 @@ theorem horn_certificate_sound_fo (G : List Triple) (R : List RulePattern) (step#guard_msgs in#print axioms SatRuleFO.to_SatRule+/-- info: 'OOCert.wellFormed_determines_instantiation' depends on axioms: [propext, Quot.sound] -/+#guard_msgs in+#print axioms wellFormed_determines_instantiation++/-- info: 'OOCert.lookup_eq_of_mem_of_keysDistinct' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms lookup_eq_of_mem_of_keysDistinct+/-- info: 'OOCert.horn_certificate_sound' depends on axioms: [propext, Classical.choice, Quot.sound] -/#guard_msgs in#print axioms horn_certificate_sounddiff --git a/lean/OOCert/HornWitness.lean b/lean/OOCert/HornWitness.leanindex 771b97d4..7a4144c8 100644--- a/lean/OOCert/HornWitness.lean+++ b/lean/OOCert/HornWitness.lean@@ -57,7 +57,7 @@ theorem demo_conclusion_entailed : EntailsR demoG demoR ⟨uA, uGp, uC⟩ :=/-! ## The gate can fail-Four ways to be wrong, each rejected. Without these the acceptance above would+Six ways to be wrong, each rejected. Without these the acceptance above wouldbe evidence of nothing. -/def badConclusion : HornStep := { demoStep with conclusion := ⟨uA, uGp, uB⟩ }@@ -80,6 +80,89 @@ theorem rejects_unknown_rule_index :theorem rejects_unknown_premise :checkHornStep demoR (fun t => decide (t ∈ demoG)) badUnknown = false := by decide+/-! ### The two shapes decision 0008 refuses++Both would have been ACCEPTED before it, and neither acceptance was unsound.+That is the point: these are refusals about what a certificate MEANS, not about+what it proves, so the evidence they can fail has to be written down here rather+than inferred from a soundness theorem that never mentions them. -/++/-- `x` is bound twice: first to the value that makes the step check, then to+one that does not. Whether this checked used to depend on `List.lookup` being+first-wins: a tie-break inside a standard-library function deciding whether a+certificate is valid. -/+def dupKey : HornStep :=+ { demoStep with binds := [("x", uA), ("y", uB), ("z", uC), ("x", uB)] }++/-- `z` is dropped. `substOf`'s default used to send it to the term `"z"`, which+is not an IRI, not a blank node and not a literal, and the conclusion below+carries exactly that fabricated term. -/+def uncovered : HornStep :=+ { rule := 0+ binds := [("x", uA), ("y", uB)]+ premises := [⟨uA, uP, uB⟩, ⟨uB, uP, "z"⟩]+ conclusion := ⟨uA, uGp, "z"⟩ }++theorem rejects_duplicate_binding_key :+ checkHornStep demoR (fun t => decide (t ∈ demoG)) dupKey = false := by decide+theorem rejects_binding_that_omits_a_rule_variable :+ checkHornStep demoR (fun t => decide (t ∈ demoG)) uncovered = false := by decide++/-- A binding for a variable the rule never mentions is NOT refused. The rule is+that the binding must DETERMINE the step, not that it must be minimal, and an+unconsulted pair cannot make a certificate mean two things. -/+def extraBind : HornStep :=+ { demoStep with binds := [("x", uA), ("y", uB), ("z", uC), ("nowhere", uP)] }++theorem accepts_a_binding_for_a_variable_the_rule_never_mentions :+ checkHornStep demoR (fun t => decide (t ∈ demoG)) extraBind = true := by decide++/-- And the refusal costs no certificate anyone meant. Binding `z` to the term+the conclusion already shows turns `uncovered` into a step BOTH kernels accept:+what decision 0008 requires is that the term be WRITTEN, not that it be+writable RDF. The second question is a separate one and this gate does not+answer it. -/+def uncoveredRepaired : HornStep :=+ { uncovered with binds := [("x", uA), ("y", uB), ("z", "z")] }++theorem the_repair_is_accepted :+ checkHornStep demoR (fun t => decide (t ∈ ⟨uB, uP, "z"⟩ :: demoG)) uncoveredRepaired+ = true := by decide++/-! ### The hypothesis of `wellFormed_determines_instantiation` is load-bearing++That theorem says a well-formed binding leaves nothing for a checker's choice of+representation to decide. It would be worth nothing if the conclusion held+anyway, so here is the counterexample: ONE binding list that is not well formed,+TWO total substitutions that both extend it, and two different conclusions. The+difference is exactly what the two kernels used to disagree about. -/++def partialBind : List (Var × Term) := [("x", uA), ("y", uB)]++/-- A second way to make `partialBind` total. It is no worse a choice than+`substOf`'s: both invent a value for `z`, and neither has any claim on the+other. -/+def otherExt : Subst := fun v => (List.lookup v partialBind).getD uC++theorem partialBind_is_not_wellFormed :+ bindingWellFormed gpRule partialBind = false := by decide++theorem otherExt_extends_partialBind :+ ∀ v t, List.lookup v partialBind = some t → otherExt v = t := by+ intro v t h+ simp [otherExt, h]++theorem substOf_extends_partialBind :+ ∀ v t, List.lookup v partialBind = some t → substOf partialBind v = t := by+ intro v t h+ simp [substOf, h]++/-- Two extensions of one binding list, two conclusions. `wellFormed_determines_+instantiation` rules this out, and only because its hypothesis is not free. -/+theorem two_extensions_of_an_uncovered_binding_disagree :+ AtomPat.inst otherExt gpRule.head ≠ AtomPat.inst (substOf partialBind) gpRule.head := by+ decide+/-! ## The rule layer does not derive everything`demoH` is `demoG` closed under the grandparent rule. Its Herbranddiff --git a/tests/cross_kernel_differential_test.rs b/tests/cross_kernel_differential_test.rsindex ac2625ed..8cd140bd 100644--- a/tests/cross_kernel_differential_test.rs+++ b/tests/cross_kernel_differential_test.rs@@ -26,35 +26,43 @@//! accept and reject the same files, the certificate format has one meaning rather than//! two. Where they do not, it has two, and that is the interesting part.//!-//! # The disagreements+//! # The disagreements, and what closed them//!-//! Four were found, in two classes, and none is papered over. They are pinned by-//! `divergence_d1_*`, `divergence_d2_*`, `divergence_d2b_*` and `divergence_d2c_*` below,-//! their certificates are committed under `isabelle/fixtures-differential/`, and the-//! corpus test classifies each disagreement BY ITS CAUSE and fails on any it cannot-//! account for. Read those tests: the analysis is there, not here.+//! Four were found, in two classes, and none was papered over. They are pinned by+//! `resolved_d1_*`, `resolved_d2_*`, `resolved_d2b_*` and `resolved_d2c_*` below, their+//! certificates are committed under `isabelle/fixtures-differential/` and+//! `isabelle/fixtures-added/`, and the corpus test now requires ZERO divergence and fails+//! on any row at all. Read those tests: the analysis is there, not here.//!//! Three were designed after reading both checkers. The fourth was found by the fuzzer,//! in a rule file one character away from a probe written for something else, which is-//! why `binding_defect` classifies by cause rather than by which edit produced the row: a-//! quarantine keyed on the edit would have hidden it.+//! why `binding_defect` works from the cause rather than from which edit produced the row:+//! a quarantine keyed on the edit would have hidden it.//!-//! All three have ONE root cause. **Isabelle validates the binding list as a data-//! structure and Lean does not.** `check_step` requires `distinct (map fst b)` and+//! All four had ONE root cause. **Isabelle validated the binding list as a data structure+//! and Lean did not.** `check_step` requires `distinct (map fst b)` and//! `binding_covers b r` before it instantiates anything; Lean's `substOf` is//! `fun v => (List.lookup v l).getD v`, which turns any binding list into a total-//! function with a silent default and never inspects it. D1 is the duplicate key, D2 the-//! missing one.+//! function with a silent default and used to be applied without the list being inspected+//! at all. D1 is the duplicate key, D2 the missing one.//!-//! Neither checker is unsound. In all three Lean accepts and Isabelle rejects, and Lean's-//! acceptance holds in Lean's own theorem, because `EntailsR` quantifies over every total-//! substitution and the one Lean used is a real one; Isabelle's rejections are false-//! alarms, which is the harmless direction. What is defective is the FORMAT: it does not-//! say whether a binding must have distinct keys or must cover the cited rule's-//! variables, so Lean's answer to the first is whatever `List.lookup` happens to do, and-//! its answer to the second fabricates a term out of a variable's name and puts it in the-//! conclusion. Until the format says, a certificate's validity depends on which verified-//! checker reads it.+//! Neither checker was unsound. In all four Lean accepted and Isabelle rejected, and+//! Lean's acceptance held in Lean's own theorem, because `EntailsR` quantifies over every+//! total substitution and the one Lean used is a real one; Isabelle's rejections were+//! false alarms, which is the harmless direction. What was defective is the FORMAT: it did+//! not say whether a binding must have distinct keys or must cover the cited rule's+//! variables, so Lean's answer to the first was whatever `List.lookup` happens to do, and+//! its answer to the second fabricated a term out of a variable's name and put it in the+//! conclusion. A certificate's validity depended on which verified checker read it.+//!+//! **`docs/decisions/0008-a-binding-is-data-and-evidence-admits-one-reading.md` settles+//! it: both shapes are refused.** The LEAN moved, and `bindingWellFormed` is now a conjunct+//! of `checkHornStep`, because the Isabelle was written from the W3C sources without reading+//! the Lean and is worth nothing once it is edited to agree. 47 rows of the corpus diverged+//! before it and none does after, and the 47 moved into rejected-by-both and nowhere else.+//! `the_two_kernels_agree_on_the_whole_corpus` now requires BOTH kernels to refuse every row+//! carrying a malformed binding, which is 286 of them and not only the 47, so the analysis+//! that used to excuse a disagreement is a gate that can fail.mod common;@@ -370,7 +378,8 @@ fn mutations() -> Vec<Mutation> {}),// D1. The key is duplicated with a WRONG second value. Whether this is a// rejection depends entirely on how a duplicate key is resolved, which is the- // thing the format does not say. See `divergence_d1_duplicate_binding_key`.+ // thing the format did not say until decision 0008. See+ // `resolved_d1_a_duplicate_binding_key_is_refused_by_both`.("duplicate_binding_key", |t| {let mut c = parse_cert(t)?;if c.first()?.binds.is_empty() {@@ -658,7 +667,7 @@ fn fixture_cases() -> Vec<Case> {("fx-bad-order", horn_fixture("builtin_rules.tsv"), horn_fixture("asserted.tsv"), added("bad_order.tsv")),// The D1 certificate is in the corpus like every other committed fixture, and// not held back because it is the one that disagrees. `binding_defect` classifies- // it, `divergence_d1_duplicate_binding_key` pins it, and its mutants are checked+ // it, `resolved_d1_a_duplicate_binding_key_is_refused_by_both` pins it, and its mutants are checked// like anything else.("fx-bad-dup-key", horn_fixture("builtin_rules.tsv"), horn_fixture("asserted.tsv"), added("bad_dup_key.tsv")),("fx-generalized", horn_fixture("builtin_rules.tsv"), added("asserted_gen.tsv"), added("generalized.tsv")),@@ -791,20 +800,20 @@ fn parse_rule_line(line: &str) -> Option<Rule> {Some(Rule { vars })}-/// Why the two kernels differ on these files, if the reason is the one known root cause:-/// **Isabelle validates the binding list as a data structure and Lean does not.**+/// Whether the binding list is malformed in one of the two ways decision 0008 refuses:+/// a repeated key (D1), or a variable of the cited rule with no binding (D2).///-/// Isabelle's `check_step` runs `distinct (map fst b)` and then `binding_covers b r`-/// before instantiating anything. Lean's `substOf` is `fun v => (List.lookup v l).getD v`-/// — a total function with a silent default, built without looking at the list at all. So-/// a binding with a repeated key (D1) or with a variable missing (D2) is rejected by one-/// and silently resolved by the other.+/// It used to EXCUSE a divergence. It no longer can, because there is nothing left to+/// excuse: `bindingWellFormed` is a conjunct of Lean's `checkHornStep` and the two+/// kernels now agree on every one of these rows. It survives, pointed the other way, as+/// the POSITIVE gate inside `the_two_kernels_agree_on_the_whole_corpus`: a file this says is+/// malformed must be accepted by NEITHER checker. That is a stronger use of the same+/// analysis: as an excuse it could only ever be satisfied by a disagreement, and as a+/// gate it is checked against all 1,718 rows whether they diverge or not.///-/// This is a POSITIVE test of that diagnosis, and that is the point. Excusing a-/// divergence because of the EDIT that produced it would hide a second, unrelated-/// divergence arriving through the same edit — and would have hidden the one the fuzzer-/// found through a one-character change to a rule file. Excusing it because the binding-/// list really is malformed, in a specific way, at the step in question, cannot.+/// It is not a third checker. If it is wrong in the permissive direction a row simply+/// goes ungated; if it is wrong in the strict direction the gate fails, which is the+/// safe way round.fn binding_defect(rules_path: &Path, cert_path: &Path) -> Option<&'static str> {let rules_text = std::fs::read_to_string(rules_path).ok()?;let rules: Vec<Rule> =@@ -819,41 +828,25 @@ fn binding_defect(rules_path: &Path, cert_path: &Path) -> Option<&'static str> {for (k, _) in &step.binds {if seen.contains(&k.as_str()) {return Some(- "D1: the binding list repeats a key. Isabelle rejects it as malformed \- (R_binding_dup_key); Lean resolves it with List.lookup, which is \- first-wins, and accepts.",+ "D1: the binding list repeats a key. Decision 0008 refuses it. Isabelle \+ has always said R_binding_dup_key; Lean used to resolve it with \+ List.lookup, which is first-wins, and accept.",);}seen.push(k);}if rule.vars.iter().any(|v| !seen.contains(&v.as_str())) {return Some(- "D2: the binding does not cover every variable of the cited rule. Isabelle \- rejects (R_binding_incomplete); Lean's substOf sends the unbound variable \- to its own NAME and carries on, so the step checks whenever that name is \- the term the certificate used.",+ "D2: the binding does not cover every variable of the cited rule. Decision \+ 0008 refuses it. Isabelle has always said R_binding_incomplete; Lean's \+ substOf used to send the unbound variable to its own NAME and carry on, so \+ the step checked whenever that name was the term the certificate used.",);}}None}-/// A divergence is excused only when Lean ACCEPTED, Isabelle REJECTED, and the binding-/// list really is malformed in one of the two known ways. Every other shape — Isabelle-/// accepting where Lean rejects, a divergence on an exit code of 2, a divergence over a-/// well-formed binding — is unexplained and fails the corpus test.-fn known_divergence(- rules: &Path,- cert: &Path,- lean: &Outcome,- isabelle: &Outcome,-) -> Option<&'static str> {- if lean.exit != 0 || isabelle.exit != 1 {- return None;- }- binding_defect(rules, cert)-}-// ── a seeded fuzzer over the file format ────────────────────────────────────/// The hand-written mutations above test the failures someone thought of. This tests the@@ -865,7 +858,7 @@ fn known_divergence(/// Seeded, so a run is reproducible. It is NOT stable across changes to the corpus: one/// stream feeds every base in order, so adding a base shifts every draw after it and a/// given row stops being generated. That is why a row the fuzzer finds interesting gets-/// COMMITTED as a fixture with its own test — `divergence_d2c_*` is one it found and+/// COMMITTED as a fixture with its own test. `resolved_d2c_*` is one it found and/// this configuration no longer reaches. The fuzzer is a search, and the fixtures are/// what the search found.struct Rng(u64);@@ -1097,12 +1090,40 @@ fn the_two_kernels_agree_on_the_whole_corpus() {let mut agree_accept = 0usize;let mut agree_reject = 0usize;let mut agree_unreadable = 0usize;- let mut classified: BTreeMap<String, usize> = BTreeMap::new();- let mut unexplained: Vec<String> = Vec::new();+ // Rows whose binding is malformed under decision 0008, by which shape and by the edit+ // that produced them. Counted rather than excused. The 47 rows that used to DIVERGE are+ // among these; most of the rest were already rejected by both kernels for some other+ // reason, which is why the gate below runs on all of them and not only on divergences.+ let mut refused: BTreeMap<String, usize> = BTreeMap::new();+ let mut accepted_malformed: Vec<String> = Vec::new();+ let mut divergent: Vec<String> = Vec::new();for case in bases.iter().chain(mutants.iter()).chain(fuzzed.iter()) {let l = run_lean(&case.rules, &case.asserted, &case.cert);let i = run_isabelle(&case.rules, &case.asserted, &case.cert);++ // The positive gate. A binding decision 0008 refuses must be accepted by NEITHER+ // kernel, whatever the two of them say about each other. Checked on every row, not+ // only on the ones that disagree, so it cannot be satisfied by silence.+ if let Some(why) = binding_defect(&case.rules, &case.cert) {+ let class = if why.starts_with("D1") { "D1 duplicate key" } else { "D2 uncovered" };+ *refused.entry(format!("{class} [{}]", case.kind)).or_default() += 1;+ if l.exit == 0 || i.exit == 0 {+ accepted_malformed.push(format!(+ "{}\n {why}\n lean: exit {} verdict {:?}\n isabelle: exit {} \+ verdict {:?}\n rules={} asserted={} cert={}",+ case.name,+ l.exit,+ l.verdict,+ i.exit,+ i.verdict,+ case.rules.display(),+ case.asserted.display(),+ case.cert.display()+ ));+ }+ }+if l == i {match l.exit {0 => agree_accept += 1,@@ -1111,51 +1132,69 @@ fn the_two_kernels_agree_on_the_whole_corpus() {}continue;}- match known_divergence(&case.rules, &case.cert, &l, &i) {- Some(why) => {- let class = if why.starts_with("D1") { "D1 duplicate key" } else { "D2 missing" };- *classified.entry(format!("{class} [{}]", case.kind)).or_default() += 1;- }- None => unexplained.push(format!(- "{}\n lean: exit {} verdict {:?}\n isabelle: exit {} verdict {:?}\n \- rules={} asserted={} cert={}",- case.name,- l.exit,- l.verdict,- i.exit,- i.verdict,- case.rules.display(),- case.asserted.display(),- case.cert.display()- )),- }+ divergent.push(format!(+ "{}\n lean: exit {} verdict {:?}\n isabelle: exit {} verdict {:?}\n \+ rules={} asserted={} cert={}",+ case.name,+ l.exit,+ l.verdict,+ i.exit,+ i.verdict,+ case.rules.display(),+ case.asserted.display(),+ case.cert.display()+ ));}- let known: usize = classified.values().sum();+ let refused_total: usize = refused.values().sum();println!("cross-kernel differential\n \certificates: {total} ({} base, {} mutated, {} fuzzed, seed {FUZZ_SEED:#x})\n \both accept: {agree_accept}\n \both reject: {agree_reject}\n \both exit 2: {agree_unreadable}\n \- known divergence: {known}\n \- unexplained: {}",+ divergent: {}\n \+ malformed binding, refused by both (decision 0008): {refused_total}",bases.len(),mutants.len(),fuzzed.len(),- unexplained.len()+ divergent.len());- for (kind, n) in &classified {+ for (kind, n) in &refused {println!(" {kind}: {n} rows");}assert!(- unexplained.is_empty(),- "THE TWO KERNELS DISAGREE, and not in a way this file has an account of. A \- disagreement is the headline result of this test, not a nuisance: do not adjust \- either checker to make it go away, and do not add it to `known_divergence` \- without first deciding from the specification which side is wrong.\n\n{}",- unexplained.join("\n\n")+ accepted_malformed.is_empty(),+ "A CERTIFICATE WITH A MALFORMED BINDING WAS ACCEPTED. Decision 0008 says a repeated \+ key and a binding that does not cover the cited rule's variables are both refused, \+ and `bindingWellFormed` is a conjunct of `checkHornStep` for that reason. A row \+ here means the gate is not doing what the decision record says it does.\n\n{}",+ accepted_malformed.join("\n\n")+ );++ assert!(+ divergent.is_empty(),+ "THE TWO KERNELS DISAGREE. This was 47 rows before decision 0008 and it is zero \+ after; a row reappearing here is a NEW finding and the headline result of this \+ test, not a nuisance. Do not adjust either checker to make it go away, and in \+ particular do not adjust the Isabelle, which was written from the specifications \+ without reading the Lean and is worth nothing once it is edited to agree. Decide \+ from the specification which side is wrong, write the decision down, and move the \+ side the decision says moves.\n\n{}",+ divergent.join("\n\n")+ );++ // The gate above is worthless if the corpus stopped containing the shapes it refuses.+ // The floor is 47 because that is how many rows DIVERGED on this corpus and seed before+ // decision 0008, so every one of them must still be generated and must still be caught.+ // The actual count is higher and is printed rather than asserted, because pinning it+ // would make an unrelated fixture addition look like a regression.+ assert!(+ refused_total >= 47,+ "only {refused_total} rows carry a binding decision 0008 refuses, and there were 47 \+ before it. The corpus has stopped generating the shape the gate is about, so the \+ gate is passing over nothing");// A corpus that is all rejections would prove only that both sides can say no.@@ -1166,38 +1205,33 @@ fn the_two_kernels_agree_on_the_whole_corpus() {let _ = std::fs::remove_dir_all(&scratch);}-/// **Divergence D1.** A binding list with a repeated key.+/// **D1, resolved by decision 0008.** A binding list with a repeated key.////// `isabelle/fixtures-added/bad_dup_key.tsv` binds `x` twice: first to `<http://ex.org/a>`,/// which is the value that makes the step check, then to `<http://ex.org/zzz>`, which/// does not.///-/// * Isabelle: `check_step` tests `distinct (map fst b)` first and returns-/// `R_binding_dup_key`. Decision M25 records this as a deliberate STRICTNESS and-/// uncertainty U10 records it as a coin-flip between two honest authors.-/// * Lean: `substOf` is `fun v => (List.lookup v l).getD v`, and `List.lookup` returns-/// the FIRST match. `x` resolves to `<http://ex.org/a>`, the step checks, and the run-/// earns the ABSOLUTE verdict.-///-/// Which is wrong? Neither, on soundness. `checkHornStep_sound` quantifies over the-/// substitution `substOf st.binds`, which is a perfectly good total substitution-/// whichever value it picks, so Lean's acceptance is sound in Lean's own theorem, and-/// Isabelle's rejection is a false alarm rather than a missed forgery.+/// It used to diverge. Isabelle's `check_step` tested `distinct (map fst b)` first and+/// returned `R_binding_dup_key`; Lean's `substOf` was `fun v => (List.lookup v l).getD v`,+/// `List.lookup` returns the FIRST match, so `x` resolved to `<http://ex.org/a>`, the step+/// checked, and the run earned the ABSOLUTE verdict `entailed`. Neither was unsound, because+/// `checkHornStep_sound` quantifies over `substOf st.binds`, a perfectly good total+/// substitution whichever value it picks, and that is exactly why the divergence was a+/// FORMAT defect rather than a bug in either checker. Whether this certificate was valid+/// turned on a tie-break inside a standard-library function.///-/// The defect is in the FORMAT, and it is real. `docs/lean-certificates.md` and decision-/// 0003 do not say what a repeated binding key means, so Lean's answer is whatever-/// `List.lookup` happens to do. That is a tie-break inside a standard-library function-/// standing in for a rule about the file format, and it decides whether a certificate is-/// valid. Isabelle's `binding_covers` comment predicted exactly this and named `map_of`'s-/// first-wins behaviour as the reason not to rely on it; the Lean side has no comment on-/// duplicate keys at all — `substOf`'s docstring discusses MISSING bindings only.+/// **How it was resolved.** Decision 0008 refuses a repeated key, and the LEAN moved:+/// `bindingWellFormed` is now a conjunct of `checkHornStep`. The Isabelle is untouched,+/// because it was written from the W3C sources without reading the Lean and is worth+/// nothing once it is edited to agree.///-/// The repair belongs on the Lean side (reject a repeated key, or write the first-wins-/// rule into the format as normative), and it is not made here: the instruction for this-/// exercise is that a disagreement is the result, and a disagreement quietly fixed is a-/// disagreement hidden.+/// Refusing rather than making first-wins normative is argued in the decision record. The+/// short form: `List.lookup` and `map_of` are first-wins while `dict()` and+/// `HashMap::from_iter` are last-wins, so a normative first-wins rule is one that half of+/// all unthinking implementations would break silently, and a duplicate key carries no+/// information any producer needs.#[test]-fn divergence_d1_duplicate_binding_key() {+fn resolved_d1_a_duplicate_binding_key_is_refused_by_both() {if skip() {return;}@@ -1207,22 +1241,61 @@ fn divergence_d1_duplicate_binding_key() {}let rules = horn_fixture("builtin_rules.tsv");let asserted = horn_fixture("asserted.tsv");++ // The fixture still has the shape the test is about. Without this, a fixture edited+ // into a well-formed certificate would make the agreement below mean nothing.+ let text = std::fs::read_to_string(&cert).unwrap();+ let step = parse_step(text.lines().next().unwrap()).expect("the fixture must parse");+ let keys: Vec<&str> = step.binds.iter().map(|(k, _)| k.as_str()).collect();+ assert!(+ keys.iter().enumerate().any(|(n, k)| keys[..n].contains(k)),+ "bad_dup_key.tsv must still repeat a binding key: {keys:?}"+ );+let lean = run_lean(&rules, &asserted, &cert);let isa = run_isabelle(&rules, &asserted, &cert);+ assert_eq!(lean.exit, 1, "Lean must now refuse a repeated key rather than resolve it");+ assert_eq!(lean.verdict, None, "and it must award no verdict at all, absolute or relativised");+ assert_eq!(isa.exit, 1, "Isabelle rejects it as malformed, as it always did");+ assert_eq!(lean, isa, "D1 is resolved: the two kernels now read these bytes the same way");+}- assert_eq!(lean.exit, 0, "Lean accepts a duplicate binding key, first-wins");- assert_eq!(- lean.verdict.as_deref(),- Some("entailed"),- "and it accepts with the ABSOLUTE verdict, which is what makes the divergence \- worth reporting rather than filing"- );- assert_eq!(isa.exit, 1, "Isabelle rejects it as malformed");- assert_ne!(lean, isa, "if these ever agree, D1 has been resolved and this test should say how");+/// The control for D1, and the reason the test above is not just a checker that says no.+/// Drop the repeated pair and the certificate is the ordinary one both kernels accept+/// with the absolute verdict, over the same rule table and the same graph.+#[test]+fn resolved_d1_the_same_certificate_without_the_repeat_is_accepted() {+ if skip() {+ return;+ }+ let rules = horn_fixture("builtin_rules.tsv");+ let asserted = horn_fixture("asserted.tsv");+ let good = horn_fixture("good.tsv");+ let dup = isabelle_dir().join("fixtures-added").join("bad_dup_key.tsv");+ if common::skip_unless(dup.exists() && good.exists(), "the D1 pair", "they are committed") {+ return;+ }++ // `bad_dup_key.tsv` IS `good.tsv` with one binding pair inserted: same rule index, same+ // conclusion, same premises. So the only difference the kernels can be reacting to is+ // the repeated key.+ let a = parse_step(std::fs::read_to_string(&good).unwrap().lines().next().unwrap()).unwrap();+ let b = parse_step(std::fs::read_to_string(&dup).unwrap().lines().next().unwrap()).unwrap();+ assert_eq!(a.idx, b.idx);+ assert_eq!(a.concl, b.concl);+ assert_eq!(a.prems, b.prems);+ assert_eq!(b.binds.len(), a.binds.len() + 1, "one pair apart, and that pair is the repeat");++ let lean = run_lean(&rules, &asserted, &good);+ let isa = run_isabelle(&rules, &asserted, &good);+ assert_eq!(lean.exit, 0, "the well-formed certificate must still be accepted by Lean");+ assert_eq!(lean.verdict.as_deref(), Some("entailed"), "with the absolute verdict");+ assert_eq!(isa.exit, 0, "and by Isabelle");+ assert_eq!(lean, isa);}-/// **Divergence D2.** A binding that does not cover every variable of the rule, where-/// the missing variable's NAME is itself a term in the graph.+/// **D2, resolved by decision 0008.** A binding that does not cover every variable of the+/// rule, where the missing variable's NAME is itself a term in the graph.////// The certificate in `isabelle/fixtures-differential/` cites a one-atom rule/// `?s <p> ?o -> ?s <q> ?o` over a graph whose only triple is `s <p> <b>` — note the@@ -1232,12 +1305,12 @@ fn divergence_d1_duplicate_binding_key() {/// * Isabelle: `binding_covers` requires every variable of the rule to have a binding,/// and returns `R_binding_incomplete`. Its instantiation `iptriple` is PARTIAL, so an/// unbound variable has no value at all and there is nothing to fall through to.-/// * Lean: `substOf` is total by construction — `(List.lookup v l).getD v` — so an-/// unbound variable takes its own NAME as its value. `s` becomes the term `s`, the-/// body instantiates to the asserted triple, the head instantiates to the claimed-/// conclusion, and the step checks.+/// * Lean, before decision 0008: `substOf` was total by construction,+/// `(List.lookup v l).getD v`, so an unbound variable took its own NAME as its value.+/// `s` became the term `s`, the body instantiated to the asserted triple, the head+/// instantiated to the claimed conclusion, and the step checked.///-/// Which side is wrong depends on which question is being asked, and the two questions+/// Which side was wrong depended on which question was being asked, and the two questions/// have opposite answers. That is worth saying plainly rather than picking a winner.////// On "is the conclusion entailed under this rule table?", LEAN IS RIGHT. `EntailsR`@@ -1247,10 +1320,10 @@ fn divergence_d1_duplicate_binding_key() {/// false alarm is the harmless direction.////// On "is this a well-formed certificate?", ISABELLE IS RIGHT, and-/// `divergence_d2b_unsafe_rule_head` is why: Lean's default does not merely admit more-/// certificates, it FABRICATES a term out of a variable's name and puts it in the-/// conclusion. A certificate can therefore be accepted whose conclusion is not a writable-/// RDF triple at all.+/// `resolved_d2b_an_unsafe_rule_head_is_refused_by_both` is why: Lean's default did not+/// merely admit more certificates, it FABRICATED a term out of a variable's name and put+/// it in the conclusion. A certificate could therefore be accepted whose conclusion is not+/// a writable RDF triple at all.////// This also contradicts, ACROSS the two checkers, a claim proved inside one of them./// Isabelle's `coverage_implied` says removing the coverage check cannot change its@@ -1260,11 +1333,17 @@ fn divergence_d1_duplicate_binding_key() {/// property proved of one formalisation's checker is not a property of the format, and/// this is what that looks like when it bites.///-/// Neither side is adjusted. What the pair needs is a sentence in the format saying-/// whether a binding must be total over the rule's variables; until there is one, a-/// certificate's validity depends on which verified checker reads it.+/// **How it was resolved.** Decision 0008 refuses an incomplete binding, and the LEAN+/// moved: `bindsCover` requires every variable of the cited rule, body AND head, to have+/// a binding before anything is instantiated.+///+/// That is a deliberate choice of well-formedness over completeness, and the decision+/// record says so rather than pretending Lean was wrong on entailment. It is free because+/// it loses no certificate anybody meant: the control below, and+/// `the_refusal_costs_no_certificate_anybody_meant`, show the same claim written with the+/// variable bound is accepted by both.#[test]-fn divergence_d2_binding_omits_a_variable_named_like_a_term() {+fn resolved_d2_a_binding_that_omits_a_rule_variable_is_refused_by_both() {if skip() {return;}@@ -1281,25 +1360,78 @@ fn divergence_d2_binding_omits_a_variable_named_like_a_term() {let lean = run_lean(&rules, &asserted, &cert);let isa = run_isabelle(&rules, &asserted, &cert);- assert_eq!(lean.exit, 0, "Lean accepts: the omitted variable takes its own name, which matches");assert_eq!(- lean.verdict.as_deref(),- Some("entailed_under_supplied_rules"),- "relativised, because this is a user table and nothing discharges it"+ lean.exit, 1,+ "Lean must now refuse the incomplete binding rather than send the omitted variable \+ to its own name");- assert_eq!(isa.exit, 1, "Isabelle rejects: binding_incomplete");- assert_ne!(lean, isa, "if these ever agree, D2 has been resolved and this test should say how");+ assert_eq!(lean.verdict, None);+ assert_eq!(isa.exit, 1, "Isabelle rejects: binding_incomplete, as it always did");+ assert_eq!(lean, isa, "D2 is resolved: the two kernels now read these bytes the same way");- // The control. Bind `s` as well and both accept, so the divergence is about the- // MISSING binding and not about anything else in these three files.+ // The control, and it is load-bearing: bind `s` as well and BOTH accept. Without it+ // the assertions above would be satisfied by a checker that had simply stopped+ // accepting anything over this rule table.let full = differential_fixture("varname_bound_cert.tsv");- if full.exists() {- let lean = run_lean(&rules, &asserted, &full);- let isa = run_isabelle(&rules, &asserted, &full);- assert_eq!(lean.exit, 0, "the fully bound certificate must be accepted by Lean");- assert_eq!(isa.exit, 0, "and by Isabelle");- assert_eq!(lean, isa, "with the same verdict");+ assert!(full.exists(), "the control certificate must be committed");+ let lean = run_lean(&rules, &asserted, &full);+ let isa = run_isabelle(&rules, &asserted, &full);+ assert_eq!(lean.exit, 0, "the fully bound certificate must still be accepted by Lean");+ assert_eq!(lean.verdict.as_deref(), Some("entailed_under_supplied_rules"));+ assert_eq!(isa.exit, 0, "and by Isabelle");+ assert_eq!(lean, isa, "with the same verdict");+}++/// **What decision 0008 costs, measured rather than asserted.**+///+/// The claim in the decision record is that refusing an incomplete binding loses no+/// certificate anybody meant, because the omitted variable can always be bound to the+/// term the conclusion already shows. This runs that repair on the sharp case, D2b, whose+/// rule head carries a variable the body never binds.+///+/// It also fixes the BOUNDARY of the decision in a test, which matters more than the+/// reassurance. The repaired certificate still concludes `<a> <q> z`, whose object is the+/// bare term `z`, which is not an IRI, not a blank node, not a literal and not writable RDF, and+/// BOTH kernels accept it. Decision 0008 requires the term to be WRITTEN by the+/// certificate's author; it does not require it to be writable RDF, and nothing here+/// should be read as saying it does.+#[test]+fn the_refusal_costs_no_certificate_anybody_meant() {+ if skip() {+ return;}+ let rules = differential_fixture("unsafehead_rules.tsv");+ let asserted = differential_fixture("unsafehead_asserted.tsv");+ let cert = differential_fixture("unsafehead_cert.tsv");+ if common::skip_unless(+ rules.exists() && asserted.exists() && cert.exists(),+ "isabelle/fixtures-differential/unsafehead_*.tsv",+ "they are committed",+ ) {+ return;+ }++ let text = std::fs::read_to_string(&cert).unwrap();+ let mut step = parse_step(text.lines().next().unwrap()).expect("the probe must parse");+ assert_eq!(step.concl[2], "z", "the claimed conclusion must carry the bare term `z`");+ assert!(!step.binds.iter().any(|(k, _)| k == "z"), "and `z` must start out unbound");++ // The repair, and it is the only one available: bind `z` to what the conclusion says.+ step.binds.push(("z".to_string(), "z".to_string()));+ let repaired = std::env::temp_dir().join(format!("oo-d2b-repaired-{}.tsv", std::process::id()));+ std::fs::write(&repaired, render_step(&step) + "\n").unwrap();++ let lean = run_lean(&rules, &asserted, &repaired);+ let isa = run_isabelle(&rules, &asserted, &repaired);+ assert_eq!(+ lean.exit, 0,+ "the repaired certificate must be accepted, or decision 0008 costs more than it \+ claims: it would be refusing the inference rather than the omission"+ );+ assert_eq!(lean.verdict.as_deref(), Some("entailed_under_supplied_rules"));+ assert_eq!(isa.exit, 0, "and both kernels must accept it, or the format still has two readings");+ assert_eq!(lean, isa);+ let _ = std::fs::remove_file(&repaired);}/// **Divergence D2c: the same hole, found by the fuzzer rather than designed.**@@ -1314,11 +1446,13 @@ fn divergence_d2_binding_omits_a_variable_named_like_a_term() {////// It is worth its own test because of where it came from. D2a needed a graph whose/// subject was spelled like a variable, and the obvious objection is that nobody writes-/// such a graph. This one needed a single character to change in a rule file. The hole is-/// reachable by a typo, and `substOf`'s silent default is what turns a typo into an-/// accepted certificate rather than an error.+/// such a graph. This one needed a single character to change in a rule file. The hole was+/// reachable by a typo, and `substOf`'s silent default was what turned a typo into an+/// accepted certificate rather than an error. That is the case that decided decision 0008+/// against making the permissive reading normative: a default nobody would write down,+/// reached by a keystroke.#[test]-fn divergence_d2c_fuzzer_found_the_same_hole_through_a_typo() {+fn resolved_d2c_the_hole_the_fuzzer_found_through_a_typo_is_closed() {if skip() {return;}@@ -1343,54 +1477,68 @@ fn divergence_d2c_fuzzer_found_the_same_hole_through_a_typo() {assert_eq!(differing.len(), 1, "exactly one field differs: {a:?} vs {b:?}");assert_eq!(b[differing[0]], "?", "and the one that differs is a bare question mark");- assert_eq!(- binding_defect(&rules, &cert),- Some(- "D2: the binding does not cover every variable of the cited rule. Isabelle \- rejects (R_binding_incomplete); Lean's substOf sends the unbound variable \- to its own NAME and carries on, so the step checks whenever that name is \- the term the certificate used."- ),- "this must be classified as D2 and not as something new"+ assert!(+ binding_defect(&rules, &cert).is_some_and(|w| w.starts_with("D2")),+ "this must still be classified as D2 and not as something new");let lean = run_lean(&rules, &asserted, &cert);let isa = run_isabelle(&rules, &asserted, &cert);- assert_eq!(lean.exit, 0, "Lean accepts: the empty-named variable takes the empty term");- assert_eq!(isa.exit, 1, "Isabelle rejects: binding_incomplete");- assert_ne!(lean, isa);+ assert_eq!(+ lean.exit, 1,+ "Lean must now refuse the empty-named variable rather than send it to the empty term"+ );+ assert_eq!(isa.exit, 1, "Isabelle rejects: binding_incomplete, as it always did");+ assert_eq!(lean, isa, "D2c is resolved: the two kernels now read these bytes the same way");++ // The control, over the probe the fuzzer started from. Its `?o` is intact and its+ // binding covers the rule, and both kernels accept it, so the refusal above is about+ // the typo and not about anything else in this family of files.+ let ok_rules = differential_fixture("probe_degen2_rules.tsv");+ let ok_asserted = differential_fixture("probe_degen2_asserted.tsv");+ let ok_cert = differential_fixture("probe_degen2_cert.tsv");+ let lean = run_lean(&ok_rules, &ok_asserted, &ok_cert);+ let isa = run_isabelle(&ok_rules, &ok_asserted, &ok_cert);+ assert_eq!(lean.exit, 0, "the un-fuzzed probe must still be accepted by Lean");+ assert_eq!(isa.exit, 0, "and by Isabelle");+ assert_eq!(lean, isa);}-/// **Divergence D2b, the sharp form of D2.** A rule whose HEAD carries a variable its-/// body never binds, and a certificate that does not bind it either.+/// **D2b, the sharp form of D2, resolved by decision 0008.** A rule whose HEAD carries a+/// variable its body never binds, and a certificate that does not bind it either.////// The rule is `?s <p> ?o -> ?s <q> ?z`. The graph is one ordinary triple of IRIs,/// `<a> <p> <b>`; nothing about it is contrived. The certificate binds `s` and `o`, omits/// `z`, and claims the conclusion `<a> <q> z`.///-/// Lean accepts it. `substOf` sends the unbound `z` to the string `"z"`, the head-/// instantiates to exactly the claimed conclusion, and the run reports-/// `entailed_under_supplied_rules`. Isabelle rejects it, `R_binding_incomplete`.+/// Lean used to accept it. `substOf` sent the unbound `z` to the string `"z"`, the head+/// instantiated to exactly the claimed conclusion, and the run reported+/// `entailed_under_supplied_rules`. Isabelle rejected it, `R_binding_incomplete`.///-/// This is the same hole as D2 and a worse consequence. The accepted conclusion contains+/// This was the same hole as D2 and a worse consequence. The accepted conclusion contained/// the term `z`, which is not an IRI, not a blank node and not a literal: it is not RDF,/// and no serialiser can write it. Lean's term type is an opaque string, so nothing in-/// the checker notices. The term was never written by the certificate's author; it was+/// the checker noticed. The term was never written by the certificate's author; it was/// minted out of a VARIABLE NAME in the rule file.///-/// It is still not unsoundness. `EntailsR` is a statement about `Interp`, whose `ι` is+/// It was still not unsoundness. `EntailsR` is a statement about `Interp`, whose `ι` is/// total over terms, so `<a> <q> z` genuinely holds in every interpretation that models-/// the graph and satisfies the rule. The theorem is true. What is false is the thing a+/// the graph and satisfies the rule. The theorem was true. What was false is the thing a/// reader takes the theorem to be about.///-/// The engine already refuses to EVALUATE such a rule: `parse_rules` in `src/reason.rs`+/// The engine already refused to EVALUATE such a rule: `parse_rules` in `src/reason.rs`/// rejects "a head variable the body never binds", and `reason_horn_emit_test.rs` gates-/// it. That guard is in the PRODUCER only. `oo-horn` is a checker anyone may point at any-/// rule file, and it has no such guard, so the guarantee evaporates exactly when the+/// it. That guard was in the PRODUCER only. `oo-horn` is a checker anyone may point at any+/// rule file, and it had no such guard, so the guarantee evaporated exactly when the/// certificate did not come from this engine — which is the only case in which an-/// independent checker is worth having.+/// independent checker is worth having. Decision 0008 puts the guard in the CHECKER, which+/// is where a guard about what a certificate means has to live.+///+/// What it does NOT do is make the conclusion writable RDF. Bind `z` explicitly and both+/// kernels accept `<a> <q> z`. See `the_refusal_costs_no_certificate_anybody_meant`, which+/// is where that boundary is pinned so nobody reads this test as closing it.#[test]-fn divergence_d2b_unsafe_rule_head() {+fn resolved_d2b_an_unsafe_rule_head_is_refused_by_both() {if skip() {return;}@@ -1418,12 +1566,13 @@ fn divergence_d2b_unsafe_rule_head() {let lean = run_lean(&rules, &asserted, &cert);let isa = run_isabelle(&rules, &asserted, &cert);assert_eq!(- lean.exit, 0,- "Lean accepts a conclusion containing a term minted from a variable's name"+ lean.exit, 1,+ "Lean must no longer accept a conclusion containing a term minted from a variable's \+ name");- assert_eq!(lean.verdict.as_deref(), Some("entailed_under_supplied_rules"));- assert_eq!(isa.exit, 1, "Isabelle rejects: binding_incomplete");- assert_ne!(lean, isa, "if these ever agree, D2b has been resolved and this test should say how");+ assert_eq!(lean.verdict, None);+ assert_eq!(isa.exit, 1, "Isabelle rejects: binding_incomplete, as it always did");+ assert_eq!(lean, isa, "D2b is resolved: the two kernels now read these bytes the same way");}/// The corners of the term format that no generated certificate reaches. Bothdiff --git a/tests/reason_horn_emit_test.rs b/tests/reason_horn_emit_test.rsindex 82f3145b..e9f6dc77 100644--- a/tests/reason_horn_emit_test.rs+++ b/tests/reason_horn_emit_test.rs@@ -329,6 +329,114 @@ fn every_binding_instantiates_the_body_and_the_head() {}}+/// **Decision 0008, on the producer side.** No binding this engine writes has a repeated+/// key, and none omits a variable of the rule it cites. Those are the two shapes the+/// checker now refuses, so if the engine could emit either it would be a producer that+/// writes certificates its own checker rejects.+///+/// It structurally cannot, and the structure is worth naming because the run below is+/// evidence and not the argument.+///+/// * **No repeated key.** `run_horn` builds the binding from `rule.vars`, and `rule.vars`+/// is assembled with `!vars.iter().any(|x| x == v)` guarding every push. It is a+/// deduplicated list before a single binding is written, so a repeat has no way in.+/// * **No omitted variable.** The same `rule.vars` is collected over `r.atoms()`, which is+/// `body.iter().chain(once(&head))`, body AND head. So the binding is written from+/// exactly the set of variables the rule mentions, which is exactly the set the checker+/// requires, and coverage holds by construction rather than by care.+/// * **And the `expect` in between cannot fire.** `env[i].expect(..)` would panic on a+/// variable the body never bound, and `parse_rules` refuses "a head variable the body+/// never binds" before any table reaches the evaluator, and+/// `a_malformed_rule_table_is_refused_with_a_reason` is that guard, run. So every member+/// of `rule.vars` occurs in the body and `match_body` has bound it.+///+/// The run is over every rule table and graph this file has, because a structural argument+/// that nobody checks against the bytes is how a structural argument goes stale.+#[test]+fn no_emitted_binding_is_one_the_format_now_refuses() {+ let Some(builtin) = builtin_table() else { return };+ let tables: Vec<(&str, String)> = vec![+ ("ancestor", ancestor_rules()),+ ("builtin", builtin),+ ("no-body", rule("fact", &[], [&iri("a"), &iri("b"), &iri("c")])),+ ];+ let graphs: Vec<(&str, &str)> = vec![("chain", CHAIN), ("every-horn-rule", EVERY_HORN_RULE)];++ let mut lines = 0usize;+ for (tn, table) in &tables {+ for (gn, ttl) in &graphs {+ let dir = scratch(&format!("wellformed-{tn}-{gn}"));+ emit(ttl, table, &dir);+ let rules = parse_rules(&std::fs::read_to_string(dir.join("rules.tsv")).unwrap())+ .expect("the table the engine wrote must parse");+ 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!("{tn}/{gn} line {}: rule index {ri} is off the end", n + 1));++ let keys: Vec<&str> = binds.iter().map(|(k, _)| k.as_str()).collect();+ let mut seen: BTreeSet<&str> = BTreeSet::new();+ for k in &keys {+ assert!(+ seen.insert(k),+ "{tn}/{gn} line {}: the binding repeats the key '{k}'. Decision 0008 \+ refuses that, so this engine would be writing a certificate its own \+ checker rejects: {keys:?}",+ n + 1+ );+ }++ // Every variable of the rule, body AND head, exactly as `bindsCover` reads+ // `RulePattern.varList`.+ let mut wanted: BTreeSet<&str> = BTreeSet::new();+ for a in r.body.iter().chain(std::iter::once(&r.head)) {+ for p in [&a.s, &a.p, &a.o] {+ if let open_ontologies::reason::Pat::Var(v) = p {+ wanted.insert(v.as_str());+ }+ }+ }+ let missing: Vec<&&str> = wanted.iter().filter(|v| !keys.contains(v)).collect();+ assert!(+ missing.is_empty(),+ "{tn}/{gn} line {}: the binding omits {missing:?}, which rule '{}' mentions. \+ Decision 0008 refuses that",+ n + 1,+ r.name+ );+ lines += 1;+ }+ }+ }++ // A test that checked nothing would also pass every assertion above.+ assert!(lines >= 20, "only {lines} emitted steps were checked; the corpus has collapsed");+}++/// The other half of the producer argument, and the one a structural claim cannot make on+/// its own: a rule table whose HEAD carries a variable the body never binds is refused+/// before it is ever evaluated, so the `expect` in `run_horn`'s binding construction has+/// no reachable input. Without this, "coverage holds by construction" would rest on a+/// panic never firing rather than on a table never arriving.+#[test]+fn a_head_variable_the_body_never_binds_never_reaches_the_evaluator() {+ let unsafe_head = "r\t1\t?s\t<http://ex.org/p>\t?o\t?s\t<http://ex.org/q>\t?z\n";+ let e = parse_rules(unsafe_head).expect_err("this table must be refused, not evaluated");+ assert!(e.to_string().contains("does not occur in the body"), "{e}");++ // And it is refused through the same door `run_horn` uses, not only through the+ // function this test calls directly.+ let dir = scratch("unsafehead");+ let table = dir.join("rules.tsv");+ std::fs::write(&table, unsafe_head).unwrap();+ let store = Arc::new(GraphStore::new());+ store.load_turtle(&format!("{PREFIXES}{CHAIN}"), None).unwrap();+ let err = Reasoner::run_horn(&store, &table, &dir.join("cert"))+ .expect_err("run_horn must refuse the table rather than run it");+ assert!(err.to_string().contains("does not occur in the body"), "{err}");+}+// ── 4. The generic path against the hardcoded one ───────────────────────────/// One graph for every built-in rule that is a Horn rule. No `owl:intersectionOf`