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
Add Rocq as an independent third formalisation, and report what it disagreed about (#186)
Fabio Rovai5e74d853317b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex f6ed8144..96da4f45 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -600,6 +600,61 @@ jobs:# distribution and the divergence count are PRINTED by the test and read# out of this log: no document is allowed to carry them by hand.run: POLYDIR=$HOME/polyml OO_REQUIRE_FIXTURES=1 cargo test --test cross_kernel_differential_test -- --nocapture+ # THE THIRD KERNEL.+ #+ # `rocq/` is a third independent formalisation of the same Horn certificate+ # checker, in Rocq 9.2, written from the specifications and the fixture data+ # with nothing under `lean/OOCert/` or `isabelle/` opened.+ # `tests/rocq_kernel_differential_test.rs` runs it beside the Lean one over a+ # corpus of its own and requires them to agree except on one named cause,+ # which is recorded in docs/decisions/0012.+ #+ # ROCQ 9.2 IS IN NO UBUNTU APT REPOSITORY, and this was checked rather than+ # assumed, because `prover9` having no installation candidate on noble is what+ # broke this job the first time it ran on main. There is no `rocq` package at+ # all; noble ships `coq` 8.18, which cannot read `From Stdlib Require`, the+ # form every theory here uses. Building from source with opam takes half an+ # hour. The official container image is the route, and the version is asserted+ # INSIDE the container so that a moved tag fails loudly rather than silently+ # checking the proofs with a different prover.+ #+ # The workspace is made group and world writable first because the image runs+ # as its own uid and the runner's checkout is owned by the runner's. The+ # ownership is handed back afterwards so the Rust legs can read the binary.+ - name: Build the third formalisation, and check its axiom footprint+ run: |+ set -euo pipefail+ chmod -R a+rwX .+ # BASH, not sh. build.sh uses arrays, and /bin/sh on the image is dash,+ # which does not have them. The image's ENTRYPOINT is `opam exec --`, so+ # rocq, ocamlopt and ocamlfind are already on PATH and no `opam env` dance+ # is needed; the tool check below fails loudly if that ever stops being+ # true, rather than leaving `make` to fail three screens later.+ docker run --rm -v "$PWD:/work" -w /work rocq/rocq-prover:9.2.0 \+ bash -c 'set -eu+ command -v rocq make ocamlopt+ rocq --version+ rocq --version | grep -q "version 9\.2" \+ || { echo "the image is not Rocq 9.2"; exit 1; }+ bash rocq/build.sh'+ sudo chown -R "$(id -u):$(id -g)" rocq+ ls -l rocq/build/oo-horn-rocq+ # A gate nobody has watched fail is decoration. This breaks one Qed in a+ # scratch copy and requires the audit to reject it, so the line above is+ # known to be measuring something.+ - name: Show the axiom gate failing on an admitted proof+ run: |+ set -euo pipefail+ chmod -R a+rwX .+ docker run --rm -v "$PWD:/work" -w /work rocq/rocq-prover:9.2.0 \+ bash -c 'bash rocq/build.sh --prove-the-gate-can-fail'+ sudo chown -R "$(id -u):$(id -g)" rocq+ - name: Run the Lean and Rocq kernels over one corpus, and require them to agree+ # --nocapture because the corpus size and every per-bucket count are PRINTED+ # by the test and read out of this log. No document is allowed to carry them+ # by hand; docs/decisions/0012 says so in the paragraph that carries a+ # snapshot of them.+ run: OO_REQUIRE_FIXTURES=1 cargo test --test rocq_kernel_differential_test -- --nocapture# And the gate on the gates. This one needs no toolchain; it fails when a# test file that can skip is run by no job under OO_REQUIRE_FIXTURES=1 and# is not on the written exception list. It is the mechanism the leg abovediff --git a/.gitignore b/.gitignoreindex 7b4b57a8..2904720c 100644--- a/.gitignore+++ b/.gitignore@@ -71,3 +71,31 @@ isabelle/build/# Claude Code agent worktrees: machine-local, never part of the repo..claude/worktrees/++# rocq/ build artefacts. Nothing here is a source.+#+# theories/FixtureData.v is GENERATED from tests/fixtures/horn/ by+# gen_fixture_data.sh on every build, deliberately rather than committed: a+# committed copy of a fixture is a second file that can drift from the first, and+# a kernel gate over a drifted copy is a gate over nothing.+#+# driver/rocq_horn_core.ml* is the extraction output and is NOT committed, which+# is the opposite of what isabelle/driver/oo_horn_generated.ML does. The reason+# the Isabelle export is committed is that regenerating it needs several+# gigabytes of Isabelle; regenerating this one needs a container image CI already+# pulls, so committing it would buy nothing and add an artefact no job rebuilds.+rocq/build/+rocq/theories/FixtureData.v+rocq/theories/*.vo+rocq/theories/*.vok+rocq/theories/*.vos+rocq/theories/*.glob+rocq/theories/.*.aux+rocq/Makefile.rocq+rocq/Makefile.rocq.conf+rocq/.Makefile.rocq.d+rocq/driver/rocq_horn_core.ml+rocq/driver/rocq_horn_core.mli+rocq/driver/*.cmi+rocq/driver/*.cmx+rocq/driver/*.odiff --git a/docs/ci-gates.md b/docs/ci-gates.mdindex 8384db36..1c681bf2 100644--- a/docs/ci-gates.md+++ b/docs/ci-gates.md@@ -77,6 +77,7 @@ job invokes the file at all.| `rule_syntax_frontend_test.rs` | lake | `lean` job | **strict** || `reason_horn_emit_test.rs` | lake + `tests/fixtures/horn/` (in tree) | `lean` job | **strict** || `cross_kernel_differential_test.rs` | lake **and** Poly/ML | `lean` job | **strict** |+| `rocq_kernel_differential_test.rs` | lake **and** Rocq 9.2, which CI gets from the `rocq/rocq-prover:9.2.0` image because no Ubuntu repository carries it | `lean` job | **strict** || `tstp_derivation_test.rs` | the recorded Vampire and E derivations in `tests/fixtures/tstp/` (in tree); ONE test also wants vampire on `PATH` | any job for the recorded part; no job installs a prover | **skips** — 34 of 35 need nothing, but the file cannot be made strict while the 35th wants a prover no job installs || `tstp_cli_test.rs` | the same fixtures + the debug CLI | any job | **strict** || `clinical_test.rs` | `data/crosswalks.parquet` | nothing — `data/` is gitignored | **skips** |diff --git a/docs/decisions/0015-a-blank-line-is-a-line-or-it-is-not.md b/docs/decisions/0015-a-blank-line-is-a-line-or-it-is-not.mdnew file mode 100644index 00000000..412aa0d1--- /dev/null+++ b/docs/decisions/0015-a-blank-line-is-a-line-or-it-is-not.md@@ -0,0 +1,131 @@+# 0015 · A blank line is a line, or it is not, and the format never said which++- **Status**: OPEN. Reported, not closed. Nothing on either side has been changed to make+ the disagreement go away, and nothing should be until somebody decides what the format+ means · found by `rocq/`, a third independent formalisation, run beside `lean/` over+ 1,593 rows by `tests/rocq_kernel_differential_test.rs` · a second finding in the same+ run, a resource defect in the NEW checker, IS closed, below+- **Written**: 2026-09-18+- **Related**: decision 0008 (a binding is data), which is the same shape of defect found+ the same way by the second kernel; decision 0003 (a rule is data)++## The problem++`rocq/` is a third formalisation of the Horn certificate checker, written from the+specifications, the decision records and the fixture bytes. Run beside the Lean checker+over a corpus of 1,593 rows built from `tests/fixtures/horn/` and systematic mutations of+it, the two agreed on 1,269 and disagreed on 324, always in the same direction, with one+cause and nothing unexplained.++**Lean skips an empty line. Rocq refuses one.**++It holds in all three input files. A rules table, an asserted graph or a certificate that+carries an empty line anywhere, at the top, in the middle, or as a second newline at the+end, is read by Lean as if the line were not there, and is refused by Rocq with exit 2.+Every one of the 324 divergent rows is that, and every row in the corpus that carries an+empty line at all is divergent: 108 in the rules table, 108 in the asserted graph, 108 in+the certificate.++Neither checker is unsound, and saying so is not a softening. An empty line is not a+step, not a triple and not a rule. Skipping it derives nothing; refusing it asserts+nothing. Both soundness theorems are untouched by this and would be untouched by either+answer. **The defect is in the FORMAT.** Nothing in `docs/lean-certificates.md` or in+decision 0003 says whether an empty line is a line, so two readings of the same bytes were+both available and a certificate's readability depends on which verified checker reads it.++## The sharp part++The obvious reaction is that tolerance is harmless and Rocq is being difficult. There is a+fact that makes that reaction worse than wrong, and it was found by the same corpus.++**Lean's tolerance is for the EMPTY string exactly.** A line holding one space is refused.+A line holding one tab is refused. A line holding one carriage return is refused. Both+checkers agree on all three.++So the leniency does not cover the case that motivates leniency. The reason a parser+tolerates blank lines is that files acquire them: an editor adds one at the end, a shell+redirection adds one, a copy and paste adds one. The single most likely way for this+repository's files to acquire a blank line is a checkout with CRLF endings, and in such a+file a blank line is `\r`, which Lean refuses. `.gitattributes` pins LF on the certificate+formats, which is the right fix and is also the reason the tolerance has never been needed:+it is a rule that fires only on the inputs it was not written for.++## What is NOT being decided here++Which side should move. That is a question about the format and it belongs to whoever owns+the format, not to whoever wrote the third checker. Both answers are defensible:++- **Refuse, as Rocq does.** A parser that repairs its input decides what the input meant.+ Refusal is the reading with no convention in it, and it is what both checkers already do+ for a line of one space.+- **Skip, as Lean does.** Then say so in `docs/lean-certificates.md`, and make it uniform:+ skip a line that is empty after stripping trailing whitespace, so that the CRLF case the+ rule exists for is actually covered.++What must not happen is the third formalisation being edited to agree with the first.+`rocq/` was written from the specifications for exactly one purpose, and an independent+reading edited to match the thing it is reading is worth nothing. The same sentence appears+in `isabelle/README.md` and it is the same sentence for the same reason.++## The other finding, which IS closed, and which was in the new checker++The same run found a defect in `rocq/` rather than in the format, and it is the more+serious of the two.++A certificate citing rule `99999999999999999999` made the Rocq checker die of a+`Stack_overflow`. Rocq's `nat` is unary, the parser built the number before it looked at+it, and a twenty digit index is not a number a machine can build that way. That is a denial+of service, and it is not the worst of it: **OCaml exits an uncaught exception with status+2, which is this tool's code for a parse error.** The crash reported a verdict. Nothing in+the output said the checker had failed; it said the file could not be read.++The only reason anybody looked is that Lean answered 1 where Rocq answered 2, and a+one-digit difference in an exit code is what a differential is for.++Both halves are closed.++1. **The cause.** Count fields are parsed into binary naturals and nothing recurses on them+ (`R-PARSE-8` in `rocq/theories/Parse.v`, `R-STEP-3` in `rocq/theories/Syntax.v`,+ `R-CHK-6` in `rocq/theories/Checker.v`). The index lookup walks the rule table and+ decrements the index in binary, so an out of range index costs the length of the table+ whatever its magnitude. The answer is now a rejection, in four milliseconds, and it+ agrees with Lean.+2. **The disguise.** `rocq/driver/main.ml` catches every exception and exits 70,+ `EX_SOFTWARE`, which nothing else in the tool uses. A crash can no longer be mistaken+ for a verdict or for a parse error, and+ `tests/rocq_kernel_differential_test.rs` treats any exit code that is not 0, 1 or 2 as a+ failure of the whole comparison rather than as a row.++`a_crash_is_not_a_verdict` is the regression, and it pins the answer and the time it takes.++## The numbers++Over 1,593 rows: 27 base triples, being three rule tables crossed with nine shipped+(asserted graph, certificate) pairs, each mutated by fourteen byte level edits applied to+each of the three files and sixteen structural edits applied to the certificate's first+step.++ both accept: 82+ both reject: 809+ both unparseable: 378+ divergent, explained: 324+ 108 the rules table contains an empty line+ 108 the asserted graph contains an empty line+ 108 the certificate contains an empty line+ divergent, unexplained: 0+ checker crashes: 0++`cargo test --test rocq_kernel_differential_test -- --nocapture` prints these and is the+only place they should be read from. The figures above are a snapshot of one run and will+be stale the moment the corpus changes, which is what happened three times to the numbers+decision 0008 carried.++The floor matters more than any of those columns. Agreement is cheap when one side refuses+everything, so the test requires at least twenty rows ACCEPTED BY BOTH, and it also+requires the quarantined divergence to still reproduce: a run in which the empty-line rows+stopped diverging means a checker changed or the generator broke, and either way somebody+should look rather than enjoy a green tick.++## Since written++Nothing yet.diff --git a/docs/decisions/README.md b/docs/decisions/README.mdindex 08fe1361..ca263ee9 100644--- a/docs/decisions/README.md+++ b/docs/decisions/README.md@@ -14,6 +14,7 @@ and whose benefit is not gets dropped the first time it is inconvenient.| [0008](0008-a-binding-is-data-and-evidence-admits-one-reading.md) | A binding is data, and evidence admits one reading | A certificate format admitting two readings, so two checkers disagree || [0012](0012-concurrency-lives-below-the-certificate.md) | Concurrency lives below the certificate, and a proof cannot follow it there | Adopting a program logic for a hazard that lives in a dependency, and calling the result assurance || [0014](0014-a-verifier-that-cannot-read-the-code-verifies-a-rewrite.md) | A verifier that cannot read the code verifies a rewrite | Counting a green verifier as evidence about code it never read |+| [0015](0015-a-blank-line-is-a-line-or-it-is-not.md) | A blank line is a line, or it is not, and the format never said which | The same failure again, found by a third kernel and still OPEN: two checkers reading one file differently because nobody wrote down what an empty line is |There is no 0004. The decision now numbered 0006 was drafted as 0004 on a branch that never merged,so the number never reached `main`. It is left as a hole rather than reused, because a reused number@@ -43,6 +44,23 @@ readings, only two ways of discarding half the certificate. Closed byreturn the same answer on every row of a corpus of 2,075 certificates, 484 of which exercise theordering property both inductions rest on, against 123 before that corpus was deepened.+**A third kernel, and a second format question nobody had written down.** `rocq/` is an independent+formalisation in Rocq 9.2, written from the specifications with `lean/OOCert/` and `isabelle/` unread.+Run beside the Lean checker over 1,593 rows it agreed on 1,269 and disagreed on 324, one cause,+nothing unexplained: Lean skips an empty line in all three input files and Rocq refuses one. Neither+is unsound, because an empty line is not a step, not a triple and not a rule. It is the same category+of defect as decision 0008's and it is+[decision 0015](0015-a-blank-line-is-a-line-or-it-is-not.md), which is OPEN rather than closed,+because which side should move is a question about the format and not about whoever wrote the third+checker.++The same run found something sharper in the new checker than in the format. A certificate citing rule+`99999999999999999999` made it die of a stack overflow, and OCaml exits an uncaught exception with+status 2, which is that tool's code for a parse error, so **the crash was reporting a verdict**. The+only reason anybody looked is that one checker answered 1 where the other answered 2. That is the+whole argument for differentials in one sentence, and it is worth more than the divergence it was+looking for.+That agreement was, until 15 September 2026, checked by nothing. No workflow installed the secondkernel, so the test requiring zero divergence skipped, and a skipped test reports `ok`. CI runs bothkernels over the whole corpus on every pull request now, and [docs/ci-gates.md](../ci-gates.md) isdiff --git a/docs/reasoning-systems-inventory.md b/docs/reasoning-systems-inventory.mdindex 4936bedd..3c1d21b0 100644--- a/docs/reasoning-systems-inventory.md+++ b/docs/reasoning-systems-inventory.md@@ -30,6 +30,7 @@ about the file we gave it. The addendum to decision 0005 draws the new line.| Prover9 | First-order prover | Declined. Unmaintained since 2011, refutations uncheckable. || cvc5 | SMT solver | Not installed. Same role as Z3 when it is. || Isabelle/HOL | Proof assistant | Built, as an independent second FORMALISATION. It disagreed with the Lean. Below. |+| Rocq 9.2 | Proof assistant | Built, as an independent THIRD formalisation of the Horn layer only. It disagreed with the Lean too, about what a line is. Below. || Dedukti, Lambdapi | Logical framework | Declined twice, for portability and for re-checking. Reasons below. || lean4export, nanoda | Lean export and external checker | Investigated, RUN, not adopted. `docs/independent-rechecking.md`. || leanchecker | Ships in the Lean toolchain | Passes here. Not in CI yet. Not an external verifier. |@@ -197,6 +198,39 @@ re-checks a Lean proof.take, including an export of this repository's own Lean and a run through an independent Rustchecker.++## Rocq, and what the third kernel found++Rocq 9.2, the proof assistant formerly called Coq, is used for the same job Isabelle is used for and+for a deliberately smaller slice of it: an independent THIRD formalisation of the Horn certificate+checker, in `rocq/`, covering the Horn layer and nothing else. It builds with no `Admitted`, no+`Axiom`, and an axiom footprint that comes back EMPTY rather than small: `Print Assumptions` reports+all fifteen advertised theorems closed under the global context, with none of the three classical+axioms the Lean layer pins. Its checker is extracted to OCaml so it can be run over the same bytes.++The independence is real but weaker than Isabelle's, and `rocq/README.md` says exactly where it stops+rather than leaving a reader to assume. Nothing under `lean/OOCert/` and no `.thy` file was opened;+`lean/HMain.lean` was, for the command line and the two verdict words, and decision 0008 quotes Lean's+`substOf` in its own text, so the two well-formedness conjuncts were known before the checker was+written. That part corroborates rather than discovers, and it is discounted accordingly.++Run beside the Lean checker over 1,593 rows the two agreed on 1,269 and disagreed on 324, with one+cause and nothing unexplained: **Lean skips an empty line and Rocq refuses one**, in all three input+files. Neither is unsound. [Decision 0015](decisions/0015-a-blank-line-is-a-line-or-it-is-not.md) is+OPEN, because which side should move is a question about the format.++The more useful thing the comparison produced was not the divergence. A certificate citing rule+`99999999999999999999` made the Rocq checker die of a stack overflow, and OCaml exits an uncaught+exception with status 2, which is that tool's code for a parse error, so the crash was reporting a+verdict about the file. Nothing in the output said the checker had failed. The only reason anybody+looked is that the two checkers differed by one in an exit code. Both halves are fixed: count fields+are binary, and the driver now exits 70 on any exception so a crash cannot wear a verdict's clothes.++What this does NOT do is cover any of the rest of `lean/`. The four non-Horn rules, the mixed+certificate layer, refutations, the description-logic and first-order model certificates, SHACL and+the institution material are all outside it, and `rocq/README.md` states the boundary in the negative+for that reason.+## Dedukti, and why notDedukti is a logical framework designed so that proofs from different systems can be expressed in onediff --git a/rocq/README.md b/rocq/README.mdnew file mode 100644index 00000000..7907569b--- /dev/null+++ b/rocq/README.md@@ -0,0 +1,170 @@+# `rocq/`: an independent third formalisation of the Horn certificate checker++This directory is a third formalisation of the Horn certificate checker and its model+theory, in Rocq 9.2 (the proof assistant formerly called Coq). It exists for the reason+`isabelle/` exists: a machine-checked proof rules out a bad argument and says nothing+about a bad definition, and a bad definition is invisible from inside a single+formalisation by construction. A second reading catches a definitional mistake only if the+second reading is genuinely a second one.++It is smaller than either of the other two and it says so throughout. What is covered and+what is not is in "Scope" below, and the boundary is stated in the negative, because a+third formalisation that overclaims is worse than no third formalisation.++## Build++Needs Rocq 9.2 and an OCaml compiler. Both come from `brew install rocq` on macOS+(`rocq` 9.2.0 with OCaml 5.5.0 as of this writing) and from `apt-get install rocq-prover`+or the `rocq-prover/rocq` Docker image elsewhere.++ rocq/build.sh++That regenerates the fixture data, compiles every theory, checks the axiom footprint and+links the extracted checker into `rocq/build/oo-horn-rocq`. It fails if any audited+theorem is not closed under the global context.++ rocq/build.sh --prove-the-gate-can-fail++That copies the tree, replaces one `Qed` with `Admitted`, runs the same build, and fails+if the build SUCCEEDS. A gate nobody has watched fail is decoration.++## Run the checker++ rocq/build/oo-horn-rocq check RULES.tsv ASSERTED.tsv HORN.tsv++Exit 0 accepted, 1 rejected, 2 unreadable or unparseable. One JSON object on stdout. The+CLI shape and the exit codes are `lean/HMain.lean`'s deliberately, so the differential+compares two checkers rather than two ways of being invoked.++## How independent is it, exactly++Less independent than `isabelle/`, and the difference matters enough to be the second+section of this file rather than a footnote.++**Read while this was written:** `docs/lean-certificates.md`, decision records 0002, 0003+and 0008, `docs/reasoning-systems-inventory.md`, `isabelle/README.md`, the committed+fixture bytes under `tests/fixtures/horn/`, and `lean/HMain.lean` for the command line,+the exit codes and the two verdict words.++**Not opened:** every file under `lean/OOCert/`, including `Horn.lean`, `HornBuiltin.lean`,+`HornParse.lean` and `Parse.lean`, and every `.thy` file under `isabelle/`. No definition,+no proof and no rule lemma from either was read. Both directories were LISTED, which is how+this paragraph can name the files it did not open, and a file name is not a definition.++**Known leakage, stated because it is unavoidable and because a reader should discount+for it:** decision 0008 quotes Lean's `substOf` and Isabelle's `distinct (map fst b)` in+its own text, so the shape of the two well-formedness conjuncts was known before+`Checker.v` was written, and `Determinacy.v` re-derives a property those records describe+rather than discovering it. That part of this development corroborates; it does not+discover. Everything else, the model theory, the premise discipline, the parser's+decisions and all twenty-seven built-in arms, was designed from the specifications and the+fixture data.++Nothing here should ever be edited to agree with `lean/` or with `isabelle/`. If the three+disagree, that is a finding and it belongs in a report before it belongs in a patch.++## Scope: what is covered++* **The rule-relative soundness theorem, end to end from the bytes.** `run_is_sound` in+ `Run.v` takes three file contents, and says that if the tool accepts then every+ conclusion of the parsed certificate is true in every world that satisfies the parsed+ graph and every parsed rule.+* **The absolute theorem for the built-in table.** `entails_of_builtin_horn` in+ `Builtin.v`: a certificate over exactly the built-in twenty-seven rows has conclusions+ true in every model of the asserted graph, with no rule assumed. Each of the+ twenty-seven arms is derived from the semantic conditions of `Interp.v` and each takes+ exactly the conditions it uses as explicit hypotheses.+* **What the two well-formedness conjuncts buy, and what they do not.**+ `horn_certificate_sound_without_wellformedness` proves the soundness theorem with both+ conjuncts deleted, so neither carries soundness content, and+ `wellformed_determines_instantiation` proves what they do carry. Both halves are refuted+ with their own hypothesis dropped.+* **Non-vacuity.** `Witness.v` exhibits a model of the conditions, exhibits a triple that+ is not absolutely entailed, and exhibits a one-line user rule table under which that+ same triple IS relatively entailed. The last of those is decision 0003's point as a+ theorem: the two verdicts are different claims.+* **The transcribed table is the committed one.** `Fixtures.v` parses+ `tests/fixtures/horn/builtin_rules.tsv` with this development's own parser inside the+ kernel and requires the result to equal the table `Builtin.v` proves things about.+* **Every shipped fixture's verdict, computed by the kernel.** Also in `Fixtures.v`, which+ is the only handle this development has on the extraction step.++## Scope: what is NOT covered++* **The four non-Horn rules.** `cls-int1`, `cls-int2`, `cls-uni` and `cls-oo` read an RDF+ list off the graph, so their premise count is data rather than fixed by the rule. They+ are outside the Horn family and outside this directory, as they are outside the Lean's+ Horn layer.+* **Everything else in `lean/`.** The mixed certificate layer, refutations, the+ description-logic model certificates, the first-order model checker, the SHACL+ evaluator, the institution and comorphism material: none of it is formalised here and+ none of it is even referred to.+* **That the conditions in `Interp.v` are a subset of the Recommendation's.** They are+ written from the RDF 1.1 and OWL 2 RDF-Based Semantics conditions and each carries the+ clause it is meant to be, but the correspondence is read cell by cell by a human and is+ not a theorem. That a subset is the safe direction is the reason it is allowed to be+ prose; a superset would not be.+* **The biconditional reading is a strengthening, and fourteen arms depend on it.**+ R-INT-5 in `Interp.v` is the warning. RDFS states its conditions as implications, and no+ implication in that direction licenses a rule that CONCLUDES a `subClassOf`,+ `subPropertyOf`, `domain` or `range` triple. The OWL 2 RDF-Based Semantics states the+ same conditions as biconditionals, which is stronger, which makes the model class+ smaller and the absolute claim weaker than it looks. The fourteen arms that consume a+ backward condition are named in `Builtin.v` and each one carries the hypothesis in its+ own statement, so the count is checked against the source text by+ `the_fourteen_arms_that_need_a_backward_condition_are_the_fourteen_named` rather than+ counted by hand. `R-BLT-3` carries the qualification that count needs: six other+ conditions are biconditionals too, and arms consume their reverse direction, but those+ are biconditional because that is what `someValuesFrom` and `sameAs` MEAN rather than+ because this development strengthened them. The fourteen is the count of arms resting on+ a reading stronger than the specification they come from, which is the number that+ matters, and it is not the count of arms that use an `iff`.+* **A total denotation.** R-INT-2: interpretations in which some literal fails to denote+ are outside the claim.+* **Extraction.** `Extract.v` uses no `Extract Inductive` and no `Extract Constant`, so+ the trusted glue is as small as it gets, but the extraction mechanism itself is trusted+ and is not verified. `Fixtures.v` computes the shipped verdicts inside the kernel and+ the differential runs the extracted binary over the same files, so a divergence between+ the two is visible; that is a check, not a proof.+* **The driver.** `driver/main.ml` is untrusted, as `isabelle/driver/` is and as+ `lean/HMain.lean` is. It opens files, converts at the boundary, prints JSON and returns+ an exit code.+* **Anything about the engine.** The theorem is conditional on the asserted graph being+ what the file says it is. `docs/trusted-computing-base.md` is where that boundary lives.++## Files++| file | what it holds |+|---|---|+| `theories/Syntax.v` | terms, triples, patterns, rules, steps. No semantics, no checking. |+| `theories/Semantics.v` | worlds, satisfaction, the rule-relative entailment relation. |+| `theories/Checker.v` | the executable checker. No semantics. |+| `theories/Determinacy.v` | what distinct keys and coverage buy, and refutations without each. |+| `theories/Sound.v` | `horn_certificate_sound`, and the same theorem with both conjuncts deleted. |+| `theories/Interp.v` | RDF-based interpretations and the seventeen semantic conditions. |+| `theories/Builtin.v` | the table as data, the twenty-seven arms, `entails_of_builtin_horn`. |+| `theories/Parse.v` | TSV bytes to datatypes, and the rule-table comparison. |+| `theories/Run.v` | the outcome type and `run_is_sound`, the end-to-end statement. |+| `theories/Witness.v` | non-vacuity, and the gap between the two verdicts. |+| `theories/Fixtures.v` | the checker run on the committed bytes, inside the kernel. |+| `theories/Audit.v` | `Print Assumptions` on every advertised theorem. |+| `theories/Extract.v` | extraction to OCaml, with no mapping of any inductive. |+| `theories/FixtureData.v` | GENERATED and gitignored. `gen_fixture_data.sh` writes it. |+| `driver/main.ml` | the untrusted driver. |+| `build.sh` | build, audit, link, and the mutation that proves the audit can fail. |++## Trust boundary++Inside: the Rocq kernel and the theories above.++Outside: the extraction mechanism, the OCaml compiler, file IO, splitting bytes,+JSON, exit codes, and the claim that `asserted.tsv` is the store it says it is.++## The differential++`tests/rocq_kernel_differential_test.rs` runs this checker and the Lean one over one+corpus built from `tests/fixtures/horn/` and systematic mutations of it, and classifies+every row. THE NUMBERS ARE NOT WRITTEN HERE. `cargo test --test+rocq_kernel_differential_test -- --nocapture` prints them and is the only place they+should be read from. What the comparison found, and what it means, is in+`docs/decisions/0015-a-blank-line-is-a-line-or-it-is-not.md`.diff --git a/rocq/_CoqProject b/rocq/_CoqProjectnew file mode 100644index 00000000..8389d503--- /dev/null+++ b/rocq/_CoqProject@@ -0,0 +1,18 @@+-Q theories OOCertRocq+-arg -w -arg -notation-overridden+-arg -w -arg -deprecated++theories/Syntax.v+theories/Semantics.v+theories/Checker.v+theories/Determinacy.v+theories/Sound.v+theories/Interp.v+theories/Builtin.v+theories/Parse.v+theories/Run.v+theories/Witness.v+theories/FixtureData.v+theories/Fixtures.v+theories/Audit.v+theories/Extract.vdiff --git a/rocq/build.sh b/rocq/build.shnew file mode 100755index 00000000..7430542d--- /dev/null+++ b/rocq/build.sh@@ -0,0 +1,161 @@+#!/usr/bin/env bash+#+# Build the Rocq development, check the axiom footprint, and link the extracted+# checker into a native binary.+#+# rocq/build.sh build and gate+# rocq/build.sh --prove-the-gate-can-fail break the audit on a scratch copy+# and require the build to fail+#+# The second form exists because a gate nobody has watched fail is decoration.+# It copies the tree, replaces one Qed with Admitted, runs the same build, and+# fails if that build SUCCEEDS.+set -euo pipefail++here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+cd "$here"++ROCQ="${ROCQ:-rocq}"+# ocamlfind is what a developer machine usually has; the Rocq container image has+# ocamlopt for certain and ocamlfind probably. Neither is needed for the PROOFS, only+# for linking the extracted checker, so fall back rather than fail.+if [ -z "${OCAMLOPT:-}" ]; then+ if command -v ocamlfind >/dev/null 2>&1; then+ OCAMLOPT="ocamlfind ocamlopt"+ else+ OCAMLOPT="ocamlopt"+ fi+fi++# The theorems whose axiom footprint has to come back empty. Every one of them+# is quoted somewhere outside this directory, in rocq/README.md or in the PR+# that added it, so every one of them is a claim that can go stale.+AUDITED=(+ run_is_sound+ horn_certificate_sound+ entails_of_builtin_horn+ horn_certificate_sound_without_wellformedness+ wellformed_determines_instantiation+ no_substitution_extends_a_duplicate_key+ two_extensions_of_an_uncovered_binding_disagree+ builtin_sound+ the_conditions_are_satisfiable+ not_everything_is_absolutely_entailed+ the_relative_verdict_is_strictly_weaker+ the_built_in_table_is_the_committed_fixture+ good_is_accepted_with_the_absolute_verdict+ deep_mutual_support_is_rejected+ deep_mutual_seeded_is_accepted+)++build() {+ local root="$1"+ cd "$root"++ # The fixture bytes become Rocq strings here rather than being committed, so+ # the kernel always evaluates what is in the tree. See gen_fixture_data.sh.+ sh gen_fixture_data.sh++ "$ROCQ" makefile -f _CoqProject -o Makefile.rocq >/dev/null+ make -f Makefile.rocq -j "$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 2)"++ # Re-run the audit file on its own so its output is captured rather than+ # buried in a parallel make log.+ mkdir -p build+ "$ROCQ" c -q -Q theories OOCertRocq -w -notation-overridden,-deprecated \+ theories/Audit.v > build/audit.txt 2>&1 || {+ echo "the audit file failed to compile" >&2+ cat build/audit.txt >&2+ exit 1+ }+}++audit_gate() {+ local root="$1"+ cd "$root"+ local report="$root/build/audit.txt"+ local closed+ closed="$(grep -c 'Closed under the global context' "$report" || true)"+ local want="${#AUDITED[@]}"++ echo "--- axiom footprint (${report#"$here"/})"+ cat "$report"+ echo "---"++ if [ "$closed" -ne "$want" ]; then+ echo "AXIOM GATE FAILED: expected $want theorems closed under the global context, saw $closed." >&2+ echo "A theorem that depends on an axiom, or that is Admitted, prints a list of" >&2+ echo "constants instead of that phrase. The report above says which." >&2+ return 1+ fi++ # The report has to actually mention every audited name, or the count above+ # could be satisfied by printing one theorem fifteen times.+ local missing=()+ for n in "${AUDITED[@]}"; do+ if ! grep -q "Print Assumptions $n\." theories/Audit.v; then missing+=("$n"); fi+ done+ if [ ${#missing[@]} -ne 0 ]; then+ echo "AXIOM GATE FAILED: theories/Audit.v does not print assumptions for: ${missing[*]}" >&2+ return 1+ fi++ # Nothing in the theories may be admitted or postulated. Print Assumptions+ # catches a dependency; this catches a file that compiles with an unused one.+ if grep -nE '^\s*(Admitted|Axiom|Parameter|Conjecture|Hypothesis)\b' theories/*.v; then+ echo "AXIOM GATE FAILED: the lines above postulate rather than prove." >&2+ return 1+ fi+ echo "axiom gate: $closed of $want theorems closed under the global context, no postulates."+}++link() {+ local root="$1"+ cd "$root/driver"+ # shellcheck disable=SC2086+ $OCAMLOPT rocq_horn_core.mli rocq_horn_core.ml main.ml -o ../build/oo-horn-rocq+ rm -f ./*.cmi ./*.cmx ./*.o+ echo "linked $root/build/oo-horn-rocq"+}++if [ "${1:-}" = "--prove-the-gate-can-fail" ]; then+ scratch="$(mktemp -d)"+ trap 'rm -rf "$scratch"' EXIT+ cp -R "$here" "$scratch/rocq"+ mkdir -p "$scratch/tests/fixtures"+ cp -R "$here/../tests/fixtures/horn" "$scratch/tests/fixtures/horn"+ rm -rf "$scratch/rocq/build" "$scratch/rocq/theories"/*.vo* "$scratch/rocq/theories"/*.glob++ # One Qed becomes Admitted. The theorem still exists and every file still compiles;+ # only the audit changes. The line is FOUND rather than written down, so a rename or+ # a reflow cannot quietly turn this into a no-op that reports success.+ target="$scratch/rocq/theories/Sound.v"+ line="$(grep -n '^Theorem horn_certificate_sound :' "$target" | head -1 | cut -d: -f1)"+ if [ -z "$line" ]; then+ echo "cannot find horn_certificate_sound in Sound.v; fix build.sh" >&2+ exit 1+ fi+ qed="$(awk -v start="$line" 'NR>=start && $0=="Qed." {print NR; exit}' "$target")"+ if [ -z "$qed" ]; then+ echo "cannot find the Qed of horn_certificate_sound; fix build.sh" >&2+ exit 1+ fi+ awk -v n="$qed" 'NR==n {print "Admitted."; next} {print}' "$target" > "$target.tmp"+ mv "$target.tmp" "$target"+ echo "mutated Sound.v line $qed: Qed became Admitted"++ mkdir -p "$scratch/rocq/build"+ echo "=== building a copy with one Qed replaced by Admitted ==="+ if build "$scratch/rocq" && audit_gate "$scratch/rocq"; then+ echo "THE GATE CANNOT FAIL. An admitted proof passed the audit." >&2+ exit 1+ fi+ echo+ echo "the gate failed on an admitted proof, which is what it is for."+ exit 0+fi++mkdir -p "$here/build"+build "$here"+audit_gate "$here"+link "$here"diff --git a/rocq/driver/main.ml b/rocq/driver/main.mlnew file mode 100644index 00000000..a1fdae57--- /dev/null+++ b/rocq/driver/main.ml@@ -0,0 +1,118 @@+(* The untrusted driver.++ Everything verified is in [rocq_horn_core.ml], which is extracted from the+ theories and read by nobody. This file opens three paths, hands their bytes+ to [run], prints one JSON object and returns an exit code. It decides+ nothing about what a certificate says: no splitting, no trimming, no+ normalising, no fallback. If it is wrong, it is wrong about file IO and+ printing, which is the same boundary the Lean and the Isabelle drivers sit+ on.++ The CLI shape and the exit codes are `oo-horn`'s deliberately, so that a+ differential compares two checkers rather than two ways of being invoked.++ oo-horn-rocq check RULES.tsv ASSERTED.tsv HORN.tsv++ 0 accepted, 1 rejected, 2 unreadable or unparseable, 70 the checker itself+ failed.++ The fourth code is not decoration. OCaml exits an uncaught exception with+ status 2, which is this tool's code for a parse error, so a Stack_overflow+ inside the extracted checker came out looking exactly like a refusal to read+ the file. That happened, on a certificate citing rule 99999999999999999999,+ and the differential against the Lean checker is what found it. The cause is+ fixed in the theories (R-STEP-3, R-PARSE-8); this handler is the second half,+ so that if anything else ever crashes it cannot be mistaken for a verdict.+ 70 is EX_SOFTWARE from sysexits, and nothing else in this tool uses it. *)++let rec nat_to_int (n : Rocq_horn_core.nat) : int =+ match n with Rocq_horn_core.O -> 0 | Rocq_horn_core.S m -> 1 + nat_to_int m++let bool_of_rocq (b : Rocq_horn_core.bool) : bool =+ match b with Rocq_horn_core.True -> true | Rocq_horn_core.False -> false++(* Rocq's Ascii constructor is little endian: the first argument is bit 0. *)+let ascii_of_char (c : char) : Rocq_horn_core.ascii =+ let n = Char.code c in+ let b i = if n land (1 lsl i) <> 0 then Rocq_horn_core.True else Rocq_horn_core.False in+ Rocq_horn_core.Ascii (b 0, b 1, b 2, b 3, b 4, b 5, b 6, b 7)++let rocq_string (s : string) : Rocq_horn_core.string =+ let acc = ref Rocq_horn_core.EmptyString in+ for i = String.length s - 1 downto 0 do+ acc := Rocq_horn_core.String (ascii_of_char s.[i], !acc)+ done;+ !acc++let read_file (path : string) : string =+ let ic = open_in_bin path in+ let n = in_channel_length ic in+ let s = really_input_string ic n in+ close_in ic;+ s++let which_file = function+ | 0 -> "rules"+ | 1 -> "asserted"+ | _ -> "certificate"++let usage () =+ prerr_endline "usage: oo-horn-rocq check RULES.tsv ASSERTED.tsv HORN.tsv";+ exit 2++let () =+ match Array.to_list Sys.argv with+ | [ _; "check"; rpath; gpath; dpath ] -> (+ let texts =+ try Some (read_file rpath, read_file gpath, read_file dpath)+ with Sys_error m ->+ prerr_endline ("cannot read: " ^ m);+ None+ in+ match texts with+ | None -> exit 2+ | Some (rtxt, gtxt, dtxt) -> (+ let result =+ try+ Ok (Rocq_horn_core.run (rocq_string rtxt) (rocq_string gtxt)+ (rocq_string dtxt))+ with e -> Error (Printexc.to_string e)+ in+ match result with+ | Error msg ->+ prerr_endline+ ("the checker failed rather than answering: " ^ msg+ ^ " (exit 70; this is NOT a verdict and NOT a parse error)");+ exit 70+ | Ok outcome -> (+ match outcome with+ | Rocq_horn_core.Accepted (b, nr, ng, ns) ->+ let builtin = bool_of_rocq b in+ let verdict =+ if builtin then "entailed" else "entailed_under_supplied_rules"+ in+ let thm =+ if builtin then "OOCertRocq.entails_of_builtin_horn"+ else "OOCertRocq.horn_certificate_sound"+ in+ let means =+ if builtin then+ "every conclusion is true in every model of the asserted graph"+ else+ "every conclusion is true in every model of the asserted graph THAT \+ ALSO SATISFIES the supplied rules; the rules themselves are assumed, \+ not checked"+ in+ Printf.printf+ "{\"ok\":true,\"kernel\":\"rocq\",\"verdict\":\"%s\",\"rules\":%d,\"asserted\":%d,\"derivations\":%d,\"theorem\":\"%s\",\"means\":\"%s\"}\n"+ verdict (nat_to_int nr) (nat_to_int ng) (nat_to_int ns) thm means;+ exit 0+ | Rocq_horn_core.Rejected (nr, ng, ns) ->+ Printf.printf+ "{\"ok\":false,\"kernel\":\"rocq\",\"rules\":%d,\"asserted\":%d,\"derivations\":%d}\n"+ (nat_to_int nr) (nat_to_int ng) (nat_to_int ns);+ exit 1+ | Rocq_horn_core.ParseError w ->+ prerr_endline ("parse error in the " ^ which_file (nat_to_int w) ^ " file");+ exit 2)))+ | _ -> usage ()diff --git a/rocq/gen_fixture_data.sh b/rocq/gen_fixture_data.shnew file mode 100755index 00000000..7a876475--- /dev/null+++ b/rocq/gen_fixture_data.sh@@ -0,0 +1,72 @@+#!/usr/bin/env sh+#+# Emit theories/FixtureData.v from the committed Horn fixtures.+#+# The point of generating rather than transcribing is that the kernel then checks the REAL+# bytes. A hand-typed copy of a fixture is a second file that can drift from the first, and+# a gate over a drifted copy is a gate over nothing. The generated file is not committed:+# build.sh runs this before every build, so there is no window in which checked-in data and+# checked-in fixtures can disagree, because there is no checked-in data.+#+# POSIX sh and sed, and nothing else. This used to be a Python script, which was fine on a+# developer machine and a hazard in CI: the only way to get Rocq 9.2 on a runner is the+# official container image, and whether that image carries a python3 is not something this+# repository controls. sed is in every image that can build anything.+#+# Rocq string literals take a newline and a tab literally and escape a double quote by+# doubling it. Nothing else needs escaping, and Rocq reads the file byte by byte into+# `string`.+set -eu++here=$(cd "$(dirname "$0")" && pwd)+fix="$here/../tests/fixtures/horn"+out="$here/theories/FixtureData.v"++# name:path pairs, relative to tests/fixtures/horn/+files="+f_builtin_rules:builtin_rules.tsv+f_short_rules:short_rules.tsv+f_user_rules:user_rules.tsv+f_asserted:asserted.tsv+f_good:good.tsv+f_bad_binding:bad_binding.tsv+f_bad_conclusion:bad_conclusion.tsv+f_bad_index:bad_index.tsv+f_bad_premise:bad_premise.tsv+f_bad_self:bad_self.tsv+f_deep_mutual_asserted:deep/mutual_asserted.tsv+f_deep_mutual_cert:deep/mutual_cert.tsv+f_deep_mutual_seeded_asserted:deep/mutual_seeded_asserted.tsv+f_deep_self_support_asserted:deep/self_support_asserted.tsv+f_deep_self_support_cert:deep/self_support_cert.tsv+"++n=0+{+ cat <<'HEADER'+(** * The committed fixture bytes, as Rocq strings.++ GENERATED by [rocq/gen_fixture_data.sh] from [tests/fixtures/horn/]. Do not edit and+ do not commit: [rocq/build.sh] regenerates it before every build, so the kernel always+ evaluates the bytes that are in the tree rather than a copy of them that was once in+ the tree. *)++From Stdlib Require Import String.+Open Scope string_scope.+HEADER++ for pair in $files; do+ name=${pair%%:*}+ rel=${pair#*:}+ if [ ! -f "$fix/$rel" ]; then+ echo "missing fixture: $fix/$rel" >&2+ exit 1+ fi+ printf '\n(** [tests/fixtures/horn/%s] *)\nDefinition %s : string :=\n"' "$rel" "$name"+ sed 's/"/""/g' "$fix/$rel"+ printf '".\n'+ n=$((n + 1))+ done+} > "$out"++echo "wrote $out from $n fixtures" >&2diff --git a/rocq/theories/Audit.v b/rocq/theories/Audit.vnew file mode 100644index 00000000..8f654ca2--- /dev/null+++ b/rocq/theories/Audit.v@@ -0,0 +1,71 @@+(** * The axiom footprint.++ A machine-checked proof is only as good as the list of things it took on+ trust, and that list is not visible from reading the proof. [Print+ Assumptions] is, so it is run here on every theorem this development+ advertises, and [rocq/build.sh] fails the build unless every one of them+ reports being closed under the global context.++ THE GATE CAN FAIL, and the way to see it fail is written down rather than+ asserted: add [Axiom cheat : False.] to any file below and rebuild, or+ replace a [Qed] with [Admitted]. The build script greps for the exact+ phrase, so an admitted proof turns the line into a list of constants and+ the grep stops matching. [rocq/build.sh --prove-the-gate-can-fail] does+ exactly that against a scratch copy and requires the build to break.++ [Print Assumptions] prints its verdict and NOT the name it is about, so fifteen+ consecutive "Closed under the global context" lines are unreadable and, worse,+ unattributable: a reader cannot tell which theorem is missing if fourteen of them+ print. Each one below is therefore preceded by a [Check], whose output carries the+ name and the statement, so the report reads as fifteen labelled pairs and+ [build.sh] can require fifteen of them.++ Nothing here is a theorem. This file adds no content and is a report. *)++From Stdlib Require Import String.+Open Scope string_scope.+From OOCertRocq Require Import Syntax Semantics Checker Determinacy Sound Interp Builtin Parse Run Witness Fixtures.++(** The relative warrant: bytes to entailment, both halves. *)+Check run_is_sound.+Print Assumptions run_is_sound.++(** The two soundness theorems it rests on. *)+Check horn_certificate_sound.+Print Assumptions horn_certificate_sound.+Check entails_of_builtin_horn.+Print Assumptions entails_of_builtin_horn.++(** The claim that neither well-formedness conjunct carries soundness content. *)+Check horn_certificate_sound_without_wellformedness.+Print Assumptions horn_certificate_sound_without_wellformedness.++(** What the two conjuncts do buy. *)+Check wellformed_determines_instantiation.+Print Assumptions wellformed_determines_instantiation.+Check no_substitution_extends_a_duplicate_key.+Print Assumptions no_substitution_extends_a_duplicate_key.+Check two_extensions_of_an_uncovered_binding_disagree.+Print Assumptions two_extensions_of_an_uncovered_binding_disagree.++(** The twenty-seven arms, as one statement. *)+Check builtin_sound.+Print Assumptions builtin_sound.++(** Non-vacuity, and the gap between the verdicts. *)+Check the_conditions_are_satisfiable.+Print Assumptions the_conditions_are_satisfiable.+Check not_everything_is_absolutely_entailed.+Print Assumptions not_everything_is_absolutely_entailed.+Check the_relative_verdict_is_strictly_weaker.+Print Assumptions the_relative_verdict_is_strictly_weaker.++(** The gates over the committed bytes. *)+Check the_built_in_table_is_the_committed_fixture.+Print Assumptions the_built_in_table_is_the_committed_fixture.+Check good_is_accepted_with_the_absolute_verdict.+Print Assumptions good_is_accepted_with_the_absolute_verdict.+Check deep_mutual_support_is_rejected.+Print Assumptions deep_mutual_support_is_rejected.+Check deep_mutual_seeded_is_accepted.+Print Assumptions deep_mutual_seeded_is_accepted.diff --git a/rocq/theories/Builtin.v b/rocq/theories/Builtin.vnew file mode 100644index 00000000..1f1c2067--- /dev/null+++ b/rocq/theories/Builtin.v@@ -0,0 +1,514 @@+(** * The built-in rule table, and the twenty-seven arms that discharge it.++ [Sound.v] gives the relative warrant, which assumes the table. This file+ removes the assumption for ONE table, the built-in one, by deriving each of+ its rows from the semantic conditions in [Interp.v]. The result is+ [entails_of_builtin_horn]: a certificate over exactly this table has+ conclusions true in every model of the asserted graph, with no rule+ assumed.++ R-BLT-1. THE TABLE IS TRANSCRIBED FROM [tests/fixtures/horn/builtin_rules.tsv]+ AND FROM NOWHERE ELSE. [Fixtures.v] parses those committed bytes with this+ development's own parser and checks the result equals the table below, so+ the transcription is a gate rather than a claim. Twenty-seven rows for+ twenty-five W3C rules, because [scm-eqc1] and [scm-eqp1] each license two+ conclusions and each therefore occupies two rows.++ R-BLT-2. EVERY ARM TAKES EXACTLY THE CONDITIONS IT USES, as separate+ hypotheses. See R-INT-4. Reading the statements gives the dependency without+ reading a proof, and in particular gives the count of arms that consume a+ BACKWARD condition, which is the number that says how much of the absolute+ claim rests on the biconditional reading R-INT-5 warns about. It is+ fourteen: [rdfs5], [rdfs11], both [scm-eqc1] rows, both [scm-eqp1] rows,+ [scm-svf1], [scm-svf2], [scm-avf1], [scm-avf2], [scm-dom1], [scm-dom2],+ [scm-rng1] and [scm-rng2]. Every one of them concludes a [subClassOf],+ [subPropertyOf], [domain] or [range] triple, and nothing that only runs+ forwards can conclude one.++ R-BLT-3. A QUALIFICATION THE COUNT NEEDS, OR IT IS SELECTIVE. Six other+ conditions are ALSO stated as biconditionals in [Interp.v]: [C_eqc], [C_eqp],+ [C_svf], [C_avf], [C_hv] and [C_sameAs]. Several arms consume the reverse+ direction of those, [cls-svf1] and [cls-hv2] among them. They are not counted+ in the fourteen, and the reason is a real distinction rather than a+ convenience.++ The RDFS conditions for [subClassOf], [subPropertyOf], [domain] and [range]+ are stated by RDFS as implications, and reading them as biconditionals is a+ CHANGE to what RDFS says. The conditions for [owl:someValuesFrom],+ [owl:allValuesFrom], [owl:hasValue], [owl:equivalentClass],+ [owl:equivalentProperty] and [owl:sameAs] are biconditionals because that is+ what those constructors MEAN: a someValuesFrom restriction is the class of+ things with such a value, not merely a subset of it, and [owl:sameAs] is+ identity rather than something implied by identity. Reading them as one-way+ implications would not be a weaker reading of the same condition, it would be+ a different condition describing a different vocabulary.++ So the fourteen is the count of arms that rest on a reading STRONGER than the+ specification they come from. It is not the count of arms that use an [iff].+ A reader who wants the second number can get it from the statements, which is+ the point of writing them this way.+*)++From Stdlib Require Import String List Bool.+From OOCertRocq Require Import Syntax Semantics Checker Sound Interp.+Import ListNotations.+Open Scope string_scope.++Notation V := PVar.+Notation T := PTerm.++(** ** The table *)++Definition r_rdfs2 := Rule "rdfs2"+ [TP (V "s") (V "p") (V "o"); TP (V "p") (T rdfs_domain) (V "c")]+ (TP (V "s") (T rdf_type) (V "c")).++Definition r_rdfs3 := Rule "rdfs3"+ [TP (V "s") (V "p") (V "o"); TP (V "p") (T rdfs_range) (V "c")]+ (TP (V "o") (T rdf_type) (V "c")).++Definition r_rdfs5 := Rule "rdfs5"+ [TP (V "a") (T rdfs_subPropertyOf) (V "b");+ TP (V "b") (T rdfs_subPropertyOf) (V "c")]+ (TP (V "a") (T rdfs_subPropertyOf) (V "c")).++Definition r_rdfs7 := Rule "rdfs7"+ [TP (V "s") (V "p") (V "o"); TP (V "p") (T rdfs_subPropertyOf) (V "q")]+ (TP (V "s") (V "q") (V "o")).++Definition r_rdfs9 := Rule "rdfs9"+ [TP (V "x") (T rdf_type) (V "a"); TP (V "a") (T rdfs_subClassOf) (V "b")]+ (TP (V "x") (T rdf_type) (V "b")).++Definition r_rdfs11 := Rule "rdfs11"+ [TP (V "a") (T rdfs_subClassOf) (V "b"); TP (V "b") (T rdfs_subClassOf) (V "c")]+ (TP (V "a") (T rdfs_subClassOf) (V "c")).++Definition r_prp_trp := Rule "prp-trp"+ [TP (V "p") (T rdf_type) (T owl_TransitiveProperty);+ TP (V "x") (V "p") (V "y");+ TP (V "y") (V "p") (V "z")]+ (TP (V "x") (V "p") (V "z")).++Definition r_prp_symp := Rule "prp-symp"+ [TP (V "p") (T rdf_type) (T owl_SymmetricProperty); TP (V "x") (V "p") (V "y")]+ (TP (V "y") (V "p") (V "x")).++Definition r_prp_inv1 := Rule "prp-inv1"+ [TP (V "p") (T owl_inverseOf) (V "q"); TP (V "x") (V "p") (V "y")]+ (TP (V "y") (V "q") (V "x")).++Definition r_prp_inv2 := Rule "prp-inv2"+ [TP (V "p") (T owl_inverseOf) (V "q"); TP (V "x") (V "q") (V "y")]+ (TP (V "y") (V "p") (V "x")).++Definition r_eq_sym := Rule "eq-sym"+ [TP (V "a") (T owl_sameAs) (V "b")]+ (TP (V "b") (T owl_sameAs) (V "a")).++Definition r_scm_eqc1a := Rule "scm-eqc1"+ [TP (V "a") (T owl_equivalentClass) (V "b")]+ (TP (V "a") (T rdfs_subClassOf) (V "b")).++Definition r_scm_eqc1b := Rule "scm-eqc1"+ [TP (V "a") (T owl_equivalentClass) (V "b")]+ (TP (V "b") (T rdfs_subClassOf) (V "a")).++Definition r_scm_eqp1a := Rule "scm-eqp1"+ [TP (V "a") (T owl_equivalentProperty) (V "b")]+ (TP (V "a") (T rdfs_subPropertyOf) (V "b")).++Definition r_scm_eqp1b := Rule "scm-eqp1"+ [TP (V "a") (T owl_equivalentProperty) (V "b")]+ (TP (V "b") (T rdfs_subPropertyOf) (V "a")).++Definition r_cls_svf1 := Rule "cls-svf1"+ [TP (V "r") (T owl_onProperty) (V "p");+ TP (V "r") (T owl_someValuesFrom) (V "c");+ TP (V "x") (V "p") (V "y");+ TP (V "y") (T rdf_type) (V "c")]+ (TP (V "x") (T rdf_type) (V "r")).++Definition r_cls_avf := Rule "cls-avf"+ [TP (V "r") (T owl_onProperty) (V "p");+ TP (V "r") (T owl_allValuesFrom) (V "c");+ TP (V "x") (T rdf_type) (V "r");+ TP (V "x") (V "p") (V "y")]+ (TP (V "y") (T rdf_type) (V "c")).++Definition r_cls_hv1 := Rule "cls-hv1"+ [TP (V "r") (T owl_onProperty) (V "p");+ TP (V "r") (T owl_hasValue) (V "v");+ TP (V "x") (T rdf_type) (V "r")]+ (TP (V "x") (V "p") (V "v")).++Definition r_cls_hv2 := Rule "cls-hv2"+ [TP (V "r") (T owl_onProperty) (V "p");+ TP (V "r") (T owl_hasValue) (V "v");+ TP (V "x") (V "p") (V "v")]+ (TP (V "x") (T rdf_type) (V "r")).++Definition r_scm_svf1 := Rule "scm-svf1"+ [TP (V "c1") (T owl_someValuesFrom) (V "y1");+ TP (V "c1") (T owl_onProperty) (V "p");+ TP (V "c2") (T owl_someValuesFrom) (V "y2");+ TP (V "c2") (T owl_onProperty) (V "p");+ TP (V "y1") (T rdfs_subClassOf) (V "y2")]+ (TP (V "c1") (T rdfs_subClassOf) (V "c2")).++Definition r_scm_svf2 := Rule "scm-svf2"+ [TP (V "c1") (T owl_someValuesFrom) (V "y");+ TP (V "c1") (T owl_onProperty) (V "p1");+ TP (V "c2") (T owl_someValuesFrom) (V "y");+ TP (V "c2") (T owl_onProperty) (V "p2");+ TP (V "p1") (T rdfs_subPropertyOf) (V "p2")]+ (TP (V "c1") (T rdfs_subClassOf) (V "c2")).++Definition r_scm_avf1 := Rule "scm-avf1"+ [TP (V "c1") (T owl_allValuesFrom) (V "y1");+ TP (V "c1") (T owl_onProperty) (V "p");+ TP (V "c2") (T owl_allValuesFrom) (V "y2");+ TP (V "c2") (T owl_onProperty) (V "p");+ TP (V "y1") (T rdfs_subClassOf) (V "y2")]+ (TP (V "c1") (T rdfs_subClassOf) (V "c2")).++(** The reversed head is not a typo. [scm-avf2] concludes [?c2 subClassOf ?c1]+ where [scm-svf2] concludes [?c1 subClassOf ?c2], because a universal+ restriction is ANTITONE in its property while an existential one is+ monotone. The fixture says so and the proof below needs it that way. *)+Definition r_scm_avf2 := Rule "scm-avf2"+ [TP (V "c1") (T owl_allValuesFrom) (V "y");+ TP (V "c1") (T owl_onProperty) (V "p1");+ TP (V "c2") (T owl_allValuesFrom) (V "y");+ TP (V "c2") (T owl_onProperty) (V "p2");+ TP (V "p1") (T rdfs_subPropertyOf) (V "p2")]+ (TP (V "c2") (T rdfs_subClassOf) (V "c1")).++Definition r_scm_dom1 := Rule "scm-dom1"+ [TP (V "p") (T rdfs_domain) (V "c1"); TP (V "c1") (T rdfs_subClassOf) (V "c2")]+ (TP (V "p") (T rdfs_domain) (V "c2")).++Definition r_scm_dom2 := Rule "scm-dom2"+ [TP (V "p2") (T rdfs_domain) (V "c"); TP (V "p1") (T rdfs_subPropertyOf) (V "p2")]+ (TP (V "p1") (T rdfs_domain) (V "c")).++Definition r_scm_rng1 := Rule "scm-rng1"+ [TP (V "p") (T rdfs_range) (V "c1"); TP (V "c1") (T rdfs_subClassOf) (V "c2")]+ (TP (V "p") (T rdfs_range) (V "c2")).++Definition r_scm_rng2 := Rule "scm-rng2"+ [TP (V "p2") (T rdfs_range) (V "c"); TP (V "p1") (T rdfs_subPropertyOf) (V "p2")]+ (TP (V "p1") (T rdfs_range) (V "c")).++Definition builtin : list rule :=+ [r_rdfs2; r_rdfs3; r_rdfs5; r_rdfs7; r_rdfs9; r_rdfs11;+ r_prp_trp; r_prp_symp; r_prp_inv1; r_prp_inv2; r_eq_sym;+ r_scm_eqc1a; r_scm_eqc1b; r_scm_eqp1a; r_scm_eqp1b;+ r_cls_svf1; r_cls_avf; r_cls_hv1; r_cls_hv2;+ r_scm_svf1; r_scm_svf2; r_scm_avf1; r_scm_avf2;+ r_scm_dom1; r_scm_dom2; r_scm_rng1; r_scm_rng2].++(** ** Proof plumbing *)++Lemma sat_rule_intro : forall (I : world) nm body hd,+ (forall s, (forall a, In a body -> I (inst s a)) -> I (inst s hd)) ->+ sat_rule I (Rule nm body hd).+Proof. intros I nm body hd H s Hb. exact (H s Hb). Qed.++Ltac unf := cbv [itrue rel icext inst inst_pat psubj ppred pobj tsubj tpred tobj] in *.++Ltac arm := apply sat_rule_intro; intros s Hb; unf.++Ltac prem1 B H := pose proof (B _ (or_introl eq_refl)) as H; unf.+Ltac prem2 B H := pose proof (B _ (or_intror (or_introl eq_refl))) as H; unf.+Ltac prem3 B H := pose proof (B _ (or_intror (or_intror (or_introl eq_refl)))) as H; unf.+Ltac prem4 B H := pose proof (B _ (or_intror (or_intror (or_intror (or_introl eq_refl))))) as H; unf.+Ltac prem5 B H :=+ pose proof (B _ (or_intror (or_intror (or_intror (or_intror (or_introl eq_refl)))))) as H; unf.++(** ** The arms++ Forward only. Thirteen rows. *)++Lemma arm_rdfs2 : forall I, C_dom_fwd I -> sat_rule (itrue I) r_rdfs2.+Proof.+ intros I Hd. arm. prem1 Hb H1. prem2 Hb H2.+ destruct (Hd _ _ H2) as [_ [_ Hsub]]. exact (Hsub _ _ H1).+Qed.++Lemma arm_rdfs3 : forall I, C_rng_fwd I -> sat_rule (itrue I) r_rdfs3.+Proof.+ intros I Hr. arm. prem1 Hb H1. prem2 Hb H2.+ destruct (Hr _ _ H2) as [_ [_ Hsub]]. exact (Hsub _ _ H1).+Qed.++Lemma arm_rdfs7 : forall I, C_sp_fwd I -> sat_rule (itrue I) r_rdfs7.+Proof.+ intros I Hp. arm. prem1 Hb H1. prem2 Hb H2.+ destruct (Hp _ _ H2) as [_ [_ Hsub]]. exact (Hsub _ _ H1).+Qed.++Lemma arm_rdfs9 : forall I, C_sc_fwd I -> sat_rule (itrue I) r_rdfs9.+Proof.+ intros I Hc. arm. prem1 Hb H1. prem2 Hb H2.+ destruct (Hc _ _ H2) as [_ [_ Hsub]]. exact (Hsub _ H1).+Qed.++Lemma arm_prp_trp : forall I, C_trp I -> sat_rule (itrue I) r_prp_trp.+Proof.+ intros I Ht. arm. prem1 Hb H1. prem2 Hb H2. prem3 Hb H3.+ exact (Ht _ H1 _ _ _ H2 H3).+Qed.++Lemma arm_prp_symp : forall I, C_symp I -> sat_rule (itrue I) r_prp_symp.+Proof.+ intros I Hs. arm. prem1 Hb H1. prem2 Hb H2. exact (Hs _ H1 _ _ H2).+Qed.++Lemma arm_prp_inv1 : forall I, C_inv I -> sat_rule (itrue I) r_prp_inv1.+Proof.+ intros I Hi. arm. prem1 Hb H1. prem2 Hb H2.+ exact (proj1 (Hi _ _ H1 _ _) H2).+Qed.++Lemma arm_prp_inv2 : forall I, C_inv I -> sat_rule (itrue I) r_prp_inv2.+Proof.+ intros I Hi. arm. prem1 Hb H1. prem2 Hb H2.+ exact (proj2 (Hi _ _ H1 _ _) H2).+Qed.++Lemma arm_eq_sym : forall I, C_sameAs I -> sat_rule (itrue I) r_eq_sym.+Proof.+ intros I Hs. arm. prem1 Hb H1.+ apply (proj1 (Hs _ _)) in H1.+ apply (proj2 (Hs _ _)). now symmetry.+Qed.++Lemma arm_cls_svf1 : forall I, C_svf I -> sat_rule (itrue I) r_cls_svf1.+Proof.+ intros I Hv. arm. prem1 Hb H1. prem2 Hb H2. prem3 Hb H3. prem4 Hb H4.+ destruct (Hv _ _ _ H1 H2) as [_ Hiff].+ apply (proj2 (Hiff _)). exists (iden I (s "y")). split; assumption.+Qed.++Lemma arm_cls_avf : forall I, C_avf I -> sat_rule (itrue I) r_cls_avf.+Proof.+ intros I Hv. arm. prem1 Hb H1. prem2 Hb H2. prem3 Hb H3. prem4 Hb H4.+ destruct (Hv _ _ _ H1 H2) as [_ Hiff].+ exact (proj1 (Hiff _) H3 _ H4).+Qed.++Lemma arm_cls_hv1 : forall I, C_hv I -> sat_rule (itrue I) r_cls_hv1.+Proof.+ intros I Hv. arm. prem1 Hb H1. prem2 Hb H2. prem3 Hb H3.+ destruct (Hv _ _ _ H1 H2) as [_ Hiff].+ exact (proj1 (Hiff _) H3).+Qed.++Lemma arm_cls_hv2 : forall I, C_hv I -> sat_rule (itrue I) r_cls_hv2.+Proof.+ intros I Hv. arm. prem1 Hb H1. prem2 Hb H2. prem3 Hb H3.+ destruct (Hv _ _ _ H1 H2) as [_ Hiff].+ exact (proj2 (Hiff _) H3).+Qed.++(** *** The fourteen that need a backward condition++ Each one concludes a [subClassOf], [subPropertyOf], [domain] or [range]+ triple. Nothing that only runs forwards can conclude one, so each of these+ statements carries a [_bwd] hypothesis and that is the machine-checked form+ of R-INT-5's warning. *)++Lemma arm_rdfs5 : forall I, C_sp_fwd I -> C_sp_bwd I -> sat_rule (itrue I) r_rdfs5.+Proof.+ intros I Hf Hb'. arm. prem1 Hb H1. prem2 Hb H2.+ destruct (Hf _ _ H1) as [Hia [_ Hab]].+ destruct (Hf _ _ H2) as [_ [Hic Hbc]].+ apply Hb'; [exact Hia | exact Hic | intros u v Huv; exact (Hbc _ _ (Hab _ _ Huv))].+Qed.++Lemma arm_rdfs11 : forall I, C_sc_fwd I -> C_sc_bwd I -> sat_rule (itrue I) r_rdfs11.+Proof.+ intros I Hf Hb'. arm. prem1 Hb H1. prem2 Hb H2.+ destruct (Hf _ _ H1) as [Hia [_ Hab]].+ destruct (Hf _ _ H2) as [_ [Hic Hbc]].+ apply Hb'; [exact Hia | exact Hic | intros u Hu; exact (Hbc _ (Hab _ Hu))].+Qed.++Lemma arm_scm_eqc1a : forall I, C_eqc I -> C_sc_bwd I -> sat_rule (itrue I) r_scm_eqc1a.+Proof.+ intros I He Hb'. arm. prem1 Hb H1.+ destruct (proj1 (He _ _) H1) as [Hia [Hib Hiff]].+ apply Hb'; [exact Hia | exact Hib | intros u Hu; exact (proj1 (Hiff u) Hu)].+Qed.++Lemma arm_scm_eqc1b : forall I, C_eqc I -> C_sc_bwd I -> sat_rule (itrue I) r_scm_eqc1b.+Proof.+ intros I He Hb'. arm. prem1 Hb H1.+ destruct (proj1 (He _ _) H1) as [Hia [Hib Hiff]].+ apply Hb'; [exact Hib | exact Hia | intros u Hu; exact (proj2 (Hiff u) Hu)].+Qed.++Lemma arm_scm_eqp1a : forall I, C_eqp I -> C_sp_bwd I -> sat_rule (itrue I) r_scm_eqp1a.+Proof.+ intros I He Hb'. arm. prem1 Hb H1.+ destruct (proj1 (He _ _) H1) as [Hia [Hib Hiff]].+ apply Hb'; [exact Hia | exact Hib | intros u v Huv; exact (proj1 (Hiff u v) Huv)].+Qed.++Lemma arm_scm_eqp1b : forall I, C_eqp I -> C_sp_bwd I -> sat_rule (itrue I) r_scm_eqp1b.+Proof.+ intros I He Hb'. arm. prem1 Hb H1.+ destruct (proj1 (He _ _) H1) as [Hia [Hib Hiff]].+ apply Hb'; [exact Hib | exact Hia | intros u v Huv; exact (proj2 (Hiff u v) Huv)].+Qed.++Lemma arm_scm_svf1 : forall I,+ C_svf I -> C_sc_fwd I -> C_sc_bwd I -> sat_rule (itrue I) r_scm_svf1.+Proof.+ intros I Hv Hf Hb'. arm.+ prem1 Hb H1. prem2 Hb H2. prem3 Hb H3. prem4 Hb H4. prem5 Hb H5.+ destruct (Hv _ _ _ H2 H1) as [Hic1 Hiff1].+ destruct (Hv _ _ _ H4 H3) as [Hic2 Hiff2].+ destruct (Hf _ _ H5) as [_ [_ Hsub]].+ apply Hb'; [exact Hic1 | exact Hic2 |].+ intros u Hu. apply (proj2 (Hiff2 u)).+ destruct (proj1 (Hiff1 u) Hu) as [w [Hw1 Hw2]].+ exists w. split; [exact Hw1 | exact (Hsub _ Hw2)].+Qed.++Lemma arm_scm_svf2 : forall I,+ C_svf I -> C_sp_fwd I -> C_sc_bwd I -> sat_rule (itrue I) r_scm_svf2.+Proof.+ intros I Hv Hf Hb'. arm.+ prem1 Hb H1. prem2 Hb H2. prem3 Hb H3. prem4 Hb H4. prem5 Hb H5.+ destruct (Hv _ _ _ H2 H1) as [Hic1 Hiff1].+ destruct (Hv _ _ _ H4 H3) as [Hic2 Hiff2].+ destruct (Hf _ _ H5) as [_ [_ Hsub]].+ apply Hb'; [exact Hic1 | exact Hic2 |].+ intros u Hu. apply (proj2 (Hiff2 u)).+ destruct (proj1 (Hiff1 u) Hu) as [w [Hw1 Hw2]].+ exists w. split; [exact (Hsub _ _ Hw1) | exact Hw2].+Qed.++Lemma arm_scm_avf1 : forall I,+ C_avf I -> C_sc_fwd I -> C_sc_bwd I -> sat_rule (itrue I) r_scm_avf1.+Proof.+ intros I Hv Hf Hb'. arm.+ prem1 Hb H1. prem2 Hb H2. prem3 Hb H3. prem4 Hb H4. prem5 Hb H5.+ destruct (Hv _ _ _ H2 H1) as [Hic1 Hiff1].+ destruct (Hv _ _ _ H4 H3) as [Hic2 Hiff2].+ destruct (Hf _ _ H5) as [_ [_ Hsub]].+ apply Hb'; [exact Hic1 | exact Hic2 |].+ intros u Hu. apply (proj2 (Hiff2 u)).+ intros w Hw. exact (Hsub _ (proj1 (Hiff1 u) Hu w Hw)).+Qed.++Lemma arm_scm_avf2 : forall I,+ C_avf I -> C_sp_fwd I -> C_sc_bwd I -> sat_rule (itrue I) r_scm_avf2.+Proof.+ intros I Hv Hf Hb'. arm.+ prem1 Hb H1. prem2 Hb H2. prem3 Hb H3. prem4 Hb H4. prem5 Hb H5.+ destruct (Hv _ _ _ H2 H1) as [Hic1 Hiff1].+ destruct (Hv _ _ _ H4 H3) as [Hic2 Hiff2].+ destruct (Hf _ _ H5) as [_ [_ Hsub]].+ apply Hb'; [exact Hic2 | exact Hic1 |].+ intros u Hu. apply (proj2 (Hiff1 u)).+ intros w Hw. exact (proj1 (Hiff2 u) Hu w (Hsub _ _ Hw)).+Qed.++Lemma arm_scm_dom1 : forall I,+ C_dom_fwd I -> C_dom_bwd I -> C_sc_fwd I -> sat_rule (itrue I) r_scm_dom1.+Proof.+ intros I Hf Hb' Hc. arm. prem1 Hb H1. prem2 Hb H2.+ destruct (Hf _ _ H1) as [Hipp [_ Hsub1]].+ destruct (Hc _ _ H2) as [_ [Hicc2 Hsub2]].+ apply Hb'; [exact Hipp | exact Hicc2 |].+ intros u v Huv. exact (Hsub2 _ (Hsub1 _ _ Huv)).+Qed.++Lemma arm_scm_dom2 : forall I,+ C_dom_fwd I -> C_dom_bwd I -> C_sp_fwd I -> sat_rule (itrue I) r_scm_dom2.+Proof.+ intros I Hf Hb' Hp. arm. prem1 Hb H1. prem2 Hb H2.+ destruct (Hf _ _ H1) as [_ [Hicc Hsub1]].+ destruct (Hp _ _ H2) as [Hipp1 [_ Hsub2]].+ apply Hb'; [exact Hipp1 | exact Hicc |].+ intros u v Huv. exact (Hsub1 _ _ (Hsub2 _ _ Huv)).+Qed.++Lemma arm_scm_rng1 : forall I,+ C_rng_fwd I -> C_rng_bwd I -> C_sc_fwd I -> sat_rule (itrue I) r_scm_rng1.+Proof.+ intros I Hf Hb' Hc. arm. prem1 Hb H1. prem2 Hb H2.+ destruct (Hf _ _ H1) as [Hipp [_ Hsub1]].+ destruct (Hc _ _ H2) as [_ [Hicc2 Hsub2]].+ apply Hb'; [exact Hipp | exact Hicc2 |].+ intros u v Huv. exact (Hsub2 _ (Hsub1 _ _ Huv)).+Qed.++Lemma arm_scm_rng2 : forall I,+ C_rng_fwd I -> C_rng_bwd I -> C_sp_fwd I -> sat_rule (itrue I) r_scm_rng2.+Proof.+ intros I Hf Hb' Hp. arm. prem1 Hb H1. prem2 Hb H2.+ destruct (Hf _ _ H1) as [_ [Hicc Hsub1]].+ destruct (Hp _ _ H2) as [Hipp1 [_ Hsub2]].+ apply Hb'; [exact Hipp1 | exact Hicc |].+ intros u v Huv. exact (Hsub1 _ _ (Hsub2 _ _ Huv)).+Qed.++(** ** The table, discharged *)++Theorem builtin_sound : forall I, RL I -> sat_rules (itrue I) builtin.+Proof.+ intros I HRL r Hr.+ destruct HRL as [Hdf Hdb Hrf Hrb Hpf Hpb Hcf Hcb Htrp Hsymp Hinv Hsame Heqc Heqp Hsvf Havf Hhv].+ cbv [builtin In] in Hr.+ destruct Hr as [<-|Hr]; [now apply arm_rdfs2|].+ destruct Hr as [<-|Hr]; [now apply arm_rdfs3|].+ destruct Hr as [<-|Hr]; [now apply arm_rdfs5|].+ destruct Hr as [<-|Hr]; [now apply arm_rdfs7|].+ destruct Hr as [<-|Hr]; [now apply arm_rdfs9|].+ destruct Hr as [<-|Hr]; [now apply arm_rdfs11|].+ destruct Hr as [<-|Hr]; [now apply arm_prp_trp|].+ destruct Hr as [<-|Hr]; [now apply arm_prp_symp|].+ destruct Hr as [<-|Hr]; [now apply arm_prp_inv1|].+ destruct Hr as [<-|Hr]; [now apply arm_prp_inv2|].+ destruct Hr as [<-|Hr]; [now apply arm_eq_sym|].+ destruct Hr as [<-|Hr]; [now apply arm_scm_eqc1a|].+ destruct Hr as [<-|Hr]; [now apply arm_scm_eqc1b|].+ destruct Hr as [<-|Hr]; [now apply arm_scm_eqp1a|].+ destruct Hr as [<-|Hr]; [now apply arm_scm_eqp1b|].+ destruct Hr as [<-|Hr]; [now apply arm_cls_svf1|].+ destruct Hr as [<-|Hr]; [now apply arm_cls_avf|].+ destruct Hr as [<-|Hr]; [now apply arm_cls_hv1|].+ destruct Hr as [<-|Hr]; [now apply arm_cls_hv2|].+ destruct Hr as [<-|Hr]; [now apply arm_scm_svf1|].+ destruct Hr as [<-|Hr]; [now apply arm_scm_svf2|].+ destruct Hr as [<-|Hr]; [now apply arm_scm_avf1|].+ destruct Hr as [<-|Hr]; [now apply arm_scm_avf2|].+ destruct Hr as [<-|Hr]; [now apply arm_scm_dom1|].+ destruct Hr as [<-|Hr]; [now apply arm_scm_dom2|].+ destruct Hr as [<-|Hr]; [now apply arm_scm_rng1|].+ destruct Hr as [<-|Hr]; [now apply arm_scm_rng2|].+ contradiction.+Qed.++(** ** THE ABSOLUTE THEOREM++ No rule is assumed. A certificate over exactly this table has conclusions+ true in every model of the asserted graph, where "model" is an interpretation+ satisfying the conditions of [Interp.v] and nothing else.++ The word this earns is not the word a user table earns. Decision 0003 makes+ that separation normative and the driver prints two different verdicts+ naming two different theorems, because a checker that collapses them is a+ machine for turning an assumption into a fact with a proof attached. *)++Theorem entails_of_builtin_horn : forall G ss,+ check_cert G builtin ss = true ->+ forall t, In t (map sconcl ss) -> entails_abs G t.+Proof.+ intros G ss Hchk t Hin I HRL HG.+ exact (horn_certificate_sound G builtin ss Hchk t Hin (itrue I) HG (builtin_sound I HRL)).+Qed.diff --git a/rocq/theories/Checker.v b/rocq/theories/Checker.vnew file mode 100644index 00000000..c8f2adc4--- /dev/null+++ b/rocq/theories/Checker.v@@ -0,0 +1,194 @@+(** * The checker.++ Executable, decidable, and consulting no semantics whatever. Checking a Horn+ certificate is purely syntactic: nothing below mentions a world, a+ substitution in the sense of [Semantics.v], or truth. That is why agreement+ between two checkers is evidence about a FILE FORMAT and not about two model+ theories, and it is why this file can be read on its own.++ The checking discipline is where independent formalisations of one format+ part company, so every decision is written down.+*)++From Stdlib Require Import String List Bool Arith NArith.+From OOCertRocq Require Import Syntax.+Import ListNotations.+Open Scope string_scope.++(** ** The binding, read as data++ R-CHK-1. A binding is a LIST OF PAIRS and this checker instantiates through+ it PARTIALLY. [blookup] returns [option term]; there is no default, no+ fallback to the variable's own name, and no total function anywhere in this+ file. A variable with no pair fails the lookup and the step fails with it.++ The reason to prefer the partial reading is that it has no hidden+ convention. A total reading has to answer "what is an unbound variable" and+ every answer is a decision the format never made. [None] is not a decision,+ it is the absence of one, and it is the shape the failure actually has. *)++Fixpoint blookup (b : list (string * term)) (v : string) : option term :=+ match b with+ | [] => None+ | (k, t) :: rest => if String.eqb k v then Some t else blookup rest v+ end.++Definition pinst (b : list (string * term)) (p : pat) : option term :=+ match p with PVar v => blookup b v | PTerm t => Some t end.++Definition ainst (b : list (string * term)) (a : tpat) : option triple :=+ match pinst b (psubj a), pinst b (ppred a), pinst b (pobj a) with+ | Some s, Some p, Some o => Some (Tri s p o)+ | _, _, _ => None+ end.++Fixpoint ainsts (b : list (string * term)) (l : list tpat) : option (list triple) :=+ match l with+ | [] => Some []+ | a :: rest =>+ match ainst b a, ainsts b rest with+ | Some t, Some ts => Some (t :: ts)+ | _, _ => None+ end+ end.++(** R-CHK-2. DISTINCT KEYS AND COVERAGE are required, and both are required+ BEFORE anything is instantiated.++ These are not soundness conditions. The theorem in [Sound.v] does not use+ either of them and would hold without them, which is stated there as+ [horn_certificate_sound_without_wellformedness] so that the claim is checked rather+ than asserted. They are here because decision 0008 made them normative for+ the format, and because of what they buy that a soundness theorem cannot+ say: that the certificate means ONE thing.++ Read a binding as a set of demands, one per written pair, "this variable is+ that term".++ - Distinct keys make those demands SATISFIABLE. A key written twice with two+ different terms demands two values for one variable and no substitution+ meets both, so first-wins and last-wins are not two readings of such a+ certificate, they are two conventions for discarding half of it.+ - Coverage makes every substitution meeting the demands instantiate the+ cited rule the SAME WAY.++ [Determinacy.v] proves both halves from scratch here rather than taking them+ on trust.++ 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 refusing it+ would be tidiness dressed as determinacy. *)++Fixpoint mem_str (v : string) (l : list string) : bool :=+ match l with+ | [] => false+ | k :: rest => String.eqb k v || mem_str v rest+ end.++Fixpoint keys_distinct (b : list (string * term)) : bool :=+ match b with+ | [] => true+ | (k, _) :: rest => negb (mem_str k (map fst rest)) && keys_distinct rest+ end.++Definition is_some {A : Type} (o : option A) : bool :=+ match o with Some _ => true | None => false end.++Definition covers (b : list (string * term)) (r : rule) : bool :=+ forallb (fun v => is_some (blookup b v)) (rule_vars r).++(** ** A step++ R-CHK-3. THE WRITTEN PREMISE LIST MUST BE EXACTLY THE INSTANTIATED BODY,+ POSITION BY POSITION.++ This is the sharpest decision in the file and it is a reading of a sentence+ rather than a deduction from one. [docs/lean-certificates.md] says the+ reasoner writes "the premises the rule read, in a fixed order per rule". If+ the order is fixed by the rule then a premise list in another order is not+ the list the format describes, and the checker that accepts it is accepting+ a file the format does not define. The alternative reading, in which the+ written premises are a hint and the checker recomputes the body and looks+ each atom up, makes the written list carry no information at all: a+ certificate with the premise fields deleted would check identically, and a+ certificate with the premises of a different step in them would check green.+ A field that cannot be wrong is not evidence.++ So: [sprem s] is compared to the instantiated body by list equality, and+ separately every instantiated body atom must be KNOWN. The first is about+ the certificate being well formed; the second is about the inference being+ supported.++ If another formalisation of this format takes the other reading, these two+ checkers disagree on a permuted premise list and on a premise list of the+ wrong length, and that disagreement is a fact about the format rather than+ about either checker. It is reported, not repaired.++ R-CHK-4. An index outside the table is a REJECTION, not a parse error. The+ file parses; it cites a rule that is not there. Which of the three exit+ codes that deserves is a judgement, and the judgement here is that a+ certificate is a claim and an unsupported claim is false rather than+ unreadable. [tests/fixtures/horn/bad_index.tsv] is the fixture. *)++Definition list_triple_eqb (a b : list triple) : bool :=+ (Nat.eqb (length a) (length b))+ && forallb (fun p => triple_eqb (fst p) (snd p)) (combine a b).++Fixpoint mem_triple (t : triple) (l : list triple) : bool :=+ match l with+ | [] => false+ | u :: rest => triple_eqb t u || mem_triple t rest+ end.++(** R-CHK-6. THE INDEX LOOKUP RECURSES ON THE TABLE, NEVER ON THE INDEX.+ [nth_error] in the standard library recurses on a unary [nat], so an index+ of twenty digits has to be BUILT before it can be examined. This walks the+ list and decrements the index in binary, so an out-of-range index costs the+ length of the table whatever its magnitude. See R-STEP-3. *)++Fixpoint nth_error_N {A : Type} (l : list A) (n : N) : option A :=+ match l with+ | [] => None+ | x :: r => if N.eqb n 0 then Some x else nth_error_N r (N.pred n)+ end.++Definition check_step (known : list triple) (R : list rule) (s : step) : bool :=+ match nth_error_N R (sidx s) with+ | None => false+ | Some r =>+ keys_distinct (sbind s)+ && covers (sbind s) r+ && match ainsts (sbind s) (rbody r), ainst (sbind s) (rhead r) with+ | Some prems, Some hd =>+ list_triple_eqb (sprem s) prems+ && triple_eqb (sconcl s) hd+ && forallb (fun p => mem_triple p known) prems+ | _, _ => false+ end+ end.++(** R-CHK-5. A STEP MAY CITE THE ASSERTED GRAPH AND STRICTLY EARLIER STEPS, AND+ NOTHING ELSE.++ The accumulator grows after the step is checked, never before, so a step+ cannot support itself and two steps cannot support each other. That is the+ whole of the well-foundedness argument and it is structural: there is no+ occurs check and no cycle detection anywhere, because a left-to-right fold+ that appends after checking cannot build a cycle.++ [tests/fixtures/horn/bad_self.tsv] is the one-step version and+ [tests/fixtures/horn/deep/mutual_cert.tsv] the two-step version. Both are+ rejected here, and the rejection is a corollary of the shape of this+ function rather than a case in it.++ The conclusions are appended in order, so [known] after [n] steps is+ [G ++ map sconcl (firstn n ss)]. [Sound.v] uses exactly that. *)++Fixpoint check_from (known : list triple) (R : list rule) (ss : list step) : bool :=+ match ss with+ | [] => true+ | s :: rest => check_step known R s && check_from (known ++ [sconcl s]) R rest+ end.++Definition check_cert (G : list triple) (R : list rule) (ss : list step) : bool :=+ check_from G R ss.diff --git a/rocq/theories/Determinacy.v b/rocq/theories/Determinacy.vnew file mode 100644index 00000000..e2156429--- /dev/null+++ b/rocq/theories/Determinacy.v@@ -0,0 +1,222 @@+(** * What the two well-formedness conjuncts buy.++ [Sound.v] proves that neither [keys_distinct] nor [covers] carries any+ soundness content: the theorem holds with both deleted. So a reader is+ entitled to ask what they are for, and "another formalisation refuses these+ shapes" is not an answer a formalisation may give.++ The answer is a sentence a soundness theorem cannot say. A soundness theorem+ quantifies over whatever substitution the checker happened to build, so it+ is satisfied by a checker that picks one reading of an ambiguous file and+ proves something about the reading it picked. The property below is about+ every checker at once, including checkers nobody has written:++ - DISTINCT KEYS buy EXISTENCE. Read the binding as a list of demands, one+ per written pair, "this variable is that term". Distinct keys make the+ demands satisfiable, and a repeated key with two different terms makes+ them unsatisfiable, so such a certificate has no reading at all rather+ than two.+ - COVERAGE buys UNIQUENESS. Every substitution meeting the demands+ instantiates the cited rule identically, so the step's premises and+ conclusion do not depend on which one a checker built.++ Both halves are refuted with their own hypothesis dropped, at the bottom of+ the file, so neither conjunct is decorative and the file says which one is+ load-bearing for which half.++ The property is deliberately stated over [extends], which is a statement+ about MEMBERSHIP IN THE LIST and mentions [blookup] nowhere. That is the+ point: it speaks about a checker carrying a partial map, a checker carrying+ a total function with a silent default, and a checker built on a hash map+ whose later key wins, and it says the same thing to all three. *)++From Stdlib Require Import String List Bool Arith.+From OOCertRocq Require Import Syntax Semantics Checker Sound.+Import ListNotations.+Open Scope list_scope.++(** A substitution MEETS the demands a binding writes down. *)+Definition extends (b : list (string * term)) (s : subst) : Prop :=+ forall v t, In (v, t) b -> s v = t.++(** ** Plumbing *)++Lemma mem_str_false_neq : forall k l v,+ mem_str k l = false -> In v l -> k <> v.+Proof.+ induction l as [|x rest IH]; simpl; intros v H Hin.+ - contradiction.+ - apply orb_false_elim in H as [Hx Hrest].+ destruct Hin as [<-|Hin].+ + intro Heq. rewrite Heq, String.eqb_refl in Hx. discriminate.+ + now apply IH.+Qed.++Lemma blookup_In : forall b v t, blookup b v = Some t -> In (v, t) b.+Proof.+ induction b as [|[k u] rest IH]; simpl; intros v t H.+ - discriminate.+ - destruct (String.eqb k v) eqn:Hk.+ + apply String.eqb_eq in Hk. subst k. injection H as <-. now left.+ + right. now apply IH.+Qed.++(** ** Existence: what distinct keys buy++ [subst_of] is a witness, and the statement is that it is ONE, not that it is+ the only one. Nothing below privileges it. *)++Lemma keys_distinct_lookup : forall b v t,+ keys_distinct b = true -> In (v, t) b -> blookup b v = Some t.+Proof.+ induction b as [|[k u] rest IH]; simpl; intros v t Hd Hin.+ - contradiction.+ - apply andb_prop in Hd as [Hfresh Hd].+ apply negb_true_iff in Hfresh.+ destruct Hin as [Heq|Hin].+ + injection Heq as <- <-. now rewrite String.eqb_refl.+ + assert (Hneq : k <> v).+ { apply (mem_str_false_neq k (map fst rest) v Hfresh).+ change v with (fst (v, t)). now apply in_map. }+ destruct (String.eqb k v) eqn:Hk.+ * apply String.eqb_eq in Hk. contradiction.+ * now apply IH.+Qed.++Theorem a_distinct_binding_has_a_substitution : forall b,+ keys_distinct b = true -> extends b (subst_of b).+Proof.+ intros b Hd v t Hin.+ unfold subst_of. now rewrite (keys_distinct_lookup _ _ _ Hd Hin).+Qed.++(** ** Uniqueness: what coverage buys *)++Lemma inst_pat_ext : forall s1 s2 p,+ (forall v, In v (pat_vars p) -> s1 v = s2 v) ->+ inst_pat s1 p = inst_pat s2 p.+Proof.+ intros s1 s2 [v|u] H; simpl in *; [apply H; now left | reflexivity].+Qed.++Lemma inst_ext : forall s1 s2 a,+ (forall v, In v (tpat_vars a) -> s1 v = s2 v) ->+ inst s1 a = inst s2 a.+Proof.+ intros s1 s2 a H. unfold inst, tpat_vars in *.+ rewrite (inst_pat_ext s1 s2 (psubj a)),+ (inst_pat_ext s1 s2 (ppred a)),+ (inst_pat_ext s1 s2 (pobj a)); try reflexivity.+ - intros v Hv. apply H. apply in_or_app. right. apply in_or_app. now right.+ - intros v Hv. apply H. apply in_or_app. right. apply in_or_app. now left.+ - intros v Hv. apply H. apply in_or_app. now left.+Qed.++Lemma covers_agree : forall b r s1 s2,+ covers b r = true -> extends b s1 -> extends b s2 ->+ forall v, In v (rule_vars r) -> s1 v = s2 v.+Proof.+ intros b r s1 s2 Hc H1 H2 v Hv.+ unfold covers in Hc. rewrite forallb_forall in Hc.+ specialize (Hc v Hv). unfold is_some in Hc.+ destruct (blookup b v) as [t|] eqn:Hl; [|discriminate].+ apply blookup_In in Hl.+ now rewrite (H1 _ _ Hl), (H2 _ _ Hl).+Qed.++Theorem a_covering_binding_fixes_the_instantiation : forall b r s1 s2,+ covers b r = true -> extends b s1 -> extends b s2 ->+ map (inst s1) (rbody r) = map (inst s2) (rbody r)+ /\ inst s1 (rhead r) = inst s2 (rhead r).+Proof.+ intros b r s1 s2 Hc H1 H2.+ assert (Hag := covers_agree b r s1 s2 Hc H1 H2).+ split.+ - apply map_ext_in. intros a Ha. apply inst_ext.+ intros v Hv. apply Hag. unfold rule_vars. apply in_or_app. left.+ apply in_flat_map. now exists a.+ - apply inst_ext. intros v Hv. apply Hag.+ unfold rule_vars. apply in_or_app. now right.+Qed.++(** ** THE STATEMENT++ Existence and uniqueness together: a well-formed binding gives the cited+ rule exactly one instantiation, whatever a checker's internal+ representation of a binding happens to be. *)++Theorem wellformed_determines_instantiation : forall b r,+ keys_distinct b = true -> covers b r = true ->+ (exists s, extends b s)+ /\ (forall s1 s2, extends b s1 -> extends b s2 ->+ map (inst s1) (rbody r) = map (inst s2) (rbody r)+ /\ inst s1 (rhead r) = inst s2 (rhead r)).+Proof.+ intros b r Hd Hc. split.+ - exists (subst_of b). now apply a_distinct_binding_has_a_substitution.+ - intros s1 s2 H1 H2. now apply (a_covering_binding_fixes_the_instantiation b r).+Qed.++(** ** Each conjunct refuted with its own hypothesis dropped++ Without these two, the theorem above is consistent with both conjuncts being+ decoration. *)++Definition dup : list (string * term) :=+ [("x"%string, "<http://ex.org/a>"%string); ("x"%string, "<http://ex.org/zzz>"%string)].++Theorem no_substitution_extends_a_duplicate_key :+ keys_distinct dup = false /\ ~ (exists s, extends dup s).+Proof.+ split; [reflexivity|].+ intros [s Hs].+ assert (H1 : s "x"%string = "<http://ex.org/a>"%string)+ by (apply Hs; simpl; now left).+ assert (H2 : s "x"%string = "<http://ex.org/zzz>"%string)+ by (apply Hs; simpl; right; now left).+ rewrite H1 in H2. discriminate.+Qed.++(** The rule [?s <p> ?o -> ?s <q> ?z], whose head carries a variable the body+ never binds. A binding for [s] and [o] omits [z]. Two substitutions meeting+ exactly the same demands then put two different terms in the conclusion, and+ neither term was written by anybody. *)++Definition unsafe_head_rule : rule :=+ Rule "unsafe"%string+ [TP (PVar "s"%string) (PTerm "<http://ex.org/p>"%string) (PVar "o"%string)]+ (TP (PVar "s"%string) (PTerm "<http://ex.org/q>"%string) (PVar "z"%string)).++Definition partial_binding : list (string * term) :=+ [("s"%string, "<http://ex.org/a>"%string); ("o"%string, "<http://ex.org/b>"%string)].++Definition pick (t : term) : subst :=+ fun v => if String.eqb v "s"%string then "<http://ex.org/a>"%string+ else if String.eqb v "o"%string then "<http://ex.org/b>"%string+ else t.++Theorem two_extensions_of_an_uncovered_binding_disagree :+ covers partial_binding unsafe_head_rule = false+ /\ extends partial_binding (pick "<http://ex.org/one>"%string)+ /\ extends partial_binding (pick "<http://ex.org/two>"%string)+ /\ inst (pick "<http://ex.org/one>"%string) (rhead unsafe_head_rule)+ <> inst (pick "<http://ex.org/two>"%string) (rhead unsafe_head_rule).+Proof.+ refine (conj _ (conj _ (conj _ _))).+ - reflexivity.+ - intros v t Hin. simpl in Hin.+ destruct Hin as [H|[H|[]]]; injection H as <- <-; reflexivity.+ - intros v t Hin. simpl in Hin.+ destruct Hin as [H|[H|[]]]; injection H as <- <-; reflexivity.+ - simpl. intro H. injection H as H. discriminate.+Qed.++(** The repair decision 0008 relies on: 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 binding covers. So the refusal loses no+ certificate anybody meant. *)++Theorem the_repair_covers :+ covers (partial_binding ++ [("z"%string, "<http://ex.org/one>"%string)])+ unsafe_head_rule = true.+Proof. reflexivity. Qed.diff --git a/rocq/theories/Extract.v b/rocq/theories/Extract.vnew file mode 100644index 00000000..d3ad1a79--- /dev/null+++ b/rocq/theories/Extract.v@@ -0,0 +1,30 @@+(** * Extraction to OCaml.++ R-EXT-1. NO [Extract Inductive] AND NO [Extract Constant]. Every one of+ those is a mapping the Rocq kernel does not check and the OCaml compiler+ cannot check either, so each is a piece of trusted glue between a proof and+ a program. The usual conveniences, [ExtrOcamlString] and [ExtrOcamlNatInt],+ each add one. They are not used: [string] and [nat] come out as the+ inductive types they are, the driver converts at the boundary in about+ twenty lines, and the whole of what is trusted about the translation is the+ extraction mechanism itself.++ The cost is that the extracted [string] is a linked list of eight-boolean+ characters and [nat] is unary, so the binary is slow. On this format, whose+ largest committed input is a few kilobytes, that is not a cost worth buying+ trust back from.++ R-EXT-2. THE DRIVER IS UNTRUSTED AND IS EXPECTED TO BE. It opens files,+ splits nothing, decides nothing, prints JSON and returns an exit code. The+ exact boundary is in [rocq/README.md]. *)++From OOCertRocq Require Import Run Builtin Parse.+From Stdlib Require Import Extraction.++Extraction Language OCaml.+Set Extraction Output Directory "driver".++(** [run] is the whole checker. [builtin] and [ruleStr]-free printing are not+ extracted: the driver never needs the table, because the comparison against+ it happens inside [run] (R-RUN-2). *)+Extraction "rocq_horn_core.ml" run.diff --git a/rocq/theories/Fixtures.v b/rocq/theories/Fixtures.vnew file mode 100644index 00000000..5477a82e--- /dev/null+++ b/rocq/theories/Fixtures.v@@ -0,0 +1,115 @@+(** * The checker run on the committed bytes, inside the kernel.++ Two things are gated here and they are different.++ THE TRANSCRIPTION GATE. [Builtin.v] writes the built-in table out as Rocq+ data, and everything the absolute theorem says is about THAT table. If the+ transcription differs from [tests/fixtures/horn/builtin_rules.tsv] in one+ field then the absolute theorem is about a table nothing uses, and no proof+ in this development would notice.+ [the_built_in_table_is_the_committed_fixture] closes that, by parsing the+ real bytes with this development's own parser and requiring the result to be+ equal to the transcription.++ THE BEHAVIOUR GATE. The verdicts below are computed by the kernel, not by+ the extracted binary, so they are what the PROVED checker does. The Rust+ differential runs the extracted binary over the same files, so a divergence+ between these lines and that run is an extraction bug and is visible rather+ than silent. That is the only handle this development has on the extraction+ step, which is trusted and not verified.++ Nothing in [Sound.v], [Determinacy.v] or [Builtin.v] depends on this file.+ It is a gate, and a gate is not a theorem. *)++From Stdlib Require Import String List Bool.+From OOCertRocq Require Import Syntax Semantics Checker Sound Interp Builtin Parse Run FixtureData.+Import ListNotations.+Open Scope string_scope.++(** ** The transcription *)++Theorem the_built_in_table_is_the_committed_fixture :+ parse_rules f_builtin_rules = Some builtin.+Proof. vm_compute. reflexivity. Qed.++(** ** Accepted++ [good.tsv] cites [rdfs9] over [asserted.tsv]: 27 rules, 2 asserted triples,+ 1 step, and the table is the built-in one, so this run earns the absolute+ verdict. *)++Theorem good_is_accepted_with_the_absolute_verdict :+ run f_builtin_rules f_asserted f_good = Accepted true 27 2 1.+Proof. vm_compute. reflexivity. Qed.++(** The certificate says something the graph does not. Without this the+ acceptance above would be compatible with a checker that only ever accepts+ certificates repeating their own input. *)++Theorem the_accepted_conclusion_is_not_asserted :+ match parse_triples f_asserted, parse_steps f_good with+ | Some G, Some (s :: _) => mem_triple (sconcl s) G = false+ | _, _ => False+ end.+Proof. vm_compute. reflexivity. Qed.++(** ** Rejected++ Five shipped forgeries, each wrong in one place, and the deep pair. *)++Theorem bad_binding_is_rejected :+ run f_builtin_rules f_asserted f_bad_binding = Rejected 27 2 1.+Proof. vm_compute. reflexivity. Qed.++Theorem bad_conclusion_is_rejected :+ run f_builtin_rules f_asserted f_bad_conclusion = Rejected 27 2 1.+Proof. vm_compute. reflexivity. Qed.++(** R-CHK-4 in action: rule index 99 into a table of 27 is a rejection and not+ a parse error. The file is readable; the claim it makes is unsupported. *)+Theorem bad_index_is_rejected :+ run f_builtin_rules f_asserted f_bad_index = Rejected 27 2 1.+Proof. vm_compute. reflexivity. Qed.++Theorem bad_premise_is_rejected :+ run f_builtin_rules f_asserted f_bad_premise = Rejected 27 2 1.+Proof. vm_compute. reflexivity. Qed.++(** R-CHK-5, the one-step version: a step whose premise is its own conclusion. *)+Theorem bad_self_is_rejected :+ run f_builtin_rules f_asserted f_bad_self = Rejected 27 2 1.+Proof. vm_compute. reflexivity. Qed.++Theorem deep_self_support_is_rejected :+ run f_builtin_rules f_deep_self_support_asserted f_deep_self_support_cert+ = Rejected 27 1 1.+Proof. vm_compute. reflexivity. Qed.++(** R-CHK-5, the two-step version: each step supported only by the other. *)+Theorem deep_mutual_support_is_rejected :+ run f_builtin_rules f_deep_mutual_asserted f_deep_mutual_cert = Rejected 27 2 2.+Proof. vm_compute. reflexivity. Qed.++(** The same two steps over a graph that seeds the cycle are ACCEPTED, which is+ what makes the rejection above about the cycle rather than about the steps.+ A gate that rejected both would prove nothing. *)+Theorem deep_mutual_seeded_is_accepted :+ run f_builtin_rules f_deep_mutual_seeded_asserted f_deep_mutual_cert+ = Accepted true 27 3 2.+Proof. vm_compute. reflexivity. Qed.++(** ** The other two committed tables parse, and neither is the built-in one *)++Theorem short_rules_parse_and_are_not_the_built_ins :+ match parse_rules f_short_rules with+ | Some R => length R = 3 /\ rules_eqb R builtin = false+ | None => False+ end.+Proof. vm_compute. split; reflexivity. Qed.++Theorem user_rules_parse_and_are_not_the_built_ins :+ match parse_rules f_user_rules with+ | Some R => rules_eqb R builtin = false+ | None => False+ end.+Proof. vm_compute. reflexivity. Qed.diff --git a/rocq/theories/Interp.v b/rocq/theories/Interp.vnew file mode 100644index 00000000..496575d0--- /dev/null+++ b/rocq/theories/Interp.v@@ -0,0 +1,233 @@+(** * An RDF-based interpretation, and the semantic conditions the built-in+ rules are discharged against.++ [Semantics.v] gives the RULE-RELATIVE warrant, which assumes the rule table.+ This file is what is needed to get rid of that assumption for the built-in+ table: a notion of model in which the RDFS and OWL vocabulary MEANS+ something, so that the built-in rules can be derived rather than assumed.++ R-INT-1. THE SHAPE IS THE RDF-BASED ONE: a domain, a total denotation, and a+ ternary extension relation. [iext I p x y] reads "the pair <x, y> is in+ IEXT(p)". Classes are read off the extension relation in the standard way,+ [ICEXT(c) = { x : <x, c> in IEXT(I(rdf:type)) }], rather than carried as a+ second field, because carrying it as a field would let an interpretation+ make a class extension disagree with the type triples that name it.++ R-INT-2. [iden] IS TOTAL ON TERMS. Every field of the certificate denotes,+ including one that is not writable RDF. This is a real restriction on the+ model class and it runs in the UNSAFE direction: interpretations in which+ some literal fails to denote are outside the claim. It is stated here rather+ than buried because the alternative, a partial denotation, would make+ [itrue] partial, and a three-valued truth would change the meaning of every+ theorem in the development. OWL 2 RDF-Based Semantics takes IL total, which+ is the precedent, and the claim is scoped to interpretations that do.++ R-INT-3. IC AND IP ARE FIELDS, not derived. RDFS conditions are stated with+ membership in IC and IP as a side condition ("then x, y are in IC and+ ICEXT(x) is a subset of ICEXT(y)"), and the conditions that run backwards+ need those memberships as HYPOTHESES. Deriving IC from the graph would make+ the backward conditions harder to satisfy and the model class smaller, which+ is the wrong direction.++ R-INT-4. THE CONDITIONS ARE SEPARATE DEFINITIONS, NOT FIELDS OF ONE RECORD,+ AND EVERY RULE LEMMA TAKES EXACTLY THE ONES IT USES. This is the only part+ of the design that is about honesty rather than about mathematics. A rule+ lemma proved from a record can be proved from a field that says the rule,+ and nothing in the proof script shows the difference. With the conditions as+ explicit hypotheses the dependency is IN THE STATEMENT, so a reader counting+ which arms consume a backward condition is reading a machine-checked fact+ rather than a comment. The count is fourteen and [Builtin.v] is where it can+ be checked.++ R-INT-5. THE BACKWARD CONDITIONS ARE A MODELLING DECISION AND THEY ARE THE+ WEAKEST POINT OF THE ABSOLUTE CLAIM. RDFS alone states its conditions as+ implications: "if <x, y> is in IEXT(I(rdfs:subClassOf)) then ...". Fourteen+ of the twenty-seven built-in rows CONCLUDE a [subClassOf], [subPropertyOf],+ [domain] or [range] triple, and no implication in that direction licenses+ them. The OWL 2 RDF-Based Semantics states the corresponding conditions as+ biconditionals, which is what makes those rows derivable, and a+ biconditional is a STRONGER condition: it admits fewer interpretations, so+ the model class is smaller and entailment over it is a WEAKER claim than+ entailment over the RDFS conditions alone. Adding [C_..._bwd] to the+ hypothesis list of a lemma is therefore never free, and the lemmas that need+ it say so in their own statement.++ WHERE THE BICONDITIONAL READING COMES FROM, AND WHAT WAS NOT DONE. It is+ taken from this repository's own correction to decision 0002, which names+ the connective in the OWL 2 RDF-Based Semantics table that carries+ [rowspan="4"] in the specification's HTML and therefore states an [iff]+ rather than the [if-then] RDFS alone gives. It was NOT re-checked cell by+ cell against the Recommendation in this work. That check is one of the+ things [rocq/README.md] lists as not covered, and it is the largest single+ piece of prose the absolute theorem rests on. A reader who wants the+ absolute verdict to mean what it says should do that reading before+ trusting it. *)++From Stdlib Require Import String List Bool.+From OOCertRocq Require Import Syntax Semantics.+Import ListNotations.+Open Scope string_scope.++(** ** The vocabulary, as the bytes the rule table actually carries *)++Definition rdf_type := "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>".+Definition rdfs_domain := "<http://www.w3.org/2000/01/rdf-schema#domain>".+Definition rdfs_range := "<http://www.w3.org/2000/01/rdf-schema#range>".+Definition rdfs_subClassOf := "<http://www.w3.org/2000/01/rdf-schema#subClassOf>".+Definition rdfs_subPropertyOf := "<http://www.w3.org/2000/01/rdf-schema#subPropertyOf>".+Definition owl_TransitiveProperty := "<http://www.w3.org/2002/07/owl#TransitiveProperty>".+Definition owl_SymmetricProperty := "<http://www.w3.org/2002/07/owl#SymmetricProperty>".+Definition owl_inverseOf := "<http://www.w3.org/2002/07/owl#inverseOf>".+Definition owl_sameAs := "<http://www.w3.org/2002/07/owl#sameAs>".+Definition owl_equivalentClass := "<http://www.w3.org/2002/07/owl#equivalentClass>".+Definition owl_equivalentProperty := "<http://www.w3.org/2002/07/owl#equivalentProperty>".+Definition owl_onProperty := "<http://www.w3.org/2002/07/owl#onProperty>".+Definition owl_someValuesFrom := "<http://www.w3.org/2002/07/owl#someValuesFrom>".+Definition owl_allValuesFrom := "<http://www.w3.org/2002/07/owl#allValuesFrom>".+Definition owl_hasValue := "<http://www.w3.org/2002/07/owl#hasValue>".++(** ** Interpretations *)++Record interp : Type := Interp {+ idom : Type ;+ iden : term -> idom ; (* IS union IL, total: R-INT-2 *)+ iext : idom -> idom -> idom -> Prop ; (* iext p x y <-> <x,y> in IEXT(p) *)+ ic : idom -> Prop ; (* IC *)+ ip : idom -> Prop (* IP *)+}.++Arguments iext {i} _ _ _.+Arguments ic {i} _.+Arguments ip {i} _.++(** Truth of a ground triple. *)+Definition itrue (I : interp) (t : triple) : Prop :=+ iext (iden I (tpred t)) (iden I (tsubj t)) (iden I (tobj t)).++(** ICEXT, read off IEXT(I(rdf:type)) rather than carried. *)+Definition icext (I : interp) (c x : idom I) : Prop :=+ iext (iden I rdf_type) x c.++(** A named property's extension, at the level of the domain. *)+Definition rel (I : interp) (v : term) (x y : idom I) : Prop :=+ iext (iden I v) x y.++(** ** The semantic conditions++ Each is the specification clause it is named for, stated over the domain and+ never over the graph. The forward halves are RDF 1.1 Semantics section 9.2.1+ (the RDFS semantic conditions); the backward halves are the biconditional+ reading the OWL 2 RDF-Based Semantics gives the same vocabulary, and R-INT-5+ is the warning about what they cost. *)++(* "If <x,y> is in IEXT(I(rdfs:domain)) and <u,v> is in IEXT(x) then u is in ICEXT(y)."+ The IP and IC memberships come with it, as they do for every RDFS condition+ of this shape. *)+Definition C_dom_fwd (I : interp) : Prop :=+ forall x y, rel I rdfs_domain x y ->+ ip x /\ ic y /\ (forall u v, iext x u v -> icext I y u).++Definition C_dom_bwd (I : interp) : Prop :=+ forall x y, ip x -> ic y ->+ (forall u v, iext x u v -> icext I y u) -> rel I rdfs_domain x y.++Definition C_rng_fwd (I : interp) : Prop :=+ forall x y, rel I rdfs_range x y ->+ ip x /\ ic y /\ (forall u v, iext x u v -> icext I y v).++Definition C_rng_bwd (I : interp) : Prop :=+ forall x y, ip x -> ic y ->+ (forall u v, iext x u v -> icext I y v) -> rel I rdfs_range x y.++(* "If <x,y> is in IEXT(I(rdfs:subPropertyOf)) then x and y are in IP and+ IEXT(x) is a subset of IEXT(y)." *)+Definition C_sp_fwd (I : interp) : Prop :=+ forall x y, rel I rdfs_subPropertyOf x y ->+ ip x /\ ip y /\ (forall u v, iext x u v -> iext y u v).++Definition C_sp_bwd (I : interp) : Prop :=+ forall x y, ip x -> ip y ->+ (forall u v, iext x u v -> iext y u v) -> rel I rdfs_subPropertyOf x y.++(* "If <x,y> is in IEXT(I(rdfs:subClassOf)) then x and y are in IC and+ ICEXT(x) is a subset of ICEXT(y)." *)+Definition C_sc_fwd (I : interp) : Prop :=+ forall x y, rel I rdfs_subClassOf x y ->+ ic x /\ ic y /\ (forall u, icext I x u -> icext I y u).++Definition C_sc_bwd (I : interp) : Prop :=+ forall x y, ic x -> ic y ->+ (forall u, icext I x u -> icext I y u) -> rel I rdfs_subClassOf x y.++(* A transitive property's extension is transitive. *)+Definition C_trp (I : interp) : Prop :=+ forall p, icext I (iden I owl_TransitiveProperty) p ->+ forall x y z, iext p x y -> iext p y z -> iext p x z.++Definition C_symp (I : interp) : Prop :=+ forall p, icext I (iden I owl_SymmetricProperty) p ->+ forall x y, iext p x y -> iext p y x.++(* owl:inverseOf relates two properties whose extensions are converses. *)+Definition C_inv (I : interp) : Prop :=+ forall p q, rel I owl_inverseOf p q ->+ forall x y, iext p x y <-> iext q y x.++(* IEXT(I(owl:sameAs)) is the identity on the domain. *)+Definition C_sameAs (I : interp) : Prop :=+ forall x y, rel I owl_sameAs x y <-> x = y.++Definition C_eqc (I : interp) : Prop :=+ forall x y, rel I owl_equivalentClass x y <->+ (ic x /\ ic y /\ (forall u, icext I x u <-> icext I y u)).++Definition C_eqp (I : interp) : Prop :=+ forall x y, rel I owl_equivalentProperty x y <->+ (ip x /\ ip y /\ (forall u v, iext x u v <-> iext y u v)).++(* The three restriction constructors this table uses. Each says the restriction+ IS a class, and says exactly which one. *)+Definition C_svf (I : interp) : Prop :=+ forall r p c, rel I owl_onProperty r p -> rel I owl_someValuesFrom r c ->+ ic r /\ (forall x, icext I r x <-> (exists y, iext p x y /\ icext I c y)).++Definition C_avf (I : interp) : Prop :=+ forall r p c, rel I owl_onProperty r p -> rel I owl_allValuesFrom r c ->+ ic r /\ (forall x, icext I r x <-> (forall y, iext p x y -> icext I c y)).++Definition C_hv (I : interp) : Prop :=+ forall r p v, rel I owl_onProperty r p -> rel I owl_hasValue r v ->+ ic r /\ (forall x, icext I r x <-> iext p x v).++(** ** The bundle++ A record, so that the top-level theorem has one hypothesis. Every field is+ one of the conditions above, and no field is a rule. *)++Record RL (I : interp) : Prop := MkRL {+ rl_dom_fwd : C_dom_fwd I ;+ rl_dom_bwd : C_dom_bwd I ;+ rl_rng_fwd : C_rng_fwd I ;+ rl_rng_bwd : C_rng_bwd I ;+ rl_sp_fwd : C_sp_fwd I ;+ rl_sp_bwd : C_sp_bwd I ;+ rl_sc_fwd : C_sc_fwd I ;+ rl_sc_bwd : C_sc_bwd I ;+ rl_trp : C_trp I ;+ rl_symp : C_symp I ;+ rl_inv : C_inv I ;+ rl_sameAs : C_sameAs I ;+ rl_eqc : C_eqc I ;+ rl_eqp : C_eqp I ;+ rl_svf : C_svf I ;+ rl_avf : C_avf I ;+ rl_hv : C_hv I+}.++(** ** THE ABSOLUTE ENTAILMENT RELATION++ True in every model of the asserted graph. No rule table appears in it,+ which is the whole difference from [entails_rel]. *)++Definition entails_abs (G : list triple) (t : triple) : Prop :=+ forall I : interp, RL I -> (forall u, In u G -> itrue I u) -> itrue I t.diff --git a/rocq/theories/Parse.v b/rocq/theories/Parse.vnew file mode 100644index 00000000..f2cf6278--- /dev/null+++ b/rocq/theories/Parse.v@@ -0,0 +1,256 @@+(** * From the bytes on disk to the objects in [Syntax.v].++ The parser is inside the development rather than in the untrusted driver,+ because the driver's job should be reading a file and printing a number and+ not deciding what a certificate says. Every decision below is one the format+ description does not settle, which is exactly why they are written down: a+ second reading of an unsettled question is how two verified checkers come to+ disagree about one file.++ R-PARSE-1. LINES ARE SEPARATED BY LF, AND A TRAILING LF AT END OF FILE DOES+ NOT MAKE A FINAL EMPTY LINE. A file of zero bytes has no lines, which makes+ an empty asserted graph and an empty certificate legal. An empty certificate+ is ACCEPTED, vacuously, and that is correct: it claims nothing.++ R-PARSE-2. AN EMPTY LINE ANYWHERE ELSE IS A PARSE ERROR. It splits into a+ single empty field, which is neither a rule nor a triple nor a step. Skipping+ it would be a repair, and a parser that repairs its input decides what the+ input meant.++ R-PARSE-3. CR IS AN ORDINARY BYTE. A file with CRLF line endings therefore+ has a trailing CR inside its last field on every line, and its terms differ+ from the LF version's terms. This is the decision most likely to produce a+ difference from another implementation, and it is made this way on purpose:+ stripping CR is a repair, the repository pins LF on these formats in+ [.gitattributes], and a checker that silently accepts two spellings of one+ term has two readings of one certificate.++ R-PARSE-4. FIELDS ARE SEPARATED BY TAB AND AN EMPTY FIELD IS A LEGAL TERM,+ namely the empty string. No field is trimmed. A term is its bytes (R-TERM-1),+ and the empty term is a term.++ R-PARSE-5. A COUNT FIELD IS DECIMAL, NON-EMPTY, AND ALL DIGITS. No sign, no+ whitespace, no leading plus. Leading zeros are allowed, so [04] is 4: the+ field is a number and nothing in the format says it has a canonical+ spelling.++ R-PARSE-8. COUNT FIELDS ARE PARSED INTO BINARY NATURALS AND THE CONSUMERS+ NEVER RECURSE ON THEM. Nothing bounds the digits, so a certificate may cite+ rule 99999999999999999999 or declare a binding of that many pairs, and a+ checker has to answer in the time it takes to read the line. Rocq's [nat] is+ unary, so building such a number is not an answer; the first version of this+ parser did build it, and the extracted checker died of a stack overflow that+ OCaml reports with exit code 2, which is this tool's code for a parse error.+ A crash was wearing a verdict's clothes. [take_tpats] and [take_pairs] now+ recurse on the FIELD LIST and decrement the count in binary, so a count+ larger than the fields available fails as fast as one that is one too big.+ See R-STEP-3 and decision 0015.++ R-PARSE-6. THE FIELD COUNT MUST BE EXACT. A rule line carries 2 + 3n + 3+ fields for a body of n atoms and no more; a triple line carries exactly 3. A+ trailing extra field is a parse error rather than something to ignore. A+ certificate step is the one place where a count is computed rather than+ declared: after the index, the binding count, the bindings and the+ conclusion, everything left is premises, and it must divide by three. *)++From Stdlib Require Import String List Bool Arith Ascii NArith.+From OOCertRocq Require Import Syntax.+Import ListNotations.+Open Scope string_scope.++Definition LF : ascii := ascii_of_nat 10.+Definition TAB : ascii := ascii_of_nat 9.+Definition QMARK : ascii := ascii_of_nat 63.++Fixpoint srev_app (s acc : string) : string :=+ match s with+ | EmptyString => acc+ | String c r => srev_app r (String c acc)+ end.++Definition srev (s : string) : string := srev_app s EmptyString.++Fixpoint split_go (sep : ascii) (s cur : string) (acc : list string) : list string :=+ match s with+ | EmptyString => List.rev (srev cur :: acc)+ | String c rest =>+ if Ascii.eqb c sep+ then split_go sep rest EmptyString (srev cur :: acc)+ else split_go sep rest (String c cur) acc+ end.++Definition split (sep : ascii) (s : string) : list string :=+ split_go sep s EmptyString [].++(** R-PARSE-1 in code: one trailing empty element, and only one, is dropped. *)+Definition lines (s : string) : list string :=+ let ls := split LF s in+ match List.rev ls with+ | EmptyString :: rest => List.rev rest+ | _ => ls+ end.++Definition fields (s : string) : list string := split TAB s.++(** R-PARSE-5 *)+Definition digit_val (c : ascii) : option nat :=+ let n := nat_of_ascii c in+ if andb (Nat.leb 48 n) (Nat.leb n 57) then Some (n - 48) else None.++Fixpoint parse_N_go (s : string) (acc : N) : option N :=+ match s with+ | EmptyString => Some acc+ | String c r =>+ match digit_val c with+ | Some d => parse_N_go r (N.add (N.mul acc 10) (N.of_nat d))+ | None => None+ end+ end.++Definition parse_N (s : string) : option N :=+ match s with+ | EmptyString => None+ | _ => parse_N_go s 0+ end.++(** R-PAT-1 in code. A field whose first byte is [?] is a variable whose name is+ the remaining bytes, so the field [?] alone names the variable whose name is+ the empty string. See the note in [Syntax.v]: this is a real corner of the+ format and it is left to the checker rather than patched here. *)+Definition parse_pat (f : string) : pat :=+ match f with+ | String c rest => if Ascii.eqb c QMARK then PVar rest else PTerm f+ | EmptyString => PTerm f+ end.++Fixpoint take_tpats (fs : list string) (n : N) {struct fs}+ : option (list tpat * list string) :=+ if N.eqb n 0 then Some ([], fs) else+ match fs with+ | a :: b :: c :: r =>+ match take_tpats r (N.pred n) with+ | Some (ps, rest) => Some (TP (parse_pat a) (parse_pat b) (parse_pat c) :: ps, rest)+ | None => None+ end+ | _ => None+ end.++Fixpoint take_pairs (fs : list string) (n : N) {struct fs}+ : option (list (string * term) * list string) :=+ if N.eqb n 0 then Some ([], fs) else+ match fs with+ | v :: t :: r =>+ match take_pairs r (N.pred n) with+ | Some (ps, rest) => Some ((v, t) :: ps, rest)+ | None => None+ end+ | _ => None+ end.++Fixpoint triples_of (fs : list string) : option (list triple) :=+ match fs with+ | [] => Some []+ | a :: b :: c :: r =>+ match triples_of r with+ | Some ts => Some (Tri a b c :: ts)+ | None => None+ end+ | _ => None+ end.++(** ** Lines *)++Definition parse_rule_line (fs : list string) : option rule :=+ match fs with+ | nm :: ns :: rest =>+ match parse_N ns with+ | None => None+ | Some n =>+ match take_tpats rest n with+ | Some (body, [h1; h2; h3]) =>+ Some (Rule nm body (TP (parse_pat h1) (parse_pat h2) (parse_pat h3)))+ | _ => None+ end+ end+ | _ => None+ end.++Definition parse_triple_line (fs : list string) : option triple :=+ match fs with+ | [a; b; c] => Some (Tri a b c)+ | _ => None+ end.++Definition parse_step_line (fs : list string) : option step :=+ match fs with+ | is_ :: ks :: rest =>+ match parse_N is_, parse_N ks with+ | Some i, Some k =>+ match take_pairs rest k with+ | Some (b, c1 :: c2 :: c3 :: prems) =>+ match triples_of prems with+ | Some ps => Some (Step i b (Tri c1 c2 c3) ps)+ | None => None+ end+ | _ => None+ end+ | _, _ => None+ end+ | _ => None+ end.++Fixpoint map_opt {A B : Type} (f : A -> option B) (l : list A) : option (list B) :=+ match l with+ | [] => Some []+ | x :: r =>+ match f x, map_opt f r with+ | Some y, Some ys => Some (y :: ys)+ | _, _ => None+ end+ end.++Definition parse_rules (txt : string) : option (list rule) :=+ map_opt (fun l => parse_rule_line (fields l)) (lines txt).++Definition parse_triples (txt : string) : option (list triple) :=+ map_opt (fun l => parse_triple_line (fields l)) (lines txt).++Definition parse_steps (txt : string) : option (list step) :=+ map_opt (fun l => parse_step_line (fields l)) (lines txt).++(** ** Comparing a supplied table against the built-in one++ R-PARSE-7. THE TABLE IS COMPARED AS PARSED DATA, NOT AS BYTES. Two files+ that parse to the same rules are the same table, so a table with different+ rule NAMES is a different table, because the name is a field of a rule. That+ is the conservative direction: the absolute verdict is awarded to fewer+ files rather than more. *)++Definition pat_eqb (p q : pat) : bool :=+ match p, q with+ | PVar a, PVar b => String.eqb a b+ | PTerm a, PTerm b => String.eqb a b+ | _, _ => false+ end.++Definition tpat_eqb (a b : tpat) : bool :=+ pat_eqb (psubj a) (psubj b) && pat_eqb (ppred a) (ppred b) && pat_eqb (pobj a) (pobj b).++Fixpoint tpats_eqb (a b : list tpat) : bool :=+ match a, b with+ | [], [] => true+ | x :: xs, y :: ys => tpat_eqb x y && tpats_eqb xs ys+ | _, _ => false+ end.++Definition rule_eqb (r q : rule) : bool :=+ String.eqb (rname r) (rname q)+ && tpats_eqb (rbody r) (rbody q)+ && tpat_eqb (rhead r) (rhead q).++Fixpoint rules_eqb (a b : list rule) : bool :=+ match a, b with+ | [], [] => true+ | x :: xs, y :: ys => rule_eqb x y && rules_eqb xs ys+ | _, _ => false+ end.diff --git a/rocq/theories/Run.v b/rocq/theories/Run.vnew file mode 100644index 00000000..e3441c38--- /dev/null+++ b/rocq/theories/Run.v@@ -0,0 +1,114 @@+(** * Bytes in, verdict out, with the theorem attached.++ [Sound.v] and [Builtin.v] talk about parsed objects. A user hands the tool+ three FILES, so the statement a user is entitled to has to start at the+ bytes. [run_is_sound] is that statement: if [run] accepts, then the+ conclusions of the certificate the third file parses to are entailed by the+ graph the second file parses to, under the table the first file parses to,+ and if the table is the built-in one then entailed outright.++ R-RUN-1. THE TWO VERDICTS NEVER SHARE A WORD, and the distinction is carried+ in the OUTCOME TYPE rather than in the printing. [Accepted] carries a boolean+ saying whether the supplied table is the built-in one, and the driver turns+ that boolean into one of two verdict strings naming two different theorems.+ Decision 0003 requires the separation; putting it in the type means the+ driver cannot lose it by accident, only by editing the one place it is+ decided.++ R-RUN-2. THE TABLE IS COMPARED AS PARSED DATA (R-PARSE-7), which is why the+ boolean is computed here and not in the driver. A driver comparing bytes+ would award the absolute verdict on the strength of a byte-for-byte match+ and withhold it from a file with a different trailing newline. *)++From Stdlib Require Import String List Bool Arith.+From OOCertRocq Require Import Syntax Semantics Checker Sound Interp Builtin Parse.+Import ListNotations.+Open Scope list_scope.++Inductive outcome : Set :=+ | Accepted : bool -> nat -> nat -> nat -> outcome+ | Rejected : nat -> nat -> nat -> outcome+ | ParseError : nat -> outcome. (* 0 rules, 1 asserted graph, 2 certificate *)++Definition run (rtxt gtxt dtxt : string) : outcome :=+ match parse_rules rtxt with+ | None => ParseError 0+ | Some R =>+ match parse_triples gtxt with+ | None => ParseError 1+ | Some G =>+ match parse_steps dtxt with+ | None => ParseError 2+ | Some ss =>+ if check_cert G R ss+ then Accepted (rules_eqb R builtin) (length R) (length G) (length ss)+ else Rejected (length R) (length G) (length ss)+ end+ end+ end.++(** ** The table comparison is an equality, not a heuristic *)++Lemma pat_eqb_true : forall p q, pat_eqb p q = true -> p = q.+Proof.+ intros [a|a] [b|b] H; simpl in H; try discriminate;+ apply String.eqb_eq in H; now subst.+Qed.++Lemma tpat_eqb_true : forall a b, tpat_eqb a b = true -> a = b.+Proof.+ intros [s1 p1 o1] [s2 p2 o2]. unfold tpat_eqb. simpl. intro H.+ apply andb_prop in H as [H1 H3]. apply andb_prop in H1 as [H1 H2].+ apply pat_eqb_true in H1, H2, H3. now subst.+Qed.++Lemma tpats_eqb_true : forall a b, tpats_eqb a b = true -> a = b.+Proof.+ induction a as [|x xs IH]; intros [|y ys] H; simpl in H; try discriminate.+ - reflexivity.+ - apply andb_prop in H as [H1 H2].+ apply tpat_eqb_true in H1. rewrite H1, (IH ys H2). reflexivity.+Qed.++Lemma rule_eqb_true : forall r q, rule_eqb r q = true -> r = q.+Proof.+ intros [n1 b1 h1] [n2 b2 h2]. unfold rule_eqb. simpl. intro H.+ apply andb_prop in H as [H1 H3]. apply andb_prop in H1 as [H1 H2].+ apply String.eqb_eq in H1. apply tpats_eqb_true in H2. apply tpat_eqb_true in H3.+ now subst.+Qed.++Lemma rules_eqb_true : forall a b, rules_eqb a b = true -> a = b.+Proof.+ induction a as [|x xs IH]; intros [|y ys] H; simpl in H; try discriminate.+ - reflexivity.+ - apply andb_prop in H as [H1 H2].+ apply rule_eqb_true in H1. rewrite H1, (IH ys H2). reflexivity.+Qed.++(** ** THE END-TO-END STATEMENT *)++Theorem run_is_sound : forall rtxt gtxt dtxt R G ss b nr ng ns,+ parse_rules rtxt = Some R ->+ parse_triples gtxt = Some G ->+ parse_steps dtxt = Some ss ->+ run rtxt gtxt dtxt = Accepted b nr ng ns ->+ (forall t, In t (map sconcl ss) -> entails_rel G R t)+ /\ (b = true -> forall t, In t (map sconcl ss) -> entails_abs G t).+Proof.+ intros rtxt gtxt dtxt R G ss b nr ng ns HR HG Hss Hrun.+ unfold run in Hrun. rewrite HR, HG, Hss in Hrun.+ destruct (check_cert G R ss) eqn:Hchk; [|discriminate].+ injection Hrun as Hb _ _ _.+ split.+ - intros t Hin. exact (horn_certificate_sound G R ss Hchk t Hin).+ - intros Htrue t Hin.+ subst b. apply rules_eqb_true in Htrue. subst R.+ exact (entails_of_builtin_horn G ss Hchk t Hin).+Qed.++(** A rejection and a parse error claim nothing, which is why there is no+ theorem about them. That asymmetry is the shape of the guarantee: this+ layer certifies an inference and never refutes one. A certificate the+ checker rejects may still have true conclusions, reached by a rule it does+ not have or written down in a way the format does not define. *)diff --git a/rocq/theories/Semantics.v b/rocq/theories/Semantics.vnew file mode 100644index 00000000..174d2058--- /dev/null+++ b/rocq/theories/Semantics.v@@ -0,0 +1,85 @@+(** * What a Horn certificate's conclusions are supposed to mean.++ Soundness is only as strong as the entailment relation it concludes, so this+ file is the one to argue with. It defines the RULE-RELATIVE relation, which+ is what a certificate over a rule table somebody supplied can possibly earn.+ The ABSOLUTE relation, which needs the built-in table discharged against a+ formal semantics of the RDFS and OWL vocabulary, is in [Interp.v] and+ [Builtin.v] and is a separate and much larger claim.++ R-SEM-1. A model here is a PREDICATE ON TRIPLES, not a structure with a+ domain. Truth of a triple is primitive.++ That is a deliberate choice and the reason for it is worth stating, because+ it is the opposite of what the absolute layer needs. At the Horn layer there+ is no vocabulary: a rule table is data, its rules mention whatever terms+ they mention, and no clause of any specification is available to interpret+ them. The weakest thing that can carry "this triple holds" is a predicate on+ triples, and the weakest semantics gives the LARGEST class of models, which+ gives the STRONGEST entailment claim. Anything with more structure would+ make the model class smaller and the soundness theorem below weaker than it+ looks, which is exactly the failure a second and third formalisation exist+ to catch. [Interp.v] puts structure back in, on purpose, because the+ built-in rules cannot be discharged without it, and pays the price in the+ size of the claim.++ R-SEM-2. A substitution is a TOTAL function from variable names to terms.+ Not a finite map, not an option-valued lookup. A rule says something about+ every way of instantiating it, so the quantifier in [sat_rule] below ranges+ over every total function, and the checker's finite binding is a fact about+ the certificate rather than a restriction on the semantics. [Checker.v]+ instantiates PARTIALLY and the bridge between the two is a lemma+ ([Sound.v], [subst_of_agrees]) rather than an identification. *)++From Stdlib Require Import String List Bool.+From OOCertRocq Require Import Syntax.+Import ListNotations.+Open Scope string_scope.++Definition subst := string -> term.++Definition inst_pat (s : subst) (p : pat) : term :=+ match p with PVar v => s v | PTerm t => t end.++Definition inst (s : subst) (a : tpat) : triple :=+ Tri (inst_pat s (psubj a)) (inst_pat s (ppred a)) (inst_pat s (pobj a)).++(** A world: the triples that hold. *)+Definition world := triple -> Prop.++Definition sat_graph (I : world) (G : list triple) : Prop :=+ forall t, In t G -> I t.++(** R-SEM-3. A world satisfies a rule when EVERY total instantiation whose body+ holds has a head that holds. This is the universal closure of the rule read+ as an implication, which is the only reading a Horn rule has. *)+Definition sat_rule (I : world) (r : rule) : Prop :=+ forall s : subst,+ (forall a, In a (rbody r) -> I (inst s a)) -> I (inst s (rhead r)).++Definition sat_rules (I : world) (R : list rule) : Prop :=+ forall r, In r R -> sat_rule I r.++(** R-SEM-4. THE RULE-RELATIVE ENTAILMENT RELATION, and the one a certificate+ over a user-supplied table earns.++ The rules are ASSUMED. A table containing "every supplier is compliant"+ makes certificates whose conclusions are entailed in this sense for ever,+ because every world that fails to satisfy that rule has been quantified+ away. Decision 0003 names this and requires the two verdicts never to share+ a word, which is why this relation has its own name here and the absolute+ one is defined in a different file over a different notion of model. *)+Definition entails_rel (G : list triple) (R : list rule) (t : triple) : Prop :=+ forall I : world, sat_graph I G -> sat_rules I R -> I t.++(** The relation is reflexive on the asserted graph, which is the base case of+ the certificate induction and nothing more. *)+Lemma entails_rel_asserted :+ forall G R t, In t G -> entails_rel G R t.+Proof. intros G R t Hin I HG _. exact (HG t Hin). Qed.++(** ** Non-vacuity, stated here and proved in [Witness.v]++ A soundness theorem over an empty model class proves nothing, so the claim+ that this relation is not the total relation is a theorem in this+ development rather than a remark. See [Witness.v]. *)diff --git a/rocq/theories/Sound.v b/rocq/theories/Sound.vnew file mode 100644index 00000000..05f87fdf--- /dev/null+++ b/rocq/theories/Sound.v@@ -0,0 +1,221 @@+(** * Soundness of the Horn certificate checker.++ THE THEOREM. If [check_cert G R ss] returns [true] then every conclusion of+ every step is true in every world that satisfies [G] and satisfies every+ rule of [R].++ The rules are assumed and never checked, so this is the RELATIVE warrant and+ it is the only one a certificate over a table somebody supplied can earn.+ See [Builtin.v] for how much of the absolute one this development reaches,+ and [rocq/README.md] for how much it does not.+*)++From Stdlib Require Import String List Bool Arith NArith.+From OOCertRocq Require Import Syntax Semantics Checker.+Import ListNotations.+Open Scope list_scope.++(** ** From the checker's partial instantiation to a total substitution++ The checker never builds a total function ([Checker.v], R-CHK-1). The+ semantics quantifies over nothing else ([Semantics.v], R-SEM-2). One+ substitution bridges them, and the bridge is needed only on the patterns+ that instantiated, so the value it takes elsewhere is irrelevant and is+ visibly arbitrary below. *)++Definition subst_of (b : list (string * term)) : subst :=+ fun v => match blookup b v with+ | Some t => t+ | None => EmptyString (* never consulted; see [pinst_agrees] *)+ end.++Lemma pinst_agrees : forall b p t,+ pinst b p = Some t -> inst_pat (subst_of b) p = t.+Proof.+ intros b [v|u] t H; simpl in *.+ - unfold subst_of. now rewrite H.+ - now injection H.+Qed.++Lemma ainst_agrees : forall b a t,+ ainst b a = Some t -> inst (subst_of b) a = t.+Proof.+ intros b a t H. unfold ainst in H. unfold inst.+ destruct (pinst b (psubj a)) eqn:Hs; try discriminate.+ destruct (pinst b (ppred a)) eqn:Hp; try discriminate.+ destruct (pinst b (pobj a)) eqn:Ho; try discriminate.+ apply pinst_agrees in Hs, Hp, Ho.+ rewrite Hs, Hp, Ho. now injection H.+Qed.++Lemma ainsts_agrees : forall b l ts,+ ainsts b l = Some ts -> map (inst (subst_of b)) l = ts.+Proof.+ induction l as [|a rest IH]; intros ts H; simpl in *.+ - now injection H.+ - destruct (ainst b a) eqn:Ha; try discriminate.+ destruct (ainsts b rest) eqn:Hr; try discriminate.+ injection H as <-. simpl.+ now rewrite (ainst_agrees _ _ _ Ha), (IH l eq_refl).+Qed.++(** ** Membership *)++Lemma mem_triple_In : forall t l, mem_triple t l = true -> In t l.+Proof.+ induction l as [|u rest IH]; simpl; intro H.+ - discriminate.+ - apply orb_prop in H as [H|H].+ + left. symmetry. now apply triple_eqb_true.+ + right. now apply IH.+Qed.++(** ** The checker with its well-formedness conjuncts removed++ R-CHK-2 claims that distinct keys and coverage carry NO soundness content.+ A claim like that is exactly the kind a formalisation should be made to+ check rather than allowed to assert, so here is the checker without them,+ and the soundness theorem is proved of THIS one. The real checker is shown+ to imply it, so the real checker inherits the theorem and the claim is+ machine-checked in the direction that matters: adding the two conjuncts+ makes the hypothesis stronger, so it cannot have weakened anything. *)++Lemma nth_error_N_In : forall {A : Type} (l : list A) n x,+ nth_error_N l n = Some x -> In x l.+Proof.+ induction l as [|y r IH]; simpl; intros n x H; [discriminate|].+ destruct (N.eqb n 0).+ - injection H as <-. now left.+ - right. exact (IH _ _ H).+Qed.++Definition check_step_weak (known : list triple) (R : list rule) (s : step) : bool :=+ match nth_error_N R (sidx s) with+ | None => false+ | Some r =>+ match ainsts (sbind s) (rbody r), ainst (sbind s) (rhead r) with+ | Some prems, Some hd =>+ triple_eqb (sconcl s) hd+ && forallb (fun p => mem_triple p known) prems+ | _, _ => false+ end+ end.++Lemma check_step_implies_weak : forall known R s,+ check_step known R s = true -> check_step_weak known R s = true.+Proof.+ intros known R s H. unfold check_step, check_step_weak in *.+ destruct (nth_error_N R (sidx s)) as [r|]; [|discriminate].+ apply andb_prop in H as [_ H].+ destruct (ainsts (sbind s) (rbody r)); [|discriminate].+ destruct (ainst (sbind s) (rhead r)); [|discriminate].+ apply andb_prop in H as [H1 H2].+ apply andb_prop in H1 as [_ H1].+ now rewrite H1, H2.+Qed.++(** ** One step++ Everything the step needs is already entailed, so the rule carries it. *)++Lemma check_step_sound : forall G R known s,+ (forall t, In t known -> entails_rel G R t) ->+ check_step_weak known R s = true ->+ entails_rel G R (sconcl s).+Proof.+ intros G R known s Hknown Hchk.+ unfold check_step_weak in Hchk.+ destruct (nth_error_N R (sidx s)) as [r|] eqn:Hr; [|discriminate].+ destruct (ainsts (sbind s) (rbody r)) as [prems|] eqn:Hprems; [|discriminate].+ destruct (ainst (sbind s) (rhead r)) as [hd|] eqn:Hhd; [|discriminate].+ apply andb_prop in Hchk as [Hconcl Hmem].+ apply triple_eqb_true in Hconcl. subst hd.+ apply ainsts_agrees in Hprems.+ apply ainst_agrees in Hhd.+ intros I HG HR.+ rewrite <- Hhd.+ apply (HR r (nth_error_N_In _ _ _ Hr)).+ intros a Ha.+ (* the instantiated body atom is one of the written premises, and every+ written premise is known, and everything known is entailed *)+ assert (Hin : In (inst (subst_of (sbind s)) a) prems).+ { rewrite <- Hprems. now apply in_map. }+ rewrite forallb_forall in Hmem.+ specialize (Hmem _ Hin).+ apply mem_triple_In in Hmem.+ exact (Hknown _ Hmem I HG HR).+Qed.++(** ** The whole certificate++ Induction on the step list, with the accumulator generalised. The invariant+ is that everything in [known] is already entailed, which R-CHK-5 keeps true+ because the accumulator only ever grows by a conclusion that has just been+ proved entailed. *)++Lemma check_from_sound : forall R ss G known,+ (forall t, In t known -> entails_rel G R t) ->+ check_from known R ss = true ->+ forall t, In t (map sconcl ss) -> entails_rel G R t.+Proof.+ intros R ss. induction ss as [|s rest IH]; intros G known Hknown Hchk t Hin.+ - simpl in Hin. contradiction.+ - simpl in Hchk. apply andb_prop in Hchk as [Hstep Hrest].+ apply check_step_implies_weak in Hstep.+ assert (Hs : entails_rel G R (sconcl s))+ by exact (check_step_sound _ _ _ _ Hknown Hstep).+ simpl in Hin. destruct Hin as [<-|Hin]; [exact Hs|].+ apply (IH G (known ++ [sconcl s])); [|exact Hrest|exact Hin].+ intros u Hu. apply in_app_or in Hu as [Hu|Hu].+ + now apply Hknown.+ + destruct Hu as [<-|[]]. exact Hs.+Qed.++(** ** THE THEOREM *)++Theorem horn_certificate_sound : forall G R ss,+ check_cert G R ss = true ->+ forall t, In t (map sconcl ss) -> entails_rel G R t.+Proof.+ intros G R ss Hchk t Hin.+ apply (check_from_sound R ss G G); [|exact Hchk|exact Hin].+ intros u Hu. now apply entails_rel_asserted.+Qed.++(** The same statement over the checker with the two well-formedness conjuncts+ deleted. This is the machine-checked form of R-CHK-2's claim that neither+ conjunct carries soundness content: the theorem holds without them, so+ adding them cannot have bought any of it. What they buy is in+ [Determinacy.v]. *)++Fixpoint check_from_weak (known : list triple) (R : list rule) (ss : list step) : bool :=+ match ss with+ | [] => true+ | s :: rest => check_step_weak known R s && check_from_weak (known ++ [sconcl s]) R rest+ end.++Lemma check_from_weak_sound : forall R ss G known,+ (forall t, In t known -> entails_rel G R t) ->+ check_from_weak known R ss = true ->+ forall t, In t (map sconcl ss) -> entails_rel G R t.+Proof.+ intros R ss. induction ss as [|s rest IH]; intros G known Hknown Hchk t Hin.+ - simpl in Hin. contradiction.+ - simpl in Hchk. apply andb_prop in Hchk as [Hstep Hrest].+ assert (Hs : entails_rel G R (sconcl s))+ by exact (check_step_sound _ _ _ _ Hknown Hstep).+ simpl in Hin. destruct Hin as [<-|Hin]; [exact Hs|].+ apply (IH G (known ++ [sconcl s])); [|exact Hrest|exact Hin].+ intros u Hu. apply in_app_or in Hu as [Hu|Hu].+ + now apply Hknown.+ + destruct Hu as [<-|[]]. exact Hs.+Qed.++Theorem horn_certificate_sound_without_wellformedness : forall G R ss,+ check_from_weak G R ss = true ->+ forall t, In t (map sconcl ss) -> entails_rel G R t.+Proof.+ intros G R ss Hchk t Hin.+ apply (check_from_weak_sound R ss G G); [|exact Hchk|exact Hin].+ intros u Hu. now apply entails_rel_asserted.+Qed.diff --git a/rocq/theories/Syntax.v b/rocq/theories/Syntax.vnew file mode 100644index 00000000..166be3cf--- /dev/null+++ b/rocq/theories/Syntax.v@@ -0,0 +1,136 @@+(** * Syntax of the Horn certificate format.++ This file fixes the OBJECTS the rest of the development talks about: terms,+ triples, triple patterns, rules, certificate steps. It carries no semantics+ and no checking, so a reader can disagree with the model theory in+ [Semantics.v] or with the discipline in [Checker.v] without disagreeing with+ anything here.++ Every modelling decision is recorded at the point it is made, tagged [R-...],+ with the source it rests on. That list is what makes a later disagreement+ with another formalisation diagnosable rather than merely embarrassing. The+ sources are the format description in [docs/lean-certificates.md], decision+ records 0002, 0003 and 0008, and the committed fixture bytes under+ [tests/fixtures/horn/]. Nothing under [lean/] or [isabelle/] is a source for+ any decision below; see [rocq/README.md] for exactly how far that goes and+ where it stops.+*)++From Stdlib Require Import String List Bool Arith NArith.+Import ListNotations.+Open Scope string_scope.++(** ** Terms++ R-TERM-1. A term is the field's bytes and nothing else. The format is a TSV+ of opaque fields: no field says whether it holds an IRI, a blank node or a+ literal, and no rule in any table this checker reads inspects a term's+ internal structure. So there is no term datatype here with an [Iri]+ constructor and a [Lit] constructor, there is a string.++ This is a real choice and it has consequences a reader should see rather+ than infer. [<http://ex.org/a>] and [http://ex.org/a] are DIFFERENT terms,+ because their bytes differ. ["01"^^xsd:integer] and ["1"^^xsd:integer] are+ different terms, because their bytes differ, and nothing here normalises a+ lexical form. A term that is not writable RDF at all, such as the bare+ string [z], is still a term. Decision 0008 says the last of those explicitly+ and it is the reason this file does not try to be cleverer. *)++Definition term := string.++Record triple : Set := Tri { tsubj : term ; tpred : term ; tobj : term }.++Definition triple_eqb (a b : triple) : bool :=+ String.eqb (tsubj a) (tsubj b)+ && String.eqb (tpred a) (tpred b)+ && String.eqb (tobj a) (tobj b).++Lemma triple_eqb_true : forall a b, triple_eqb a b = true -> a = b.+Proof.+ intros [s1 p1 o1] [s2 p2 o2]. unfold triple_eqb. simpl.+ intro H.+ apply andb_prop in H as [H1 H3]. apply andb_prop in H1 as [H1 H2].+ apply String.eqb_eq in H1, H2, H3. subst. reflexivity.+Qed.++Lemma triple_eqb_refl : forall a, triple_eqb a a = true.+Proof.+ intros [s p o]. unfold triple_eqb. simpl.+ now rewrite !String.eqb_refl.+Qed.++(** ** Patterns++ R-PAT-1. A pattern position is a variable exactly when its first byte is+ [?], and the variable's name is everything after it. That is read off the+ rule fixtures, where [?s] is a variable and+ [<http://www.w3.org/2000/01/rdf-schema#domain>] is not.++ The rule is deliberately stated as "first byte is [?]" rather than "first+ byte is [?] and the rest is non-empty", because the bare field [?] then+ names a variable whose name is the EMPTY STRING. That is not an accident and+ it is not tidied away here. A format whose lexer has an exception has an+ exception somewhere else too, and the empty-named variable is a real corner+ of this format that a fuzzer reached by a one-character typo. It is refused+ or admitted by the CHECKING rules in [Checker.v], where a refusal can be+ stated and proved, rather than by the lexer, where it would be silent. *)++Inductive pat : Set :=+ | PVar : string -> pat+ | PTerm : term -> pat.++Record tpat : Set := TP { psubj : pat ; ppred : pat ; pobj : pat }.++(** A rule is a name, a body (a list of triple patterns, order significant) and+ a head (one triple pattern).++ R-RULE-1. The name is carried and is NEVER consulted by the checker. It+ exists so a report can say which rule was cited. Two rules with the same+ name and different shapes are two rules, which the built-in table needs:+ [scm-eqc1] appears twice there, licensing two conclusions. *)++Record rule : Set := Rule { rname : string ; rbody : list tpat ; rhead : tpat }.++(** ** Certificate steps++ R-STEP-1. A step cites a rule by INDEX into the supplied table, carries a+ binding as a list of (variable name, term) pairs, states one conclusion, and+ lists the premises it read. The premise list is part of the written+ certificate rather than something the checker recomputes and keeps to+ itself. [docs/lean-certificates.md] says the premises are written "in a+ fixed order per rule", so the order is contractual; [Checker.v] decides what+ that means and records the decision as R-CHK-3.++ R-STEP-3. THE RULE INDEX IS A BINARY NATURAL, not a unary one. Nothing in+ the format bounds it, so a certificate may cite rule 99999999999999999999,+ and a checker has to answer that in the time it takes to read the digits.+ With Rocq's unary [nat] the answer takes longer than the universe has left:+ the extracted checker built the number before it looked at it and died of a+ stack overflow, which OCaml reports with exit code 2, which is this tool's+ code for a parse error. So a crash was impersonating a verdict. The+ differential against the Lean checker found it; see decision 0015.++ R-STEP-2. The binding's keys are BARE variable names with no [?] prefix,+ which is read off [tests/fixtures/horn/good.tsv]: the rule at index 4 uses+ [?x], [?a], [?b] and the certificate binds [x], [a], [b]. *)++Record step : Set := Step {+ sidx : N ;+ sbind : list (string * term) ;+ sconcl : triple ;+ sprem : list triple+}.++(** ** Variables of a rule++ Body and head, in that order, with duplicates left in. Only membership is+ ever asked of this list, so deduplicating it would be work for nothing. *)++Definition pat_vars (p : pat) : list string :=+ match p with PVar v => [v] | PTerm _ => [] end.++Definition tpat_vars (a : tpat) : list string :=+ pat_vars (psubj a) ++ pat_vars (ppred a) ++ pat_vars (pobj a).++Definition rule_vars (r : rule) : list string :=+ flat_map tpat_vars (rbody r) ++ tpat_vars (rhead r).diff --git a/rocq/theories/Witness.v b/rocq/theories/Witness.vnew file mode 100644index 00000000..30887a7e--- /dev/null+++ b/rocq/theories/Witness.v@@ -0,0 +1,144 @@+(** * Non-vacuity, and the gap between the two verdicts.++ A soundness theorem over an empty class of models proves nothing, and a+ soundness theorem over a class in which every triple is true proves nothing+ either. Both failures are invisible from inside the soundness proof, so both+ are ruled out here by exhibiting structures rather than by arguing.++ Three things are established.++ 1. THE CONDITIONS OF [Interp.v] ARE SATISFIABLE. If they were contradictory,+ [entails_abs] would hold of everything and [entails_of_builtin_horn]+ would be a theorem about nothing.+ 2. [entails_abs] IS NOT THE TOTAL RELATION. Some triple is not entailed by+ the empty graph, so the absolute verdict distinguishes cases.+ 3. THE RELATIVE VERDICT IS STRICTLY WEAKER THAN THE ABSOLUTE ONE, and the+ gap is exhibited by a rule anybody could write. This is decision 0003's+ point made into a theorem: a certificate over a user table proves its+ conclusion only in models that satisfy the table, and a one-line table+ makes any triple at all come out relatively entailed. Printing one word+ for both would be a machine for turning an assumption into a fact with a+ proof attached. *)++From Stdlib Require Import String List Bool NArith.+From OOCertRocq Require Import Syntax Semantics Checker Sound Interp Builtin.+Import ListNotations.+Open Scope string_scope.++(** ** A model of the conditions++ Everything is false except that [owl:sameAs] denotes the identity, which is+ the one condition of [Interp.v] stated as an equality and so the one that+ cannot be satisfied by making the extension empty. IC and IP are empty,+ which is what makes every backward condition vacuous: they demand a triple+ only of things already in IC or IP.++ The domain is the set of terms and the denotation is the identity, so two+ different terms denote two different things. That is what lets the+ [owl:sameAs] condition hold without forcing anything else to. *)++Definition Iempty : interp :=+ Interp term+ (fun t => t)+ (fun p x y => String.eqb p owl_sameAs = true /\ x = y)+ (fun _ => False)+ (fun _ => False).++(** Every condition is discharged the same way: the hypothesis says a pair is+ in the extension of some property other than [owl:sameAs], which this+ interpretation makes false, or it says something is in IC or IP, which this+ interpretation makes empty. *)++Ltac no_such_rel H := destruct H as [H _]; vm_compute in H; discriminate.++Theorem the_conditions_are_satisfiable : RL Iempty.+Proof.+ constructor.+ - intros x y H; no_such_rel H.+ - intros x y H; contradiction.+ - intros x y H; no_such_rel H.+ - intros x y H; contradiction.+ - intros x y H; no_such_rel H.+ - intros x y H; contradiction.+ - intros x y H; no_such_rel H.+ - intros x y H; contradiction.+ - intros p H; no_such_rel H.+ - intros p H; no_such_rel H.+ - intros p q H; no_such_rel H.+ - intros x y; split.+ + intros [_ Hxy]; exact Hxy.+ + intros <-; split; [vm_compute; reflexivity | reflexivity].+ - intros x y; split.+ + intros H; no_such_rel H.+ + intros [H _]; contradiction.+ - intros x y; split.+ + intros H; no_such_rel H.+ + intros [H _]; contradiction.+ - intros r p c H _; no_such_rel H.+ - intros r p c H _; no_such_rel H.+ - intros r p v H _; no_such_rel H.+Qed.++(** ** The absolute relation is not the total relation *)++Definition probe : triple :=+ Tri "<http://ex.org/a>" "<http://ex.org/p>" "<http://ex.org/b>".++Theorem not_everything_is_absolutely_entailed : ~ entails_abs [] probe.+Proof.+ intro H.+ specialize (H Iempty the_conditions_are_satisfiable).+ assert (Hg : forall u, In u (@nil triple) -> itrue Iempty u) by (intros u []).+ specialize (H Hg).+ destruct H as [Hp _]. vm_compute in Hp. discriminate.+Qed.++(** ** The relative relation is not the total relation either *)++Theorem not_everything_is_relatively_entailed : ~ entails_rel [] [] probe.+Proof.+ intro H. exact (H (fun _ => False) (fun t Ht => match Ht with end)+ (fun r Hr => match Hr with end)).+Qed.++(** ** THE GAP BETWEEN THE VERDICTS++ One rule with an empty body and a ground head. Nothing about it is exotic+ and nothing in the checker refuses it: a rule is data, and this is data.+ Under it the probe triple is relatively entailed by the EMPTY graph, and it+ is not absolutely entailed by the empty graph, so the two verdicts are+ genuinely different claims and a checker that prints one word for both is+ reporting a fact it does not have. *)++Definition laundering_table : list rule :=+ [Rule "assume-it" [] (TP (PTerm "<http://ex.org/a>")+ (PTerm "<http://ex.org/p>")+ (PTerm "<http://ex.org/b>"))].++Theorem a_user_rule_makes_anything_relatively_entailed :+ entails_rel [] laundering_table probe.+Proof.+ intros I _ HR.+ exact (HR _ (or_introl eq_refl) (fun v => v) (fun a Ha => match Ha with end)).+Qed.++Theorem the_relative_verdict_is_strictly_weaker :+ entails_rel [] laundering_table probe /\ ~ entails_abs [] probe.+Proof.+ split.+ - exact a_user_rule_makes_anything_relatively_entailed.+ - exact not_everything_is_absolutely_entailed.+Qed.++(** ** The checker accepts a certificate over that table++ Otherwise the gap above would be a statement about a table no certificate+ can cite. A one-step certificate citing rule 0 with an empty binding checks,+ so the weaker verdict is reachable from real bytes. *)++Definition laundering_cert : list step :=+ [Step 0%N [] (Tri "<http://ex.org/a>" "<http://ex.org/p>" "<http://ex.org/b>") []].++Theorem the_laundering_certificate_is_accepted :+ check_cert [] laundering_table laundering_cert = true.+Proof. reflexivity. Qed.diff --git a/tests/rocq_kernel_differential_test.rs b/tests/rocq_kernel_differential_test.rsnew file mode 100644index 00000000..f1d057cb--- /dev/null+++ b/tests/rocq_kernel_differential_test.rs@@ -0,0 +1,1071 @@+//! A third proof assistant, the same certificate format, and the question of whether+//! three formalisations say the same thing.+//!+//! `lean/OOCert/Horn.lean`, `isabelle/OO_Check.thy` and `rocq/theories/Checker.v` are+//! three formalisations of one Horn certificate checker.+//! `tests/cross_kernel_differential_test.rs` runs the first two over one corpus. This+//! file runs the FIRST AND THIRD over a corpus of its own and requires them to agree,+//! except on one named cause.+//!+//! # What agreement here is, and is not+//!+//! The same caveat the Lean-Isabelle comparison carries applies here unchanged and is+//! repeated rather than cross-referenced, because a caveat nobody reads is not a caveat.+//! Checking a Horn certificate is PURELY SYNTACTIC. Neither checker consults its own+//! semantics: no interpretation, no domain, no truth. Two checkers built on contradictory+//! model theories agree on every certificate and on every forgery. Agreement here is+//! evidence about the FILE FORMAT and the CHECKING DISCIPLINE, and it is not a proof of+//! anything.+//!+//! The evidence that the DEFINITIONS agree is elsewhere: in which rule arms each side can+//! discharge and from which conditions (`rocq/theories/Builtin.v` against+//! `lean/OOCert/HornBuiltin.lean`), and in whether those conditions describe anything at+//! all (`rocq/theories/Witness.v`).+//!+//! # What this comparison found+//!+//! TWO things, and they are different in kind.+//!+//! **One divergence, one cause, no soundness content: AN EMPTY LINE.** Lean skips an+//! empty line in all three input files. Rocq refuses one, anywhere, in any of the three+//! (`R-PARSE-2` in `rocq/theories/Parse.v`). So a certificate file that ends with two+//! newlines is accepted by one verified checker and refused by the other, and the same+//! goes for the rules table and the asserted graph. Neither is unsound: an empty line is+//! not a step, not a triple and not a rule, so skipping it derives nothing and refusing+//! it asserts nothing. What is defective is the FORMAT, which never said whether an empty+//! line is a line. The quarantine below is keyed on the CAUSE, computed from the bytes,+//! and not on which mutation produced the row, because a quarantine keyed on the edit+//! hides the rows nobody designed.+//!+//! The sharp detail, and the reason this is worth a decision record rather than a shrug:+//! Lean's tolerance is for the EMPTY string exactly. A line holding one space, one tab or+//! one carriage return is refused by both. So the leniency does not cover the case that+//! motivates leniency, which is a file checked out with CRLF endings, whose blank lines+//! are `\r` and not empty. See+//! `docs/decisions/0015-a-blank-line-is-a-line-or-it-is-not.md`.+//!+//! **One defect, in the NEW checker, found by running it beside the old one.** A+//! certificate citing rule `99999999999999999999` made the Rocq checker die of a+//! `Stack_overflow`: Rocq's `nat` is unary, the parser built the number before looking at+//! it, and OCaml reports an uncaught exception with exit status 2, which is this tool's+//! code for a parse error. A crash was wearing a verdict's clothes, and the only reason+//! anybody looked was that Lean answered 1 where Rocq answered 2. Both halves are fixed:+//! `R-STEP-3` and `R-PARSE-8` put the count fields in binary, and the driver now exits 70+//! on any exception so that a crash can never again be read as a refusal. `a_crash_is_not+//! _a_verdict` below is the regression.+//!+//! Nothing on either side was adjusted to make a divergence go away. The empty-line+//! divergence is open and reported.++mod common;++use std::collections::BTreeMap;+use std::path::{Path, PathBuf};+use std::process::Command;+use std::sync::OnceLock;++fn repo() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+}++fn horn_fixture(name: &str) -> PathBuf {+ repo().join("tests").join("fixtures").join("horn").join(name)+}++// ---------------------------------------------------------------------------+// The two checkers+// ---------------------------------------------------------------------------++fn lake_available() -> bool {+ Command::new("lake").arg("--version").output().map(|o| o.status.success()).unwrap_or(false)+}++fn rocq_available() -> bool {+ Command::new("rocq").arg("--version").output().map(|o| o.status.success()).unwrap_or(false)+}++fn lean_checker() -> Option<&'static Path> {+ static P: OnceLock<Option<PathBuf>> = OnceLock::new();+ P.get_or_init(|| {+ let bin = repo().join("lean").join(".lake").join("build").join("bin").join("oo-horn");+ if bin.exists() {+ return Some(bin);+ }+ if !lake_available() {+ return None;+ }+ let ok = Command::new("lake")+ .current_dir(repo().join("lean"))+ .args(["build", "oo-horn"])+ .status()+ .map(|s| s.success())+ .unwrap_or(false);+ if ok && bin.exists() { Some(bin) } else { None }+ })+ .as_deref()+}++fn rocq_checker() -> Option<&'static Path> {+ static P: OnceLock<Option<PathBuf>> = OnceLock::new();+ P.get_or_init(|| {+ let bin = repo().join("rocq").join("build").join("oo-horn-rocq");+ if bin.exists() {+ return Some(bin);+ }+ if !rocq_available() {+ return None;+ }+ let ok = Command::new("bash")+ .arg(repo().join("rocq").join("build.sh"))+ .status()+ .map(|s| s.success())+ .unwrap_or(false);+ if ok && bin.exists() { Some(bin) } else { None }+ })+ .as_deref()+}++fn skip() -> bool {+ let lean = lean_checker().is_some();+ let rocq = rocq_checker().is_some();+ let what = match (lean, rocq) {+ (true, true) => return false,+ (false, true) => "the Lean checker (lake build oo-horn, in lean/)",+ (true, false) => "the Rocq checker (rocq/build.sh)",+ (false, false) => "both checkers: lake and rocq",+ };+ common::skip_unless(false, what, "install the toolchain it names and re-run; a differential with one half missing measures nothing")+}++/// 0 accepted, 1 rejected, 2 unreadable or unparseable, and anything else is a bug in+/// the checker rather than a verdict about the file. The fourth case is why this is an+/// enum and not an integer: an exit code nobody enumerated is exactly how a+/// `Stack_overflow` came to be read as a parse error.+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+enum Outcome {+ Accept,+ Reject,+ Unparseable,+ Broken(i32),+}++fn run(bin: &Path, rules: &Path, asserted: &Path, cert: &Path) -> Outcome {+ let out = Command::new(bin)+ .arg("check")+ .arg(rules)+ .arg(asserted)+ .arg(cert)+ .output()+ .unwrap_or_else(|e| panic!("cannot run {}: {e}", bin.display()));+ match out.status.code() {+ Some(0) => Outcome::Accept,+ Some(1) => Outcome::Reject,+ Some(2) => Outcome::Unparseable,+ Some(n) => Outcome::Broken(n),+ None => Outcome::Broken(-1),+ }+}++// ---------------------------------------------------------------------------+// The corpus+// ---------------------------------------------------------------------------++#[derive(Clone)]+struct Case {+ name: String,+ rules: Vec<u8>,+ asserted: Vec<u8>,+ cert: Vec<u8>,+}++fn read(p: PathBuf) -> Vec<u8> {+ std::fs::read(&p).unwrap_or_else(|e| panic!("cannot read {}: {e}", p.display()))+}++/// Every (rule table, asserted graph, certificate) triple the repository ships, crossed.+/// The three rule tables matter because two of them do not contain the rule the+/// certificates cite, which exercises the out-of-range path on real bytes.+fn bases() -> Vec<Case> {+ let tables = [+ ("builtin", "builtin_rules.tsv"),+ ("short", "short_rules.tsv"),+ ("user", "user_rules.tsv"),+ ];+ let pairs = [+ ("good", "asserted.tsv", "good.tsv"),+ ("bad_binding", "asserted.tsv", "bad_binding.tsv"),+ ("bad_conclusion", "asserted.tsv", "bad_conclusion.tsv"),+ ("bad_index", "asserted.tsv", "bad_index.tsv"),+ ("bad_premise", "asserted.tsv", "bad_premise.tsv"),+ ("bad_self", "asserted.tsv", "bad_self.tsv"),+ ("self_support", "deep/self_support_asserted.tsv", "deep/self_support_cert.tsv"),+ ("mutual", "deep/mutual_asserted.tsv", "deep/mutual_cert.tsv"),+ ("mutual_seeded", "deep/mutual_seeded_asserted.tsv", "deep/mutual_cert.tsv"),+ ];+ let mut out = Vec::new();+ for (tname, tfile) in tables {+ for (pname, afile, cfile) in pairs {+ out.push(Case {+ name: format!("{tname}/{pname}"),+ rules: read(horn_fixture(tfile)),+ asserted: read(horn_fixture(afile)),+ cert: read(horn_fixture(cfile)),+ });+ }+ }+ out+}++const ALIEN: &str = "<http://ex.invalid/never-derived>";++/// Byte-level edits, applied to each of the three files in turn. These are the ones that+/// ask lexical questions: what is a line, what is a field, what is the end of a file.+/// A named mutation of a file's bytes. Named because the differential reports+/// which edit produced a divergence, and a row that cannot say what it did to+/// the input is not a finding anyone can act on.+type ByteEdit = (&'static str, fn(&[u8]) -> Vec<u8>);++/// The same, for an edit that rewrites one step in place.+type StepEdit = (&'static str, fn(&mut Step));++fn byte_edits() -> Vec<ByteEdit> {+ fn trailing_blank(b: &[u8]) -> Vec<u8> {+ let mut v = b.to_vec();+ v.push(b'\n');+ v+ }+ fn leading_blank(b: &[u8]) -> Vec<u8> {+ let mut v = vec![b'\n'];+ v.extend_from_slice(b);+ v+ }+ fn interior_blank(b: &[u8]) -> Vec<u8> {+ match b.iter().position(|c| *c == b'\n') {+ Some(i) => {+ let mut v = b[..=i].to_vec();+ v.push(b'\n');+ v.extend_from_slice(&b[i + 1..]);+ v+ }+ None => b.to_vec(),+ }+ }+ fn no_final_newline(b: &[u8]) -> Vec<u8> {+ let mut v = b.to_vec();+ while v.last() == Some(&b'\n') {+ v.pop();+ }+ v+ }+ fn crlf(b: &[u8]) -> Vec<u8> {+ String::from_utf8_lossy(b).replace('\n', "\r\n").into_bytes()+ }+ fn emptied(_b: &[u8]) -> Vec<u8> {+ Vec::new()+ }+ fn blank_only(_b: &[u8]) -> Vec<u8> {+ b"\n\n".to_vec()+ }+ fn trailing_tab(b: &[u8]) -> Vec<u8> {+ let mut v = no_final_newline(b);+ v.push(b'\t');+ v.push(b'\n');+ v+ }+ fn space_line(b: &[u8]) -> Vec<u8> {+ let mut v = b.to_vec();+ v.extend_from_slice(b" \n");+ v+ }+ fn cr_line(b: &[u8]) -> Vec<u8> {+ let mut v = b.to_vec();+ v.extend_from_slice(b"\r\n");+ v+ }+ fn dup_first_line(b: &[u8]) -> Vec<u8> {+ match b.iter().position(|c| *c == b'\n') {+ Some(i) => {+ let mut v = b[..=i].to_vec();+ v.extend_from_slice(b);+ v+ }+ None => b.to_vec(),+ }+ }+ fn drop_first_line(b: &[u8]) -> Vec<u8> {+ match b.iter().position(|c| *c == b'\n') {+ Some(i) => b[i + 1..].to_vec(),+ None => Vec::new(),+ }+ }+ fn tab_to_space(b: &[u8]) -> Vec<u8> {+ let mut v = b.to_vec();+ if let Some(i) = v.iter().position(|c| *c == b'\t') {+ v[i] = b' ';+ }+ v+ }+ fn halved(b: &[u8]) -> Vec<u8> {+ b[..b.len() / 2].to_vec()+ }+ vec![+ ("trailing_blank_line", trailing_blank),+ ("leading_blank_line", leading_blank),+ ("interior_blank_line", interior_blank),+ ("no_final_newline", no_final_newline),+ ("crlf", crlf),+ ("emptied", emptied),+ ("blank_lines_only", blank_only),+ ("trailing_empty_field", trailing_tab),+ ("line_of_one_space", space_line),+ ("line_of_one_cr", cr_line),+ ("duplicated_first_line", dup_first_line),+ ("dropped_first_line", drop_first_line),+ ("tab_became_space", tab_to_space),+ ("truncated_in_half", halved),+ ]+}++/// A certificate step, split on tabs and reassembled. This is the test's own reading of+/// the format and it is deliberately NOT either checker's: it only has to be good enough+/// to build interesting mutants, and a mutant it gets wrong is still a pair of bytes both+/// checkers have to answer for.+struct Step {+ idx: String,+ bind: Vec<(String, String)>,+ concl: [String; 3],+ prems: Vec<[String; 3]>,+}++fn parse_step(line: &str) -> Option<Step> {+ let f: Vec<&str> = line.split('\t').collect();+ if f.len() < 5 {+ return None;+ }+ let k: usize = f[1].parse().ok()?;+ if f.len() < 2 + 2 * k + 3 {+ return None;+ }+ let bind = (0..k).map(|i| (f[2 + 2 * i].to_string(), f[3 + 2 * i].to_string())).collect();+ let rest = &f[2 + 2 * k..];+ let concl = [rest[0].to_string(), rest[1].to_string(), rest[2].to_string()];+ let tail = &rest[3..];+ if !tail.len().is_multiple_of(3) {+ return None;+ }+ let prems = tail+ .chunks(3)+ .map(|c| [c[0].to_string(), c[1].to_string(), c[2].to_string()])+ .collect();+ Some(Step { idx: f[0].to_string(), bind, concl, prems })+}++fn render_step(s: &Step) -> String {+ let mut f = vec![s.idx.clone(), s.bind.len().to_string()];+ for (k, v) in &s.bind {+ f.push(k.clone());+ f.push(v.clone());+ }+ f.extend(s.concl.iter().cloned());+ for p in &s.prems {+ f.extend(p.iter().cloned());+ }+ f.join("\t")+}++/// Structural edits to the FIRST step of a certificate. These are the ones that ask+/// checking questions: what is a binding, what is a premise list, what is an index.+fn step_edits() -> Vec<StepEdit> {+ fn permute_premises(s: &mut Step) {+ if s.prems.len() >= 2 {+ s.prems.swap(0, 1);+ }+ }+ fn drop_premise(s: &mut Step) {+ s.prems.pop();+ }+ fn dup_premise(s: &mut Step) {+ if let Some(p) = s.prems.first().cloned() {+ s.prems.push(p);+ }+ }+ fn no_premises(s: &mut Step) {+ s.prems.clear();+ }+ fn dup_key_different(s: &mut Step) {+ if let Some((k, _)) = s.bind.first().cloned() {+ s.bind.push((k, ALIEN.to_string()));+ }+ }+ fn dup_key_same(s: &mut Step) {+ if let Some(p) = s.bind.first().cloned() {+ s.bind.push(p);+ }+ }+ fn drop_binding(s: &mut Step) {+ s.bind.pop();+ }+ fn extra_binding(s: &mut Step) {+ s.bind.push(("never_mentioned".to_string(), ALIEN.to_string()));+ }+ fn index_zero(s: &mut Step) {+ s.idx = "0".to_string();+ }+ fn index_last(s: &mut Step) {+ s.idx = "26".to_string();+ }+ fn index_past_end(s: &mut Step) {+ s.idx = "27".to_string();+ }+ fn index_astronomical(s: &mut Step) {+ s.idx = "99999999999999999999".to_string();+ }+ fn index_leading_zero(s: &mut Step) {+ s.idx = format!("0{}", s.idx);+ }+ fn alien_conclusion(s: &mut Step) {+ s.concl[2] = ALIEN.to_string();+ }+ fn alien_premise(s: &mut Step) {+ if let Some(p) = s.prems.first_mut() {+ p[0] = ALIEN.to_string();+ }+ }+ fn swap_conclusion_and_premise(s: &mut Step) {+ if let Some(p) = s.prems.first_mut() {+ std::mem::swap(&mut s.concl, p);+ }+ }+ vec![+ ("permuted_premises", permute_premises),+ ("dropped_premise", drop_premise),+ ("duplicated_premise", dup_premise),+ ("no_premises", no_premises),+ ("duplicate_binding_key_different_value", dup_key_different),+ ("duplicate_binding_key_same_value", dup_key_same),+ ("dropped_binding", drop_binding),+ ("binding_for_an_unmentioned_variable", extra_binding),+ ("index_zero", index_zero),+ ("index_last_row", index_last),+ ("index_one_past_the_end", index_past_end),+ ("index_astronomical", index_astronomical),+ ("index_with_a_leading_zero", index_leading_zero),+ ("alien_conclusion", alien_conclusion),+ ("alien_premise", alien_premise),+ ("conclusion_swapped_with_premise", swap_conclusion_and_premise),+ ]+}++fn mutate_first_step(cert: &[u8], f: fn(&mut Step)) -> Option<Vec<u8>> {+ let text = String::from_utf8(cert.to_vec()).ok()?;+ let mut lines: Vec<String> = text.lines().map(|s| s.to_string()).collect();+ if lines.is_empty() {+ return None;+ }+ let mut s = parse_step(&lines[0])?;+ f(&mut s);+ lines[0] = render_step(&s);+ let mut out = lines.join("\n");+ out.push('\n');+ Some(out.into_bytes())+}++fn corpus() -> Vec<Case> {+ let mut out = Vec::new();+ for base in bases() {+ out.push(base.clone());+ for (ename, edit) in byte_edits() {+ out.push(Case {+ name: format!("{}+rules.{ename}", base.name),+ rules: edit(&base.rules),+ asserted: base.asserted.clone(),+ cert: base.cert.clone(),+ });+ out.push(Case {+ name: format!("{}+asserted.{ename}", base.name),+ rules: base.rules.clone(),+ asserted: edit(&base.asserted),+ cert: base.cert.clone(),+ });+ out.push(Case {+ name: format!("{}+cert.{ename}", base.name),+ rules: base.rules.clone(),+ asserted: base.asserted.clone(),+ cert: edit(&base.cert),+ });+ }+ for (ename, edit) in step_edits() {+ if let Some(cert) = mutate_first_step(&base.cert, edit) {+ out.push(Case {+ name: format!("{}+step.{ename}", base.name),+ rules: base.rules.clone(),+ asserted: base.asserted.clone(),+ cert,+ });+ }+ }+ }+ out+}++// ---------------------------------------------------------------------------+// The one quarantine, keyed on the cause+// ---------------------------------------------------------------------------++/// True when some input file carries an EMPTY line, which is the one lexical question the+/// format never answered and the one place these two checkers part company.+///+/// Computed from the bytes and not from the name of the edit that produced them. That+/// distinction is the whole design of this function: the Lean-Isabelle comparison found+/// its most interesting row through a fuzzer's typo rather than through a designed+/// mutation, and a quarantine keyed on the edit would have hidden exactly that row.+/// Several edits here produce an empty line without being named for one, `truncated_in_half`+/// and `dropped_first_line` among them.+fn has_empty_line(b: &[u8]) -> bool {+ let text = String::from_utf8_lossy(b);+ let mut parts: Vec<&str> = text.split('\n').collect();+ // A single trailing newline terminates the last line rather than starting an empty+ // one, and both checkers agree about that.+ if parts.last() == Some(&"") {+ parts.pop();+ }+ parts.iter().any(|l| l.is_empty())+}++fn empty_line_cause(c: &Case) -> Option<&'static str> {+ if has_empty_line(&c.rules) {+ Some("the rules table contains an empty line")+ } else if has_empty_line(&c.asserted) {+ Some("the asserted graph contains an empty line")+ } else if has_empty_line(&c.cert) {+ Some("the certificate contains an empty line")+ } else {+ None+ }+}++/// One directory per test, because `cargo test` runs them in parallel and they all write+/// three files with the same three names. Sharing one directory made the unmutated base+/// case report a parse error, which read exactly like a finding and was a race.+fn scratch(who: &str) -> PathBuf {+ let d = std::env::temp_dir().join("oo-rocq-differential").join(who);+ std::fs::create_dir_all(&d).expect("scratch dir");+ d+}++fn write_case(dir: &Path, c: &Case) -> (PathBuf, PathBuf, PathBuf) {+ let r = dir.join("rules.tsv");+ let a = dir.join("asserted.tsv");+ let d = dir.join("cert.tsv");+ std::fs::write(&r, &c.rules).expect("write rules");+ std::fs::write(&a, &c.asserted).expect("write asserted");+ std::fs::write(&d, &c.cert).expect("write cert");+ (r, a, d)+}++// ---------------------------------------------------------------------------+// The tests+// ---------------------------------------------------------------------------++#[test]+fn the_skip_says_which_half_is_missing() {+ if skip() {+ return;+ }+ assert!(lean_checker().is_some() && rocq_checker().is_some());+}++/// THE COMPARISON.+#[test]+fn the_two_kernels_agree_except_on_one_named_cause() {+ if skip() {+ return;+ }+ let lean = lean_checker().expect("checked above");+ let rocq = rocq_checker().expect("checked above");+ let dir = scratch("corpus");++ let cases = corpus();+ assert!(+ cases.len() > 500,+ "the corpus collapsed to {} rows, which means the generator is broken rather \+ than that the format got simple",+ cases.len()+ );++ let mut both_accept = 0usize;+ let mut both_reject = 0usize;+ let mut both_unparseable = 0usize;+ let mut quarantined: BTreeMap<&'static str, usize> = BTreeMap::new();+ let mut broken: Vec<String> = Vec::new();+ let mut unexplained: Vec<String> = Vec::new();+ let mut empty_line_rows = 0usize;++ for c in &cases {+ let (r, a, d) = write_case(&dir, c);+ let l = run(lean, &r, &a, &d);+ let q = run(rocq, &r, &a, &d);++ if let Outcome::Broken(n) = l {+ broken.push(format!("{}: the LEAN checker exited {n}", c.name));+ }+ if let Outcome::Broken(n) = q {+ broken.push(format!("{}: the ROCQ checker exited {n}", c.name));+ }++ let cause = empty_line_cause(c);+ if cause.is_some() {+ empty_line_rows += 1;+ }++ if l == q {+ match l {+ Outcome::Accept => both_accept += 1,+ Outcome::Reject => both_reject += 1,+ Outcome::Unparseable => both_unparseable += 1,+ Outcome::Broken(_) => {}+ }+ continue;+ }+ match cause {+ Some(why) => *quarantined.entry(why).or_default() += 1,+ None => unexplained.push(format!("{}: lean {l:?}, rocq {q:?}", c.name)),+ }+ }++ let divergent: usize = quarantined.values().sum();+ println!("\n=== Lean against Rocq, over {} rows ===", cases.len());+ println!("both accept: {both_accept}");+ println!("both reject: {both_reject}");+ println!("both unparseable: {both_unparseable}");+ println!("divergent, explained: {divergent}");+ for (why, n) in &quarantined {+ println!(" {n:>5} {why}");+ }+ println!("divergent, unexplained: {}", unexplained.len());+ println!("rows carrying an empty line at all: {empty_line_rows}");+ println!(+ " of which the two kernels still agreed: {}",+ empty_line_rows.saturating_sub(divergent)+ );+ println!("checker crashes: {}", broken.len());++ assert!(+ broken.is_empty(),+ "a checker exited with a code that is not a verdict:\n {}\n\nAn exit code \+ nobody enumerated is how a Stack_overflow came to be read as a parse error. \+ This is a bug in the checker, not a finding about the format.",+ broken.join("\n ")+ );++ assert!(+ unexplained.is_empty(),+ "The two kernels disagreed on rows with no empty line in them:\n {}\n\nThis is \+ a NEW finding and it belongs in a report before it belongs in a patch. Do not \+ edit either formalisation to make it go away, and in particular do not edit \+ rocq/ to agree with lean/: the only thing a third formalisation is for is \+ disagreeing.",+ unexplained.join("\n ")+ );++ // Agreement bought by refusing everything is worth nothing, so the floor is on the+ // column that cannot be bought that way.+ assert!(+ both_accept >= 20,+ "only {both_accept} rows were ACCEPTED by both kernels. Agreement is cheap when \+ one side refuses everything, so this floor is what makes the count above mean \+ anything."+ );+ assert!(+ divergent > 0,+ "the empty-line divergence reported in this file's header did not reproduce. \+ Either a checker changed, in which case delete the quarantine and say so in \+ docs/decisions/0015, or the corpus stopped generating empty lines, in which \+ case the generator is broken."+ );+}++/// The divergence, pinned on the smallest input that shows it, so that a change in either+/// checker turns this red rather than silently emptying the quarantine above.+#[test]+fn known_divergence_an_empty_line_is_a_line_here_and_not_there() {+ if skip() {+ return;+ }+ let lean = lean_checker().expect("checked above");+ let rocq = rocq_checker().expect("checked above");+ let dir = scratch("empty-line");++ let base = Case {+ name: "good".into(),+ rules: read(horn_fixture("builtin_rules.tsv")),+ asserted: read(horn_fixture("asserted.tsv")),+ cert: read(horn_fixture("good.tsv")),+ };++ // The unmutated triple agrees, so the divergence below is about the edit.+ let (r, a, d) = write_case(&dir, &base);+ assert_eq!(run(lean, &r, &a, &d), Outcome::Accept);+ assert_eq!(run(rocq, &r, &a, &d), Outcome::Accept);++ for (what, mutated) in [+ ("certificate", Case { cert: [base.cert.clone(), b"\n".to_vec()].concat(), ..base.clone() }),+ ("asserted graph", Case { asserted: [base.asserted.clone(), b"\n".to_vec()].concat(), ..base.clone() }),+ ("rules table", Case { rules: [base.rules.clone(), b"\n".to_vec()].concat(), ..base.clone() }),+ ] {+ let (r, a, d) = write_case(&dir, &mutated);+ assert_eq!(+ run(lean, &r, &a, &d),+ Outcome::Accept,+ "Lean used to skip an empty line in the {what}. If it no longer does, the \+ two kernels now agree and the quarantine should go."+ );+ assert_eq!(+ run(rocq, &r, &a, &d),+ Outcome::Unparseable,+ "Rocq used to refuse an empty line in the {what} (R-PARSE-2). If it no \+ longer does, somebody edited the third formalisation to agree with the \+ first, which is the one thing it must never be edited for."+ );+ }++ // And the sharp half: the tolerance is for the EMPTY string exactly, so it does not+ // cover a file whose blank lines carry a carriage return, which is what a CRLF+ // checkout produces. Both refuse those.+ for filler in [" ", "\t", "\r"] {+ let mutated = Case {+ cert: [base.cert.clone(), filler.as_bytes().to_vec(), b"\n".to_vec()].concat(),+ ..base.clone()+ };+ let (r, a, d) = write_case(&dir, &mutated);+ assert_eq!(run(lean, &r, &a, &d), Outcome::Unparseable, "filler {filler:?}");+ assert_eq!(run(rocq, &r, &a, &d), Outcome::Unparseable, "filler {filler:?}");+ }+}++/// The regression for the defect this comparison found in the Rocq checker.+///+/// An index of twenty digits used to overflow the stack while the number was being built+/// out of unary successors, and OCaml's uncaught-exception status is 2, which this tool+/// uses for a parse error. So the crash reported a verdict. Both halves are pinned: the+/// answer is now a rejection, and it arrives in well under a second.+#[test]+fn a_crash_is_not_a_verdict() {+ if skip() {+ return;+ }+ let lean = lean_checker().expect("checked above");+ let rocq = rocq_checker().expect("checked above");+ let dir = scratch("astronomical-index");++ let cert = std::fs::read_to_string(horn_fixture("good.tsv")).expect("good.tsv");+ let mut step = parse_step(cert.lines().next().expect("one step")).expect("parses");+ step.idx = "99999999999999999999".to_string();+ let c = Case {+ name: "astronomical index".into(),+ rules: read(horn_fixture("builtin_rules.tsv")),+ asserted: read(horn_fixture("asserted.tsv")),+ cert: format!("{}\n", render_step(&step)).into_bytes(),+ };+ let (r, a, d) = write_case(&dir, &c);++ let started = std::time::Instant::now();+ let q = run(rocq, &r, &a, &d);+ let took = started.elapsed();++ assert_eq!(+ q,+ Outcome::Reject,+ "a rule index no table can contain is a REJECTION (R-CHK-4). Exit 2 here means \+ the checker crashed and the crash is wearing a parse error's exit code, which \+ is the defect this test exists for."+ );+ assert_eq!(run(lean, &r, &a, &d), Outcome::Reject);+ assert!(+ took.as_secs() < 10,+ "the Rocq checker took {took:?} on a twenty-digit index. The count fields are \+ supposed to be binary (R-PARSE-8); if this is slow again, something went back \+ to unary."+ );+}++/// The extracted binary against the kernel.+///+/// `rocq/theories/Fixtures.v` computes the verdict for the shipped fixtures INSIDE the+/// Rocq kernel, so those lines are what the proved checker does. Extraction is trusted+/// and not verified, so this is the only handle there is on it: the binary must give the+/// same answers on the same bytes.+#[test]+fn the_extracted_binary_matches_the_verdicts_the_kernel_computed() {+ if skip() {+ return;+ }+ let rocq = rocq_checker().expect("checked above");++ // Each row is a theorem in rocq/theories/Fixtures.v, named in the comment.+ let expected: &[(&str, &str, &str, Outcome)] = &[+ // good_is_accepted_with_the_absolute_verdict+ ("builtin_rules.tsv", "asserted.tsv", "good.tsv", Outcome::Accept),+ // bad_binding_is_rejected+ ("builtin_rules.tsv", "asserted.tsv", "bad_binding.tsv", Outcome::Reject),+ // bad_conclusion_is_rejected+ ("builtin_rules.tsv", "asserted.tsv", "bad_conclusion.tsv", Outcome::Reject),+ // bad_index_is_rejected+ ("builtin_rules.tsv", "asserted.tsv", "bad_index.tsv", Outcome::Reject),+ // bad_premise_is_rejected+ ("builtin_rules.tsv", "asserted.tsv", "bad_premise.tsv", Outcome::Reject),+ // bad_self_is_rejected+ ("builtin_rules.tsv", "asserted.tsv", "bad_self.tsv", Outcome::Reject),+ // deep_self_support_is_rejected+ (+ "builtin_rules.tsv",+ "deep/self_support_asserted.tsv",+ "deep/self_support_cert.tsv",+ Outcome::Reject,+ ),+ // deep_mutual_support_is_rejected+ ("builtin_rules.tsv", "deep/mutual_asserted.tsv", "deep/mutual_cert.tsv", Outcome::Reject),+ // deep_mutual_seeded_is_accepted+ (+ "builtin_rules.tsv",+ "deep/mutual_seeded_asserted.tsv",+ "deep/mutual_cert.tsv",+ Outcome::Accept,+ ),+ ];++ let mut wrong = Vec::new();+ for (r, a, c, want) in expected {+ let got = run(rocq, &horn_fixture(r), &horn_fixture(a), &horn_fixture(c));+ if got != *want {+ wrong.push(format!("{c}: kernel says {want:?}, extracted binary says {got:?}"));+ }+ }+ assert!(+ wrong.is_empty(),+ "The extracted checker disagrees with the Rocq kernel on the shipped \+ fixtures:\n {}\n\nThe kernel is right by construction, so this is an \+ extraction bug and it is the one thing rocq/theories/Fixtures.v exists to \+ catch.",+ wrong.join("\n ")+ );+}++/// A certificate over a table nobody discharged must never earn the word a certificate+/// over the built-ins earns. Decision 0003 requires it of the Lean; the third+/// formalisation has to carry its own copy or the separation is only as good as one+/// implementation.+#[test]+fn a_user_rule_never_earns_the_absolute_verdict_in_rocq() {+ if skip() {+ return;+ }+ let rocq = rocq_checker().expect("checked above");+ let dir = scratch("user-verdict");++ // The built-in table with one extra row appended is not the built-in table.+ let mut rules = read(horn_fixture("builtin_rules.tsv"));+ rules.extend_from_slice(+ b"mine\t1\t?s\t<http://ex.org/p>\t?o\t?s\t<http://ex.org/q>\t?o\n",+ );+ let c = Case {+ name: "builtins plus one".into(),+ rules,+ asserted: read(horn_fixture("asserted.tsv")),+ cert: read(horn_fixture("good.tsv")),+ };+ let (r, a, d) = write_case(&dir, &c);++ let out = Command::new(rocq).arg("check").arg(&r).arg(&a).arg(&d).output().expect("run");+ let text = String::from_utf8_lossy(&out.stdout).to_string();+ assert_eq!(out.status.code(), Some(0), "the certificate still checks: {text}");+ assert!(+ text.contains("entailed_under_supplied_rules"),+ "a table that is not the built-in one must earn the relativised verdict, and \+ this run said: {text}"+ );+ assert!(+ !text.contains("\"verdict\":\"entailed\""),+ "the absolute verdict was awarded to a table nothing discharged: {text}"+ );++ // And the built-in table itself still earns the absolute one, or the check above+ // would be satisfied by a checker that never says `entailed` at all.+ let base = Case {+ name: "builtins".into(),+ rules: read(horn_fixture("builtin_rules.tsv")),+ asserted: read(horn_fixture("asserted.tsv")),+ cert: read(horn_fixture("good.tsv")),+ };+ let (r, a, d) = write_case(&dir, &base);+ let out = Command::new(rocq).arg("check").arg(&r).arg(&a).arg(&d).output().expect("run");+ let text = String::from_utf8_lossy(&out.stdout).to_string();+ assert!(+ text.contains("\"verdict\":\"entailed\""),+ "the built-in table no longer earns the absolute verdict, so the guard above \+ proves nothing: {text}"+ );+}++/// The fourteen, counted from the source text rather than from a comment.+///+/// `rocq/theories/Builtin.v` claims that exactly fourteen of the twenty-seven built-in+/// arms consume a BACKWARD RDFS condition, and names them. That number is the size of the+/// gap between what RDFS states and what the absolute verdict rests on, so it is quoted in+/// `rocq/README.md` and in the pull request that added it. A number quoted in three places+/// and checked in none is how a claim goes stale, and this repository has the receipts.+///+/// Each arm carries the conditions it uses as explicit hypotheses (`R-INT-4`), so the+/// dependency is in the STATEMENT and this can be read off the file with a regular+/// expression rather than inferred from a proof. Needs no toolchain: it reads the source.+#[test]+fn the_fourteen_arms_that_need_a_backward_condition_are_the_fourteen_named() {+ let src = std::fs::read_to_string(repo().join("rocq").join("theories").join("Builtin.v"))+ .expect("rocq/theories/Builtin.v must be readable");++ // Every `Lemma arm_... : <statement>.` up to the `Proof.` that follows it.+ let mut arms: Vec<(String, bool)> = Vec::new();+ let mut rest = src.as_str();+ while let Some(i) = rest.find("\nLemma arm_") {+ let after = &rest[i + 1..];+ let Some(colon) = after.find(" : ") else { break };+ let name = after[..colon].trim_start_matches("Lemma ").to_string();+ let Some(proof) = after.find("\nProof.") else { break };+ let statement = &after[colon..proof];+ arms.push((name, statement.contains("_bwd")));+ rest = &after[proof..];+ }++ assert_eq!(+ arms.len(),+ 27,+ "found {} arms in Builtin.v, not 27. Either the built-in table changed, in which \+ case docs and README need changing with it, or this scan broke.",+ arms.len()+ );++ let with_bwd: Vec<&str> =+ arms.iter().filter(|(_, b)| *b).map(|(n, _)| n.as_str()).collect();++ let expected = [+ "arm_rdfs5",+ "arm_rdfs11",+ "arm_scm_eqc1a",+ "arm_scm_eqc1b",+ "arm_scm_eqp1a",+ "arm_scm_eqp1b",+ "arm_scm_svf1",+ "arm_scm_svf2",+ "arm_scm_avf1",+ "arm_scm_avf2",+ "arm_scm_dom1",+ "arm_scm_dom2",+ "arm_scm_rng1",+ "arm_scm_rng2",+ ];++ let mut got = with_bwd.clone();+ got.sort_unstable();+ let mut want = expected.to_vec();+ want.sort_unstable();++ assert_eq!(+ got,+ want,+ "\nBuiltin.v's R-BLT-2 names fourteen arms that consume a backward RDFS condition. \+ The statements say: {with_bwd:?}\n\nThis number is the size of the gap between \+ what RDFS states and what the absolute verdict rests on, and it is quoted in \+ rocq/README.md. Correct the prose, or correct the proof, but do not leave them \+ disagreeing."+ );++ // The other thirteen must not be empty either, or `_bwd` could have stopped appearing+ // for a reason that has nothing to do with the claim.+ assert_eq!(arms.len() - with_bwd.len(), 13);+}++/// Every decision record this directory cites exists, and every number it cites is that+/// record's number.+///+/// This exists because it was needed, twice. `rocq/README.md` shipped a link to a record+/// named `0012-a-premise-list-is-evidence-or-it-is-decoration`, a filename that has never+/// existed, left over from a draft in which the record had a different name. Then the record+/// itself was renumbered to 0015 when main gained a 0012 of its own, and three files under+/// `rocq/` went on citing the old number, which by then named a DIFFERENT decision about+/// concurrency. A stale cross-reference that resolves to the wrong record is worse than one+/// that resolves to nothing, because nothing about it looks broken.+///+/// The example above is spelled without its `docs/decisions/` prefix ON PURPOSE. This file+/// is scanned by the check it contains, so a literal path written here as an illustration is+/// a path the check has to resolve, and the first run of this test failed on its own+/// docstring. `ci_gate_coverage_test.rs` hit the same wall and solved it by excluding+/// itself; excluding this file would stop it checking its own citation of 0015, which is a+/// live reference, so the example is defanged instead.+///+/// Two things are checked, and the second is the one the renumber missed: that a cited path+/// exists, and that a bare "decision NNNN" names a record that exists. Needs no toolchain.+#[test]+fn every_decision_this_directory_cites_exists() {+ let decisions = repo().join("docs").join("decisions");+ let numbers: std::collections::BTreeSet<String> = std::fs::read_dir(&decisions)+ .expect("docs/decisions/ must be readable")+ .filter_map(|e| e.ok())+ .filter_map(|e| e.file_name().to_str().map(str::to_owned))+ .filter(|n| n.ends_with(".md") && n.len() > 4)+ .map(|n| n[..4].to_string())+ .filter(|n| n.chars().all(|c| c.is_ascii_digit()))+ .collect();+ assert!(+ numbers.len() > 5,+ "only {} decision records found, so this scan is broken rather than the tree tidy",+ numbers.len()+ );++ let mut sources: Vec<PathBuf> = vec![repo().join("tests").join("rocq_kernel_differential_test.rs")];+ for dir in [repo().join("rocq"), repo().join("rocq").join("theories"), repo().join("rocq").join("driver")] {+ let Ok(entries) = std::fs::read_dir(&dir) else { continue };+ for e in entries.filter_map(|e| e.ok()) {+ let p = e.path();+ if p.is_file() {+ sources.push(p);+ }+ }+ }++ let mut bad = Vec::new();+ for src in &sources {+ let Ok(text) = std::fs::read_to_string(src) else { continue };+ let name = src.strip_prefix(repo()).unwrap_or(src).display().to_string();++ // A cited PATH must resolve.+ for (i, _) in text.match_indices("docs/decisions/") {+ let rest = &text[i + "docs/decisions/".len()..];+ let end = rest.find(['`', ']', ')', ' ', '\n', '"']).unwrap_or(rest.len());+ let file = &rest[..end];+ if file.ends_with(".md") && !decisions.join(file).exists() {+ bad.push(format!("{name}: cites docs/decisions/{file}, which does not exist"));+ }+ }++ // A bare "decision NNNN" must name a record that exists.+ let lower = text.to_lowercase();+ for (i, _) in lower.match_indices("decision ") {+ let rest = &lower[i + "decision ".len()..];+ let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();+ if digits.len() == 4 && !numbers.contains(&digits) {+ bad.push(format!("{name}: cites decision {digits}, and no such record exists"));+ }+ }+ }++ bad.sort();+ bad.dedup();+ assert!(+ bad.is_empty(),+ "Dangling or stale decision references:\n {}\n\nA reference that resolves to the \+ wrong record looks fine and says something false, which is why this checks the \+ number and not only the link.",+ bad.join("\n ")+ );+}+