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
Give every OWL-RL inference a certificate, and prove the checker sound in Lean
FABIOTESSb18e94582d62
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex ed09e946..00e4a28b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -283,3 +283,32 @@ jobs:- name: Type-checkworking-directory: studiorun: npx tsc --noEmit++ # The Lean certificate layer. `lean/` holds a checker for the reasoner's+ # derivation certificates with a machine-checked soundness proof. Building+ # that directory IS the proof check: the `#guard_msgs` axiom tripwire in+ # OOCert/Soundness.lean fails the build on any `sorry`. The Rust test then+ # certifies every ontology this repository ships through the built checker+ # and proves the checker can also say no. OO_REQUIRE_FIXTURES=1 turns the+ # "no lake installed" skip into a failure, so this job cannot pass by not+ # running.+ lean:+ timeout-minutes: 45+ name: lean / certificate checker+ runs-on: ubuntu-latest+ env:+ CARGO_INCREMENTAL: 0+ CARGO_PROFILE_DEV_DEBUG: 0+ steps:+ - uses: actions/checkout@v4+ - uses: leanprover/lean-action@v1+ with:+ lake-package-directory: lean+ build: true+ test: false+ lint: false+ use-github-cache: true+ - uses: dtolnay/rust-toolchain@stable+ - uses: Swatinem/rust-cache@v2+ - name: Certify every shipped ontology through the proved checker+ run: OO_REQUIRE_FIXTURES=1 cargo test --test lean_certificate_test -- --nocapturediff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9f6ceaa6..49181ae4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,21 @@ All notable changes to Open Ontologies are documented here.## [Unreleased]+### Added+- **Derivation certificates, checked by a proved-sound Lean checker.**+ `reason --certificate DIR` (also `onto_reason`'s `certificate_dir` and batch+ `reason --certificate`) writes `asserted.tsv` and `derivations.tsv`: every+ inferred triple with the rule that produced it and the premises the rule+ read, in a fixed order per rule. `lean/` holds a checker for that format+ whose soundness is a machine-checked theorem, `OOCert.certificate_sound`,+ with its axioms pinned by `#guard_msgs` so that a `sorry` fails the build: a+ certificate it accepts contains only triples entailed by the asserted graph+ under the RDF-based semantics of the twenty rules' vocabulary. Core Lean, no+ Mathlib, no dependencies. A new CI job builds the proofs, certifies every+ RDF file the repository ships, and appends forged lines the checker must+ reject. `owl-dl` refuses the flag rather than pretending it has a rule+ trace. See docs/lean-certificates.md and decision 0002.+### Fixed- **`sh:sparql` reported `conforms: true` when any single focus nodeconformed (#132).** The author's SELECT was wrapped as a subquery under a@@ -22,6 +37,17 @@ All notable changes to Open Ontologies are documented here.them (#131).** Every violation carries `source_shape` (the shape IRI),`source_constraint_component` (the `sh:*ConstraintComponent` IRI) and`result_path` wherever a path is known. Existing keys are unchanged.+- **`owl-rl-ext` derived the converse of a subclass axiom.** `cls-svf1`+ inferred `x rdf:type C` from `C rdfs:subClassOf ∃p.D`, `x p y` and+ `y rdf:type D`, and treated `x p D`, with `D` the filler class IRI itself,+ as a witness. Neither has a sound rule; both derivations are gone. The+ `owl:equivalentClass` case that made the first look right is carried by+ `rdfs9` over the `rdfs:subClassOf` triple `scm-eqc` emits. Found while+ giving every rule a soundness proof for the certificate checker.+- **Malformed `owl:intersectionOf` and `owl:unionOf` lists no longer fire the+ class rules.** A list is read only when every node carries `rdf:first` and+ `rdf:rest` and the chain reaches `rdf:nil`; the old lenient walk derived+ from whatever it recovered.## [1.3.0] - 2026-09-04diff --git a/CLAUDE.md b/CLAUDE.mdindex da01b7c5..b44b6243 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -75,7 +75,7 @@ Claude dynamically decides the next tool call based on what the previous tool re| `onto_shacl` | To validate loaded data against SHACL shapes (cardinality, datatypes, classes) || `onto_vocab_check` | To closed-world-check generated DATA: flags any predicate/class used that is not declared in the loaded ontology (hallucinated terms). Catches what open-world SHACL silently passes. Run on LLM-generated Turtle before `onto_load` || `onto_defects` | BEFORE trusting any fact-level result, and on every marketplace pack before adopting it. Checks the ONTOLOGY against itself with no data present: `transitive_and_functional`, `symmetric_and_asymmetric`, `subclass_cycle`, `sub_property_cycle`, `disjoint_with_ancestor`, `inherited_disjoint`, `self_inverse`, `inverse_not_mutual`. A different question from `onto_dl_check`: a transitive functional property is satisfiable and is still a trap, because the pair manufactures contradictions the moment instances arrive. Each kind is listed at most 50 times, with the full total under `truncated` |-| `onto_reason` | To run RDFS or OWL-RL inference, materializing inferred triples. Pass `inference_graph: true` to keep them in `https://open-ontologies.org/graph/inferred` instead of the default graph, so nothing downstream can read an inference as an assertion and `onto_save` to Turtle/RDF-XML cannot publish one. Default false (unchanged behaviour); not available for `owl-dl` |+| `onto_reason` | To run RDFS or OWL-RL inference, materializing inferred triples. Pass `inference_graph: true` to keep them in `https://open-ontologies.org/graph/inferred` instead of the default graph, so nothing downstream can read an inference as an assertion and `onto_save` to Turtle/RDF-XML cannot publish one. Default false (unchanged behaviour); not available for `owl-dl`. Pass `certificate_dir` to also write a derivation certificate (`asserted.tsv` + `derivations.tsv`) that the proved-sound Lean checker in `lean/` verifies; see docs/lean-certificates.md || `onto_reason_incremental` | After adding facts to an already-materialised graph. Derives the consequences of the ADDED triples only (semi-naive evaluation, joining the delta against the closure), so the cost tracks what changed rather than the size of the store: effectively instant against a 1.9M-triple store where full re-materialisation takes seconds. Refuses schema axioms (subClassOf, domain, range, inverseOf, equivalentClass) with an explanation, because those change what the whole store entails: run `onto_reason` for them || `onto_extend` | To run the full pipeline: ingest → SHACL validate → reason in one call || `onto_import_schema` | To import a PostgreSQL or DuckDB database schema as an OWL ontology (requires `postgres` and/or `duckdb` features). Auto-dispatches on connection-string scheme. |diff --git a/README.md b/README.mdindex 76855f1c..a7c52f2e 100644--- a/README.md+++ b/README.md@@ -994,6 +994,20 @@ flowchart TDDataPipe --> PG```+### Certified inference++The forward-chaining reasoner (`rdfs`, `owl-rl`, `owl-rl-ext`) can write a+derivation certificate beside its result: `reason --certificate DIR` records+every inferred triple with the rule that produced it and the premises the rule+read. `lean/` holds a checker for that certificate whose soundness is a+machine-checked theorem (`OOCert.certificate_sound`, core Lean, no Mathlib), so+a run whose certificate checks contains only triples entailed by the asserted+graph, whatever this engine did to find them. CI builds the proofs and+certifies every RDF file in this repository. The first thing the checker caught+was in the engine: `cls-svf1` derived the converse of a subclass axiom. Details+in [docs/lean-certificates.md](docs/lean-certificates.md) and+[decision 0002](docs/decisions/0002-an-inference-carries-a-certificate.md).+### Studio```mermaid@@ -1078,6 +1092,7 @@ flowchart TD| Ontology Lifecycle | [docs/lifecycle.md](docs/lifecycle.md) || Schema Alignment | [docs/alignment.md](docs/alignment.md) || SHIQ Reasoning | [docs/reasoning.md](docs/reasoning.md) |+| Derivation certificates, Lean checker | [docs/lean-certificates.md](docs/lean-certificates.md) || Semantic Embeddings | [docs/embeddings.md](docs/embeddings.md) || Clinical Crosswalks | [docs/clinical.md](docs/clinical.md) || IES Ecosystem | [docs/ies-ecosystem.md](docs/ies-ecosystem.md) |diff --git a/docs/decisions/0002-an-inference-carries-a-certificate.md b/docs/decisions/0002-an-inference-carries-a-certificate.mdnew file mode 100644index 00000000..d7c9cc65--- /dev/null+++ b/docs/decisions/0002-an-inference-carries-a-certificate.md@@ -0,0 +1,62 @@+# 0002 · An inference carries a certificate, and the certificate has a proof++- **Status**: implemented for the forward-chaining family (`rdfs`, `owl-rl`, `owl-rl-ext`) ·+ `reason --certificate DIR`, `onto_reason` with `certificate_dir`, batch `reason --certificate` ·+ checker in `lean/` with `OOCert.certificate_sound` machine-checked, axioms pinned by+ `#guard_msgs` · every shipped ontology certified in CI (`tests/lean_certificate_test.rs`) ·+ **opt-in, default unchanged** · the `owl-dl` tableaux path refuses the flag rather than+ pretending · not covered: SHACL, the tableaux reasoner, the parsers+- **Written**: 2026-09-13+- **Related**: decision 0001 (an inference is not an assertion); issues #131 and #132, fixed the+ same day; `tests/reason_rl_ext_soundness_test.rs`, the first thing the layer caught++## The problem++The engine's inferences were trusted because the engine was trusted. The reasoner is a few hundred+lines of Rust applying rules by hand, and on 13 September 2026 two of those rules turned out to be+unsound: `cls-svf1` derived membership in a class from membership in its restriction *superclass*+(the converse of the axiom), and it treated a class IRI in object position as an instance of that+class. Both had been there since the extended profile was written. Both were found not by a test+but by asking, rule by rule, "what semantic condition would make this sound", and finding none.++A test suite catches the bugs someone thought of. What was missing is a check that does not depend+on the engine's author having thought of the bug.++## Decisions++1. **The reasoner emits a certificate, not a claim.** With `--certificate DIR` every inferred+ triple is written with the rule that produced it and the premises the rule read, in a fixed+ order per rule. The asserted graph goes beside it. Nothing about the engine's internals is+ needed to read the two files.+2. **The checker re-derives, it does not search.** `OOCert.checkStep` matches the premises+ against the rule's shape, checks each premise is asserted or was concluded by an earlier step,+ and checks the conclusion is the one the rule yields. No fixpoint, no indices, no search: a few+ hundred lines that a reader can hold at once.+3. **The checker's soundness is a theorem, not a test.** `OOCert.certificate_sound` states that a+ certificate the checker accepts contains only triples entailed by the asserted graph under the+ RDF-based semantics of the vocabulary the rules use (`lean/OOCert/Semantics.lean`). The proof+ is one lemma per rule plus an induction over the certificate. `#guard_msgs` pins the axioms to+ `propext`, `Classical.choice` and `Quot.sound`; a `sorry` or a `native_decide` fails the build.+4. **The semantic conditions are the weakest the rules need.** Each is the *if* direction of the+ corresponding W3C condition or a consequence of it. Weaker conditions admit more+ interpretations, so soundness here implies soundness under the OWL 2 RDF-Based Semantics and+ under the Direct Semantics read through triples. Where the W3C reads a list off the graph, so+ does `Model`, through `Chain`.+5. **Core Lean only.** No Mathlib. `Std.HashSet` for membership, with its own lemmas bridging to+ list membership in the proof. The trust surface is the Lean kernel plus `lean/`.+6. **The gate is proved able to fail.** The test suite appends a forged conclusion, a premise+ outside the graph, and the exact line the old `cls-svf1` emitted, and requires each to be+ rejected. A gate that cannot fail is decoration.+7. **The reasoner derives less from malformed lists.** `owl:intersectionOf` and `owl:unionOf`+ lists are read only when every node carries `rdf:first` and `rdf:rest` and the chain reaches+ `rdf:nil`. The old lenient walk fired the class rules on whatever it recovered; the checker has+ no rule for a list it cannot walk, so neither does the reasoner. Deriving less from malformed+ input is the sound direction.++## What this does not claim++It does not make ontologies "correct". It makes every OWL-RL inference the engine reports+independently checkable against a formal semantics with a proved checker. Whether an ontology says+what its author meant is a different question and no proof answers it. The SHACL validator, the+SHIQ tableaux reasoner and the RDF parsers are outside the theorem; the differential oracle+against pyshacl (`tools/shacl_differential.py`) remains the gate for SHACL.diff --git a/docs/lean-certificates.md b/docs/lean-certificates.mdnew file mode 100644index 00000000..2501fe2b--- /dev/null+++ b/docs/lean-certificates.md@@ -0,0 +1,112 @@+# Derivation certificates and the Lean checker++Every inference the forward-chaining reasoner makes can be written out with the rule that+produced it and the premises the rule read, and a checker in `lean/` verifies that record against a+formal semantics. The checker's soundness is a machine-checked theorem, so a certificate it accepts+contains only triples entailed by the asserted graph, whatever the Rust engine did to find them.++This page is the how-to. The design and its limits are in+[decision 0002](decisions/0002-an-inference-carries-a-certificate.md).++## Produce a certificate++```bash+# CLI: any of rdfs, owl-rl, owl-rl-ext. The tableaux path (owl-dl) refuses the flag.+open-ontologies load ontology.ttl+open-ontologies reason --profile owl-rl-ext --certificate /tmp/cert++# Batch, when the store is in-memory per process:+printf 'load ontology.ttl\nreason --profile owl-rl-ext --certificate /tmp/cert\n' \+ | open-ontologies --no-connect --data-dir /tmp/store batch -+```++Over MCP, `onto_reason` takes `certificate_dir`. The response gains a `certificate` object:++```json+{+ "inferred_count": 268,+ "certificate": {+ "dir": "/tmp/cert",+ "format": "oo-cert/1",+ "asserted": 1128,+ "derivations": 268,+ "by_rule": {"rdfs2": 41, "rdfs9": 190, "scm-eqc1": 3, "...": "..."},+ "check_with": "cd lean && lake exe oo-cert <dir>/asserted.tsv <dir>/derivations.tsv"+ }+}+```++`derivations` always equals `inferred_count`: one line per inferred triple, recorded the first time+it is derived.++## Check it++The checker needs a Lean 4 toolchain. [elan](https://github.com/leanprover/elan) installs the+version `lean/lean-toolchain` pins; nothing else is downloaded, the project has no dependencies.++```bash+cd lean+lake build # builds the checker AND checks the proofs+lake exe oo-cert /tmp/cert/asserted.tsv /tmp/cert/derivations.tsv+```++Exit codes: `0` every step checks; `1` a step was rejected, and the JSON on stdout names the first+one with its rule, conclusion and premises; `2` a file could not be read or parsed.++```json+{"ok":true,"asserted":1128,"derivations":268,"theorem":"OOCert.certificate_sound"}+```++## The files++Two tab-separated files. Terms are in N-Triples spelling, exactly as the engine's interner holds+them, so a term is spelled identically wherever it appears and tabs and newlines cannot occur+inside one.++- `asserted.tsv`: one triple per line, `s TAB p TAB o`. Every triple the run started from.+- `derivations.tsv`: one step per line, `rule TAB s TAB p TAB o` for the conclusion, then the+ premises as further triples, in the order documented per rule in `lean/OOCert/Rules.lean`.++## What is proved++`OOCert.certificate_sound` in `lean/OOCert/Soundness.lean`:++> if `checkCert G steps = true` then for every step, `G ⊨ step.conclusion`++where `G ⊨ t` is truth in every model of `G` under the semantics in `lean/OOCert/Semantics.lean`:+the RDF-based reading of the twenty rules' vocabulary, with each semantic condition the *if*+direction of the W3C condition or a consequence of it, never more. Weaker conditions admit more+interpretations, so the result carries over to the OWL 2 RDF-Based Semantics and to the Direct+Semantics read through triples.++The axioms the theorem depends on are pinned in the source by `#guard_msgs`:+`propext`, `Classical.choice`, `Quot.sound`. A `sorry`, or a `native_decide`, fails `lake build`.++## What is not proved++- Completeness. The checker rejects anything it cannot re-derive by pattern, including valid+ inferences in an order it does not expect. A rejection is a false alarm at worst, never a false+ pass.+- The parser and the file format (`lean/OOCert/Parse.lean`, `lean/Main.lean`). A parse error+ rejects.+- Anything outside the forward-chaining family: the SHACL validator (the pyshacl differential in+ `tools/shacl_differential.py` is its gate), the SHIQ tableaux reasoner, the RDF parsers.+- Datatype semantics. Two spellings of one literal value are two terms. No rule compares literals+ by value, so nothing is lost, but do not read `Entails` as datatype-aware.++## What it caught on day one++`cls-svf1` in the `owl-rl-ext` profile derived `x rdf:type C` from `C rdfs:subClassOf ∃p.D`,+`x p y` and `y rdf:type D`. That is the converse of the axiom. It also treated `x p D`, with `D` the+filler class IRI itself, as a witness. Neither has a sound rule, so neither could be given one in+the checker, and both are gone (`tests/reason_rl_ext_soundness_test.rs`). The old derivation is+kept in `tests/lean_certificate_test.rs` as a forged certificate the checker must reject.++## In CI++The `lean` job builds `lean/` (which is the proof check), then runs+`tests/lean_certificate_test.rs` with `OO_REQUIRE_FIXTURES=1`: every RDF file under+`case-studies/`, `demo/`, `tests/fixtures/`, `data/` and `examples/` is loaded, reasoned under+`owl-rl-ext` with a certificate, and the certificate checked. Files over 4 MB and files that do not+parse are listed with the reason, never dropped silently. The same test appends three forgeries+and requires each to be rejected.diff --git a/docs/reasoning.md b/docs/reasoning.mdindex f5898735..c8b87b23 100644--- a/docs/reasoning.md+++ b/docs/reasoning.md@@ -60,3 +60,10 @@ measurements are in| `onto_reason` | Run inference with selected profile || `onto_dl_explain` | Explain why a class is unsatisfiable (clash trace) || `onto_dl_check` | Check if one class is subsumed by another |++## Certified inference++Every profile except `owl-dl` can emit a derivation certificate+(`reason --certificate DIR`) that the checker in `lean/` verifies against a+machine-checked soundness theorem. What is proved, what is not, and how to run+it: [lean-certificates.md](lean-certificates.md).diff --git a/docs/superpowers/specs/2026-09-13-lean-certificate-layer-design.md b/docs/superpowers/specs/2026-09-13-lean-certificate-layer-design.mdnew file mode 100644index 00000000..6f90a42e--- /dev/null+++ b/docs/superpowers/specs/2026-09-13-lean-certificate-layer-design.md@@ -0,0 +1,97 @@+# Lean certificate layer, design++Date: 2026-09-13. Status: implemented on branch `lean-certificate-layer`.++## Purpose++Give every inference the forward-chaining reasoner makes an independent, machine-checked+justification, so that trusting a materialised graph no longer means trusting the Rust that+produced it.++## Constraints that shaped it++- The request was "a Lean layer so all ontologies are correct, no bugs". No proof can deliver the+ literal reading: correctness of an ontology against the world is not a formal property. The+ deliverable is the strongest formal property available: **soundness of every reported+ inference**, checked per run by a program whose own correctness is a theorem.+- The reasoner is a hand-written rule engine (`src/reason.rs`). Verifying that code directly+ would mean re-implementing it in Lean and proving equivalence, which is large and brittle.+ Certifying its *output* is small and decoupled: the engine may change freely, the checker does+ not care how a derivation was found.+- Repository convention: core Lean only, small trust surface, every kill condition executable+ (see `~/projects/owl-lean`, the sibling formalisation this follows in style).+- A green run must mean something. Tests that cannot fail, and skips that look like passes, are+ the failure mode this repository exists to catch (`tests/common/mod.rs`).++## Architecture++```+ ontology (Turtle)+ │ load+ ▼+ GraphStore ──reason --certificate DIR──▶ asserted.tsv (every asserted triple, s TAB p TAB o)+ │ derivations.tsv (rule TAB conclusion TAB premises…)+ │ materialise │+ ▼ ▼+ materialised graph lake exe oo-cert asserted.tsv derivations.tsv+ │+ exit 0 ⇔ OOCert.checkCert = true+ │+ theorem certificate_sound:+ checkCert G steps = true → ∀ st ∈ steps, G ⊨ st.conclusion+```++Components:++| unit | where | does | depends on |+|---|---|---|---|+| emitter | `src/reason.rs` (`Reasoner::run_full`) | records the first derivation of each inferred triple with rule id and premises; writes the two TSVs | the interner's N-Triples spellings |+| semantics | `lean/OOCert/Semantics.lean` | `Interp`, `Conditions`, `Chain`, `Model`, `Entails` | `Triple.lean` |+| checker | `lean/OOCert/Rules.lean` | `Rule`, `Step`, `takeChain`, `allTyped`, `checkStep`, `checkAll`, `checkCert` | `Std.HashSet` |+| proof | `lean/OOCert/Soundness.lean` | per-rule lemmas, `checkAll_sound`, `certificate_sound`, axiom tripwire | checker + semantics |+| front end | `lean/OOCert/Parse.lean`, `lean/Main.lean` | TSV parsing, exit codes, diagnostic naming the first rejected step | unverified by design |+| gate | `tests/lean_certificate_test.rs`, CI job `lean` | builds the checker, certifies every shipped ontology, proves the gate rejects forgeries | `lake` on PATH |++## Data flow and contract++- One certificate line per inferred triple; `derivations == inferred_count` is asserted by the+ tests.+- Premise order per rule is fixed and documented in `Rules.lean`. The emitter and the checker are+ held to it by a test that fires all twenty rules and requires the certificate to be accepted.+- The list constructors' chain triples must be asserted; every other premise may be asserted or+ previously derived.+- Blank nodes are constants scoped to one certificate (the skolemised reading). Both files come+ from one run, so labels agree.++## Semantics, in one paragraph++An interpretation is a domain, a denotation for every term, and one relation `iext p x y`. A+triple holds when its predicate's extension contains its subject and object; class membership is+`rdf:type`'s extension. Schema meaning lives in `Conditions`, each the *if* half of the W3C+RDF-based condition or a consequence of it, never more. Lists are read off the asserted graph+(`Chain`), as the W3C tables do. `G ⊨ t` is truth in every model of `G`.++## Error handling++- Parse error in either file: exit 2, nothing accepted.+- Any step rejected: exit 1 with the index, rule, conclusion and premises of the first rejected+ step (from an unverified diagnostic pass that runs only after the verified checker said no).+- `owl-dl` with a certificate directory: the engine refuses with a message; it has no rule trace.+- `lake` missing locally: the Rust tests skip through `common::skip_unless`, printing the marker;+ CI sets `OO_REQUIRE_FIXTURES=1` so the skip is a failure there.++## Testing++- `every_rule_family_appears_in_an_accepted_certificate`: all twenty rules, accepted.+- `a_forged_conclusion_is_rejected`, `a_premise_outside_the_graph_is_rejected`,+ `the_derivation_the_old_svf_rule_made_is_rejected`: the gate fails when it should.+- `every_shipped_ontology_certifies`: walks `case-studies/`, `demo/`, `tests/fixtures/`, `data/`,+ `examples/`; files over 4 MB and files that do not parse are listed with the reason, never+ dropped silently; at least 30 files must certify and at least one inference must be checked.+- `lean/`'s own build is the proof check; `#guard_msgs` pins the axiom list.++## Out of scope, stated++SHACL (pyshacl differential remains the gate), the SHIQ tableaux reasoner (would need+model or refutation certificates; SHIQ lacks the finite model property so this is real work), the+RDF parsers, datatype-aware literal semantics, and `owl:sameAs` beyond symmetry.diff --git a/lean/.gitignore b/lean/.gitignorenew file mode 100644index 00000000..01f8cdb6--- /dev/null+++ b/lean/.gitignore@@ -0,0 +1 @@+.lake/diff --git a/lean/Main.lean b/lean/Main.leannew file mode 100644index 00000000..f3fba0ec--- /dev/null+++ b/lean/Main.lean@@ -0,0 +1,63 @@+import OOCert++/-!+`oo-cert ASSERTED.tsv DERIVATIONS.tsv`++Exit 0 when every step checks, 1 when one does not, 2 when a file cannot be+read or parsed. The verdict comes from `OOCert.checkCert`, the function+`OOCert.certificate_sound` is proved about. The diagnostic pass that names the+first rejected step is separate and unverified; it runs only after the+verified checker has already said no.+-/+open OOCert++def firstFailure (G : List Triple) (steps : List Step) : Option (Nat × Step) := Id.run do+ let gset := Std.HashSet.ofList G+ let inG := fun t => gset.contains t+ let mut derived : Std.HashSet Triple := ∅+ let mut i := 0+ for st in steps do+ if !checkStep inG (fun t => derived.contains t) st then+ return some (i, st)+ derived := derived.insert st.conclusion+ i := i + 1+ return none++def jsonStr (s : String) : String :=+ let escaped := s.foldl (fun acc c =>+ match c with+ | '"' => acc ++ "\\\""+ | '\\' => acc ++ "\\\\"+ | '\n' => acc ++ "\\n"+ | '\t' => acc ++ "\\t"+ | c => acc.push c) ""+ "\"" ++ escaped ++ "\""++def showTriple (t : Triple) : String := s!"{t.s} {t.p} {t.o}"++def main (args : List String) : IO UInt32 := do+ match args with+ | [gPath, dPath] =>+ let g ← IO.FS.readFile gPath+ let d ← IO.FS.readFile dPath+ match Parse.parseTriples g, Parse.parseSteps d with+ | .ok G, .ok steps =>+ if checkCert G steps then+ IO.println s!"\{\"ok\":true,\"asserted\":{G.length},\"derivations\":{steps.length},\"theorem\":\"OOCert.certificate_sound\"}"+ return 0+ else+ match firstFailure G steps with+ | some (i, st) =>+ IO.println s!"\{\"ok\":false,\"asserted\":{G.length},\"derivations\":{steps.length},\"first_rejected\":{i},\"rule\":{jsonStr st.rule.name},\"conclusion\":{jsonStr (showTriple st.conclusion)},\"premises\":[{String.intercalate "," (st.premises.map (fun t => jsonStr (showTriple t)))}]}"+ | none =>+ IO.println "{\"ok\":false,\"error\":\"the verified checker rejected the certificate and the diagnostic pass could not name a step\"}"+ return 1+ | .error e, _ =>+ IO.eprintln e+ return 2+ | _, .error e =>+ IO.eprintln e+ return 2+ | _ =>+ IO.eprintln "usage: oo-cert ASSERTED.tsv DERIVATIONS.tsv"+ return 2diff --git a/lean/OOCert.lean b/lean/OOCert.leannew file mode 100644index 00000000..dc7fe92e--- /dev/null+++ b/lean/OOCert.lean@@ -0,0 +1,5 @@+import OOCert.Triple+import OOCert.Semantics+import OOCert.Rules+import OOCert.Soundness+import OOCert.Parsediff --git a/lean/OOCert/Parse.lean b/lean/OOCert/Parse.leannew file mode 100644index 00000000..ebc02776--- /dev/null+++ b/lean/OOCert/Parse.lean@@ -0,0 +1,55 @@+import OOCert.Rules++/-!+# Certificate files++Two tab-separated files, both written by the engine's interner so that a term+is spelled identically wherever it appears. Tabs and newlines cannot occur+inside an N-Triples term (they are escaped), so splitting on them is exact.++* `asserted.tsv`: one triple per line, `s TAB p TAB o`.+* `derivations.tsv`: one step per line,+ `rule TAB s TAB p TAB o [TAB ps TAB pp TAB po]*`, conclusion first, then+ the premises in the order `Rules.lean` documents.++This module is not part of the proof. A parse error is a rejected certificate,+never an accepted one.+-/+namespace OOCert.Parse++def tripleOf? : List String → Option Triple+ | [s, p, o] => some ⟨s, p, o⟩+ | _ => none++def groupTriples : List String → Option (List Triple)+ | [] => some []+ | s :: p :: o :: rest => (groupTriples rest).map (⟨s, p, o⟩ :: ·)+ | _ => none++def parseTriples (content : String) : Except String (List Triple) := do+ let mut out : Array Triple := #[]+ let mut n := 0+ for line in content.splitOn "\n" do+ n := n + 1+ if line.isEmpty then continue+ match tripleOf? (line.splitOn "\t") with+ | some t => out := out.push t+ | none => throw s!"asserted.tsv line {n}: expected three tab-separated terms"+ return out.toList++def parseSteps (content : String) : Except String (List Step) := do+ let mut out : Array Step := #[]+ let mut n := 0+ for line in content.splitOn "\n" do+ n := n + 1+ if line.isEmpty then continue+ match line.splitOn "\t" with+ | rule :: s :: p :: o :: prem =>+ match Rule.ofName? rule, groupTriples prem with+ | some r, some ps => out := out.push ⟨r, ps, ⟨s, p, o⟩⟩+ | none, _ => throw s!"derivations.tsv line {n}: unknown rule '{rule}'"+ | _, none => throw s!"derivations.tsv line {n}: premises are not whole triples"+ | _ => throw s!"derivations.tsv line {n}: expected rule, conclusion, premises"+ return out.toList++end OOCert.Parsediff --git a/lean/OOCert/Rules.lean b/lean/OOCert/Rules.leannew file mode 100644index 00000000..c11dcbf4--- /dev/null+++ b/lean/OOCert/Rules.lean@@ -0,0 +1,192 @@+import Std.Data.HashSet+import OOCert.Semantics++/-!+# Rules and the checker++A certificate is a list of steps. Each step names a rule, lists the premises+the engine used, and states the conclusion. `checkStep` re-derives the+conclusion from the premises by pattern alone: it checks that the premises+have the shape the rule requires, that each is asserted or was concluded by an+earlier step, and that the conclusion is the one the rule produces from them.+It does no search. That is what keeps it small and what makes+`certificate_sound` (in `Soundness.lean`) a short proof.++## Premise order is part of the contract++The engine writes premises in the order listed with each rule below, and the+checker matches on that order. A certificate with the right triples in the+wrong order is rejected, which is a false alarm and never a false pass.++| rule | premises | conclusion |+|------------|-----------------------------------------------------------------|------------------|+| rdfs2 | `s p o`, `p rdfs:domain c` | `s rdf:type c` |+| rdfs3 | `s p o`, `p rdfs:range c` | `o rdf:type c` |+| rdfs5 | `a sp b`, `b sp c` | `a sp c` |+| rdfs7 | `s p o`, `p sp q` | `s q o` |+| rdfs9 | `x rdf:type a`, `a sc b` | `x rdf:type b` |+| rdfs11 | `a sc b`, `b sc c` | `a sc c` |+| prp-trp | `p rdf:type owl:TransitiveProperty`, `x p y`, `y p z` | `x p z` |+| prp-symp | `p rdf:type owl:SymmetricProperty`, `x p y` | `y p x` |+| prp-inv1 | `p owl:inverseOf q`, `x p y` | `y q x` |+| prp-inv2 | `p owl:inverseOf q`, `x q y` | `y p x` |+| eq-sym | `a owl:sameAs b` | `b owl:sameAs a` |+| scm-eqc1 | `a owl:equivalentClass b` | `a sc b` |+| scm-eqc2 | `a owl:equivalentClass b` | `b sc a` |+| scm-eqp1 | `a owl:equivalentProperty b` | `a sp b` |+| scm-eqp2 | `a owl:equivalentProperty b` | `b sp a` |+| cls-svf1 | `r owl:onProperty p`, `r owl:someValuesFrom c`, `x p y`, `y rdf:type c` | `x rdf:type r` |+| cls-hv1 | `r owl:onProperty p`, `r owl:hasValue v`, `k sc r`, `x rdf:type k` | `x p v` |+| cls-hv2 | `r owl:onProperty p`, `r owl:hasValue v`, `x p v` | `x rdf:type r` |+| cls-int1 | `c owl:intersectionOf l`, the list chain of `l`, `x rdf:type m` for every member `m` | `x rdf:type c` |+| cls-uni | `c owl:unionOf l`, the list chain of `l`, `x rdf:type m` for one member `m` | `x rdf:type c` |++The list chain is the sequence `l rdf:first m₁`, `l rdf:rest l₂`,+`l₂ rdf:first m₂`, `l₂ rdf:rest l₃`, … down to a node whose `rdf:rest` is+`rdf:nil`. The chain and the constructor triple must be asserted, not derived,+because `Model` reads lists off the asserted graph.+-/+namespace OOCert++inductive Rule+ | rdfs2 | rdfs3 | rdfs5 | rdfs7 | rdfs9 | rdfs11+ | prpTrp | prpSymp | prpInv1 | prpInv2 | eqSym+ | scmEqc1 | scmEqc2 | scmEqp1 | scmEqp2+ | clsSvf1 | clsHv1 | clsHv2 | clsInt1 | clsUni+deriving DecidableEq, Repr++def Rule.name : Rule → String+ | .rdfs2 => "rdfs2" | .rdfs3 => "rdfs3" | .rdfs5 => "rdfs5" | .rdfs7 => "rdfs7"+ | .rdfs9 => "rdfs9" | .rdfs11 => "rdfs11"+ | .prpTrp => "prp-trp" | .prpSymp => "prp-symp" | .prpInv1 => "prp-inv1"+ | .prpInv2 => "prp-inv2" | .eqSym => "eq-sym"+ | .scmEqc1 => "scm-eqc1" | .scmEqc2 => "scm-eqc2" | .scmEqp1 => "scm-eqp1"+ | .scmEqp2 => "scm-eqp2"+ | .clsSvf1 => "cls-svf1" | .clsHv1 => "cls-hv1" | .clsHv2 => "cls-hv2"+ | .clsInt1 => "cls-int1" | .clsUni => "cls-uni"++def Rule.all : List Rule :=+ [.rdfs2, .rdfs3, .rdfs5, .rdfs7, .rdfs9, .rdfs11,+ .prpTrp, .prpSymp, .prpInv1, .prpInv2, .eqSym,+ .scmEqc1, .scmEqc2, .scmEqp1, .scmEqp2,+ .clsSvf1, .clsHv1, .clsHv2, .clsInt1, .clsUni]++def Rule.ofName? (s : String) : Option Rule :=+ Rule.all.find? (fun r => r.name == s)++structure Step where+ rule : Rule+ premises : List Triple+ conclusion : Triple+deriving Repr++/-- Consume the list chain for node `l` from the front of `ps`, checking each+chain triple with `inG`. Returns the members and the premises left over. -/+def takeChain (inG : Triple → Bool) : Term → List Triple → Option (List Term × List Triple)+ | l, ps =>+ if l = V.nil then some ([], ps)+ else+ match ps with+ | ⟨l1, f, m⟩ :: ⟨l2, r, l'⟩ :: ps' =>+ if l1 = l ∧ f = V.first ∧ l2 = l ∧ r = V.rest ∧ inG ⟨l1, f, m⟩ ∧ inG ⟨l2, r, l'⟩ then+ match takeChain inG l' ps' with+ | some (ms, q) => some (m :: ms, q)+ | none => none+ else none+ | _ => none++/-- `ps` is exactly `x rdf:type m` for each `m` in `ms`, in order, each known. -/+def allTyped (x : Term) (k : Triple → Bool) : List Term → List Triple → Bool+ | [], [] => true+ | m :: ms, ⟨x', t, m'⟩ :: ps =>+ x' = x ∧ t = V.type ∧ m' = m ∧ k ⟨x', t, m'⟩ ∧ allTyped x k ms ps+ | _, _ => false++/-- Check one step. `inG` answers "asserted"; `derived` answers "concluded by+an earlier step". A premise may be either, except the list constructor and its+chain, which must be asserted. -/+def checkStep (inG derived : Triple → Bool) (st : Step) : Bool :=+ let k : Triple → Bool := fun t => inG t || derived t+ match st.rule, st.premises with+ | .rdfs2, [⟨s, p, o⟩, ⟨p', d, c⟩] =>+ p' = p ∧ d = V.domain ∧ k ⟨s, p, o⟩ ∧ k ⟨p', d, c⟩ ∧+ st.conclusion = ⟨s, V.type, c⟩+ | .rdfs3, [⟨s, p, o⟩, ⟨p', r, c⟩] =>+ p' = p ∧ r = V.range ∧ k ⟨s, p, o⟩ ∧ k ⟨p', r, c⟩ ∧+ st.conclusion = ⟨o, V.type, c⟩+ | .rdfs5, [⟨a, sp1, b⟩, ⟨b', sp2, c⟩] =>+ sp1 = V.subPropertyOf ∧ sp2 = V.subPropertyOf ∧ b' = b ∧+ k ⟨a, sp1, b⟩ ∧ k ⟨b', sp2, c⟩ ∧ st.conclusion = ⟨a, V.subPropertyOf, c⟩+ | .rdfs7, [⟨s, p, o⟩, ⟨p', sp, q⟩] =>+ p' = p ∧ sp = V.subPropertyOf ∧ k ⟨s, p, o⟩ ∧ k ⟨p', sp, q⟩ ∧+ st.conclusion = ⟨s, q, o⟩+ | .rdfs9, [⟨x, t, a⟩, ⟨a', sc, b⟩] =>+ t = V.type ∧ a' = a ∧ sc = V.subClassOf ∧ k ⟨x, t, a⟩ ∧ k ⟨a', sc, b⟩ ∧+ st.conclusion = ⟨x, V.type, b⟩+ | .rdfs11, [⟨a, sc1, b⟩, ⟨b', sc2, c⟩] =>+ sc1 = V.subClassOf ∧ sc2 = V.subClassOf ∧ b' = b ∧+ k ⟨a, sc1, b⟩ ∧ k ⟨b', sc2, c⟩ ∧ st.conclusion = ⟨a, V.subClassOf, c⟩+ | .prpTrp, [⟨p, t, tp⟩, ⟨x, p1, y⟩, ⟨y', p2, z⟩] =>+ t = V.type ∧ tp = V.transitiveProperty ∧ p1 = p ∧ p2 = p ∧ y' = y ∧+ k ⟨p, t, tp⟩ ∧ k ⟨x, p1, y⟩ ∧ k ⟨y', p2, z⟩ ∧ st.conclusion = ⟨x, p, z⟩+ | .prpSymp, [⟨p, t, sy⟩, ⟨x, p1, y⟩] =>+ t = V.type ∧ sy = V.symmetricProperty ∧ p1 = p ∧+ k ⟨p, t, sy⟩ ∧ k ⟨x, p1, y⟩ ∧ st.conclusion = ⟨y, p, x⟩+ | .prpInv1, [⟨p, io, q⟩, ⟨x, p1, y⟩] =>+ io = V.inverseOf ∧ p1 = p ∧ k ⟨p, io, q⟩ ∧ k ⟨x, p1, y⟩ ∧+ st.conclusion = ⟨y, q, x⟩+ | .prpInv2, [⟨p, io, q⟩, ⟨x, q1, y⟩] =>+ io = V.inverseOf ∧ q1 = q ∧ k ⟨p, io, q⟩ ∧ k ⟨x, q1, y⟩ ∧+ st.conclusion = ⟨y, p, x⟩+ | .eqSym, [⟨a, sa, b⟩] =>+ sa = V.sameAs ∧ k ⟨a, sa, b⟩ ∧ st.conclusion = ⟨b, V.sameAs, a⟩+ | .scmEqc1, [⟨a, e, b⟩] =>+ e = V.equivalentClass ∧ k ⟨a, e, b⟩ ∧ st.conclusion = ⟨a, V.subClassOf, b⟩+ | .scmEqc2, [⟨a, e, b⟩] =>+ e = V.equivalentClass ∧ k ⟨a, e, b⟩ ∧ st.conclusion = ⟨b, V.subClassOf, a⟩+ | .scmEqp1, [⟨a, e, b⟩] =>+ e = V.equivalentProperty ∧ k ⟨a, e, b⟩ ∧ st.conclusion = ⟨a, V.subPropertyOf, b⟩+ | .scmEqp2, [⟨a, e, b⟩] =>+ e = V.equivalentProperty ∧ k ⟨a, e, b⟩ ∧ st.conclusion = ⟨b, V.subPropertyOf, a⟩+ | .clsSvf1, [⟨r, op, p⟩, ⟨r', sv, c⟩, ⟨x, p1, y⟩, ⟨y', t, c'⟩] =>+ op = V.onProperty ∧ sv = V.someValuesFrom ∧ r' = r ∧ p1 = p ∧ y' = y ∧+ t = V.type ∧ c' = c ∧+ k ⟨r, op, p⟩ ∧ k ⟨r', sv, c⟩ ∧ k ⟨x, p1, y⟩ ∧ k ⟨y', t, c'⟩ ∧+ st.conclusion = ⟨x, V.type, r⟩+ | .clsHv1, [⟨r, op, p⟩, ⟨r', hv, v⟩, ⟨cls, sc, r''⟩, ⟨x, t, cls'⟩] =>+ op = V.onProperty ∧ hv = V.hasValue ∧ r' = r ∧ sc = V.subClassOf ∧ r'' = r ∧+ t = V.type ∧ cls' = cls ∧+ k ⟨r, op, p⟩ ∧ k ⟨r', hv, v⟩ ∧ k ⟨cls, sc, r''⟩ ∧ k ⟨x, t, cls'⟩ ∧+ st.conclusion = ⟨x, p, v⟩+ | .clsHv2, [⟨r, op, p⟩, ⟨r', hv, v⟩, ⟨x, p1, v'⟩] =>+ op = V.onProperty ∧ hv = V.hasValue ∧ r' = r ∧ p1 = p ∧ v' = v ∧+ k ⟨r, op, p⟩ ∧ k ⟨r', hv, v⟩ ∧ k ⟨x, p1, v'⟩ ∧+ st.conclusion = ⟨x, V.type, r⟩+ | .clsInt1, ⟨c, io, l⟩ :: ps =>+ decide (io = V.intersectionOf) && inG ⟨c, io, l⟩ &&+ (match takeChain inG l ps with+ | some (ms, q) =>+ allTyped st.conclusion.s k ms q &&+ decide (st.conclusion.p = V.type ∧ st.conclusion.o = c)+ | none => false)+ | .clsUni, ⟨c, uo, l⟩ :: ps =>+ decide (uo = V.unionOf) && inG ⟨c, uo, l⟩ &&+ (match takeChain inG l ps with+ | some (ms, [⟨x, t, m⟩]) =>+ decide (t = V.type ∧ m ∈ ms ∧ k ⟨x, t, m⟩ ∧ st.conclusion = ⟨x, V.type, c⟩)+ | _ => false)+ | _, _ => false++/-- Check every step in order, each seeing the conclusions of the ones before. -/+def checkAll (inG : Triple → Bool) : List Step → Std.HashSet Triple → Bool+ | [], _ => true+ | st :: rest, derived =>+ checkStep inG (fun t => derived.contains t) st &&+ checkAll inG rest (derived.insert st.conclusion)++/-- The checker. `G` is the asserted graph, `steps` the certificate. -/+def checkCert (G : List Triple) (steps : List Step) : Bool :=+ let gset := Std.HashSet.ofList G+ checkAll (fun t => gset.contains t) steps ∅++end OOCertdiff --git a/lean/OOCert/Semantics.lean b/lean/OOCert/Semantics.leannew file mode 100644index 00000000..55178e71--- /dev/null+++ b/lean/OOCert/Semantics.lean@@ -0,0 +1,134 @@+import OOCert.Triple++/-!+# Semantics++The meaning against which a certificate is checked. It is the RDF-based+reading of a graph (RDF 1.1 Semantics, section 5; OWL 2 RDF-Based Semantics,+section 5), restricted to the vocabulary the engine's rules use.++## Shape of an interpretation++An interpretation is a domain `D`, a denotation `ι` for every term, and one+ternary relation `iext p x y`, read "(x, y) is in the extension of the+property p". Class membership is not a separate primitive: `x` is in class+`c` when `(x, c)` is in the extension of `rdf:type`. That is the RDF-based+semantics' `ICEXT`, and it is what makes a triple `s rdf:type o` mean the same+thing whether it was asserted or derived by a domain rule.++A triple `s p o` is satisfied when `iext (ι p) (ι s) (ι o)`. Nothing else.+Every piece of schema meaning is a condition on the interpretation+(`Conditions`), quantified over domain elements, the way the W3C tables state+them ("if (p, c) is in IEXT(I(rdfs:domain)) then ...").++## The conditions are the weakest the rules need++Each condition is the *if* direction of the corresponding W3C semantic+condition, or a consequence of it, never more. Where the W3C table states an+*iff* (subClassOf, for instance, is extensional in the RDF-based semantics)+only the half the rules use is assumed, plus transitivity where a rule+concludes a schema triple. Weaker assumptions mean more interpretations, so a+rule proved sound here is sound under the W3C semantics and under the OWL 2+Direct Semantics translated to triples, since every model of those satisfies+these conditions.++The two list constructors are the exception to "conditions on the+interpretation alone". `owl:intersectionOf` and `owl:unionOf` point at an RDF+list, and a list is a syntactic object: the W3C tables read it off the graph+with the sequence notation. `Model` therefore reads the list off the graph+too, through `Chain`, and states the class condition relative to the graph+being interpreted.++## What is not here++Literal values are terms like any other: two spellings of one value are two+terms. No rule compares literals by value, so nothing is lost, but a+consumer must not read `Entails` as datatype-aware. `owl:sameAs` is read as+identity of denotation, which is the standard condition; only its symmetry is+used.+-/+namespace OOCert++structure Interp where+ D : Type+ ι : Term → D+ iext : D → D → D → Prop++namespace Interp+variable (I : Interp)++/-- `x` is in class `c`: `(x, c) ∈ IEXT(rdf:type)`. -/+def cext (c x : I.D) : Prop := I.iext (I.ι V.type) x c+/-- `(a, b) ∈ IEXT(rdfs:subClassOf)`. -/+def sc (a b : I.D) : Prop := I.iext (I.ι V.subClassOf) a b+/-- `(a, b) ∈ IEXT(rdfs:subPropertyOf)`. -/+def sp (a b : I.D) : Prop := I.iext (I.ι V.subPropertyOf) a b+/-- A triple holds when its predicate's extension contains the pair. -/+def sat (t : Triple) : Prop := I.iext (I.ι t.p) (I.ι t.s) (I.ι t.o)++end Interp++/-- The semantic conditions, one group per rule family. -/+structure Conditions (I : Interp) : Prop where+ /-- rdfs9. RDF-based semantics: subClassOf implies extension inclusion. -/+ sc_sub : ∀ a b, I.sc a b → ∀ x, I.cext a x → I.cext b x+ /-- rdfs11. Follows from the extensional reading of subClassOf. -/+ sc_trans : ∀ a b c, I.sc a b → I.sc b c → I.sc a c+ /-- rdfs7. -/+ sp_sub : ∀ a b, I.sp a b → ∀ x y, I.iext a x y → I.iext b x y+ /-- rdfs5. -/+ sp_trans : ∀ a b c, I.sp a b → I.sp b c → I.sp a c+ /-- rdfs2. -/+ dom : ∀ p c, I.iext (I.ι V.domain) p c → ∀ x y, I.iext p x y → I.cext c x+ /-- rdfs3. -/+ rng : ∀ p c, I.iext (I.ι V.range) p c → ∀ x y, I.iext p x y → I.cext c y+ /-- prp-trp. Members of owl:TransitiveProperty have transitive extensions. -/+ trp : ∀ p, I.cext (I.ι V.transitiveProperty) p →+ ∀ x y z, I.iext p x y → I.iext p y z → I.iext p x z+ /-- prp-symp. -/+ symp : ∀ p, I.cext (I.ι V.symmetricProperty) p → ∀ x y, I.iext p x y → I.iext p y x+ /-- prp-inv1, prp-inv2. -/+ inv : ∀ p q, I.iext (I.ι V.inverseOf) p q → ∀ x y, (I.iext p x y ↔ I.iext q y x)+ /-- eq-sym. owl:sameAs is identity of denotation. -/+ same : ∀ a b, I.iext (I.ι V.sameAs) a b → a = b+ /-- scm-eqc1, scm-eqc2. -/+ eqc : ∀ a b, I.iext (I.ι V.equivalentClass) a b → I.sc a b ∧ I.sc b a+ /-- scm-eqp1, scm-eqp2. -/+ eqp : ∀ a b, I.iext (I.ι V.equivalentProperty) a b → I.sp a b ∧ I.sp b a+ /-- cls-svf1. A witness puts `x` into the restriction class. Only this+ direction is assumed; the converse is not needed by any rule. -/+ svf : ∀ r p c, I.iext (I.ι V.onProperty) r p → I.iext (I.ι V.someValuesFrom) r c →+ ∀ x y, I.iext p x y → I.cext c y → I.cext r x+ /-- cls-hv1 needs the forward direction, cls-hv2 the backward one. -/+ hv : ∀ r p v, I.iext (I.ι V.onProperty) r p → I.iext (I.ι V.hasValue) r v →+ ∀ x, (I.cext r x ↔ I.iext p x v)++/-- `Chain G l ms`: the RDF list whose head node is `l` in graph `G` has the+members `ms`, read through `rdf:first` / `rdf:rest` down to `rdf:nil`. A node+with two `rdf:first` values has two chains; the class condition then applies to+both, which can only strengthen the constraint on a model. -/+inductive Chain (G : List Triple) : Term → List Term → Prop+ | nil : Chain G V.nil []+ | cons {l m l' ms} :+ (⟨l, V.first, m⟩ : Triple) ∈ G → (⟨l, V.rest, l'⟩ : Triple) ∈ G →+ Chain G l' ms → Chain G l (m :: ms)++/-- `I` is a model of `G`: the conditions hold, every triple of `G` holds, and+the two list constructors mean intersection and union of their members. -/+structure Model (I : Interp) (G : List Triple) : Prop where+ conds : Conditions I+ facts : ∀ t ∈ G, I.sat t+ /-- cls-int1. -/+ int : ∀ c l ms, (⟨c, V.intersectionOf, l⟩ : Triple) ∈ G → Chain G l ms →+ ∀ x, (∀ m ∈ ms, I.cext (I.ι m) x) → I.cext (I.ι c) x+ /-- cls-uni. -/+ uni : ∀ c l ms, (⟨c, V.unionOf, l⟩ : Triple) ∈ G → Chain G l ms →+ ∀ x m, m ∈ ms → I.cext (I.ι m) x → I.cext (I.ι c) x++/-- `G ⊨ t`: every model of `G` satisfies `t`. -/+def Entails (G : List Triple) (t : Triple) : Prop := ∀ I : Interp, Model I G → I.sat t++theorem Entails.of_mem {G : List Triple} {t : Triple} (h : t ∈ G) : Entails G t :=+ fun _ M => M.facts t h++end OOCertdiff --git a/lean/OOCert/Soundness.lean b/lean/OOCert/Soundness.leannew file mode 100644index 00000000..dc1b4f04--- /dev/null+++ b/lean/OOCert/Soundness.lean@@ -0,0 +1,321 @@+import OOCert.Rules++/-!+# Soundness++`certificate_sound`: if `checkCert G steps` returns `true`, then every+conclusion in `steps` is entailed by `G` under the semantics in+`Semantics.lean`. The proof is one lemma per rule, each a direct appeal to+the matching condition on the interpretation, plus an induction over the+certificate carrying the invariant "everything concluded so far is entailed".++What the theorem does not say, so that nobody reads more into it:++* Nothing about completeness. A certificate the checker rejects may still be+ a valid inference; the checker is a gate, not an oracle.+* Nothing about the parser (`Parse.lean`) or the file format. The theorem is+ about `checkCert` applied to lists of triples and steps. A parse error+ rejects; it cannot accept.+* Nothing about what the engine does with a rejected certificate. That is+ the caller's contract: the engine's run is trusted only when the checker+ says yes.++The `#guard_msgs` at the end pins the axioms the theorem depends on. If a+`sorry` ever enters this file, or a `native_decide`, the build fails there.+-/+namespace OOCert++section+variable {G : List Triple}++theorem allTyped_sound {x : Term} {k : Triple → Bool} :+ ∀ {ms : List Term} {ps : List Triple}, allTyped x k ms ps = true →+ ∀ m ∈ ms, k ⟨x, V.type, m⟩ = true := by+ intro ms+ induction ms with+ | nil =>+ intro ps _ m hm+ simp at hm+ | cons m ms ih =>+ intro ps h m' hm'+ rcases ps with _ | ⟨⟨x', t, m''⟩, ps⟩+ · simp [allTyped] at h+ · simp only [allTyped, decide_eq_true_eq] at h+ obtain ⟨rfl, rfl, rfl, hk, hrest⟩ := h+ rcases List.mem_cons.mp hm' with rfl | hmem+ · exact hk+ · exact ih hrest m' hmem++theorem takeChain_sound {inG : Triple → Bool} (hG : ∀ t, inG t = true → t ∈ G) :+ ∀ (n : Nat) (ps : List Triple), ps.length ≤ n →+ ∀ (l : Term) (ms : List Term) (q : List Triple),+ takeChain inG l ps = some (ms, q) → Chain G l ms := by+ intro n+ induction n with+ | zero =>+ intro ps hlen l ms q h+ unfold takeChain at h+ split at h+ · simp only [Option.some.injEq, Prod.mk.injEq] at h+ obtain ⟨rfl, rfl⟩ := h+ rename_i hl+ subst hl+ exact Chain.nil+ · rcases ps with _ | ⟨_, _⟩+ · simp at h+ · simp at hlen+ | succ n ih =>+ intro ps hlen l ms q h+ unfold takeChain at h+ split at h+ · simp only [Option.some.injEq, Prod.mk.injEq] at h+ obtain ⟨rfl, rfl⟩ := h+ rename_i hl+ subst hl+ exact Chain.nil+ · rcases ps with _ | ⟨⟨l1, f, m⟩, _ | ⟨⟨l2, r, l'⟩, ps'⟩⟩+ · simp at h+ · simp at h+ · simp only at h+ split at h+ · rename_i hc+ obtain ⟨rfl, rfl, rfl, rfl, h1, h2⟩ := hc+ revert h+ cases hrec : takeChain inG l' ps' with+ | none =>+ intro h+ simp at h+ | some pr =>+ intro h+ obtain ⟨ms', q'⟩ := pr+ simp only [Option.some.injEq, Prod.mk.injEq] at h+ obtain ⟨rfl, rfl⟩ := h+ have hlen' : ps'.length ≤ n := by+ simp at hlen+ omega+ exact Chain.cons (hG _ h1) (hG _ h2) (ih ps' hlen' l' ms' q' hrec)+ · simp at h++theorem checkStep_sound {inG derived : Triple → Bool} {st : Step}+ (hG : ∀ t, inG t = true → t ∈ G)+ (hD : ∀ t, derived t = true → Entails G t)+ (h : checkStep inG derived st = true) : Entails G st.conclusion := by+ have hk : ∀ t, (inG t || derived t) = true → Entails G t := by+ intro t ht+ simp only [Bool.or_eq_true] at ht+ rcases ht with h1 | h1+ · exact Entails.of_mem (hG t h1)+ · exact hD t h1+ obtain ⟨rule, premises, conclusion⟩ := st+ unfold checkStep at h+ dsimp only at h+ cases rule+ case rdfs2 =>+ rcases premises with _ | ⟨⟨s, p, o⟩, _ | ⟨⟨p', d, c⟩, _ | _⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, h1, h2, rfl⟩ := h+ intro I M+ exact M.conds.dom _ _ (hk _ h2 I M) _ _ (hk _ h1 I M)+ case rdfs3 =>+ rcases premises with _ | ⟨⟨s, p, o⟩, _ | ⟨⟨p', r, c⟩, _ | _⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, h1, h2, rfl⟩ := h+ intro I M+ exact M.conds.rng _ _ (hk _ h2 I M) _ _ (hk _ h1 I M)+ case rdfs5 =>+ rcases premises with _ | ⟨⟨a, sp1, b⟩, _ | ⟨⟨b', sp2, c⟩, _ | _⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, rfl, h1, h2, rfl⟩ := h+ intro I M+ exact M.conds.sp_trans _ _ _ (hk _ h1 I M) (hk _ h2 I M)+ case rdfs7 =>+ rcases premises with _ | ⟨⟨s, p, o⟩, _ | ⟨⟨p', sp, q⟩, _ | _⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, h1, h2, rfl⟩ := h+ intro I M+ exact M.conds.sp_sub _ _ (hk _ h2 I M) _ _ (hk _ h1 I M)+ case rdfs9 =>+ rcases premises with _ | ⟨⟨x, t, a⟩, _ | ⟨⟨a', sc, b⟩, _ | _⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, rfl, h1, h2, rfl⟩ := h+ intro I M+ exact M.conds.sc_sub _ _ (hk _ h2 I M) _ (hk _ h1 I M)+ case rdfs11 =>+ rcases premises with _ | ⟨⟨a, sc1, b⟩, _ | ⟨⟨b', sc2, c⟩, _ | _⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, rfl, h1, h2, rfl⟩ := h+ intro I M+ exact M.conds.sc_trans _ _ _ (hk _ h1 I M) (hk _ h2 I M)+ case prpTrp =>+ rcases premises with _ | ⟨⟨p, t, tp⟩, _ | ⟨⟨x, p1, y⟩, _ | ⟨⟨y', p2, z⟩, _ | _⟩⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, rfl, rfl, rfl, h1, h2, h3, rfl⟩ := h+ intro I M+ exact M.conds.trp _ (hk _ h1 I M) _ _ _ (hk _ h2 I M) (hk _ h3 I M)+ case prpSymp =>+ rcases premises with _ | ⟨⟨p, t, sy⟩, _ | ⟨⟨x, p1, y⟩, _ | _⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, rfl, h1, h2, rfl⟩ := h+ intro I M+ exact M.conds.symp _ (hk _ h1 I M) _ _ (hk _ h2 I M)+ case prpInv1 =>+ rcases premises with _ | ⟨⟨p, io, q⟩, _ | ⟨⟨x, p1, y⟩, _ | _⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, h1, h2, rfl⟩ := h+ intro I M+ exact (M.conds.inv _ _ (hk _ h1 I M) _ _).mp (hk _ h2 I M)+ case prpInv2 =>+ rcases premises with _ | ⟨⟨p, io, q⟩, _ | ⟨⟨x, q1, y⟩, _ | _⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, h1, h2, rfl⟩ := h+ intro I M+ exact (M.conds.inv _ _ (hk _ h1 I M) _ _).mpr (hk _ h2 I M)+ case eqSym =>+ rcases premises with _ | ⟨⟨a, sa, b⟩, _ | _⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, h1, rfl⟩ := h+ intro I M+ have s : I.iext (I.ι V.sameAs) (I.ι a) (I.ι b) := hk _ h1 I M+ have e := M.conds.same _ _ s+ show I.iext (I.ι V.sameAs) (I.ι b) (I.ι a)+ rw [← e]+ rw [← e] at s+ exact s+ case scmEqc1 =>+ rcases premises with _ | ⟨⟨a, e, b⟩, _ | _⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, h1, rfl⟩ := h+ intro I M+ exact (M.conds.eqc _ _ (hk _ h1 I M)).1+ case scmEqc2 =>+ rcases premises with _ | ⟨⟨a, e, b⟩, _ | _⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, h1, rfl⟩ := h+ intro I M+ exact (M.conds.eqc _ _ (hk _ h1 I M)).2+ case scmEqp1 =>+ rcases premises with _ | ⟨⟨a, e, b⟩, _ | _⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, h1, rfl⟩ := h+ intro I M+ exact (M.conds.eqp _ _ (hk _ h1 I M)).1+ case scmEqp2 =>+ rcases premises with _ | ⟨⟨a, e, b⟩, _ | _⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, h1, rfl⟩ := h+ intro I M+ exact (M.conds.eqp _ _ (hk _ h1 I M)).2+ case clsSvf1 =>+ rcases premises with+ _ | ⟨⟨r, op, p⟩, _ | ⟨⟨r', sv, c⟩, _ | ⟨⟨x, p1, y⟩, _ | ⟨⟨y', t, c'⟩, _ | _⟩⟩⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, h1, h2, h3, h4, rfl⟩ := h+ intro I M+ exact M.conds.svf _ _ _ (hk _ h1 I M) (hk _ h2 I M) _ _ (hk _ h3 I M) (hk _ h4 I M)+ case clsHv1 =>+ rcases premises with+ _ | ⟨⟨r, op, p⟩, _ | ⟨⟨r', hv, v⟩, _ | ⟨⟨cls, sc, r''⟩, _ | ⟨⟨x, t, cls'⟩, _ | _⟩⟩⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, h1, h2, h3, h4, rfl⟩ := h+ intro I M+ exact (M.conds.hv _ _ _ (hk _ h1 I M) (hk _ h2 I M) _).mp+ (M.conds.sc_sub _ _ (hk _ h3 I M) _ (hk _ h4 I M))+ case clsHv2 =>+ rcases premises with+ _ | ⟨⟨r, op, p⟩, _ | ⟨⟨r', hv, v⟩, _ | ⟨⟨x, p1, v'⟩, _ | _⟩⟩⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at h+ obtain ⟨rfl, rfl, rfl, rfl, rfl, h1, h2, h3, rfl⟩ := h+ intro I M+ exact (M.conds.hv _ _ _ (hk _ h1 I M) (hk _ h2 I M) _).mpr (hk _ h3 I M)+ case clsInt1 =>+ rcases premises with _ | ⟨⟨c, io, l⟩, ps⟩+ · simp at h+ · simp only [Bool.and_eq_true, decide_eq_true_eq] at h+ obtain ⟨⟨rfl, hin⟩, hm⟩ := h+ revert hm+ cases hchain : takeChain inG l ps with+ | none =>+ intro hm+ simp at hm+ | some pr =>+ intro hm+ obtain ⟨ms, q⟩ := pr+ simp only [Bool.and_eq_true, decide_eq_true_eq] at hm+ obtain ⟨hall, hp, ho⟩ := hm+ have hC : Chain G l ms :=+ takeChain_sound hG ps.length ps (Nat.le_refl _) l ms q hchain+ intro I M+ have hx : ∀ m ∈ ms, I.cext (I.ι m) (I.ι conclusion.s) :=+ fun m hm => hk _ (allTyped_sound hall m hm) I M+ have hc := M.int c l ms (hG _ hin) hC (I.ι conclusion.s) hx+ show I.iext (I.ι conclusion.p) (I.ι conclusion.s) (I.ι conclusion.o)+ rw [hp, ho]+ exact hc+ case clsUni =>+ rcases premises with _ | ⟨⟨c, uo, l⟩, ps⟩+ · simp at h+ · simp only [Bool.and_eq_true, decide_eq_true_eq] at h+ obtain ⟨⟨rfl, hin⟩, hm⟩ := h+ revert hm+ cases hchain : takeChain inG l ps with+ | none =>+ intro hm+ simp at hm+ | some pr =>+ intro hm+ obtain ⟨ms, q⟩ := pr+ rcases q with _ | ⟨⟨x, t, m⟩, _ | _⟩ <;>+ simp only [decide_eq_true_eq, Bool.false_eq_true] at hm+ obtain ⟨rfl, hmem, hkx, rfl⟩ := hm+ have hC : Chain G l ms :=+ takeChain_sound hG ps.length ps (Nat.le_refl _) l ms _ hchain+ intro I M+ exact M.uni c l ms (hG _ hin) hC (I.ι x) m hmem (hk _ hkx I M)++theorem checkAll_sound {inG : Triple → Bool} (hG : ∀ t, inG t = true → t ∈ G) :+ ∀ (steps : List Step) (derived : Std.HashSet Triple),+ (∀ t, derived.contains t = true → Entails G t) →+ checkAll inG steps derived = true →+ ∀ st ∈ steps, Entails G st.conclusion := by+ intro steps+ induction steps with+ | nil =>+ intro _ _ _ st hst+ simp at hst+ | cons st rest ih =>+ intro derived hD h st' hst'+ simp only [checkAll, Bool.and_eq_true] at h+ obtain ⟨h1, h2⟩ := h+ have hst : Entails G st.conclusion := checkStep_sound hG hD h1+ have hD' : ∀ t, (derived.insert st.conclusion).contains t = true → Entails G t := by+ intro t ht+ rw [Std.HashSet.contains_insert] at ht+ simp only [Bool.or_eq_true, beq_iff_eq] at ht+ rcases ht with rfl | ht+ · exact hst+ · exact hD t ht+ rcases List.mem_cons.mp hst' with rfl | hmem+ · exact hst+ · exact ih _ hD' h2 st' hmem++end++/-- The theorem the checker is trusted for. -/+theorem certificate_sound (G : List Triple) (steps : List Step)+ (h : checkCert G steps = true) : ∀ st ∈ steps, Entails G st.conclusion := by+ unfold checkCert at h+ refine checkAll_sound (G := G) (inG := fun t => (Std.HashSet.ofList G).contains t)+ ?_ steps ∅ ?_ h+ · intro t ht+ rw [Std.HashSet.contains_ofList] at ht+ simpa using ht+ · intro t ht+ simp at ht++/-! The axiom tripwire. `sorryAx`, `native_decide`'s `Lean.ofReduceBool` or any+other addition to this list fails the build. -/+/-- info: 'OOCert.certificate_sound' depends on axioms: [propext, Classical.choice, Quot.sound] -/+#guard_msgs in+#print axioms certificate_sound++end OOCertdiff --git a/lean/OOCert/Triple.lean b/lean/OOCert/Triple.leannew file mode 100644index 00000000..4f1ba376--- /dev/null+++ b/lean/OOCert/Triple.lean@@ -0,0 +1,48 @@+/-!+# Terms and triples++A term is kept in its N-Triples spelling: `<iri>`, `_:label`, or a literal+with its quotes, datatype or language tag. The checker never looks inside a+term. Two terms are the same term when their spellings are the same string,+which is exactly how the engine's interner treats them, and the certificate+is written by that interner.++Blank nodes are therefore constants with a scope of one certificate. That is+the skolemised reading of a graph, the one every OWL 2 RL materialiser uses;+the certificate and the asserted graph it refers to come from the same run,+so a label names the same node in both files.+-/+namespace OOCert++abbrev Term := String++structure Triple where+ s : Term+ p : Term+ o : Term+deriving DecidableEq, Hashable, Repr++/-! The vocabulary the rules mention, in N-Triples spelling. -/+namespace V+def type : Term := "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>"+def first : Term := "<http://www.w3.org/1999/02/22-rdf-syntax-ns#first>"+def rest : Term := "<http://www.w3.org/1999/02/22-rdf-syntax-ns#rest>"+def nil : Term := "<http://www.w3.org/1999/02/22-rdf-syntax-ns#nil>"+def subClassOf : Term := "<http://www.w3.org/2000/01/rdf-schema#subClassOf>"+def subPropertyOf : Term := "<http://www.w3.org/2000/01/rdf-schema#subPropertyOf>"+def domain : Term := "<http://www.w3.org/2000/01/rdf-schema#domain>"+def range : Term := "<http://www.w3.org/2000/01/rdf-schema#range>"+def transitiveProperty : Term := "<http://www.w3.org/2002/07/owl#TransitiveProperty>"+def symmetricProperty : Term := "<http://www.w3.org/2002/07/owl#SymmetricProperty>"+def inverseOf : Term := "<http://www.w3.org/2002/07/owl#inverseOf>"+def sameAs : Term := "<http://www.w3.org/2002/07/owl#sameAs>"+def equivalentClass : Term := "<http://www.w3.org/2002/07/owl#equivalentClass>"+def equivalentProperty : Term := "<http://www.w3.org/2002/07/owl#equivalentProperty>"+def onProperty : Term := "<http://www.w3.org/2002/07/owl#onProperty>"+def someValuesFrom : Term := "<http://www.w3.org/2002/07/owl#someValuesFrom>"+def hasValue : Term := "<http://www.w3.org/2002/07/owl#hasValue>"+def intersectionOf : Term := "<http://www.w3.org/2002/07/owl#intersectionOf>"+def unionOf : Term := "<http://www.w3.org/2002/07/owl#unionOf>"+end V++end OOCertdiff --git a/lean/lake-manifest.json b/lean/lake-manifest.jsonnew file mode 100644index 00000000..5726e236--- /dev/null+++ b/lean/lake-manifest.json@@ -0,0 +1,6 @@+{"version": "1.2.0",+ "packagesDir": ".lake/packages",+ "packages": [],+ "name": "oocert",+ "lakeDir": ".lake",+ "fixedToolchain": false}diff --git a/lean/lakefile.toml b/lean/lakefile.tomlnew file mode 100644index 00000000..33518c4a--- /dev/null+++ b/lean/lakefile.toml@@ -0,0 +1,14 @@+name = "oocert"+version = "0.1.0"+defaultTargets = ["OOCert", "oo-cert"]++# Core Lean only. No Mathlib, no external packages: the checker's trust surface+# is the Lean kernel plus what is written in this directory, and it should stay+# small enough to read in an afternoon.++[[lean_lib]]+name = "OOCert"++[[lean_exe]]+name = "oo-cert"+root = "Main"diff --git a/lean/lean-toolchain b/lean/lean-toolchainnew file mode 100644index 00000000..a8afa7d1--- /dev/null+++ b/lean/lean-toolchain@@ -0,0 +1 @@+leanprover/lean4:v4.33.1diff --git a/src/batch.rs b/src/batch.rsindex 18949c4a..ab121362 100644--- a/src/batch.rs+++ b/src/batch.rs@@ -237,11 +237,13 @@ impl BatchRunner {}fn exec_reason(&self, args: &[String]) -> Value {- use crate::reason::Reasoner;+ use crate::reason::{InferenceTarget, Reasoner};let profile = Self::flag_value(args, "--profile").or_else(|| args.first().cloned()).unwrap_or("rdfs".to_string());- let result = Reasoner::run(&self.graph, &profile, true)+ let certificate = Self::flag_value(args, "--certificate");+ let dir = certificate.as_deref().map(std::path::Path::new);+ let result = Reasoner::run_full(&self.graph, &profile, true, InferenceTarget::DefaultGraph, dir).unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));serde_json::from_str(&result).unwrap_or(json!({"raw": result}))}diff --git a/src/inputs.rs b/src/inputs.rsindex 575a05fb..634eda74 100644--- a/src/inputs.rs+++ b/src/inputs.rs@@ -262,6 +262,12 @@ pub struct OntoReasonInput {/// `onto_save` to a triple format cannot publish one. Default false, which/// keeps the historical behaviour. Not available for the `owl-dl` profile.pub inference_graph: Option<bool>,+ /// Directory to write a derivation certificate to (`asserted.tsv` and+ /// `derivations.tsv`). The Lean checker in `lean/` verifies it against a+ /// machine-checked soundness theorem, so a run whose certificate checks+ /// contains only entailed triples whatever this engine did. Not available+ /// for `owl-dl`.+ pub certificate_dir: Option<String>,}#[derive(Deserialize, JsonSchema)]diff --git a/src/main.rs b/src/main.rsindex ffa52239..ed505dca 100644--- a/src/main.rs+++ b/src/main.rs@@ -428,6 +428,11 @@ enum Commands {Reason {#[arg(long, default_value = "rdfs")]profile: String,+ /// Write a derivation certificate (asserted.tsv + derivations.tsv)+ /// to this directory. `lean/` holds a checker for it whose soundness+ /// is a machine-checked theorem; see docs/lean-certificates.md.+ #[arg(long)]+ certificate: Option<String>,},/// Full pipeline: ingest → SHACL → reasonExtend {@@ -619,8 +624,13 @@ impl Commands {Commands::Query { query } => cmd("query", vec![query.clone()]),Commands::Lint { input } => cmd("lint", vec![absolutize(input)]),Commands::Defects { input } => cmd("defects", vec![absolutize(input)]),- Commands::Reason { profile } => {- cmd("reason", vec!["--profile".into(), profile.clone()])+ Commands::Reason { profile, certificate } => {+ let mut a = vec!["--profile".into(), profile.clone()];+ if let Some(c) = certificate {+ a.push("--certificate".into());+ a.push(absolutize(c));+ }+ cmd("reason", a)}Commands::Shacl { shapes } => cmd("shacl", vec![absolutize(shapes)]),Commands::Status => cmd("status", vec![]),@@ -2302,10 +2312,11 @@ async fn async_main() -> anyhow::Result<()> {.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));output_result_checked(&result, cli.pretty);}- Commands::Reason { profile } => {- use open_ontologies::reason::Reasoner;+ Commands::Reason { profile, certificate } => {+ use open_ontologies::reason::{InferenceTarget, Reasoner};let (_db, graph) = setup(&cli.data_dir)?;- let result = Reasoner::run(&graph, &profile, true)+ let dir = certificate.as_deref().map(std::path::Path::new);+ let result = Reasoner::run_full(&graph, &profile, true, InferenceTarget::DefaultGraph, dir).unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));output_result_checked(&result, cli.pretty);}@@ -2822,7 +2833,7 @@ mod proxy_serialization_tests {Commands::Stats,Commands::Query { query: "SELECT ?s WHERE { ?s ?p ?o }".into() },Commands::Lint { input: "x.ttl".into() },- Commands::Reason { profile: "rdfs".into() },+ Commands::Reason { profile: "rdfs".into(), certificate: None },Commands::Shacl { shapes: "s.ttl".into() },Commands::Status,Commands::Pull { url: "http://example.org".into(), sparql: false, query: None },diff --git a/src/reason.rs b/src/reason.rsindex 2e74be40..30dfdf25 100644--- a/src/reason.rs+++ b/src/reason.rs@@ -25,6 +25,17 @@ const RDF_FIRST: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#first>";const RDF_REST: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#rest>";const RDF_NIL: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#nil>";+/// A triple over interned ids.+type Fact = (u32, u32, u32);++/// One line of a certificate: the rule, what it concluded, and the premises+/// it read, in the order `lean/OOCert/Rules.lean` documents for that rule.+struct Derivation {+ rule: &'static str,+ conclusion: Fact,+ premises: Vec<Fact>,+}+/// Intern strings to u32 IDs for efficient reasoning.struct Interner {to_id: HashMap<String, u32>,@@ -99,9 +110,44 @@ impl Reasoner {profile: &str,materialize: bool,target: InferenceTarget,+ ) -> anyhow::Result<String> {+ Self::run_full(graph, profile, materialize, target, None)+ }++ /// Run the forward-chaining reasoner and, when `certificate_dir` is given,+ /// write a derivation certificate beside the result.+ ///+ /// The certificate is two tab-separated files: `asserted.tsv`, every+ /// triple the run started from, and `derivations.tsv`, one line per+ /// inferred triple naming the rule that produced it and the premises the+ /// rule read. `lean/` holds a checker for that format whose soundness is a+ /// machine-checked theorem (`OOCert.certificate_sound`): a certificate it+ /// accepts contains only triples entailed by the asserted graph under the+ /// RDF-based semantics of the vocabulary the rules use. The engine's own+ /// correctness is therefore not the thing a consumer has to trust; the+ /// checker's is, and the checker is a few hundred lines with a proof.+ ///+ /// The first thing the checker caught was in this file: `cls-svf1` used+ /// to derive membership in a subclass from membership in its restriction+ /// superclass, the converse of the axiom+ /// (tests/reason_rl_ext_soundness_test.rs).+ ///+ /// Not available for `owl-dl`: the tableaux path has no rule trace.+ pub fn run_full(+ graph: &Arc<GraphStore>,+ profile: &str,+ materialize: bool,+ target: InferenceTarget,+ certificate_dir: Option<&std::path::Path>,) -> anyhow::Result<String> {// Delegate OWL-DL to tableaux reasonerif profile == "owl-dl" {+ if certificate_dir.is_some() {+ anyhow::bail!(+ "the owl-dl tableaux path emits no derivation certificate; \+ run rdfs, owl-rl or owl-rl-ext for a certified run"+ );+ }if target == InferenceTarget::Inferred {// Say so rather than materialise into the default graph while// the caller believes the inferences were kept apart.@@ -191,16 +237,25 @@ impl Reasoner {.filter_map(|(&r, &filler)| restr_prop.get(&r).map(|&prop| (prop, filler, r))).collect();- // Parse RDF lists for intersectionOf/unionOf- let mut intersection_classes: Vec<(u32, Vec<u32>)> = Vec::new();- let mut union_classes: Vec<(u32, Vec<u32>)> = Vec::new();+ // Parse RDF lists for intersectionOf/unionOf.+ //+ // A list is read only when it is well formed: every node carries the+ // rdf:first and rdf:rest the certificate checker will look for, and+ // the chain reaches rdf:nil. It used to be read leniently (a node+ // without rdf:first was skipped, the walk stopped at 100 nodes) and+ // the class rules fired on whatever came back. The checker has no+ // rule for a list it cannot walk, so the reasoner no longer derives+ // from one either; deriving less from malformed input is the sound+ // direction. Each entry keeps the head node and the chain triples so+ // that a certificate can cite them.+ let rdf_first = interner.intern(RDF_FIRST);+ let rdf_rest = interner.intern(RDF_REST);+ let rdf_nil = interner.intern(RDF_NIL);+ let owl_intersection = interner.intern(OWL_INTERSECTION);+ let owl_union = interner.intern(OWL_UNION);+ let mut intersection_classes: Vec<(u32, u32, Vec<Fact>, Vec<u32>)> = Vec::new();+ let mut union_classes: Vec<(u32, u32, Vec<Fact>, Vec<u32>)> = Vec::new();if include_ext {- let rdf_first = interner.intern(RDF_FIRST);- let rdf_rest = interner.intern(RDF_REST);- let rdf_nil = interner.intern(RDF_NIL);- let owl_intersection = interner.intern(OWL_INTERSECTION);- let owl_union = interner.intern(OWL_UNION);-let first_map: HashMap<u32, u32> = facts.iter().filter(|&&(_, p, _)| p == rdf_first).map(|&(s, _, o)| (s, o)).collect();@@ -208,38 +263,69 @@ impl Reasoner {.filter(|&&(_, p, _)| p == rdf_rest).map(|&(s, _, o)| (s, o)).collect();- let walk_list = |head: u32| -> Vec<u32> {+ let walk_list = |head: u32| -> Option<(Vec<Fact>, Vec<u32>)> {+ let mut chain = Vec::new();let mut items = Vec::new();let mut cur = head;- for _ in 0..100 {- if cur == rdf_nil { break; }- if let Some(&item) = first_map.get(&cur) { items.push(item); }- cur = *rest_map.get(&cur).unwrap_or(&rdf_nil);+ // Bounded so that a cyclic rdf:rest cannot spin.+ for _ in 0..100_000 {+ if cur == rdf_nil {+ return Some((chain, items));+ }+ let item = *first_map.get(&cur)?;+ let next = *rest_map.get(&cur)?;+ chain.push((cur, rdf_first, item));+ chain.push((cur, rdf_rest, next));+ items.push(item);+ cur = next;}- items+ None};for &(s, p, o) in &facts {- if p == owl_intersection {- let items = walk_list(o);- if !items.is_empty() { intersection_classes.push((s, items)); }+ if p == owl_intersection+ && let Some((chain, items)) = walk_list(o)+ && !items.is_empty()+ {+ intersection_classes.push((s, o, chain, items));}- if p == owl_union {- let items = walk_list(o);- if !items.is_empty() { union_classes.push((s, items)); }+ if p == owl_union+ && let Some((chain, items)) = walk_list(o)+ && !items.is_empty()+ {+ union_classes.push((s, o, chain, items));}}}+ // Ids the certificate cites as premises. Interning a term twice+ // returns the same id, so these agree with the filters above.+ let rdfs_domain = interner.intern(RDFS_DOMAIN);+ let rdfs_range = interner.intern(RDFS_RANGE);+ let owl_transitive = interner.intern(OWL_TRANSITIVE);+ let owl_symmetric = interner.intern(OWL_SYMMETRIC);+ let owl_inverse = interner.intern(OWL_INVERSE);+ let owl_equiv_class = interner.intern(OWL_EQUIV_CLASS);+ let owl_equiv_prop = interner.intern(OWL_EQUIV_PROP);+// ── Fixpoint iteration ──────────────────────────────────────- let mut triple_set: HashSet<(u32, u32, u32)> = facts.iter().copied().collect();+ let mut triple_set: HashSet<Fact> = facts.iter().copied().collect();let initial_size = triple_set.len();let mut iterations = 0;+ // Certificate bookkeeping. A conclusion is recorded the first time it+ // is derived and never again, so the certificate has exactly one line+ // per inferred triple and `derivations.len() == inferred_count` is an+ // invariant the tests pin. Nothing here runs unless a certificate was+ // asked for: the hot path pays one branch per candidate triple.+ let certify = certificate_dir.is_some();+ let mut derivations: Vec<Derivation> = Vec::new();+ let mut recorded: HashSet<Fact> = HashSet::new();+loop {iterations += 1;let before = triple_set.len();- let mut new: Vec<(u32, u32, u32)> = Vec::new();+ let mut new: Vec<Fact> = Vec::new();// Build per-iteration indiceslet type_idx: Vec<(u32, u32)> = triple_set.iter()@@ -258,6 +344,17 @@ impl Reasoner {sub_to_super.entry(sub).or_default().push(sup);}+ // Every rule goes through this. It pushes the candidate and, when a+ // certificate was asked for, records the first derivation of each+ // triple not already in the closure, with the premises in the+ // order the checker expects for that rule.+ let mut emit = |t: Fact, rule: &'static str, premises: &[Fact]| {+ if certify && !triple_set.contains(&t) && recorded.insert(t) {+ derivations.push(Derivation { rule, conclusion: t, premises: premises.to_vec() });+ }+ new.push(t);+ };+// ── RDFS rules ──────────────────────────────────────────// rdfs9: x type sub, sub subClassOf super → x type super@@ -265,7 +362,8 @@ impl Reasoner {if let Some(supers) = sub_to_super.get(&sub) {for &sup in supers {if sub != sup {- new.push((x, rdf_type, sup));+ emit((x, rdf_type, sup), "rdfs9",+ &[(x, rdf_type, sub), (sub, rdfs_subclass, sup)]);}}}@@ -276,7 +374,8 @@ impl Reasoner {if let Some(cs) = sub_to_super.get(&b) {for &c in cs {if a != b && b != c && a != c {- new.push((a, rdfs_subclass, c));+ emit((a, rdfs_subclass, c), "rdfs11",+ &[(a, rdfs_subclass, b), (b, rdfs_subclass, c)]);}}}@@ -284,16 +383,18 @@ impl Reasoner {// rdfs2: s p o, p domain class → s type classfor &(prop, cls) in &domain_map {- for &(s, p, _) in &triple_set.iter().collect::<Vec<_>>() {- if *p == prop { new.push((*s, rdf_type, cls)); }+ for &(s, p, o) in triple_set.iter() {+ if p == prop {+ emit((s, rdf_type, cls), "rdfs2", &[(s, p, o), (prop, rdfs_domain, cls)]);+ }}}// rdfs3: s p o, p range class → o type class (IRI only)for &(prop, cls) in &range_map {- for &(_, p, o) in &triple_set.iter().collect::<Vec<_>>() {- if *p == prop && interner.resolve(*o).starts_with('<') {- new.push((*o, rdf_type, cls));+ for &(s, p, o) in triple_set.iter() {+ if p == prop && interner.resolve(o).starts_with('<') {+ emit((o, rdf_type, cls), "rdfs3", &[(s, p, o), (prop, rdfs_range, cls)]);}}}@@ -307,7 +408,8 @@ impl Reasoner {if let Some(cs) = subp_to_super.get(&b) {for &c in cs {if a != b && b != c && a != c {- new.push((a, rdfs_subprop, c));+ emit((a, rdfs_subprop, c), "rdfs5",+ &[(a, rdfs_subprop, b), (b, rdfs_subprop, c)]);}}}@@ -316,15 +418,17 @@ impl Reasoner {// rdfs7: s sub o, sub subPropertyOf super → s super ofor &(sub, sup) in &subprop_idx {if sub != sup {- for &(s, p, o) in &triple_set.iter().collect::<Vec<_>>() {- if *p == sub { new.push((*s, sup, *o)); }+ for &(s, p, o) in triple_set.iter() {+ if p == sub {+ emit((s, sup, o), "rdfs7", &[(s, sub, o), (sub, rdfs_subprop, sup)]);+ }}}}// ── OWL-RL rules ────────────────────────────────────────if include_owl {- // Transitive: x P y, y P z → x P z+ // prp-trp: x P y, y P z → x P zfor &tp in &transitive_set {let pairs: Vec<(u32, u32)> = triple_set.iter().filter(|&&(_, p, _)| p == tp)@@ -336,50 +440,53 @@ impl Reasoner {for &(x, y) in &pairs {if let Some(zs) = by_subj.get(&y) {for &z in zs {- if x != z { new.push((x, tp, z)); }+ if x != z {+ emit((x, tp, z), "prp-trp",+ &[(tp, rdf_type, owl_transitive), (x, tp, y), (y, tp, z)]);+ }}}}}- // Symmetric: s P o → o P s+ // prp-symp: s P o → o P sfor &sp in &symmetric_set {- let to_add: Vec<_> = triple_set.iter()- .filter(|&&(_, p, _)| p == sp)- .map(|&(s, _, o)| (o, sp, s)).collect();- new.extend(to_add);+ for &(s, p, o) in triple_set.iter() {+ if p == sp {+ emit((o, sp, s), "prp-symp", &[(sp, rdf_type, owl_symmetric), (s, sp, o)]);+ }+ }}- // Inverse: s P o, P inverseOf Q → o Q s (both directions)+ // prp-inv1, prp-inv2: s P o, P inverseOf Q → o Q s (both directions)for &(p, q) in &inverse_pairs {- let fwd: Vec<_> = triple_set.iter()- .filter(|&&(_, pred, _)| pred == p)- .map(|&(s, _, o)| (o, q, s)).collect();- let rev: Vec<_> = triple_set.iter()- .filter(|&&(_, pred, _)| pred == q)- .map(|&(s, _, o)| (o, p, s)).collect();- new.extend(fwd);- new.extend(rev);+ for &(s, pred, o) in triple_set.iter() {+ if pred == p {+ emit((o, q, s), "prp-inv1", &[(p, owl_inverse, q), (s, p, o)]);+ }+ if pred == q {+ emit((o, p, s), "prp-inv2", &[(p, owl_inverse, q), (s, q, o)]);+ }+ }}- // sameAs: symmetry + transitivity- let sameas: Vec<(u32, u32)> = triple_set.iter()- .filter(|&&(_, p, _)| p == owl_sameas)- .map(|&(s, _, o)| (s, o)).collect();- for &(a, b) in &sameas {- new.push((b, owl_sameas, a));+ // eq-sym: sameAs symmetry+ for &(s, p, o) in triple_set.iter() {+ if p == owl_sameas {+ emit((o, owl_sameas, s), "eq-sym", &[(s, owl_sameas, o)]);+ }}- // equivalentClass → bidirectional subClassOf+ // scm-eqc1, scm-eqc2: equivalentClass → bidirectional subClassOffor &(a, b) in &equiv_class {- new.push((a, rdfs_subclass, b));- new.push((b, rdfs_subclass, a));+ emit((a, rdfs_subclass, b), "scm-eqc1", &[(a, owl_equiv_class, b)]);+ emit((b, rdfs_subclass, a), "scm-eqc2", &[(a, owl_equiv_class, b)]);}- // equivalentProperty → bidirectional subPropertyOf+ // scm-eqp1, scm-eqp2: equivalentProperty → bidirectional subPropertyOffor &(a, b) in &equiv_prop {- new.push((a, rdfs_subprop, b));- new.push((b, rdfs_subprop, a));+ emit((a, rdfs_subprop, b), "scm-eqp1", &[(a, owl_equiv_prop, b)]);+ emit((b, rdfs_subprop, a), "scm-eqp2", &[(a, owl_equiv_prop, b)]);}}@@ -391,8 +498,21 @@ impl Reasoner {inst_types.entry(x).or_default().insert(cls);}- // cls-svf1: x P y, y type filler, restriction(P, svf=filler),- // class subClassOf restriction → x type class+ // cls-svf1: x P y, y type filler, restriction(P, svf=filler)+ // → x type restriction+ //+ // Two derivations this rule used to make are gone, both found+ // when every rule had to correspond to one the Lean checker+ // can prove sound (tests/reason_rl_ext_soundness_test.rs):+ // * `x type C` for every `C rdfs:subClassOf restriction`.+ // That is the converse of the axiom. Membership in a+ // superclass never gives membership in a subclass; the+ // equivalentClass case that made it look right is carried+ // by rdfs9 over the subClassOf triple scm-eqc emits.+ // * `x type restriction` from `x P filler`, where the+ // object is the filler class IRI itself. A class in+ // object position is a resource, not an instance of+ // itself.for &(prop, filler, restr) in &svf_rules {let prop_pairs: Vec<(u32, u32)> = triple_set.iter().filter(|&&(_, p, _)| p == prop)@@ -402,23 +522,20 @@ impl Reasoner {.filter(|&&(_, cls)| cls == filler).map(|&(inst, _)| inst).collect();- // Classes whose superclass is this restriction- let parent_classes: Vec<u32> = subclass_idx.iter()- .filter(|&&(_, sup)| sup == restr)- .map(|&(sub, _)| sub).collect();-for &(x, y) in &prop_pairs {- if filler_insts.contains(&y) || y == filler {- new.push((x, rdf_type, restr));- for &cls in &parent_classes {- new.push((x, rdf_type, cls));- }+ if filler_insts.contains(&y) {+ emit((x, rdf_type, restr), "cls-svf1", &[+ (restr, owl_on_property, prop),+ (restr, owl_some_values, filler),+ (x, prop, y),+ (y, rdf_type, filler),+ ]);}}}- // cls-hv: x type class, class subClassOf restriction(P, hasValue v) → x P v- // and: x P v, restriction(P, hasValue v) → x type restriction+ // cls-hv1: x type class, class subClassOf restriction(P, hasValue v) → x P v+ // cls-hv2: x P v, restriction(P, hasValue v) → x type restrictionfor &(prop, val, restr) in &hv_rules {let parent_classes: Vec<u32> = subclass_idx.iter().filter(|&&(_, sup)| sup == restr)@@ -427,32 +544,56 @@ impl Reasoner {for &cls in &parent_classes {for &(x, c) in &type_idx {if c == cls {- new.push((x, prop, val));+ emit((x, prop, val), "cls-hv1", &[+ (restr, owl_on_property, prop),+ (restr, owl_has_value, val),+ (cls, rdfs_subclass, restr),+ (x, rdf_type, cls),+ ]);}}}- for &(s, p, o) in &triple_set.iter().collect::<Vec<_>>() {- if *p == prop && *o == val {- new.push((*s, rdf_type, restr));+ for &(s, p, o) in triple_set.iter() {+ if p == prop && o == val {+ emit((s, rdf_type, restr), "cls-hv2", &[+ (restr, owl_on_property, prop),+ (restr, owl_has_value, val),+ (s, prop, val),+ ]);}}}- // cls-int: x type ALL members → x type intersection class- for (cls, members) in &intersection_classes {- for &(x, _) in &type_idx {- if let Some(x_types) = inst_types.get(&x)- && members.iter().all(|m| x_types.contains(m)) {- new.push((x, rdf_type, *cls));- }+ // cls-int1: x type ALL members → x type intersection class+ for (cls, head, chain, members) in &intersection_classes {+ for (&x, x_types) in &inst_types {+ if members.iter().all(|m| x_types.contains(m)) {+ let premises: Vec<Fact> = if certify {+ let mut v = vec![(*cls, owl_intersection, *head)];+ v.extend(chain.iter().copied());+ v.extend(members.iter().map(|&m| (x, rdf_type, m)));+ v+ } else {+ Vec::new()+ };+ emit((x, rdf_type, *cls), "cls-int1", &premises);+ }}}// cls-uni: x type ANY member → x type union class- for (cls, members) in &union_classes {+ for (cls, head, chain, members) in &union_classes {for &(x, c) in &type_idx {if members.contains(&c) {- new.push((x, rdf_type, *cls));+ let premises: Vec<Fact> = if certify {+ let mut v = vec![(*cls, owl_union, *head)];+ v.extend(chain.iter().copied());+ v.push((x, rdf_type, c));+ v+ } else {+ Vec::new()+ };+ emit((x, rdf_type, *cls), "cls-uni", &premises);}}}@@ -472,7 +613,7 @@ impl Reasoner {// Materialize inferred triplesif materialize && inferred_count > 0 {- let original: HashSet<(u32, u32, u32)> = facts.iter().copied().collect();+ let original: HashSet<Fact> = facts.iter().copied().collect();let mut lines = String::new();for &(s, p, o) in &triple_set {if !original.contains(&(s, p, o)) {@@ -496,7 +637,7 @@ impl Reasoner {}// Sample- let original: HashSet<(u32, u32, u32)> = facts.iter().copied().collect();+ let original: HashSet<Fact> = facts.iter().copied().collect();let sample: Vec<String> = triple_set.iter().filter(|t| !original.contains(t)).filter(|&&(_, p, _)| p == rdf_type)@@ -520,6 +661,47 @@ impl Reasoner {// they were put.result["inference_graph"] = serde_json::json!(INFERRED_GRAPH);}++ if let Some(dir) = certificate_dir {+ std::fs::create_dir_all(dir)?;+ let mut asserted = String::with_capacity(facts.len() * 96);+ for &(s, p, o) in &facts {+ asserted.push_str(interner.resolve(s));+ asserted.push('\t');+ asserted.push_str(interner.resolve(p));+ asserted.push('\t');+ asserted.push_str(interner.resolve(o));+ asserted.push('\n');+ }+ std::fs::write(dir.join("asserted.tsv"), asserted)?;++ let mut by_rule: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new();+ let mut lines = String::with_capacity(derivations.len() * 256);+ for d in &derivations {+ *by_rule.entry(d.rule).or_default() += 1;+ lines.push_str(d.rule);+ for &(s, p, o) in std::iter::once(&d.conclusion).chain(d.premises.iter()) {+ lines.push('\t');+ lines.push_str(interner.resolve(s));+ lines.push('\t');+ lines.push_str(interner.resolve(p));+ lines.push('\t');+ lines.push_str(interner.resolve(o));+ }+ lines.push('\n');+ }+ std::fs::write(dir.join("derivations.tsv"), lines)?;++ result["certificate"] = serde_json::json!({+ "dir": dir.display().to_string(),+ "format": "oo-cert/1",+ "asserted": facts.len(),+ "derivations": derivations.len(),+ "by_rule": by_rule,+ "check_with": "cd lean && lake exe oo-cert <dir>/asserted.tsv <dir>/derivations.tsv",+ });+ }+Ok(result.to_string())}}diff --git a/src/server.rs b/src/server.rsindex b869c035..3cf6041e 100644--- a/src/server.rs+++ b/src/server.rs@@ -1886,7 +1886,8 @@ impl OpenOntologiesServer {} else {crate::reason::InferenceTarget::DefaultGraph};- Reasoner::run_with_target(&self.graph, profile, materialize, target)+ let dir = input.certificate_dir.as_deref().map(std::path::Path::new);+ Reasoner::run_full(&self.graph, profile, materialize, target, dir).unwrap_or_else(Self::err_json)}diff --git a/tests/lean_certificate_test.rs b/tests/lean_certificate_test.rsnew file mode 100644index 00000000..4a984ea4--- /dev/null+++ b/tests/lean_certificate_test.rs@@ -0,0 +1,335 @@+//! The Lean certificate layer, end to end.+//!+//! `reason --certificate DIR` writes what the reasoner started from and, for+//! every triple it inferred, the rule and premises it used. `lean/` holds a+//! checker for that certificate whose soundness is a machine-checked theorem+//! (`OOCert.certificate_sound`): a certificate it accepts contains only+//! triples entailed by the asserted graph. These tests close the loop.+//!+//! 1. Every ontology this repository ships certifies. The list is walked,+//! not hand-picked, and anything excluded is named with the reason.+//! 2. Every rule the reasoner has appears in a certificate the checker+//! accepts, so the emitter and the checker agree on all twenty premise+//! orders, not just the common ones.+//! 3. The checker can say no. A forged conclusion, a premise outside the+//! graph, and the exact derivation `cls-svf1` used to make before it was+//! found unsound are each rejected. A gate that cannot fail is not a gate.+//!+//! The checker needs a Lean toolchain (`lake`). Without one these tests skip+//! loudly through `common::skip_unless`; the CI job that installs Lean runs+//! them with `OO_REQUIRE_FIXTURES=1`, which turns that skip into a failure.++mod common;++use open_ontologies::graph::GraphStore;+use open_ontologies::reason::{InferenceTarget, Reasoner};+use std::path::{Path, PathBuf};+use std::process::Command;+use std::sync::{Arc, OnceLock};++fn repo() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+}++fn lean_dir() -> PathBuf {+ repo().join("lean")+}++fn lake_available() -> bool {+ Command::new("lake")+ .arg("--version")+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+}++fn skip() -> bool {+ common::skip_unless(+ lake_available(),+ "lake (the Lean 4 build tool)",+ "install elan from https://github.com/leanprover/elan; lean/lean-toolchain pins the version",+ )+}++/// Build the checker once per test binary. The proofs are part of the build,+/// so a failure here is a failure, never a skip.+fn checker() -> &'static Path {+ static BUILT: OnceLock<PathBuf> = OnceLock::new();+ BUILT.get_or_init(|| {+ let out = Command::new("lake")+ .arg("build")+ .current_dir(lean_dir())+ .output()+ .expect("run lake build");+ assert!(+ out.status.success(),+ "lake build failed:\n{}\n{}",+ String::from_utf8_lossy(&out.stdout),+ String::from_utf8_lossy(&out.stderr)+ );+ let exe = lean_dir().join(".lake").join("build").join("bin").join("oo-cert");+ assert!(exe.exists(), "checker binary missing at {}", exe.display());+ exe+ })+}++/// Run the checker on a certificate directory. Returns (accepted, output).+fn check(dir: &Path) -> (bool, String) {+ let out = Command::new(checker())+ .arg(dir.join("asserted.tsv"))+ .arg(dir.join("derivations.tsv"))+ .output()+ .expect("run oo-cert");+ let text = format!(+ "{}{}",+ String::from_utf8_lossy(&out.stdout),+ String::from_utf8_lossy(&out.stderr)+ );+ (out.status.success(), text)+}++fn scratch(name: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("oo-cert-{}-{}", name, std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+}++fn certify_turtle(ttl: &str, profile: &str, dir: &Path) -> serde_json::Value {+ let store = Arc::new(GraphStore::new());+ store.load_turtle(ttl, None).unwrap();+ let out = Reasoner::run_full(&store, profile, false, InferenceTarget::DefaultGraph, Some(dir)).unwrap();+ serde_json::from_str(&out).unwrap()+}++const PREFIXES: &str = r#"+ @prefix : <http://ex.org/> .+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+"#;++/// One ontology that fires all twenty rules.+const EVERY_RULE: &str = r#"+ :A rdfs:subClassOf :B . :B rdfs:subClassOf :C . :a a :A .+ :p rdfs:domain :Dom ; rdfs:range :Rng . :s :p :o .+ :q rdfs:subPropertyOf :r . :r rdfs:subPropertyOf :t . :s :q :o .+ :anc a owl:TransitiveProperty . :x :anc :y . :y :anc :z .+ :near a owl:SymmetricProperty . :x :near :y .+ :parent owl:inverseOf :child . :m :parent :n . :u :child :v .+ :a owl:sameAs :a2 .+ :E1 owl:equivalentClass :E2 . :pe1 owl:equivalentProperty :pe2 .+ :R1 a owl:Restriction ; owl:onProperty :has ; owl:someValuesFrom :F . :w :has :f . :f a :F .+ :R2 a owl:Restriction ; owl:onProperty :col ; owl:hasValue :red .+ :K rdfs:subClassOf :R2 . :k a :K . :j :col :red .+ :I owl:intersectionOf ( :M1 :M2 ) . :i a :M1 , :M2 .+ :U owl:unionOf ( :N1 :N2 ) . :n a :N2 .+"#;++const ALL_RULES: [&str; 20] = [+ "rdfs2", "rdfs3", "rdfs5", "rdfs7", "rdfs9", "rdfs11",+ "prp-trp", "prp-symp", "prp-inv1", "prp-inv2", "eq-sym",+ "scm-eqc1", "scm-eqc2", "scm-eqp1", "scm-eqp2",+ "cls-svf1", "cls-hv1", "cls-hv2", "cls-int1", "cls-uni",+];++#[test]+fn every_rule_family_appears_in_an_accepted_certificate() {+ if skip() {+ return;+ }+ let dir = scratch("every-rule");+ let r = certify_turtle(&format!("{PREFIXES}{EVERY_RULE}"), "owl-rl-ext", &dir);+ let by_rule = r["certificate"]["by_rule"].as_object().expect("by_rule in the response");+ let missing: Vec<&str> = ALL_RULES.iter().copied().filter(|k| !by_rule.contains_key(*k)).collect();+ assert!(missing.is_empty(), "rules that never fired on the all-rules ontology: {missing:?}\n{r}");+ assert_eq!(+ r["certificate"]["derivations"], r["inferred_count"],+ "one certificate line per inferred triple: {r}"+ );+ let (ok, out) = check(&dir);+ assert!(ok, "the checker rejected the all-rules certificate:\n{out}");+ assert!(out.contains("\"ok\":true"), "{out}");+}++#[test]+fn a_forged_conclusion_is_rejected() {+ if skip() {+ return;+ }+ let dir = scratch("forged");+ certify_turtle(&format!("{PREFIXES}{EVERY_RULE}"), "owl-rl-ext", &dir);+ let (ok, _) = check(&dir);+ assert!(ok, "the honest certificate must pass first");++ // rdfs9 with premises that do not support the conclusion.+ let forged = "rdfs9\t<http://ex.org/a>\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>\t<http://ex.org/Z>\t\+ <http://ex.org/a>\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>\t<http://ex.org/A>\t\+ <http://ex.org/A>\t<http://www.w3.org/2000/01/rdf-schema#subClassOf>\t<http://ex.org/B>\n";+ let path = dir.join("derivations.tsv");+ let mut content = std::fs::read_to_string(&path).unwrap();+ content.push_str(forged);+ std::fs::write(&path, content).unwrap();++ let (ok, out) = check(&dir);+ assert!(!ok, "a conclusion the premises do not support must be rejected:\n{out}");+ assert!(out.contains("\"ok\":false") && out.contains("first_rejected"), "{out}");+}++#[test]+fn a_premise_outside_the_graph_is_rejected() {+ if skip() {+ return;+ }+ let dir = scratch("outside");+ certify_turtle(&format!("{PREFIXES}{EVERY_RULE}"), "owl-rl-ext", &dir);++ // Well-formed rdfs9 whose subClassOf premise nobody asserted or derived.+ let forged = "rdfs9\t<http://ex.org/a>\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>\t<http://ex.org/Ghost>\t\+ <http://ex.org/a>\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>\t<http://ex.org/A>\t\+ <http://ex.org/A>\t<http://www.w3.org/2000/01/rdf-schema#subClassOf>\t<http://ex.org/Ghost>\n";+ let path = dir.join("derivations.tsv");+ let mut content = std::fs::read_to_string(&path).unwrap();+ content.push_str(forged);+ std::fs::write(&path, content).unwrap();++ let (ok, out) = check(&dir);+ assert!(!ok, "a premise that is neither asserted nor derived must be rejected:\n{out}");+}++#[test]+fn the_derivation_the_old_svf_rule_made_is_rejected() {+ if skip() {+ return;+ }+ // The ontology from tests/reason_rl_ext_soundness_test.rs, and the line+ // the reasoner used to emit for it: x ∈ C from C ⊑ ∃p.D and x ∈ ∃p.D.+ let dir = scratch("old-svf");+ let ttl = format!(+ "{PREFIXES}+ :C rdfs:subClassOf :R .+ :R a owl:Restriction ; owl:onProperty :p ; owl:someValuesFrom :D .+ :x :p :y . :y a :D ."+ );+ let r = certify_turtle(&ttl, "owl-rl-ext", &dir);+ let (ok, out) = check(&dir);+ assert!(ok, "the sound derivations must pass: {out}\n{r}");++ let forged = "cls-svf1\t<http://ex.org/x>\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>\t<http://ex.org/C>\t\+ <http://ex.org/R>\t<http://www.w3.org/2002/07/owl#onProperty>\t<http://ex.org/p>\t\+ <http://ex.org/R>\t<http://www.w3.org/2002/07/owl#someValuesFrom>\t<http://ex.org/D>\t\+ <http://ex.org/x>\t<http://ex.org/p>\t<http://ex.org/y>\t\+ <http://ex.org/y>\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>\t<http://ex.org/D>\n";+ let path = dir.join("derivations.tsv");+ let mut content = std::fs::read_to_string(&path).unwrap();+ content.push_str(forged);+ std::fs::write(&path, content).unwrap();++ let (ok, out) = check(&dir);+ assert!(!ok, "the converse of a subclass axiom has no rule; the checker must reject it:\n{out}");+ assert!(out.contains("cls-svf1"), "the rejection names the step: {out}");+}++#[test]+fn owl_dl_refuses_to_pretend_it_has_a_certificate() {+ let store = Arc::new(GraphStore::new());+ store.load_turtle(&format!("{PREFIXES} :A rdfs:subClassOf :B ."), None).unwrap();+ let dir = scratch("owl-dl");+ let err = Reasoner::run_full(&store, "owl-dl", false, InferenceTarget::DefaultGraph, Some(&dir))+ .expect_err("owl-dl has no rule trace and must say so");+ assert!(err.to_string().contains("no derivation certificate"), "{err}");+}++/// Everything under these roots that parses as RDF, up to the size cap.+const ROOTS: [&str; 5] = ["case-studies", "demo", "tests/fixtures", "data", "examples"];+const SIZE_CAP: u64 = 4 * 1024 * 1024;++fn walk(dir: &Path, out: &mut Vec<PathBuf>) {+ let Ok(entries) = std::fs::read_dir(dir) else { return };+ for entry in entries.flatten() {+ let path = entry.path();+ let name = entry.file_name().to_string_lossy().to_string();+ if path.is_dir() {+ // Tooling trees that live beside the corpus locally but are not+ // part of it: a Python venv drops pyshacl's own shacl.ttl under+ // site-packages, and it certified happily, but it is not ours.+ if matches!(+ name.as_str(),+ "node_modules" | "target" | ".lake" | ".git" | ".venv" | "venv" | "site-packages" | "__pycache__"+ ) {+ continue;+ }+ walk(&path, out);+ } else if matches!(+ path.extension().and_then(|e| e.to_str()),+ Some("ttl" | "owl" | "rdf" | "nt")+ ) {+ out.push(path);+ }+ }+}++#[test]+fn every_shipped_ontology_certifies() {+ if skip() {+ return;+ }+ let mut files = Vec::new();+ for root in ROOTS {+ walk(&repo().join(root), &mut files);+ }+ files.sort();+ assert!(files.len() >= 40, "expected the shipped corpus, found {} files", files.len());++ let mut excluded: Vec<(String, String)> = Vec::new();+ let mut failures: Vec<(String, String)> = Vec::new();+ let mut certified = 0usize;+ let mut total_derivations = 0u64;++ for path in &files {+ let rel = path.strip_prefix(repo()).unwrap().display().to_string();+ let size = std::fs::metadata(path).unwrap().len();+ if size > SIZE_CAP {+ excluded.push((rel, format!("{} bytes, over the {} byte cap", size, SIZE_CAP)));+ continue;+ }+ let store = Arc::new(GraphStore::new());+ if let Err(e) = store.load_file(&path.display().to_string()) {+ excluded.push((rel, format!("does not parse: {}", e.to_string().lines().next().unwrap_or(""))));+ continue;+ }+ let dir = scratch(&format!("corpus-{}", certified));+ let out = match Reasoner::run_full(&store, "owl-rl-ext", false, InferenceTarget::DefaultGraph, Some(&dir)) {+ Ok(o) => o,+ Err(e) => {+ failures.push((rel, format!("reasoner error: {e}")));+ continue;+ }+ };+ let r: serde_json::Value = serde_json::from_str(&out).unwrap();+ if r["certificate"]["derivations"] != r["inferred_count"] {+ failures.push((rel.clone(), format!("certificate has {} lines for {} inferred triples", r["certificate"]["derivations"], r["inferred_count"])));+ }+ let (ok, text) = check(&dir);+ if ok {+ certified += 1;+ total_derivations += r["inferred_count"].as_u64().unwrap_or(0);+ eprintln!("CERTIFIED {rel}: {} asserted, {} derived", r["initial_triples"], r["inferred_count"]);+ } else {+ failures.push((rel, text));+ }+ let _ = std::fs::remove_dir_all(&dir);+ }++ eprintln!("certified {certified} files, {total_derivations} derivations checked");+ for (f, why) in &excluded {+ eprintln!("EXCLUDED {f}: {why}");+ }+ assert!(certified >= 30, "too few files certified ({certified}); excluded: {excluded:?}");+ assert!(total_derivations > 0, "the corpus produced no inferences at all, so nothing was checked");+ assert!(+ failures.is_empty(),+ "{} certificate(s) rejected or malformed:\n{}",+ failures.len(),+ failures.iter().map(|(f, t)| format!("--- {f}\n{t}")).collect::<Vec<_>>().join("\n")+ );+}diff --git a/tests/reason_rl_ext_soundness_test.rs b/tests/reason_rl_ext_soundness_test.rsnew file mode 100644index 00000000..07f4882f--- /dev/null+++ b/tests/reason_rl_ext_soundness_test.rs@@ -0,0 +1,110 @@+//! Soundness of the `owl-rl-ext` forward-chaining rules.+//!+//! Found 13 Sep 2026 while designing the Lean certificate layer: `cls-svf1`+//! derived two things no OWL semantics licenses.+//!+//! 1. From `C rdfs:subClassOf [ owl:onProperty p ; owl:someValuesFrom D ]`,+//! `x p y` and `y a D`, it inferred `x a C`. That is the CONVERSE of the+//! axiom: being in `∃p.D` says nothing about being in `C`. Only an+//! `owl:equivalentClass` licenses the step, and it is licensed there by+//! the two `rdfs:subClassOf` triples the equivalence expands to.+//! 2. From `z p D`, where `D` is the filler class IRI itself, it inferred+//! `z a ∃p.D`. A class used in object position is a resource, not an+//! instance of itself.+//!+//! Every rule the reasoner applies has to correspond to a rule the Lean checker+//! can prove sound. These two had no such rule, which is how they were found.++use open_ontologies::graph::GraphStore;+use open_ontologies::reason::Reasoner;+use std::sync::Arc;++const PREFIXES: &str = r#"+ @prefix : <http://ex.org/> .+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+"#;++fn run(ttl: &str) -> Arc<GraphStore> {+ let store = Arc::new(GraphStore::new());+ store.load_turtle(&format!("{PREFIXES}{ttl}"), None).unwrap();+ Reasoner::run(&store, "owl-rl-ext", true).unwrap();+ store+}++fn holds(store: &Arc<GraphStore>, s: &str, o: &str) -> bool {+ let q = format!(+ "SELECT ?s WHERE {{ <http://ex.org/{s}> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex.org/{o}> }}"+ );+ let json: serde_json::Value =+ serde_json::from_str(&store.sparql_select_union(&q).unwrap()).unwrap();+ !json["results"].as_array().unwrap().is_empty()+}++fn restriction_members(store: &Arc<GraphStore>) -> Vec<String> {+ let q = "SELECT ?x WHERE { ?x a ?r . ?r <http://www.w3.org/2002/07/owl#onProperty> ?p }";+ let json: serde_json::Value =+ serde_json::from_str(&store.sparql_select_union(q).unwrap()).unwrap();+ let mut v: Vec<String> = json["results"]+ .as_array()+ .unwrap()+ .iter()+ .map(|r| r["x"].as_str().unwrap().to_string())+ .collect();+ v.sort();+ v.dedup();+ v+}++#[test]+fn a_subclass_of_a_restriction_is_not_inferred_from_the_restriction() {+ let store = run(r#"+ :C rdfs:subClassOf [ a owl:Restriction ; owl:onProperty :p ; owl:someValuesFrom :D ] .+ :x :p :y .+ :y a :D .+ "#);+ assert!(+ !holds(&store, "x", "C"),+ "x ∈ ∃p.D and C ⊑ ∃p.D do not give x ∈ C (converse of the axiom)"+ );+ // The sound half of the rule still fires: x is in the restriction class.+ assert_eq!(restriction_members(&store), vec!["<http://ex.org/x>".to_string()]);+}++#[test]+fn a_class_iri_in_object_position_is_not_an_instance_of_itself() {+ let store = run(r#"+ :E owl:equivalentClass [ a owl:Restriction ; owl:onProperty :p ; owl:someValuesFrom :D ] .+ :z :p :D .+ "#);+ assert!(!holds(&store, "z", "E"), "z p D says nothing about z ∈ ∃p.D");+ assert!(restriction_members(&store).is_empty(), "nobody is in ∃p.D here");+}++#[test]+fn an_equivalent_class_of_a_restriction_is_still_inferred() {+ // Positive control: the case the unsound rule happened to get right must+ // keep working through the sound route (equivalentClass expands to two+ // subClassOf triples, and rdfs9 carries membership across one of them).+ let store = run(r#"+ :E owl:equivalentClass [ a owl:Restriction ; owl:onProperty :p ; owl:someValuesFrom :D ] .+ :x :p :y .+ :y a :D .+ "#);+ assert!(holds(&store, "x", "E"), "x ∈ ∃p.D and E ≡ ∃p.D give x ∈ E");+}++#[test]+fn has_value_rules_are_unchanged() {+ let store = run(r#"+ :F rdfs:subClassOf [ a owl:Restriction ; owl:onProperty :q ; owl:hasValue :v ] .+ :a a :F .+ :G owl:equivalentClass [ a owl:Restriction ; owl:onProperty :q ; owl:hasValue :v ] .+ :b :q :v .+ "#);+ let q = "SELECT ?s WHERE { <http://ex.org/a> <http://ex.org/q> <http://ex.org/v> }";+ let json: serde_json::Value =+ serde_json::from_str(&store.sparql_select_union(q).unwrap()).unwrap();+ assert!(!json["results"].as_array().unwrap().is_empty(), "F ⊑ ∃q.{{v}} and a ∈ F give a q v");+ assert!(holds(&store, "b", "G"), "b q v and G ≡ ∃q.{{v}} give b ∈ G");+}