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
tcb: prove six, enforce five, and fix the one that was pinned as a defect
FABIOTESSd44689223690
diff --git a/Makefile b/Makefileindex 6a000517..64af2cf4 100644--- a/Makefile+++ b/Makefile@@ -20,16 +20,28 @@ audit:# own toolchain, so this is NOT part of `check`: it is minutes per harness and# a developer without Kani installed must still be able to run the gates.# `cargo test` covers the same statements by sampling.-# `parse_pat_and_render_are_inverse` is deliberately NOT here. It is a fourth-# harness in the same module and it does not terminate: no verdict at 14 minutes-# and 9.5GB, worse when the input is constrained, because `parse_pat` returns-# `anyhow::Result` and CBMC flattens the error-formatting machinery whether or-# not the refusal paths are reachable. The harness carries the measurements and-# what would close it. A target that hangs is worse than one that is honest-# about its coverage.+# Every harness in `src/reason.rs` is here, which was not true before 15+# September 2026: `parse_pat_and_render_are_inverse` did not terminate (no+# verdict at 14 minutes and 9.5GB, worse when the input was constrained) because+# `parse_pat` returns `anyhow::Result` and CBMC flattens the error-formatting+# machinery whether or not the refusal paths are reachable. Lifting the+# classification into the pure `pat_of` closed it: it is now+# `pat_of_and_render_are_inverse_*` and it verifies in about four seconds.verify:- cargo kani --harness asserted_line_round_trips- cargo kani --harness triple_fields_append_exactly_three+ cargo kani --harness asserted_line_round_trips_at_0+ cargo kani --harness asserted_line_round_trips_at_1+ cargo kani --harness asserted_line_round_trips_at_2+ cargo kani --harness asserted_line_round_trips_at_3+ cargo kani --harness asserted_line_round_trips_at_4+ cargo kani --harness triple_fields_append_exactly_three_at_0+ cargo kani --harness triple_fields_append_exactly_three_at_2+ cargo kani --harness triple_fields_append_exactly_three_at_3+ cargo kani --harness triple_fields_append_exactly_three_at_4+ cargo kani --harness term_guard_admits_no_separator_at_3+ cargo kani --harness term_guard_admits_no_separator_at_6+ cargo kani --harness term_guard_separates_the_three_spellings+ cargo kani --harness pat_of_and_render_are_inverse_at_2+ cargo kani --harness pat_of_and_render_are_inverse_at_3cargo kani --harness writable_triple_decides_both_positionscheck: lint test auditdiff --git a/README.md b/README.mdindex 6445eae8..097e8a8f 100644--- a/README.md+++ b/README.md@@ -100,13 +100,13 @@ carries a certificate per claim. See [decision 0007](docs/decisions/0007-a-sliceEvery line above is worth less if this section is missing, so it is here rather than in a filenobody opens. These are the load-bearing limits, and none of them is hypothetical.-**The Rust engine is almost entirely unverified.** The theorems are conditional: they say that IF-the asserted graph is what the certificate claims and IF the derivation steps are the ones taken,-THEN the conclusions hold. Everything to the left of that is a serialiser, a parser and an-interner, and if they misrepresent the run, a valid proof certifies the wrong thing. That boundary-is named property by property in [docs/trusted-computing-base.md](docs/trusted-computing-base.md),-property-tested, and partly bounded-model-checked. It is not verified. This work verified the-joint, not the machine.+**The Rust engine is not verified.** The theorems are conditional on it reporting the run+faithfully. That boundary is twenty-nine properties: `make verify` bounded-model-checks six, and+five are enforced by the engine rather than observed of a dependency, two properties being in both+counts. Two are irreducible, because they are about an execution and not a function: that+`asserted.tsv` is the graph reasoned over, and that `derivations.tsv` covers every triple added.+Those are property-tested end to end, which is not proved.+[docs/trusted-computing-base.md](docs/trusted-computing-base.md) says which is which.**The bridge to the specification is prose, not a theorem.** Fourteen rule arms used to beassumed rather than derived, and they are now derived, each with an empty axiom footprint, over adiff --git a/docs/ci-gates.md b/docs/ci-gates.mdindex 6fecc873..ef2fb19c 100644--- a/docs/ci-gates.md+++ b/docs/ci-gates.md@@ -62,6 +62,7 @@ job invokes the file at all.| `gate_demonstration_test.rs` | lake | `lean` job | **strict** || `w3c_shacl_conformance_test.rs` | vendored W3C SHACL suite (in tree) | `w3c-shacl` job | **strict** || `certificate_boundary_proptest.rs` | lake | `lean` job | **strict** |+| `premise_order_test.rs` | `lean/OOCert/Rules.lean` (in tree) | every job that runs `cargo test` | **runs everywhere**: it READS the Lean source rather than building it, so TCB-14 is gated without a toolchain || `reason_rl_coverage_test.rs` | lake | `lean` job | **strict** || `rule_syntax_frontend_test.rs` | lake | `lean` job | **strict** || `reason_horn_emit_test.rs` | lake + `tests/fixtures/horn/` (in tree) | `lean` job | **strict** |diff --git a/docs/decisions/0001-an-inference-is-not-an-assertion.md b/docs/decisions/0001-an-inference-is-not-an-assertion.mdindex baeea389..1f3ea9fb 100644--- a/docs/decisions/0001-an-inference-is-not-an-assertion.md+++ b/docs/decisions/0001-an-inference-is-not-an-assertion.md@@ -60,7 +60,12 @@ subject is register integrity that is the wrong defect to be carrying.- **`onto_pack` writes sorted N-Triples.** A pack built after a reasoning run therefore nowexcludes the inferences. That is the safe direction and probably the right one, since a pack isa promotable artefact, but the manifest should say so rather than leaving it to be discovered.-- **When the default flips**, `all_triples()` reads the whole store including named graphs, so a- second reasoning run consumes the first run's output as premises. OWL-RL is monotone, so the- closure is unchanged and `inferred_count` correctly reports zero new triples, but the reported- `initial_triples` then includes inferences and no longer means "what was asserted".+- **`all_triples()` was the hole in this decision, and it is closed.** It reads the whole store+ including named graphs, so a second reasoning run consumed the first run's output as premises:+ OWL-RL is monotone, so the closure was unchanged and `inferred_count` correctly reported zero new+ triples, but `initial_triples` then included inferences and no longer meant "what was asserted",+ and `asserted.tsv` listed them as axioms. That made this decision protect `save` and not the+ certificate, which is not what it says. Since 15 September 2026 both certified paths read+ `GraphStore::triples_outside(&[INFERRED_GRAPH])` instead, and report `graphs_read` and+ `graphs_excluded`. `all_triples()` is unchanged and still means every graph; its doc comment now+ says which callers must not use it. See TCB-8 in `docs/trusted-computing-base.md`.diff --git a/docs/lean-certificates.md b/docs/lean-certificates.mdindex af3617ab..3474bfb7 100644--- a/docs/lean-certificates.md+++ b/docs/lean-certificates.md@@ -748,10 +748,15 @@ Stated rather than discovered later.- **`asserted.tsv` is the store, not your file.** Quads are flattened, so a triple present in twonamed graphs appears on two lines. Literals are in the store's post-parse canonical spelling, so`"01"^^xsd:integer` is written `"1"^^xsd:integer`. The guarantee is relative to that file.-- **Reasoning twice into one store.** The run now reaches a fixpoint, so a second run adds nothing,- but if you materialise into a store that already held inferences they appear in `asserted.tsv` as- assumptions with nothing marking them derived. Use `inference_graph: true` (decision 0001) when- that distinction matters.+- **Reasoning twice into one store.** The run reaches a fixpoint, so a second run adds nothing. If+ you materialise into the DEFAULT graph of a store that already held inferences, they appear in+ `asserted.tsv` as assumptions with nothing marking them derived: the merge is what the caller+ asked for and it is lossy. `inference_graph: true` (decision 0001) now fixes it rather than+ mitigating it. The certified paths read `GraphStore::triples_outside(&[INFERRED_GRAPH])`, so a+ later run does not read an earlier run's conclusions back as axioms, and the JSON reports+ `graphs_read` and `graphs_excluded` so the certificate says which graphs it is about. Until 15+ September 2026 `all_triples` read every named graph and the separation protected `save` and not+ the certificate; TCB-8 in `docs/trusted-computing-base.md` has the history.- **No clash found is not consistency.** Seven of the seventeen clash rules are not looked for atall and eight of the ten that are cannot be certified, so a clean `reason` run means "none of theten rules tried fired", never "this ontology is consistent". A rejected refutation means the same:diff --git a/docs/trusted-computing-base.md b/docs/trusted-computing-base.mdindex 81e32df5..167cfc68 100644--- a/docs/trusted-computing-base.md+++ b/docs/trusted-computing-base.md@@ -13,6 +13,15 @@ The point of writing it down is that an unwritten trusted base cannot be reviewefinishes this page should be able to say how much of the engine is verified (almost none of it) andwhich specific, small pieces carry the weight (the ones below).+**Where this stands on 15 September 2026.** Of the twenty-nine properties, six are PROVED by bounded+model checking rather than sampled: TCB-1, TCB-2, TCB-3, TCB-4, TCB-5 and TCB-20. Five moved from+something this repository OBSERVED to something it ENFORCES: TCB-4 and TCB-5 are now a refusal at+the certificate writer rather than a fact about `oxrdf` and `oxiri`; TCB-8 across runs was a DEFECT+pinned by a test and is fixed for the named inference graph; TCB-14 is derived from one rule table+instead of hand-written at thirty-one call sites; TCB-26 is checked at the point of writing instead+of by a second loop. The two lists overlap at TCB-4 and TCB-5, so nine distinct properties changed+level. What is left irreducible is two things, and they are named at the end.+## What the Lean side never seesThe checkers are pure functions of files on disk. They read `asserted.tsv`, `derivations.tsv`,@@ -48,19 +57,35 @@ functions.### Serialisation: the format cannot be forged from inside a termAll six files are tab-separated, carry arbitrary RDF terms, and have no escaping layer of their own.-`src/reason.rs` writes terms with `push('\t')` between them and `push('\n')` at the end of a line,-and nothing in that code inspects a term. `lean/OOCert/Parse.lean` states the assumption that makes-this safe, in a comment rather than a theorem:+`lean/OOCert/Parse.lean` states the assumption that makes this safe, in a comment rather than a+theorem:> Tabs and newlines cannot occur inside an N-Triples term (they are escaped), so splitting on them is> exact.-That sentence is the whole of the escaping argument, and it is a claim about a third-party crate.-The terms come from `oxrdf`'s `Display`, through `GraphStore::all_triples`, which calls-`quad.subject.to_string()` and friends. `oxrdf 0.3.3` escapes `\t`, `\n`, `\r`, `"` and `\` inside a-literal's lexical form (`print_quoted_str` in `literal.rs`), and does **not** escape anything inside-an IRI: `NamedNodeRef`'s `Display` is `write!(f, "<{}>", self.as_str())`. Nothing in this repository-re-checks either half.+Until 15 September 2026 that sentence was the whole of the escaping argument, and it was a claim+about a third-party crate. The terms come from `oxrdf`'s `Display`, through the store readers, which+call `quad.subject.to_string()` and friends. `oxrdf 0.3.3` escapes+`\t`, `\n`, `\r`, `"` and `\` inside a literal's lexical form (`print_quoted_str` in `literal.rs`),+and does **not** escape anything inside an IRI: `NamedNodeRef`'s `Display` is+`write!(f, "<{}>", self.as_str())`, so the only thing standing between a tab and `asserted.tsv` was+that `oxiri` refused to parse the IRI. That is a dependency's behaviour observed rather than+enforced, and an upgrade could change it.++**This repository now enforces it.** `term_fits_the_format` in `src/reason.rs` is the predicate, and+the two writers `push_asserted_line` and `push_triple_fields` are the only functions that append a+term to a certificate buffer. A term is written only if it is non-empty, carries no `\t`, `\n` or+`\r`, and is in one of the three N-Triples spellings (`<iri>`, `_:blank`, or a quoted literal). A+term that is not means no certificate: the writer returns `Err(Position)`, the caller turns that into+an error naming the term, and nothing is written. The check happens before anything is appended, so a+refusal cannot leave half a line in the buffer.++The refusing direction is the point. Escaping at the writer would be the other way to close it, and+it would need `lean/OOCert/Parse.lean` and `Shacl.Parse` to learn the same escaping, which is a+change to the verified side for a case that cannot arise from a well-formed store. Refusing needs+nothing from the checkers and fails safe: the engine declines to make a claim rather than making one+a reader cannot trust. The cost is liveness, and it is real: if `oxrdf` ever started emitting a raw+tab inside a literal, this engine would stop writing certificates instead of writing forgeable ones.- **TCB-1 (field integrity, asserted).** Every line of `asserted.tsv` splits on `\t` into exactlythree fields, and the number of lines equals the number of triples the run started from. A term@@ -72,12 +97,16 @@ re-checks either half.`2 + 2 * binds + 3 * (1 + body)` fields, with `binds` and `body` read from the line's own headerand from `rules.tsv`.- **TCB-4 (no separator in any term).** No term written to any certificate file contains `\t`,- `\n` or `\r`. This is the property TCB-1 to TCB-3 exist to detect the failure of; stated- separately because it is the one that has to survive an `oxrdf` upgrade.+ `\n` or `\r`. **Enforced** by `term_fits_the_format` at the writer and **proved** by+ `kani_harnesses::term_guard_admits_no_separator_at_3` and `_at_6`, which state it over a symbolic+ index rather than restating the implementation's own scan, and by the writer harnesses, which+ prove the writer returns `Ok` exactly when all three terms pass.- **TCB-5 (term spellings do not collide).** A literal whose lexical form is `<http://example/x>`- and the IRI `<http://example/x>` must not have the same spelling in a certificate file. They do- not, because a literal is quoted, but the two checkers compare terms as opaque strings and would- be unable to tell them apart if they ever agreed.+ and the IRI `<http://example/x>` must not have the same spelling in a certificate file. **Enforced**+ by the same predicate, whose leading-byte condition makes the kind of a term a function of its+ first byte, and **proved** by `kani_harnesses::term_guard_separates_the_three_spellings`: an+ accepted term is exactly one of the three kinds, and two accepted terms of different kinds are+ different strings. That is what entitles both checkers to compare terms as opaque strings.### The asserted graph@@ -88,16 +117,23 @@ re-checks either half.triple that was in the store at the start of the run. This is the unsafe direction. An extra lineis an axiom nobody asserted, and every conclusion resting on it is certified against a graph thatdoes not exist.-- **TCB-8 (no inference leaks into the assertions, within a run).** No conclusion of- `derivations.tsv` appears in `asserted.tsv`. The engine reaches a fixpoint in one pass and- captures `facts` before materialising, so this holds within a run.- **Across runs it does not hold and cannot be made to hold by this layer.** Materialising into the- default graph turns run N's conclusions into run N+1's assertions, and `asserted.tsv` has no- column that says "derived". `docs/lean-certificates.md` states this under "Known limitations" and- decision 0001 is the mitigation (`inference_graph: true` keeps them in a named graph). Note that- `GraphStore::all_triples` iterates `store.iter()` over every graph, so inferences parked in- `https://open-ontologies.org/graph/inferred` by an earlier run are read back as assertions by a- later certified run. The separation protects `save`, not the certificate.+- **TCB-8 (no inference leaks into the assertions).** No conclusion of `derivations.tsv` appears in+ `asserted.tsv`. Within a run this holds because the engine reaches a fixpoint in one pass and+ captures `facts` before materialising.+ **Across runs, the half that was a defect is fixed and the half that is a caller's choice is+ not.** The defect: `GraphStore::all_triples` iterates `store.iter()` over every graph, so+ inferences that `inference_graph: true` parked in `https://open-ontologies.org/graph/inferred`+ under decision 0001 were read back as assertions by the next certified run. The separation+ protected `save` and not the certificate, and a test asserted that failure rather than the+ property. Both certified paths now read `GraphStore::triples_outside(&[INFERRED_GRAPH])`, and both+ report `graphs_read` and `graphs_excluded` in their JSON, so a certificate says which graphs it is+ about and that claim can be checked against the store.+ What remains is `InferenceTarget::DefaultGraph`, which merges conclusions into the default graph+ beside the assertions because the caller asked for that. After the merge nothing distinguishes+ them, `asserted.tsv` has no column that says "derived", and no layer above the store can recover+ the distinction. `tests/certificate_boundary_proptest.rs::tcb_8_across_runs_only_the_default_graph_leaks`+ asserts the fix for the named graph and the leak for the merged one, in one test, so neither half+ can change without the documentation being forced to change with it.- **TCB-9 (the store is a set, the file is a list).** A triple present in two named graphs iswritten twice, because `all_triples` flattens quads. Duplicate lines are harmless to soundness(the Lean side builds a `HashSet`) but `asserted` in the JSON report counts lines, not distinct@@ -110,7 +146,11 @@ re-checks either half.uncertified triple sitting in the store under the certificate's cover. Structurally this holdsbecause the single `emit` closure is the only path that pushes a candidate, and it records thefirst derivation of anything not already in the closure, but nothing outside that reading enforces- it.+ it. The reading is shorter than it was: `emit` now computes the conclusion from the rule table for+ twenty-seven of the thirty-one sites, so a site cannot push a triple its rule does not license,+ and a site that passed a conclusion and premises that did not correspond is no longer expressible.+ It is still a reading of a loop plus a property test comparing conclusions against the store's+ before and after.- **TCB-11 (one line per inference).** `derivations.len() == inferred_count`. A conclusion isrecorded the first time it is derived and never again.- **TCB-12 (premises precede conclusions).** Every premise of the step on line `i` is either in@@ -124,10 +164,21 @@ re-checks either half.accepted by `OOCert.Rule.ofName?`. An unknown name is a parse error, so this is fail-safe, but arule renamed on one side and not the other silently stops the corpus test from covering it.- **TCB-14 (the premise order matches the rule's arm).** `OOCert.checkStep` pattern-matches the- premises positionally per rule. The emitter passes them in a hand-written order at each of the- thirty-one `emit` call sites. A wrong order is a rejection, not a false pass, and- `tests/lean_certificate_test.rs` covers every rule, but nothing derives the order from a single- source.+ premises positionally per rule. **The emitter no longer chooses the order.** Twenty-seven of the+ thirty-one call sites now fire as `Fired::Bound(rule, binding)`: the site supplies the terms and+ the premise list AND the conclusion are computed from that rule's row in `BUILTIN_RULES`+ (`src/reason.rs`), which is one table. A site has no order to get wrong.+ The remaining four are the list rules `cls-int1`, `cls-int2`, `cls-uni` and `cls-oo`, whose+ premises are a constructor triple plus an RDF list chain as long as the list; the checker matches+ those with `takeChain` rather than positionally, so they are not a fixed pattern on either side+ and they keep an explicit premise vector.+ That leaves one question: is `BUILTIN_RULES` the checker's table? `tests/premise_order_test.rs`+ answers it by parsing the `checkStep` ARMS out of `lean/OOCert/Rules.lean` (the code, not the+ prose table in its docstring), rebuilding each arm's pattern from its premise list, its `x = y` and+ `x = V.foo` conjuncts and its `st.conclusion = ⟨..⟩`, and comparing the two up to renaming of+ variables. A disagreement in order, in arity, in which position is fixed, or in which vocabulary+ term is fixed, fails `cargo test`. Checked by refutation both ways: swapping `rdfs2`'s two premises+ fails it, and writing `scm-avf2`'s conclusion the natural way round fails it twice.### The interner@@ -181,10 +232,17 @@ tabs.contains a space, tab, carriage return or newline, and the emitter refuses to write a certificateif any name fails. This is the only explicit injection guard in the codebase, and it is in theright place.-- **TCB-26 (the guard covers every name that is written).** The `names` vector is built by walking- every axiom variant, every role in `model.rext` and every class in `model.cext`. Individuals in- `model.ind` are covered only because `DlAxiom::Indiv(i)` is emitted for every individual that- reaches the model. That is an argument about two separate loops agreeing, not a check.+- **TCB-26 (the guard covers every name that is written).** It used to be an argument about two+ separate loops agreeing: a `names` vector built by walking every axiom variant plus `model.rext`+ and `model.cext`, with individuals in `model.ind` covered only because `DlAxiom::Indiv(i)` happens+ to be emitted for every individual that reaches the model. **The separate loop is gone.**+ `push_name` is the only function that appends a name to either buffer; it applies `name_is_safe`+ as it writes and records the first refusal, and the emitter refuses the whole certificate before+ anything reaches disk. Coverage is therefore not a question: there is no other way to write a+ name. `tableaux::certificate_boundary_tests::tcb_26_only_push_name_writes_a_name` reads the+ source of the serialisers and of the emitter and fails if any other `resolve` reaches a+ certificate buffer, and the TCB-25 property tests now condition on the GUARD's verdict rather+ than on the test author's recollection of which names a variant mentions.- **TCB-27 (the emitter refuses rather than lies).** Before writing, the emitter runs the samesemantics the checker runs (`model.well_formed`, then `model.holds` on every axiom) and refuseson failure. A certificate that will not check is worse than no certificate.@@ -208,28 +266,35 @@ Lean parser is a second, independent RDF reader.## Status-| property | checked by | how |-|---|---|---|-| TCB-1 | `tests/certificate_boundary_proptest.rs`, `src/reason.rs` | property, end to end and on the writer |-| TCB-2, TCB-3 | same | property |-| TCB-4 | `tests/certificate_boundary_proptest.rs` | property, plus two deterministic tests: the parser refuses a separator inside an IRI, and Turtle's long-string form (which carries RAW control characters) comes back escaped |-| TCB-5 | proptest | property |-| TCB-6, TCB-7 | proptest | `asserted.tsv` is re-read through the N-Triples parser into a fresh store and compared |-| TCB-8 | proptest | property within a run; the across-run failure is pinned by a test that asserts the DEFECT, so the day it changes the documentation is forced to change |-| TCB-9 | deterministic test | a quad in two named graphs is two lines |-| TCB-10, TCB-11 | proptest | conclusions compared against the store's before and after |-| TCB-12 | proptest | both the built-in and the Horn path |-| TCB-13 | proptest | the name list is read out of `lean/OOCert/Rules.lean` at test time |-| **TCB-14** | `tests/lean_certificate_test.rs` | the real checker, over every rule. **Not** re-derived here |-| TCB-15, TCB-16, TCB-17 | `src/reason.rs` unit property tests | the interner is private |-| TCB-18 | in the code, and proptest | the engine re-parses what it wrote and refuses on mismatch |-| TCB-19, TCB-21 | proptest, plus the REAL checker | property against a transcription of `OOCert.HornParse` in the test file, because a Lean process per case is not a property test. The transcription's fidelity is then an assumption, so one deterministic test puts the adversarial shapes (a numeric rule name, a non-ASCII one, a `??x` variable, a literal spelled exactly like an IRI as a constant, a blank node, an empty-bodied rule) through `oo-horn check` itself and requires the conditional verdict |-| TCB-20, TCB-22 | proptest | render and parse are inverse, and no rendered line is empty |-| TCB-23, TCB-24 | proptest | the substitution is re-applied from `rules.tsv` independently of the engine |-| TCB-25 | `src/tableaux.rs` unit property tests | `name_is_safe`, `concept_string` token counts, `axiom_line` field counts |-| **TCB-26** | nothing | the argument that `names` covers `model.ind` is two loops agreeing |-| TCB-27 | in the code | `tests/dl_model_certificate_test.rs` exercises it; not property-tested |-| **TCB-28, TCB-29** | nothing here | the SHACL boundary is different in kind, see below |+The `level` column is the point of this table. **proved** means a bounded model checker verified the+statement over every input up to a stated bound; **enforced** means the engine refuses rather than+relies on something being true; **property** means a generator samples it; **argued** means a reading+of the code with nothing checking it. Nothing here is unbounded-verified, and a reader quoting+"proved" off this table without the bound in the section below is misquoting it.++| property | level | checked by | how |+|---|---|---|---|+| TCB-1 | **proved** + property | five Kani harnesses, `tests/certificate_boundary_proptest.rs`, `src/reason.rs` | the byte layout at term lengths 0 to 4, plus the property end to end and on the writer |+| TCB-2, TCB-3 | **proved** + property | four Kani harnesses, same tests | as above at lengths 0, 2, 3 and 4 |+| TCB-4 | **proved** + **enforced** | `kani_harnesses::term_guard_admits_no_separator_at_3` and `_at_6`, `term_fits_the_format` | the writers refuse a term carrying a separator; the harness states "no separator anywhere" over a symbolic index. Two deterministic tests remain: the parser refuses a separator inside an IRI, and Turtle's long-string form (which carries RAW control characters) comes back escaped |+| TCB-5 | **proved** + **enforced** | `kani_harnesses::term_guard_separates_the_three_spellings` | an accepted term is exactly one of the three N-Triples kinds, and the kind is its leading byte |+| TCB-6, TCB-7 | property | proptest | `asserted.tsv` is re-read through the N-Triples parser into a fresh store and compared |+| TCB-8 | **enforced** + property | `GraphStore::triples_outside`, proptest | the certified paths do not read `INFERRED_GRAPH` and report the graphs they did read; within a run the property is sampled; the DefaultGraph merge is pinned in the same test as the leak it still is |+| TCB-9 | deterministic test | | a quad in two named graphs is two lines |+| TCB-10, TCB-11 | property | proptest | conclusions compared against the store's before and after |+| TCB-12 | property | proptest | both the built-in and the Horn path |+| TCB-13 | property | proptest | the name list is read out of `lean/OOCert/Rules.lean` at test time |+| TCB-14 | **enforced** | `BUILTIN_RULES`, `tests/premise_order_test.rs` | 27 of 31 sites get the order from one table; that table is compared with the `checkStep` arms parsed out of `Rules.lean`. `tests/lean_certificate_test.rs` still runs the real checker over the corpus |+| TCB-15, TCB-16, TCB-17 | property | `src/reason.rs` unit property tests | the interner is private |+| TCB-18 | **enforced** + property | in the code, and proptest | the engine re-parses what it wrote and refuses on mismatch |+| TCB-19, TCB-21 | property | proptest, plus the REAL checker | property against a transcription of `OOCert.HornParse` in the test file, because a Lean process per case is not a property test. The transcription's fidelity is then an assumption, so one deterministic test puts the adversarial shapes (a numeric rule name, a non-ASCII one, a `??x` variable, a literal spelled exactly like an IRI as a constant, a blank node, an empty-bodied rule) through `oo-horn check` itself and requires the conditional verdict |+| TCB-20 | **proved** + property | `kani_harnesses::pat_of_and_render_are_inverse_at_2` and `_at_3`, proptest | `pat_of` and `Pat::render` are inverse over every byte pattern at two and three bytes. This is the harness the previous version of this page reported as NOT TERMINATING |+| TCB-22 | property | proptest | the rule index is a position in a list rendered in the same order, and no rendered line is empty |+| TCB-23, TCB-24 | property | proptest | the substitution is re-applied from `rules.tsv` independently of the engine |+| TCB-25 | **enforced** + property | `name_is_safe`, `src/tableaux.rs` unit property tests | the emitter refuses; `concept_string` token counts and `axiom_line` field counts are sampled |+| TCB-26 | **enforced** | `push_name`, `tcb_26_only_push_name_writes_a_name` | the guard is the write, and a source-level test fails if any other `resolve` reaches a certificate buffer |+| TCB-27 | **enforced** | in the code | the emitter runs the checker's own semantics and refuses; `tests/dl_model_certificate_test.rs` exercises it |+| **TCB-28, TCB-29** | nothing here | | the SHACL boundary is different in kind, see below |The generators build adversarial graphs (literals holding tabs, newlines, carriage returns, quotesand backslashes; a lexical form spelled exactly like an IRI; a lexical form spelled exactly like a@@ -242,48 +307,78 @@ leg puts the adversarial shapes through `oo-horn check` itself. Until 15 Septembinvoked it: the `build` job ran it with no lake and it skipped, and the `lean` job, which has lake,never named it. It is now a strict leg of the `lean` job under `OO_REQUIRE_FIXTURES=1`, so theskip is a failure there, and so are `reason_rl_coverage_test`, `rule_syntax_frontend_test` and-`reason_horn_emit_test`, which were in the same position. `docs/ci-gates.md` is the table of which-gate runs where, and Kani is still in no job at all, which is why the section below reports its-results rather than pointing at a build.+`reason_horn_emit_test`, which were in the same position. `tests/premise_order_test.rs` needs no+toolchain at all, because it READS `lean/OOCert/Rules.lean` rather than building it, so TCB-14 is+gated in every job that runs `cargo test`. `docs/ci-gates.md` is the table of which gate runs where,+and Kani is still in no job at all, which is why the section below reports its results rather than+pointing at a build.### Bounded model checkingKani 0.67.0 installed and ran here, on `nightly-2025-11-21-aarch64-apple-darwin`, over the whole-crate. Three harnesses in `src/reason.rs` prove the serialisation properties over every byte pattern-at a fixed shape, rather than over the patterns a generator drew. A fourth was written and does not-terminate; it is reported below rather than quietly dropped. `make verify` runs the three. None are-part of `make check`, because Kani pulls its own toolchain and the same statements are sampled by+crate. Fifteen harnesses in `src/reason.rs` prove the serialisation properties over every byte+pattern at a stated length, rather than over the patterns a generator drew. `make verify` runs all+fifteen; it used to run three of four, because the fourth did not terminate. None are part of+`make check`, because Kani pulls its own toolchain and the same statements are sampled by`cargo test` for anyone without it.| harness | property | result ||---|---|---|-| `asserted_line_round_trips` | TCB-1 | SUCCESSFUL, 1476 checks, 0 failed, 12.8s |-| `triple_fields_append_exactly_three` | TCB-2, TCB-3 | SUCCESSFUL, 1485 checks, 0 failed, 32.5s |-| `writable_triple_decides_both_positions` | the guard that fixed the defect below | SUCCESSFUL, 198 checks, 0 failed, 1.6s |-| `parse_pat_and_render_are_inverse` | TCB-20 | **NO VERDICT.** Abandoned at 14 minutes and 9.5 GB |--**The one that failed to run.** `parse_pat` returns `anyhow::Result` and every refusal formats a-message naming the line and the position, so the function body carries the whole formatting-machinery. CBMC flattens a function before it solves, so an `assume` that makes the refusal paths-infeasible is a constraint for the solver and not a cut in the program: constraining the input made-it worse, not better. Measured, with nothing else competing: four unconstrained ASCII bytes, no-verdict at 7 minutes and 3.0 GB; two bytes, no verdict at 8 minutes and 2.8 GB; two bytes with the-first constrained to the three spellings the function accepts, no verdict at 14 minutes and 9.5 GB.-It is excluded from `make verify`, because a target that hangs is worse than one that is honest-about its coverage, and the property is sampled instead (1024 cases on the function, plus whole-rule tables in the integration suite). What would close it is lifting the classification out of-`parse_pat` into a pure `Option<Pat>` function, leaving the messages where they are. That is a-refactor of shipped code and it was not made here.--**What the bounds are, and they are real.** In the three that verify, terms are a FIXED three bytes,-each byte unconstrained ASCII. The length is fixed rather than symbolic because a symbolic length-makes every offset in the line symbolic and every slice bound a case split: at two bytes per term-with a symbolic length, CBMC reached fifteen gigabytes without a verdict. So the harnesses prove-every byte pattern at one shape, and the property tests sample the shapes, including the empty-string. Neither alone is the whole claim, and anyone quoting "verified" off this table without the-bound is misquoting it.--Two other costs were paid down rather than hidden, because both are the kind of thing that makes a+| `asserted_line_round_trips_at_0` | TCB-1, TCB-4 | SUCCESSFUL, 646 checks, 0 failed, 3.6s |+| `asserted_line_round_trips_at_1` | TCB-1, TCB-4 | SUCCESSFUL, 652 checks, 0 failed, 5.4s |+| `asserted_line_round_trips_at_2` | TCB-1, TCB-4 | SUCCESSFUL, 652 checks, 0 failed, 6.3s |+| `asserted_line_round_trips_at_3` | TCB-1, TCB-4 | SUCCESSFUL, 652 checks, 0 failed, 7.0s |+| `asserted_line_round_trips_at_4` | TCB-1, TCB-4 | SUCCESSFUL, 652 checks, 0 failed, 7.8s |+| `triple_fields_append_exactly_three_at_0` | TCB-2, TCB-3, TCB-4 | SUCCESSFUL, 647 checks, 0 failed, 3.5s |+| `triple_fields_append_exactly_three_at_2` | TCB-2, TCB-3, TCB-4 | SUCCESSFUL, 653 checks, 0 failed, 6.2s |+| `triple_fields_append_exactly_three_at_3` | TCB-2, TCB-3, TCB-4 | SUCCESSFUL, 653 checks, 0 failed, 7.0s |+| `triple_fields_append_exactly_three_at_4` | TCB-2, TCB-3, TCB-4 | SUCCESSFUL, 653 checks, 0 failed, 7.7s |+| `term_guard_admits_no_separator_at_3` | TCB-4 | SUCCESSFUL, 131 checks, 0 failed, 0.3s |+| `term_guard_admits_no_separator_at_6` | TCB-4 | SUCCESSFUL, 131 checks, 0 failed, 0.4s |+| `term_guard_separates_the_three_spellings` | TCB-5 | SUCCESSFUL, 264 checks, 0 failed, 1.1s |+| `pat_of_and_render_are_inverse_at_2` | TCB-20 | SUCCESSFUL, 585 checks, 0 failed, 4.2s |+| `pat_of_and_render_are_inverse_at_3` | TCB-20 | SUCCESSFUL, 585 checks, 0 failed, 4.6s |+| `writable_triple_decides_both_positions` | the guard that fixed the defect below | SUCCESSFUL, 198 checks, 0 failed, 0.5s |++15 harnesses, 7754 checks, 0 failed, 66s of solver time in total.++**What changed on 15 September 2026.**++- **The writers now decide, so the harnesses prove the decision.** They used to `assume` that no+ term carried a separator, because nothing in this repository enforced it: it was a fact about+ `oxrdf` and `oxiri`. `term_fits_the_format` is now the predicate and the writers return+ `Err(Position)`, so the assumption became a branch of the function under test: the harnesses prove+ `Ok` exactly when all three terms pass, the byte layout when it is `Ok`, and an untouched buffer+ when it is not.+- **The harness that did not terminate, terminates.** The previous version of this page reported+ `parse_pat_and_render_are_inverse` as NO VERDICT, abandoned at 14 minutes and 9.5 GB, and named+ what would close it: "lifting the classification out of `parse_pat` into a pure `Option<Pat>`+ function, leaving the messages where they are. That is a refactor of shipped code and it was not+ made here." It was made here. `pat_of` is that function, `parse_pat` is now `pat_of` plus the same+ three messages, and `Pat::render` builds its string instead of `format!`-ing it for the same+ reason. The harness verifies in about four seconds. The measurements that motivated it are kept on+ the harness in the source, because the next person to write one against an `anyhow`-returning+ function should not have to rediscover why it is hard.+- **A bound that was too low was found by raising it.** The byte-scan loops run `3N+3` or `3N+4`+ times, so at four bytes per term the second needs seventeen unwindings and had sixteen. CBMC+ reported `1 of 653 failed (652 undetermined)`, which is its own unwinding assertion, and it was+ found+ because `cargo kani --harness NAME` selects by SUBSTRING, so the bare name ran all five length+ instantiations together and one of them failed inside a run reported under another heading. Every+ harness now has a full name ending in its length, and the bound is 24. A verification target that+ reports a failure under the wrong name is worse than one that does not run.++**What the bounds are, and they are real.** Terms are a FIXED number of bytes, each byte+unconstrained ASCII, and the harnesses are instantiated at several lengths rather than one: 0, 1, 2,+3 and 4 for the asserted line, 0, 2, 3 and 4 for the triple fields, 3 and 6 for the term guard, 2 and+3 for the rule-table position. The length is fixed rather than symbolic because a symbolic `n` makes+every offset in the line symbolic and every slice bound a case split, and the cost compounds across+three terms: two bytes per term with a symbolic length reached fifteen gigabytes without a verdict.+So these prove every byte pattern at each of those lengths, and the property tests sample the+lengths beyond them. Neither alone is the whole claim, and anyone quoting "verified" off this table+without the bound is misquoting it.++Two costs were paid down rather than hidden, because both are the kind of thing that makes averification effort quietly measure the wrong function:- `core::str::from_utf8` put CBMC inside `run_utf8_validation` once per buffer: seventeen minutes and@@ -298,10 +393,11 @@ verification effort quietly measure the wrong function:splitter needs and all it needs. The `split` formulation is kept as a property test, where it isfree.-The pattern in all three is the same, and it is the thing to take away from this section: twice, the-first formulation of a harness measured a function nobody asked about. A verification effort that-does not check what it is actually measuring produces a green result about the wrong thing, which is-the failure mode this whole layer exists to attack.+The pattern in all of these is one thing, and it is what to take away from this section: three+times, the first formulation of a harness measured a function nobody asked about, and once a green+result was reported under the wrong harness's name. A verification effort that does not check what+it is actually measuring produces a green result about the wrong thing, which is the failure mode+this whole layer exists to attack.### What this found@@ -340,65 +436,72 @@ central guard is the fix; the property test is what found the sites.## What is still trusted after all of this-This is the part that matters, and it is longer than the part that is checked. Nothing below is-verified. Each entry says what would close it.--1. **`oxrdf`'s escaping is the entire escaping layer.** `asserted.tsv` is safe because- `print_quoted_str` turns a tab inside a literal into `\t`. This repository has no escaper of its- own and never inspects a term. TCB-4 pins the behaviour a test can observe, which means an- upgrade that changed it would fail loudly; it does not mean it cannot change, and it does not- cover a term that reaches the store by a route the tests do not exercise.- *To close it:* escape at the certificate writer rather than relying on the term's `Display`, or- change the format to one that cannot be forged by its payload (length-prefixed, or JSON Lines).- Both are changes to `lean/`'s parsers as well, which is why neither was done here.-2. **`oxiri`'s IRI validation is why a separator cannot reach an IRI.** `NamedNodeRef`'s `Display`- is `write!(f, "<{}>", self.as_str())` with no escaping at all, so the only thing standing between- a tab and `asserted.tsv` is that the parser refused to build the IRI. Tens of thousands of lines- of parsing sit behind that sentence and none of it is verified here.- *To close it:* check the term at the writer, as in (1). The check is four lines; the reason it is- not there is that it would be a second place the question is decided.-3. **TCB-14, the premise ORDER per rule.** `OOCert.checkStep` matches premises positionally, arm by- arm, and the emitter passes them in a hand-written order at thirty-one call sites. The two agree- because `tests/lean_certificate_test.rs` walks every rule and the checker accepts. Nothing- derives one from the other, so a rule added with the wrong order fails at the checker rather than- at compile time. *To close it:* generate both sides from one table, which is what the Horn path- already does and the built-in path does not.-4. **TCB-26, the DL name guard's coverage.** `name_is_safe` is applied to a `names` vector built by- one loop; the files are written by another. Individuals in `model.ind` are covered only because- `DlAxiom::Indiv(i)` happens to be emitted for every individual that reaches the model.- *To close it:* check at the point of writing, not in a separate pass.-5. **TCB-8 across runs.** Materialising into the default graph turns an inference into the next- run's assertion, and `asserted.tsv` has no column that says "derived". `inference_graph: true`- does not fix it either: `GraphStore::all_triples` reads every named graph, so a later certified- run sees them as assertions. The separation protects `save`; it does not protect the certificate.- *To close it:* have the certified path read the asserted graph only, and say in the certificate- which graphs it read.-6. **Materialisation is not atomic, and that is now latent rather than fixed.** `GraphStore::- load_lines` runs `for quad in parser { store.insert(&quad?)?; }`, so a parse error partway- through a batch leaves everything before it inserted and propagates the error. That is what- turned the `rdfs7` defect from a crash into uncertified triples in the store. `writable_triple`- removes the only way the reasoner could hand it an unparseable line, so the path is unreachable- TODAY; the hazard is still there for any future caller.+This is the part that matters. Nothing below is verified. Each entry says what would close it. It+was ten entries on 14 September 2026 and it is six, because four of them were closed rather than+re-worded: the two that rested on `oxrdf` and `oxiri`, the premise order, and the DL name guard's+coverage.++1. **TCB-6 and TCB-7, that `asserted.tsv` IS the store's contents.** The engine reads the store,+ interns what it reads, and writes the interned strings back out. Nothing between the store and+ the file checks that the file is the store. `tests/certificate_boundary_proptest.rs` re-reads+ `asserted.tsv` through the N-Triples parser into a fresh store and compares the two, over+ adversarial graphs, which is the strongest thing a test can do here and is not a proof. This is+ the unsafe direction: an extra line is an axiom nobody asserted, and every conclusion resting on+ it is certified against a graph that does not exist.+ *To close it:* nothing pure-functional reaches it. It is a statement about an execution over a+ store, so it needs either a verified store or a checker that can see the store, and neither+ exists.+2. **TCB-10, that `derivations.tsv` covers every triple the run added.** A triple materialised+ without a line covering it sits in the store under the certificate's cover. The argument is that+ the single `emit` closure is the only path that pushes a candidate and records the first+ derivation of anything not already in the closure. That argument is now shorter than it was,+ because `emit` computes the conclusion from the rule table rather than taking one from the call+ site, so a site cannot push a triple the table does not license. It is still a reading of a loop+ plus a property test comparing conclusions against the store's before and after.+ *To close it:* the same obstacle as (1). It is a property of the run, not of a function.+3. **TCB-19 and TCB-21, that the two rule-table parsers agree.** `parse_rules` in Rust and+ `OOCert.HornParse.parseRules` in Lean are independent implementations of one grammar. The+ property test runs against a transcription of the Lean parser, and one deterministic test puts+ the adversarial shapes through `oo-horn check` itself. Measurement, not proof. TCB-18 and TCB-20+ are closed around it, because the engine re-parses what it wrote and refuses on mismatch and+ `pat_of`/`render` are proved inverse, so what is left is exactly the cross-language half.+ *To close it:* generate both parsers from one grammar, or verify the Rust one against the Lean+ one as a refinement. Neither was done here.+4. **TCB-8 under `InferenceTarget::DefaultGraph`.** Merging conclusions into the default graph is+ what the caller asked for and it loses the distinction; a later certified run over that store is+ conditional on a graph that includes inferences. The named-graph path no longer has this problem.+ *To close it:* there is nothing to close in this layer. The caller chooses, and+ `inference_graph: true` is the choice that keeps the certificate honest.+5. **Materialisation is not atomic, and that is latent rather than fixed.** `GraphStore::load_lines`+ runs `for quad in parser { store.insert(&quad?)?; }`, so a parse error partway through a batch+ leaves everything before it inserted and propagates the error. That is what turned the `rdfs7`+ defect from a crash into uncertified triples in the store. `writable_triple` removes the only way+ the reasoner could hand it an unparseable line, so the path is unreachable TODAY; the hazard is+ still there for any future caller.*To close it:* insert into a transaction, or build the batch through a serialiser that cannotproduce an unparseable line rather than through string concatenation.-7. **The reasoner's completeness.** The checker proves each recorded step is a sound instance of a- rule it knows. It says nothing about whether the engine found every inference, so a certificate- is evidence about what was derived and not about what follows.-8. **The SHIQ tableaux reasoner.** Model certificates cover positive satisfiability answers only.- Unsatisfiability and inconsistency carry no certificate at all, and those are the answers a- consistency check is usually asked for.-9. **The Rust SHACL validator (TCB-28, TCB-29).** Not certified. `oo-shacl` is a second, verified- evaluator that the Rust one is measured against; a measurement is not a proof, and the two read- RDF with two different parsers whose agreement is by construction on both sides rather than by a- check.-10. **Everything between the store and the certificate that is not a term:** the SPARQL layer, the- MCP server, the CLI, the daemon, the file I/O, the roughly fifty thousand lines of `src/`. The- Kani harnesses cover four pure functions totalling about twenty lines. That is the correct- proportion to report: this work verified the joint, not the machine.--The honest summary is that the trusted base is four things: the serialisation of a term, the+6. **Everything that is not the certificate boundary at all.** The reasoner's COMPLETENESS: the+ checker proves each recorded step is a sound instance of a rule it knows and says nothing about+ whether the engine found every inference, so a certificate is evidence about what was derived and+ not about what follows. The SHIQ tableaux reasoner: model certificates cover positive+ satisfiability answers only, and unsatisfiability and inconsistency carry no certificate at all.+ The Rust SHACL validator (TCB-28, TCB-29): not certified, measured against a second verified+ evaluator, and the two read RDF with two different parsers whose agreement is by construction on+ both sides rather than by a check. And the SPARQL layer, the MCP server, the CLI, the daemon, the+ file I/O, the roughly fifty thousand lines of `src/`. The Kani harnesses cover five pure+ functions totalling about sixty lines. That is the correct proportion to report: this work+ verified the joint, not the machine.++The honest summary is that the trusted base used to be four things: the serialisation of a term, theidentity of the asserted graph, the completeness of the derivation record, and the identity of the-rule table. Those are now property-tested and, for the pure parts, bounded-model-checked. Every one-of them still rests on a dependency's behaviour that this repository observes rather than enforces.-The engine is not verified. It was never going to be, and a report that read as though it were-would be the same defect this project exists to attack.+rule table. The serialisation of a term is no longer one of them: it is enforced here and proved+over every byte pattern at the bounds below, rather than observed of a dependency. The identity of+the rule table is most of the way off the list: the engine re-parses what it wrote and refuses on+mismatch, and the render-parse round trip is proved; what is left is two independent parsers of one+grammar, which is a different kind of risk from an engine misreporting its own run.++**So it is two things.** That `asserted.tsv` is the graph the engine reasoned over, and that+`derivations.tsv` covers every triple it added. Both are statements about an execution rather than+about a function, which is why no amount of bounded model checking reaches them, and both are+property-tested end to end against the store. The engine is not verified. It was never going to be,+and a report that read as though it were would be the same defect this project exists to attack.diff --git a/src/graph.rs b/src/graph.rsindex 07da2347..7503927c 100644--- a/src/graph.rs+++ b/src/graph.rs@@ -58,6 +58,15 @@ impl SparqlAuth {}}+/// What [`GraphStore::triples_outside`] returns: the triples, and the names of+/// the graphs they came from.+///+/// The second half is not decoration. A certificate that says which graphs its+/// assertions came from can be checked against the store; one that does not+/// cannot, and `asserted.tsv` has no column that says "derived". See TCB-8 in+/// `docs/trusted-computing-base.md`.+pub type AssertedTriples = (Vec<(String, String, String)>, Vec<String>);+/// In-memory RDF graph store backed by Oxigraph.////// The store is held directly rather than behind a `Mutex`. Oxigraph's `Store`@@ -710,6 +719,13 @@ impl GraphStore {}/// Extract all triples as (subject, predicate, object) string tuples.+ ///+ /// EVERY graph, the default one and every named one, flattened. A caller+ /// that is going to treat what it gets back as ASSERTED wants+ /// [`triples_outside`](Self::triples_outside) instead: this method cannot+ /// tell an assertion from a triple some earlier run of the reasoner parked+ /// in a named graph, and the certificate layer's soundness theorem is+ /// conditional on the assertions.pub fn all_triples(&self) -> anyhow::Result<Vec<(String, String, String)>> {let store = &self.store;let mut triples = Vec::new();@@ -723,6 +739,48 @@ impl GraphStore {Ok(triples)}+ /// Every triple in the store EXCEPT those in the named graphs listed, in+ /// the same spelling [`all_triples`](Self::all_triples) yields, together+ /// with the names of the graphs that were read.+ ///+ /// See [`AssertedTriples`] for the pair it returns.+ ///+ /// This exists for the certified reasoning paths and it closes a real+ /// defect. `onto_reason` with `inference_graph: true` parks its conclusions+ /// in `https://open-ontologies.org/graph/inferred` so that nothing+ /// downstream reads an inference as an assertion, but the reasoner is+ /// itself downstream: `all_triples` reads every named graph, so a second+ /// certified run listed the first run's conclusions in `asserted.tsv` as+ /// axioms, with no column saying they were derived. The separation+ /// protected `save` and not the certificate. See TCB-8 in+ /// `docs/trusted-computing-base.md`.+ ///+ /// The graph names are returned because a certificate that says which+ /// graphs it read is checkable against the store, and one that does not is+ /// not. `<default>` is the unnamed graph.+ pub fn triples_outside(&self, excluded: &[&str]) -> anyhow::Result<AssertedTriples> {+ let mut triples = Vec::new();+ let mut read: BTreeSet<String> = BTreeSet::new();+ for quad in self.store.iter() {+ let quad = quad?;+ let name = match &quad.graph_name {+ GraphName::DefaultGraph => "<default>".to_string(),+ GraphName::NamedNode(n) => n.as_str().to_string(),+ GraphName::BlankNode(b) => format!("_:{}", b.as_str()),+ };+ if excluded.iter().any(|e| *e == name) {+ continue;+ }+ read.insert(name);+ triples.push((+ quad.subject.to_string(),+ quad.predicate.to_string(),+ quad.object.to_string(),+ ));+ }+ Ok((triples, read.into_iter().collect()))+ }+/// Copy one named graph of this store into a fresh store's DEFAULT graph,/// by model term.///diff --git a/src/reason.rs b/src/reason.rsindex ecad9591..56c717d2 100644--- a/src/reason.rs+++ b/src/reason.rs@@ -446,6 +446,81 @@ fn writable_triple(subject: &str, predicate: &str) -> bool {!subject.starts_with('"') && predicate.starts_with('<')}+/// Which position of a certificate line refused to be written.+///+/// Deliberately a bare enum and not an `anyhow::Error`. The writers below are+/// the functions the Kani harnesses at the bottom of this file prove things+/// about, and a formatted error inside a function is what put CBMC inside the+/// formatting machinery and killed the first `parse_pat` harness. The message a+/// user reads is built by the caller, from this and the term.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Position {+ Subject,+ Predicate,+ Object,+}++impl Position {+ fn name(self) -> &'static str {+ match self {+ Position::Subject => "subject",+ Position::Predicate => "predicate",+ Position::Object => "object",+ }+ }+}++/// Whether a term can be written to a certificate file without forging it.+///+/// This is TCB-4 and TCB-5, enforced here rather than observed of `oxrdf`.+///+/// The files are tab separated with one record per line and have no escaping+/// layer of their own, so a term carrying a tab gains a field, a term carrying a+/// newline splits a record in two, and either forges a triple the store never+/// held. Until 15 September 2026 the only thing standing between a tab and+/// `asserted.tsv` was `oxrdf`'s `print_quoted_str` for a literal and `oxiri`+/// refusing to parse for an IRI: `NamedNodeRef`'s `Display` is+/// `write!(f, "<{}>", self.as_str())` and escapes nothing at all. That is a+/// dependency's behaviour, pinned by a test that an upgrade would break loudly+/// but that cannot make it hold. This function makes it hold, in the refusing+/// direction: a term that does not fit the format means no certificate, not a+/// certificate a reader cannot trust.+///+/// The leading-byte condition is TCB-5. A literal is quoted and an IRI is+/// bracketed, so a literal whose lexical form is spelled exactly like an IRI+/// cannot collide with that IRI in a file where the two checkers compare terms+/// as opaque strings. Every term `GraphStore::all_triples` yields satisfies it+/// (`oxrdf`'s `Display` brackets a `NamedNode`, prefixes a `BlankNode` with+/// `_:` and quotes a `Literal`), and so does every constant `parse_pat` accepts,+/// so this refuses nothing the engine has any business writing.+fn term_fits_the_format(t: &str) -> bool {+ if !field_fits_the_format(t) {+ return false;+ }+ let b = t.as_bytes();+ b[0] == b'<' || b[0] == b'"' || (b[0] == b'_' && b.len() > 1 && b[1] == b':')+}++/// The half of [`term_fits_the_format`] that is about the FORMAT and not about+/// N-Triples: a field is non-empty and carries no separator.+///+/// `horn.tsv` also writes variable names, which are not terms and have no+/// N-Triples spelling, and this is what they have to satisfy.+fn field_fits_the_format(f: &str) -> bool {+ let b = f.as_bytes();+ if b.is_empty() {+ return false;+ }+ let mut i = 0;+ while i < b.len() {+ if b[i] == b'\t' || b[i] == b'\n' || b[i] == b'\r' {+ return false;+ }+ i += 1;+ }+ true+}+/// Append one line of `asserted.tsv`: `s TAB p TAB o NEWLINE`.////// This is the whole of that file's grammar, and it is the narrowest point of@@ -455,24 +530,394 @@ fn writable_triple(subject: &str, predicate: &str) -> bool {/// in one function so that the claim "a line is exactly three fields" is a/// claim about one place, verified in `kani_harnesses` below rather than only/// sampled.-fn push_asserted_line(out: &mut String, s: &str, p: &str, o: &str) {+///+/// Every term is checked BEFORE anything is appended, so a refusal leaves `out`+/// byte for byte as it was. A writer that appended a subject and then refused+/// the object would leave a half-line in the buffer, which is the same defect+/// the non-atomic materialiser had.+fn push_asserted_line(out: &mut String, s: &str, p: &str, o: &str) -> Result<(), Position> {+ if !term_fits_the_format(s) {+ return Err(Position::Subject);+ }+ if !term_fits_the_format(p) {+ return Err(Position::Predicate);+ }+ if !term_fits_the_format(o) {+ return Err(Position::Object);+ }out.push_str(s);out.push('\t');out.push_str(p);out.push('\t');out.push_str(o);out.push('\n');+ Ok(())}/// Append a triple as three further fields of a line already begun, the shape-/// `derivations.tsv` and `horn.tsv` use after their header fields.-fn push_triple_fields(out: &mut String, s: &str, p: &str, o: &str) {+/// `derivations.tsv` and `horn.tsv` use after their header fields. Same guard+/// and same all-or-nothing discipline as [`push_asserted_line`].+fn push_triple_fields(out: &mut String, s: &str, p: &str, o: &str) -> Result<(), Position> {+ if !term_fits_the_format(s) {+ return Err(Position::Subject);+ }+ if !term_fits_the_format(p) {+ return Err(Position::Predicate);+ }+ if !term_fits_the_format(o) {+ return Err(Position::Object);+ }out.push('\t');out.push_str(s);out.push('\t');out.push_str(p);out.push('\t');out.push_str(o);+ Ok(())+}++// ─────────────────────────────────────────────────────────────────────────────+// The built-in rules, as data+//+// TCB-14 used to read: "`OOCert.checkStep` pattern-matches the premises+// positionally per rule. The emitter passes them in a hand-written order at+// each of the thirty-one `emit` call sites. A wrong order is a rejection, not a+// false pass, and `tests/lean_certificate_test.rs` covers every rule, but+// nothing derives the order from a single source."+//+// This is the single source. Each rule is a pattern over numbered variables,+// in the order `lean/OOCert/Rules.lean` matches them, and the emitter computes+// both the premise list AND the conclusion from it. A call site supplies the+// BINDING and nothing else, so it has no order to get wrong: the twenty-seven+// fixed-arity rules cannot drift from the checker by a mistake at the site.+// `tests/lean_certificate_test.rs` still runs the real checker over the corpus,+// and `tests/premise_order_test.rs` parses the arms out of `Rules.lean` and+// compares them with this table, so a change to either side that the other does+// not follow fails at `cargo test` rather than at a user's certificate.+//+// The four list rules (`cls-int1`, `cls-int2`, `cls-uni`, `cls-oo`) are not+// here. Their premises include an RDF list chain whose length is the length of+// the list, so they are not a fixed pattern and the checker matches them with+// `takeChain` rather than positionally. They keep an explicit premise vector+// and say so at the site.+// ─────────────────────────────────────────────────────────────────────────────++/// A vocabulary term a built-in rule's pattern fixes.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Kw {+ Type,+ SubClassOf,+ SubPropertyOf,+ Domain,+ Range,+ SameAs,+ InverseOf,+ TransitiveProperty,+ SymmetricProperty,+ EquivalentClass,+ EquivalentProperty,+ OnProperty,+ SomeValuesFrom,+ AllValuesFrom,+ HasValue,+}++impl Kw {+ /// The IRI, in the N-Triples spelling the store uses. Reading this out is+ /// how `tests/premise_order_test.rs` maps a `V.foo` in the Lean source onto+ /// a row of this table.+ pub fn iri(self) -> &'static str {+ match self {+ Kw::Type => RDF_TYPE,+ Kw::SubClassOf => RDFS_SUBCLASS,+ Kw::SubPropertyOf => RDFS_SUBPROP,+ Kw::Domain => RDFS_DOMAIN,+ Kw::Range => RDFS_RANGE,+ Kw::SameAs => OWL_SAMEAS,+ Kw::InverseOf => OWL_INVERSE,+ Kw::TransitiveProperty => OWL_TRANSITIVE,+ Kw::SymmetricProperty => OWL_SYMMETRIC,+ Kw::EquivalentClass => OWL_EQUIV_CLASS,+ Kw::EquivalentProperty => OWL_EQUIV_PROP,+ Kw::OnProperty => OWL_ON_PROPERTY,+ Kw::SomeValuesFrom => OWL_SOME_VALUES,+ Kw::AllValuesFrom => OWL_ALL_VALUES,+ Kw::HasValue => OWL_HAS_VALUE,+ }+ }++ /// The name `lean/OOCert/Semantics.lean` gives it, without the `V.`.+ pub fn lean_name(self) -> &'static str {+ match self {+ Kw::Type => "type",+ Kw::SubClassOf => "subClassOf",+ Kw::SubPropertyOf => "subPropertyOf",+ Kw::Domain => "domain",+ Kw::Range => "range",+ Kw::SameAs => "sameAs",+ Kw::InverseOf => "inverseOf",+ Kw::TransitiveProperty => "transitiveProperty",+ Kw::SymmetricProperty => "symmetricProperty",+ Kw::EquivalentClass => "equivalentClass",+ Kw::EquivalentProperty => "equivalentProperty",+ Kw::OnProperty => "onProperty",+ Kw::SomeValuesFrom => "someValuesFrom",+ Kw::AllValuesFrom => "allValuesFrom",+ Kw::HasValue => "hasValue",+ }+ }+}++/// One position of a built-in rule's pattern: a slot in the binding, or a+/// vocabulary term the rule fixes.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Slot {+ Var(usize),+ Fixed(Kw),+}++const V0: Slot = Slot::Var(0);+const V1: Slot = Slot::Var(1);+const V2: Slot = Slot::Var(2);+const V3: Slot = Slot::Var(3);+const V4: Slot = Slot::Var(4);+const TYPE: Slot = Slot::Fixed(Kw::Type);+const SUBCLASS: Slot = Slot::Fixed(Kw::SubClassOf);+const SUBPROP: Slot = Slot::Fixed(Kw::SubPropertyOf);+const DOMAIN: Slot = Slot::Fixed(Kw::Domain);+const RANGE: Slot = Slot::Fixed(Kw::Range);+const SAMEAS: Slot = Slot::Fixed(Kw::SameAs);+const INVERSE: Slot = Slot::Fixed(Kw::InverseOf);+const TRANSITIVE: Slot = Slot::Fixed(Kw::TransitiveProperty);+const SYMMETRIC: Slot = Slot::Fixed(Kw::SymmetricProperty);+const EQ_CLASS: Slot = Slot::Fixed(Kw::EquivalentClass);+const EQ_PROP: Slot = Slot::Fixed(Kw::EquivalentProperty);+const ON_PROP: Slot = Slot::Fixed(Kw::OnProperty);+const SVF: Slot = Slot::Fixed(Kw::SomeValuesFrom);+const AVF: Slot = Slot::Fixed(Kw::AllValuesFrom);+const HAS_VALUE: Slot = Slot::Fixed(Kw::HasValue);++/// A built-in rule with a fixed premise arity, as a pattern.+pub struct BuiltinRule {+ /// The rule id written into `derivations.tsv`, which `OOCert.Rule.ofName?`+ /// has to accept. Two rows may share a name: `scm-eqc1` and `scm-eqp1` each+ /// license two conclusions from one premise, and the checker accepts+ /// either.+ pub name: &'static str,+ /// Names for the binding slots, for readability and for the error a+ /// mis-sized binding produces. The LENGTH is the arity.+ pub vars: &'static [&'static str],+ /// The premises, in the order the checker matches them.+ pub body: &'static [[Slot; 3]],+ pub head: [Slot; 3],+}++/// The rows of [`BUILTIN_RULES`], by name, so a call site names a rule rather+/// than an index. `builtin_rule_table_is_indexed_by_its_enum` pins the+/// correspondence.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Rl {+ Rdfs2,+ Rdfs3,+ Rdfs5,+ Rdfs7,+ Rdfs9,+ Rdfs11,+ PrpTrp,+ PrpSymp,+ PrpInv1,+ PrpInv2,+ EqSym,+ ScmEqc1Fwd,+ ScmEqc1Rev,+ ScmEqp1Fwd,+ ScmEqp1Rev,+ ClsSvf1,+ ClsAvf,+ ClsHv1,+ ClsHv2,+ ScmSvf1,+ ScmSvf2,+ ScmAvf1,+ ScmAvf2,+ ScmDom1,+ ScmDom2,+ ScmRng1,+ ScmRng2,+}++impl Rl {+ /// Every row, in table order. `each_row_is_at_its_own_index` pins that+ /// `Rl::X as usize` really is the index of `X`'s row, which is the whole+ /// basis of `BUILTIN_RULES[r as usize]`.+ pub const ALL: &'static [Rl] = &[+ Rl::Rdfs2, Rl::Rdfs3, Rl::Rdfs5, Rl::Rdfs7, Rl::Rdfs9, Rl::Rdfs11,+ Rl::PrpTrp, Rl::PrpSymp, Rl::PrpInv1, Rl::PrpInv2, Rl::EqSym,+ Rl::ScmEqc1Fwd, Rl::ScmEqc1Rev, Rl::ScmEqp1Fwd, Rl::ScmEqp1Rev,+ Rl::ClsSvf1, Rl::ClsAvf, Rl::ClsHv1, Rl::ClsHv2,+ Rl::ScmSvf1, Rl::ScmSvf2, Rl::ScmAvf1, Rl::ScmAvf2,+ Rl::ScmDom1, Rl::ScmDom2, Rl::ScmRng1, Rl::ScmRng2,+ ];+}++/// Every fixed-arity built-in rule, in `Rl` order.+///+/// Read this against the table in the module docstring of+/// `lean/OOCert/Rules.lean`. They are the same table; `tests/premise_order_test.rs`+/// checks that mechanically against the `checkStep` arms rather than against+/// the prose.+pub const BUILTIN_RULES: &[BuiltinRule] = &[+ BuiltinRule { name: "rdfs2", vars: &["s", "p", "o", "c"],+ body: &[[V0, V1, V2], [V1, DOMAIN, V3]], head: [V0, TYPE, V3] },+ BuiltinRule { name: "rdfs3", vars: &["s", "p", "o", "c"],+ body: &[[V0, V1, V2], [V1, RANGE, V3]], head: [V2, TYPE, V3] },+ BuiltinRule { name: "rdfs5", vars: &["a", "b", "c"],+ body: &[[V0, SUBPROP, V1], [V1, SUBPROP, V2]], head: [V0, SUBPROP, V2] },+ BuiltinRule { name: "rdfs7", vars: &["s", "p", "o", "q"],+ body: &[[V0, V1, V2], [V1, SUBPROP, V3]], head: [V0, V3, V2] },+ BuiltinRule { name: "rdfs9", vars: &["x", "a", "b"],+ body: &[[V0, TYPE, V1], [V1, SUBCLASS, V2]], head: [V0, TYPE, V2] },+ BuiltinRule { name: "rdfs11", vars: &["a", "b", "c"],+ body: &[[V0, SUBCLASS, V1], [V1, SUBCLASS, V2]], head: [V0, SUBCLASS, V2] },+ BuiltinRule { name: "prp-trp", vars: &["p", "x", "y", "z"],+ body: &[[V0, TYPE, TRANSITIVE], [V1, V0, V2], [V2, V0, V3]], head: [V1, V0, V3] },+ BuiltinRule { name: "prp-symp", vars: &["p", "x", "y"],+ body: &[[V0, TYPE, SYMMETRIC], [V1, V0, V2]], head: [V2, V0, V1] },+ BuiltinRule { name: "prp-inv1", vars: &["p", "q", "x", "y"],+ body: &[[V0, INVERSE, V1], [V2, V0, V3]], head: [V3, V1, V2] },+ BuiltinRule { name: "prp-inv2", vars: &["p", "q", "x", "y"],+ body: &[[V0, INVERSE, V1], [V2, V1, V3]], head: [V3, V0, V2] },+ BuiltinRule { name: "eq-sym", vars: &["a", "b"],+ body: &[[V0, SAMEAS, V1]], head: [V1, SAMEAS, V0] },+ BuiltinRule { name: "scm-eqc1", vars: &["a", "b"],+ body: &[[V0, EQ_CLASS, V1]], head: [V0, SUBCLASS, V1] },+ BuiltinRule { name: "scm-eqc1", vars: &["a", "b"],+ body: &[[V0, EQ_CLASS, V1]], head: [V1, SUBCLASS, V0] },+ BuiltinRule { name: "scm-eqp1", vars: &["a", "b"],+ body: &[[V0, EQ_PROP, V1]], head: [V0, SUBPROP, V1] },+ BuiltinRule { name: "scm-eqp1", vars: &["a", "b"],+ body: &[[V0, EQ_PROP, V1]], head: [V1, SUBPROP, V0] },+ BuiltinRule { name: "cls-svf1", vars: &["r", "p", "c", "x", "y"],+ body: &[[V0, ON_PROP, V1], [V0, SVF, V2], [V3, V1, V4], [V4, TYPE, V2]],+ head: [V3, TYPE, V0] },+ BuiltinRule { name: "cls-avf", vars: &["r", "p", "c", "x", "y"],+ body: &[[V0, ON_PROP, V1], [V0, AVF, V2], [V3, TYPE, V0], [V3, V1, V4]],+ head: [V4, TYPE, V2] },+ BuiltinRule { name: "cls-hv1", vars: &["r", "p", "v", "x"],+ body: &[[V0, ON_PROP, V1], [V0, HAS_VALUE, V2], [V3, TYPE, V0]],+ head: [V3, V1, V2] },+ BuiltinRule { name: "cls-hv2", vars: &["r", "p", "v", "x"],+ body: &[[V0, ON_PROP, V1], [V0, HAS_VALUE, V2], [V3, V1, V2]],+ head: [V3, TYPE, V0] },+ BuiltinRule { name: "scm-svf1", vars: &["c1", "y1", "p", "c2", "y2"],+ body: &[[V0, SVF, V1], [V0, ON_PROP, V2], [V3, SVF, V4], [V3, ON_PROP, V2],+ [V1, SUBCLASS, V4]],+ head: [V0, SUBCLASS, V3] },+ BuiltinRule { name: "scm-svf2", vars: &["c1", "y", "p1", "c2", "p2"],+ body: &[[V0, SVF, V1], [V0, ON_PROP, V2], [V3, SVF, V1], [V3, ON_PROP, V4],+ [V2, SUBPROP, V4]],+ head: [V0, SUBCLASS, V3] },+ BuiltinRule { name: "scm-avf1", vars: &["c1", "y1", "p", "c2", "y2"],+ body: &[[V0, AVF, V1], [V0, ON_PROP, V2], [V3, AVF, V4], [V3, ON_PROP, V2],+ [V1, SUBCLASS, V4]],+ head: [V0, SUBCLASS, V3] },+ // The conclusion is the other way round, and it is the one place in this+ // table where that is true. A universal restriction is antitone in its+ // property, so `all p2 y` is the SMALLER class; writing this row the way+ // `scm-svf2` is written gives a step no model supports, and+ // `OOCert.the_natural_avf2_direction_is_not_entailed` is the refutation.+ BuiltinRule { name: "scm-avf2", vars: &["c1", "y", "p1", "c2", "p2"],+ body: &[[V0, AVF, V1], [V0, ON_PROP, V2], [V3, AVF, V1], [V3, ON_PROP, V4],+ [V2, SUBPROP, V4]],+ head: [V3, SUBCLASS, V0] },+ BuiltinRule { name: "scm-dom1", vars: &["p", "c1", "c2"],+ body: &[[V0, DOMAIN, V1], [V1, SUBCLASS, V2]], head: [V0, DOMAIN, V2] },+ BuiltinRule { name: "scm-dom2", vars: &["p2", "c", "p1"],+ body: &[[V0, DOMAIN, V1], [V2, SUBPROP, V0]], head: [V2, DOMAIN, V1] },+ BuiltinRule { name: "scm-rng1", vars: &["p", "c1", "c2"],+ body: &[[V0, RANGE, V1], [V1, SUBCLASS, V2]], head: [V0, RANGE, V2] },+ BuiltinRule { name: "scm-rng2", vars: &["p2", "c", "p1"],+ body: &[[V0, RANGE, V1], [V2, SUBPROP, V0]], head: [V2, RANGE, V1] },+];++/// The rule names the four list rules use. Not in [`BUILTIN_RULES`] because+/// their premises are a variable-length chain, listed here so a test can assert+/// that the two sets together are exactly the checker's rule set and that+/// nothing fell between them.+pub const CHAINED_RULES: &[&str] = &["cls-int1", "cls-int2", "cls-uni", "cls-oo"];++/// The interned id of each vocabulary term a rule pattern can fix.+struct RuleVocab {+ type_: u32,+ subclass: u32,+ subprop: u32,+ domain: u32,+ range: u32,+ sameas: u32,+ inverse: u32,+ transitive: u32,+ symmetric: u32,+ equiv_class: u32,+ equiv_prop: u32,+ on_property: u32,+ svf: u32,+ avf: u32,+ has_value: u32,+}++/// What a rule site hands the emitter.+///+/// `Bound` is a row of [`BUILTIN_RULES`] plus the binding for its variables:+/// the site chooses the terms, the table chooses the order and the conclusion.+/// `Chained` is one of the four list rules, whose premises are a constructor+/// triple, an RDF list chain of the list's own length, and the typings, and+/// which therefore has no fixed pattern to be a row of.+enum Fired<'a> {+ Bound(Rl, &'a [u32]),+ Chained(&'static str, Fact, &'a [Fact]),+}++impl RuleVocab {+ fn id(&self, k: Kw) -> u32 {+ match k {+ Kw::Type => self.type_,+ Kw::SubClassOf => self.subclass,+ Kw::SubPropertyOf => self.subprop,+ Kw::Domain => self.domain,+ Kw::Range => self.range,+ Kw::SameAs => self.sameas,+ Kw::InverseOf => self.inverse,+ Kw::TransitiveProperty => self.transitive,+ Kw::SymmetricProperty => self.symmetric,+ Kw::EquivalentClass => self.equiv_class,+ Kw::EquivalentProperty => self.equiv_prop,+ Kw::OnProperty => self.on_property,+ Kw::SomeValuesFrom => self.svf,+ Kw::AllValuesFrom => self.avf,+ Kw::HasValue => self.has_value,+ }+ }++ fn fill(&self, a: &[Slot; 3], b: &[u32]) -> Fact {+ let one = |s: Slot| match s {+ Slot::Var(i) => b[i],+ Slot::Fixed(k) => self.id(k),+ };+ (one(a[0]), one(a[1]), one(a[2]))+ }+}++/// The message a refused term produces. One place, so the four writers say the+/// same thing, and outside the functions Kani reasons about.+fn unwritable_term(file: &str, pos: Position, term: &str) -> anyhow::Error {+ anyhow::anyhow!(+ "internal: the {} of a triple bound for {file} is {term:?}, which does not fit the \+ certificate format: a term must be non-empty, must carry no tab, newline or carriage \+ return, and must be in N-Triples spelling (<iri>, _:blank or a quoted literal). Writing \+ it would let the term forge a field or a record, so no certificate was written. See \+ TCB-4 and TCB-5 in docs/trusted-computing-base.md",+ pos.name()+ )}/// Intern strings to u32 IDs for efficient reasoning.@@ -647,8 +1092,17 @@ impl Reasoner {let include_owl = profile_used == "owl-rl" || profile_used == "owl-rl-ext";let include_ext = profile_used == "owl-rl-ext";- // Extract and intern all triples- let raw_triples = graph.all_triples()?;+ // Extract and intern the ASSERTED triples.+ //+ // Every graph except [`INFERRED_GRAPH`], which is where this same+ // function parks its own conclusions when the caller asks for them to+ // be kept apart. Reading them back would make run N's conclusions run+ // N+1's axioms, and `asserted.tsv` has no column that says "derived",+ // so the certificate would be conditional on a graph that was never+ // asserted. Until 15 September 2026 it did exactly that and the defect+ // was pinned by a test rather than fixed; TCB-8 in+ // `docs/trusted-computing-base.md` has the history.+ let (raw_triples, graphs_read) = graph.triples_outside(&[INFERRED_GRAPH])?;let mut interner = Interner::new();let mut facts: Vec<(u32, u32, u32)> = Vec::with_capacity(raw_triples.len());for (s, p, o) in &raw_triples {@@ -681,6 +1135,27 @@ impl Reasoner {let rdf_rest = interner.intern(RDF_REST);let rdf_nil = interner.intern(RDF_NIL);+ // The same well-known ids, in the shape `BUILTIN_RULES` reads them.+ // Every fixed term in every built-in rule pattern resolves through+ // this, so a rule's vocabulary is not restated at its call site either.+ let rule_vocab = RuleVocab {+ type_: rdf_type,+ subclass: rdfs_subclass,+ subprop: rdfs_subprop,+ domain: rdfs_domain,+ range: rdfs_range,+ sameas: owl_sameas,+ inverse: owl_inverse,+ transitive: owl_transitive,+ symmetric: owl_symmetric,+ equiv_class: owl_equiv_class,+ equiv_prop: owl_equiv_prop,+ on_property: owl_on_property,+ svf: owl_some_values,+ avf: owl_all_values,+ has_value: owl_has_value,+ };+// The clash detector's vocabulary. Nothing below drives a rule in the// fixpoint: it is read once, after it, by `find_clashes`. Interning a// term the graph never mentions costs one entry and makes every lookup@@ -880,6 +1355,17 @@ impl Reasoner {// triple not already in the closure, with the premises in the// order the checker expects for that rule.//+ // THE ORDER IS NOT THE CALL SITE'S. A fixed-arity rule fires as+ // `Fired::Bound(rule, binding)`, and the conclusion and the premise+ // list are both computed from that rule's row in `BUILTIN_RULES`,+ // which is the table `tests/premise_order_test.rs` checks against+ // the `checkStep` arms in `lean/OOCert/Rules.lean`. A site that got+ // the order wrong used to produce a certificate the checker+ // rejected for a reason no user could act on; there is now no order+ // at a site to get wrong. The four list rules keep an explicit+ // premise vector, because an RDF list chain is not a fixed pattern,+ // and they say so where they fire.+ //// It is also the one place that refuses a conclusion no RDF// serialiser can write. Four rules below guard the subject position// themselves and are left alone; this guard is central because the@@ -890,7 +1376,27 @@ impl Reasoner {let interner_ref = &interner;let refused_ref = &mut refused;let samples_ref = &mut skipped_samples;- let mut emit = |t: Fact, rule: &'static str, premises: &[Fact]| {+ let rv = &rule_vocab;+ let mut emit = |f: Fired| {+ let (rule, t) = match &f {+ Fired::Bound(r, b) => {+ let row = &BUILTIN_RULES[*r as usize];+ // A real assert and not a `debug_assert`. The cost is+ // one comparison beside two interner lookups the next+ // lines already do, and the alternative in a release+ // build is an index panic inside `fill` with nothing+ // naming the rule.+ assert_eq!(+ row.vars.len(),+ b.len(),+ "{} takes a binding of {} terms",+ row.name,+ row.vars.len()+ );+ (row.name, rv.fill(&row.head, b))+ }+ Fired::Chained(name, t, _) => (*name, *t),+ };let (s, p, _) = t;if !writable_triple(interner_ref.resolve(s), interner_ref.resolve(p)) {if refused_ref.insert(t) && samples_ref.len() < 3 {@@ -904,7 +1410,15 @@ impl Reasoner {return;}if certify && !triple_set.contains(&t) && recorded.insert(t) {- derivations.push(Derivation { rule, conclusion: t, premises: premises.to_vec() });+ let premises: Vec<Fact> = match &f {+ Fired::Bound(r, b) => BUILTIN_RULES[*r as usize]+ .body+ .iter()+ .map(|a| rv.fill(a, b))+ .collect(),+ Fired::Chained(_, _, ps) => ps.to_vec(),+ };+ derivations.push(Derivation { rule, conclusion: t, premises });}new.push(t);};@@ -916,8 +1430,7 @@ impl Reasoner {if let Some(supers) = sub_to_super.get(&sub) {for &sup in supers {if sub != sup {- emit((x, rdf_type, sup), "rdfs9",- &[(x, rdf_type, sub), (sub, rdfs_subclass, sup)]);+ emit(Fired::Bound(Rl::Rdfs9, &[x, sub, sup]));}}}@@ -928,8 +1441,7 @@ impl Reasoner {if let Some(cs) = sub_to_super.get(&b) {for &c in cs {if a != b && b != c && a != c {- emit((a, rdfs_subclass, c), "rdfs11",- &[(a, rdfs_subclass, b), (b, rdfs_subclass, c)]);+ emit(Fired::Bound(Rl::Rdfs11, &[a, b, c]));}}}@@ -939,7 +1451,7 @@ impl Reasoner {for &(prop, cls) in &domain_map {for &(s, p, o) in triple_set.iter() {if p == prop {- emit((s, rdf_type, cls), "rdfs2", &[(s, p, o), (prop, rdfs_domain, cls)]);+ emit(Fired::Bound(Rl::Rdfs2, &[s, p, o, cls]));}}}@@ -954,7 +1466,7 @@ impl Reasoner {// behind it, and a SHACL shape targeting that class found// no focus nodes. rdfs2 twelve lines up has no such guard.if p == prop && !interner.resolve(o).starts_with('"') {- emit((o, rdf_type, cls), "rdfs3", &[(s, p, o), (prop, rdfs_range, cls)]);+ emit(Fired::Bound(Rl::Rdfs3, &[s, p, o, cls]));}}}@@ -968,8 +1480,7 @@ impl Reasoner {if let Some(cs) = subp_to_super.get(&b) {for &c in cs {if a != b && b != c && a != c {- emit((a, rdfs_subprop, c), "rdfs5",- &[(a, rdfs_subprop, b), (b, rdfs_subprop, c)]);+ emit(Fired::Bound(Rl::Rdfs5, &[a, b, c]));}}}@@ -980,7 +1491,7 @@ impl Reasoner {if sub != sup {for &(s, p, o) in triple_set.iter() {if p == sub {- emit((s, sup, o), "rdfs7", &[(s, sub, o), (sub, rdfs_subprop, sup)]);+ emit(Fired::Bound(Rl::Rdfs7, &[s, sub, o, sup]));}}}@@ -1012,8 +1523,7 @@ impl Reasoner {if let Some(zs) = by_subj.get(&y) {for &z in zs {if x != z {- emit((x, tp, z), "prp-trp",- &[(tp, rdf_type, owl_transitive), (x, tp, y), (y, tp, z)]);+ emit(Fired::Bound(Rl::PrpTrp, &[tp, x, y, z]));}}}@@ -1024,7 +1534,7 @@ impl Reasoner {for &sp in &symmetric_set {for &(s, p, o) in triple_set.iter() {if p == sp && !is_literal(o) {- emit((o, sp, s), "prp-symp", &[(sp, rdf_type, owl_symmetric), (s, sp, o)]);+ emit(Fired::Bound(Rl::PrpSymp, &[sp, s, o]));}}}@@ -1036,10 +1546,10 @@ impl Reasoner {continue;}if pred == p {- emit((o, q, s), "prp-inv1", &[(p, owl_inverse, q), (s, p, o)]);+ emit(Fired::Bound(Rl::PrpInv1, &[p, q, s, o]));}if pred == q {- emit((o, p, s), "prp-inv2", &[(p, owl_inverse, q), (s, q, o)]);+ emit(Fired::Bound(Rl::PrpInv2, &[p, q, s, o]));}}}@@ -1047,7 +1557,7 @@ impl Reasoner {// eq-sym: sameAs symmetryfor &(s, p, o) in triple_set.iter() {if p == owl_sameas && !is_literal(o) {- emit((o, owl_sameas, s), "eq-sym", &[(s, owl_sameas, o)]);+ emit(Fired::Bound(Rl::EqSym, &[s, o]));}}@@ -1061,15 +1571,15 @@ impl Reasoner {// both steps under the rule that licenses them also frees the// name for the real scm-eqc2 when it is implemented.for &(a, b) in &equiv_class {- emit((a, rdfs_subclass, b), "scm-eqc1", &[(a, owl_equiv_class, b)]);- emit((b, rdfs_subclass, a), "scm-eqc1", &[(a, owl_equiv_class, b)]);+ emit(Fired::Bound(Rl::ScmEqc1Fwd, &[a, b]));+ emit(Fired::Bound(Rl::ScmEqc1Rev, &[a, b]));}// scm-eqp1, scm-eqp2: equivalentProperty → bidirectional subPropertyOf// Same for scm-eqp1 and the name scm-eqp2.for &(a, b) in &equiv_prop {- emit((a, rdfs_subprop, b), "scm-eqp1", &[(a, owl_equiv_prop, b)]);- emit((b, rdfs_subprop, a), "scm-eqp1", &[(a, owl_equiv_prop, b)]);+ emit(Fired::Bound(Rl::ScmEqp1Fwd, &[a, b]));+ emit(Fired::Bound(Rl::ScmEqp1Rev, &[a, b]));}// scm-dom1, scm-dom2, scm-rng1, scm-rng2: a declared domain or@@ -1097,8 +1607,7 @@ impl Reasoner {if let Some(supers) = sub_to_super.get(&c1) {for &c2 in supers {if c1 != c2 {- emit((p, rdfs_domain, c2), "scm-dom1",- &[(p, rdfs_domain, c1), (c1, rdfs_subclass, c2)]);+ emit(Fired::Bound(Rl::ScmDom1, &[p, c1, c2]));}}}@@ -1111,8 +1620,7 @@ impl Reasoner {}for &(pd, c) in &domain_map {if pd == p2 {- emit((p1, rdfs_domain, c), "scm-dom2",- &[(p2, rdfs_domain, c), (p1, rdfs_subprop, p2)]);+ emit(Fired::Bound(Rl::ScmDom2, &[p2, c, p1]));}}}@@ -1122,8 +1630,7 @@ impl Reasoner {if let Some(supers) = sub_to_super.get(&c1) {for &c2 in supers {if c1 != c2 {- emit((p, rdfs_range, c2), "scm-rng1",- &[(p, rdfs_range, c1), (c1, rdfs_subclass, c2)]);+ emit(Fired::Bound(Rl::ScmRng1, &[p, c1, c2]));}}}@@ -1136,8 +1643,7 @@ impl Reasoner {}for &(pr, c) in &range_map {if pr == p2 {- emit((p1, rdfs_range, c), "scm-rng2",- &[(p2, rdfs_range, c), (p1, rdfs_subprop, p2)]);+ emit(Fired::Bound(Rl::ScmRng2, &[p2, c, p1]));}}}@@ -1177,12 +1683,7 @@ impl Reasoner {for &(x, y) in &prop_pairs {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),- ]);+ emit(Fired::Bound(Rl::ClsSvf1, &[restr, prop, filler, x, y]));}}}@@ -1205,12 +1706,7 @@ impl Reasoner {}for &(x, p, y) in triple_set.iter() {if p == prop && in_restr.contains(&x) {- emit((y, rdf_type, filler), "cls-avf", &[- (restr, owl_on_property, prop),- (restr, owl_all_values, filler),- (x, rdf_type, restr),- (x, prop, y),- ]);+ emit(Fired::Bound(Rl::ClsAvf, &[restr, prop, filler, x, y]));}}}@@ -1232,20 +1728,12 @@ impl Reasoner {for &(prop, val, restr) in &hv_rules {for &(x, c) in &type_idx {if c == restr {- emit((x, prop, val), "cls-hv1", &[- (restr, owl_on_property, prop),- (restr, owl_has_value, val),- (x, rdf_type, restr),- ]);+ emit(Fired::Bound(Rl::ClsHv1, &[restr, prop, val, x]));}}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),- ]);+ emit(Fired::Bound(Rl::ClsHv2, &[restr, prop, val, s]));}}}@@ -1289,13 +1777,7 @@ impl Reasoner {let Some(twos) = svf_by_pf.get(&(p, y2)) else { continue };for &r2 in twos {if r1 != r2 {- emit((r1, rdfs_subclass, r2), "scm-svf1", &[- (r1, owl_some_values, y1),- (r1, owl_on_property, p),- (r2, owl_some_values, y2),- (r2, owl_on_property, p),- (y1, rdfs_subclass, y2),- ]);+ emit(Fired::Bound(Rl::ScmSvf1, &[r1, y1, p, r2, y2]));}}}@@ -1309,13 +1791,7 @@ impl Reasoner {let Some(twos) = svf_by_pf.get(&(p2, y)) else { continue };for &r2 in twos {if r1 != r2 {- emit((r1, rdfs_subclass, r2), "scm-svf2", &[- (r1, owl_some_values, y),- (r1, owl_on_property, p1),- (r2, owl_some_values, y),- (r2, owl_on_property, p2),- (p1, rdfs_subprop, p2),- ]);+ emit(Fired::Bound(Rl::ScmSvf2, &[r1, y, p1, r2, p2]));}}}@@ -1329,13 +1805,7 @@ impl Reasoner {let Some(twos) = avf_by_pf.get(&(p, y2)) else { continue };for &r2 in twos {if r1 != r2 {- emit((r1, rdfs_subclass, r2), "scm-avf1", &[- (r1, owl_all_values, y1),- (r1, owl_on_property, p),- (r2, owl_all_values, y2),- (r2, owl_on_property, p),- (y1, rdfs_subclass, y2),- ]);+ emit(Fired::Bound(Rl::ScmAvf1, &[r1, y1, p, r2, y2]));}}}@@ -1359,13 +1829,7 @@ impl Reasoner {let Some(twos) = avf_by_pf.get(&(p2, y)) else { continue };for &r2 in twos {if r1 != r2 {- emit((r2, rdfs_subclass, r1), "scm-avf2", &[- (r1, owl_all_values, y),- (r1, owl_on_property, p1),- (r2, owl_all_values, y),- (r2, owl_on_property, p2),- (p1, rdfs_subprop, p2),- ]);+ emit(Fired::Bound(Rl::ScmAvf2, &[r1, y, p1, r2, p2]));}}}@@ -1383,7 +1847,7 @@ impl Reasoner {} else {Vec::new()};- emit((x, rdf_type, *cls), "cls-int1", &premises);+ emit(Fired::Chained("cls-int1", (x, rdf_type, *cls), &premises));}}}@@ -1409,7 +1873,7 @@ impl Reasoner {Vec::new()};for &m in members {- emit((x, rdf_type, m), "cls-int2", &premises);+ emit(Fired::Chained("cls-int2", (x, rdf_type, m), &premises));}}}@@ -1430,7 +1894,7 @@ impl Reasoner {};for &m in members {if !is_literal(m) {- emit((m, rdf_type, *cls), "cls-oo", &premises);+ emit(Fired::Chained("cls-oo", (m, rdf_type, *cls), &premises));}}}@@ -1447,7 +1911,7 @@ impl Reasoner {} else {Vec::new()};- emit((x, rdf_type, *cls), "cls-uni", &premises);+ emit(Fired::Chained("cls-uni", (x, rdf_type, *cls), &premises));}}}@@ -1545,7 +2009,12 @@ impl Reasoner {interner.resolve(s),interner.resolve(p),interner.resolve(o),- );+ )+ .map_err(|pos| unwritable_term("asserted.tsv", pos, interner.resolve(match pos {+ Position::Subject => s,+ Position::Predicate => p,+ Position::Object => o,+ })))?;}std::fs::write(dir.join("asserted.tsv"), asserted)?;@@ -1560,7 +2029,12 @@ impl Reasoner {interner.resolve(s),interner.resolve(p),interner.resolve(o),- );+ )+ .map_err(|pos| unwritable_term("derivations.tsv", pos, interner.resolve(match pos {+ Position::Subject => s,+ Position::Predicate => p,+ Position::Object => o,+ })))?;}lines.push('\n');}@@ -1581,6 +2055,11 @@ impl Reasoner {"asserted": facts.len(),"derivations": derivations.len(),"by_rule": by_rule,+ // Which graphs the assertions came from, and which were held+ // back. A certificate that does not say this cannot be checked+ // against the store it claims to be about.+ "graphs_read": graphs_read,+ "graphs_excluded": [INFERRED_GRAPH],"check_with": "cd lean && lake exe oo-cert <dir>/asserted.tsv <dir>/derivations.tsv",});}@@ -1821,10 +2300,22 @@ impl Pat {/// The `rules.tsv` spelling: `?x` for a variable, the term itself for a/// constant. Inverse of the parse below, and byte-identical to/// `OOCert.HornParse.patStr`.+ ///+ /// The variable arm builds the string rather than `format!`-ing it, and the+ /// reason is verification and not speed: `format!` drags the whole+ /// `core::fmt` machinery into any function that calls it, and CBMC flattens+ /// a function before it solves. With `format!` here,+ /// `kani_harnesses::pat_of_and_render_are_inverse` measures the formatter.+ /// The bytes it produces are the same either way.fn render(&self) -> String {match self {Pat::Const(c) => c.clone(),- Pat::Var(v) => format!("?{v}"),+ Pat::Var(v) => {+ let mut s = String::with_capacity(v.len() + 1);+ s.push('?');+ s.push_str(v);+ s+ }}}}@@ -1873,15 +2364,38 @@ fn pat_vars<'a>(a: &'a AtomPat, out: &mut Vec<&'a str>) {/// constant that is not in N-Triples spelling can never equal a term the store/// holds, so a rule carrying one silently never fires. That is a typo, not a/// rule, and it is refused rather than run.-fn parse_pat(field: &str, line: usize, which: &str) -> anyhow::Result<Pat> {+/// The classification half of [`parse_pat`], with no error value and no+/// formatting.+///+/// Split out on 15 September 2026 for one reason, and it is a verification+/// reason rather than a style one. `parse_pat` returns `anyhow::Result` and+/// every refusal formats a message naming the line and the position, so the+/// function body carries the whole formatting machinery; CBMC flattens a+/// function before it solves, so a Kani harness on `parse_pat` was measuring+/// `format!` and never returned a verdict (14 minutes, 9.5 GB, and worse when+/// the input was constrained). This function is pure, total and allocates only+/// the `Pat` it returns, and `kani_harnesses::pat_of_and_render_are_inverse`+/// proves TCB-20 over every byte pattern at a bound. The messages stayed where+/// they were.+fn pat_of(field: &str) -> Option<Pat> {if let Some(name) = field.strip_prefix('?') {if name.is_empty() {- anyhow::bail!("rules line {line}: {which} is '?' with no variable name");+ return None;}- return Ok(Pat::Var(name.to_string()));+ return Some(Pat::Var(name.to_string()));}if field.starts_with('<') || field.starts_with("_:") || field.starts_with('"') {- return Ok(Pat::Const(field.to_string()));+ return Some(Pat::Const(field.to_string()));+ }+ None+}++fn parse_pat(field: &str, line: usize, which: &str) -> anyhow::Result<Pat> {+ if let Some(p) = pat_of(field) {+ return Ok(p);+ }+ if field == "?" {+ anyhow::bail!("rules line {line}: {which} is '?' with no variable name");}if field.is_empty() {anyhow::bail!("rules line {line}: {which} is empty");@@ -2167,7 +2681,10 @@ impl Reasoner {);}- let raw_triples = graph.all_triples()?;+ // The asserted triples, every graph except the one the built-in path+ // parks its own conclusions in. See TCB-8; this path materialises+ // nothing itself (decision 0003) but it reads the same store.+ let (raw_triples, graphs_read) = graph.triples_outside(&[INFERRED_GRAPH])?;let mut interner = Interner::new();let mut facts: Vec<Fact> = Vec::with_capacity(raw_triples.len());for (s, p, o) in &raw_triples {@@ -2325,7 +2842,12 @@ impl Reasoner {interner.resolve(s),interner.resolve(p),interner.resolve(o),- );+ )+ .map_err(|pos| unwritable_term("asserted.tsv", pos, interner.resolve(match pos {+ Position::Subject => s,+ Position::Predicate => p,+ Position::Object => o,+ })))?;}std::fs::write(certificate_dir.join("asserted.tsv"), asserted)?;@@ -2337,10 +2859,24 @@ impl Reasoner {horn.push('\t');horn.push_str(&st.binds.len().to_string());for (v, term) in &st.binds {+ // A variable name is not a term and has no N-Triples spelling,+ // so it gets the format half of the guard. `parse_rules` cannot+ // produce one carrying a separator, which is exactly why this+ // is cheap: it enforces here what is argued there.+ if !field_fits_the_format(v) {+ anyhow::bail!(+ "internal: the rule variable name {v:?} does not fit the certificate \+ format, so no certificate was written"+ );+ }+ let bound = interner.resolve(*term);+ if !term_fits_the_format(bound) {+ return Err(unwritable_term("horn.tsv", Position::Object, bound));+ }horn.push('\t');horn.push_str(v);horn.push('\t');- horn.push_str(interner.resolve(*term));+ horn.push_str(bound);}for &(s, p, o) in std::iter::once(&st.conclusion).chain(st.premises.iter()) {push_triple_fields(@@ -2348,7 +2884,12 @@ impl Reasoner {interner.resolve(s),interner.resolve(p),interner.resolve(o),- );+ )+ .map_err(|pos| unwritable_term("horn.tsv", pos, interner.resolve(match pos {+ Position::Subject => s,+ Position::Predicate => p,+ Position::Object => o,+ })))?;}horn.push('\n');}@@ -2385,6 +2926,8 @@ impl Reasoner {"rules": rules.len(),"asserted_triples": facts.len(),"distinct_asserted_triples": asserted_count,+ "graphs_read": graphs_read,+ "graphs_excluded": [INFERRED_GRAPH],"derived_triples": steps.len(),"iterations": iterations,"fixpoint_reached": fixpoint,@@ -2458,6 +3001,25 @@ mod boundary_tests {use super::*;use proptest::prelude::*;+ /// `BUILTIN_RULES[r as usize]` is `r`'s row. Everything the emitter does+ /// with the table rests on this one line of arithmetic, and a row inserted+ /// in the middle without a matching enum variant would silently give every+ /// rule after it the next rule's premises.+ #[test]+ fn each_row_is_at_its_own_index() {+ assert_eq!(Rl::ALL.len(), BUILTIN_RULES.len());+ for (i, r) in Rl::ALL.iter().enumerate() {+ assert_eq!(*r as usize, i, "{r:?} is not at index {i}");+ }+ // The two rules that license two conclusions from one premise are the+ // only names that appear twice.+ let mut names: Vec<&str> = BUILTIN_RULES.iter().map(|r| r.name).collect();+ names.sort_unstable();+ let mut dups: Vec<&str> = names.windows(2).filter(|w| w[0] == w[1]).map(|w| w[0]).collect();+ dups.dedup();+ assert_eq!(dups, vec!["scm-eqc1", "scm-eqp1"]);+ }+/// Terms that carry no separator, so the writer's precondition holds and/// the round trip is the thing under test.fn term() -> impl Strategy<Value = String> {@@ -2476,6 +3038,27 @@ mod boundary_tests {proptest! {#![proptest_config(ProptestConfig { cases: 1024, ..ProptestConfig::default() })]+ /// Every slot a rule pattern mentions is within the arity it declares,+ /// and every variable it declares is actually used. An unused slot is a+ /// binding a call site has to invent a term for; an out-of-range slot+ /// is a panic on a graph nobody happened to test.+ #[test]+ fn every_rule_slot_is_within_its_arity(i in 0usize..BUILTIN_RULES.len()) {+ let r = &BUILTIN_RULES[i];+ let mut seen = vec![false; r.vars.len()];+ for a in r.body.iter().chain(std::iter::once(&r.head)) {+ for s in a {+ if let Slot::Var(k) = s {+ prop_assert!(*k < r.vars.len(), "{} slot {k} of {}", r.name, r.vars.len());+ seen[*k] = true;+ }+ }+ }+ for (k, used) in seen.iter().enumerate() {+ prop_assert!(*used, "{} declares {} and never uses it", r.name, r.vars[k]);+ }+ }+/// TCB-15 and TCB-16. The interner is a bijection between the strings it/// has seen and the ids it has issued. Every term in every certificate/// file passes through it, so if it were not, two different terms would@@ -2513,18 +3096,35 @@ mod boundary_tests {}}- /// TCB-1, as a statement about the writer alone. Given three terms that- /// carry no separator, the line splits back into exactly those three.- /// The Kani harness below proves the same thing over every input up to- /// a bound; this one runs in CI without a model checker installed.+ /// TCB-1, as a statement about the writer alone. The writer accepts+ /// exactly the terms that fit the format, and what it accepts splits+ /// back into exactly those three terms. A refusal leaves the buffer+ /// untouched.+ ///+ /// This used to be a statement about terms the generator kept+ /// separator-free, because the writer took anything. The writer now+ /// decides, so the test covers both verdicts. The Kani harnesses below+ /// prove the same statement over every byte pattern up to a bound; this+ /// one runs in CI without a model checker installed and samples the+ /// lengths, including the empty string.#[test]fn tcb_1_an_asserted_line_splits_back_into_its_three_terms(s in term(), p in term(), o in term(),) {- let mut out = String::new();- push_asserted_line(&mut out, &s, &p, &o);+ let mut out = String::from("<a>\t<b>\t<c>\n");+ let before = out.clone();+ let r = push_asserted_line(&mut out, &s, &p, &o);+ let fits = term_fits_the_format(&s)+ && term_fits_the_format(&p)+ && term_fits_the_format(&o);+ prop_assert_eq!(r.is_ok(), fits);+ if r.is_err() {+ prop_assert_eq!(out, before, "a refused line left a fragment behind");+ return Ok(());+ }prop_assert!(out.ends_with('\n'));- let body = &out[..out.len() - 1];+ let line = out.strip_prefix(&before).expect("the line was appended");+ let body = &line[..line.len() - 1];prop_assert!(!body.contains('\n'));let f: Vec<&str> = body.split('\t').collect();prop_assert_eq!(f, vec![s.as_str(), p.as_str(), o.as_str()]);@@ -2538,28 +3138,96 @@ mod boundary_tests {) {let mut out = String::new();out.push_str(&head);+ let mut written = 0usize;for (s, p, o) in &ts {- push_triple_fields(&mut out, s, p, o);+ let fits = term_fits_the_format(s)+ && term_fits_the_format(p)+ && term_fits_the_format(o);+ let before = out.clone();+ let r = push_triple_fields(&mut out, s, p, o);+ prop_assert_eq!(r.is_ok(), fits);+ if r.is_err() {+ prop_assert_eq!(out.clone(), before);+ } else {+ written += 1;+ }}let f: Vec<&str> = out.split('\t').collect();- prop_assert_eq!(f.len(), 1 + 3 * ts.len());+ prop_assert_eq!(f.len(), 1 + 3 * written);prop_assert_eq!(f[0], head.as_str());- for (i, (s, p, o)) in ts.iter().enumerate() {+ let mut i = 0usize;+ for (s, p, o) in ts.iter() {+ if !(term_fits_the_format(s) && term_fits_the_format(p) && term_fits_the_format(o)) {+ continue;+ }prop_assert_eq!(f[1 + 3 * i], s.as_str());prop_assert_eq!(f[2 + 3 * i], p.as_str());prop_assert_eq!(f[3 + 3 * i], o.as_str());+ i += 1;+ }+ }++ /// TCB-4 and TCB-5, as a statement about the guard alone. A term the+ /// guard accepts carries no separator and is in one of the three+ /// N-Triples spellings, and two accepted terms of different spellings+ /// are different strings, which is what lets the two checkers compare+ /// terms as opaque strings.+ ///+ /// The Kani harness `term_guard_is_exact` proves this over every byte+ /// pattern at a bound rather than over a sample.+ #[test]+ fn tcb_4_5_the_guard_decides_separators_and_spelling(a in term(), b in term()) {+ for t in [&a, &b] {+ if term_fits_the_format(t) {+ prop_assert!(!t.contains(['\t', '\n', '\r']));+ prop_assert!(!t.is_empty());+ prop_assert!(t.starts_with('<') || t.starts_with('"') || t.starts_with("_:"));+ }+ }+ if term_fits_the_format(&a) && term_fits_the_format(&b) {+ let kind = |t: &str| t.as_bytes()[0];+ if kind(&a) != kind(&b) {+ prop_assert_ne!(&a, &b);+ }}}/// TCB-20 at one rule position. `parse_pat` and `Pat::render` are/// inverse, so a constant never renders to something that reads back as/// a variable. `run_horn`'s re-parse guard rests on this.+ ///+ /// Both directions, and `pat_of` is the classifier `parse_pat` is now+ /// built on, so this also pins that the refactor did not move the+ /// boundary between accept and refuse.#[test]fn tcb_20_parse_pat_and_render_are_inverse(field in "[^\t\n\r]{0,8}") {- if let Ok(p) = parse_pat(&field, 1, "position") {+ let via_pat_of = pat_of(&field);+ prop_assert_eq!(+ parse_pat(&field, 1, "position").ok(),+ via_pat_of.clone(),+ "parse_pat and pat_of disagree on {:?}", field+ );+ if let Some(p) = via_pat_of {prop_assert_eq!(p.render(), field);}}++ /// TCB-20, the other direction: a pattern renders to a field that reads+ /// back as the same pattern. This is the direction `rules_tsv` needs,+ /// because it renders the table the checker then parses.+ #[test]+ fn tcb_20_render_then_parse_returns_the_pattern(+ name in "[^\t\n\r]{1,8}",+ c in prop_oneof![+ Just("<http://e/a>".to_string()),+ Just("\"lit\"".to_string()),+ Just("_:b0".to_string()),+ ],+ is_var in any::<bool>(),+ ) {+ let p = if is_var { Pat::Var(name) } else { Pat::Const(c) };+ prop_assert_eq!(pat_of(&p.render()), Some(p));+ }}}@@ -2591,12 +3259,11 @@ mod kani_harnesses {/// A FIXED length rather than a symbolic one. A symbolic `n` makes every/// offset in the produced line symbolic, every slice bound a case split,/// and the cost compounds across three terms: two bytes per term with a- /// symbolic length reached fifteen gigabytes without a verdict. Fixing the- /// length leaves every BYTE unconstrained, which is the dimension that- /// matters here (a tab or a newline getting into a term), and moves the- /// length dimension to `boundary_tests`, which samples it including the- /// empty string. That is a real limitation of these proofs and it is stated- /// on each of them rather than left for a reader to infer.+ /// symbolic length reached fifteen gigabytes without a verdict. The length+ /// dimension is covered instead by INSTANTIATING the generic harnesses+ /// below at several lengths, `0` included, so the claim is "every byte+ /// pattern at each of these lengths" rather than "every byte pattern at one+ /// length". That is still a bound and it is stated on each harness.fn any_ascii<const N: usize>(buf: &mut [u8; N]) -> &str {*buf = kani::any();for b in buf.iter() {@@ -2608,56 +3275,49 @@ mod kani_harnesses {unsafe { core::str::from_utf8_unchecked(&buf[..]) }}- /// TCB-1, over every byte pattern rather than over a sample.+ /// TCB-1 and TCB-4, over every byte pattern at length `N` rather than over+ /// a sample, and with no assumption that the terms are separator-free.///- /// For ANY three separator-free ASCII terms, `push_asserted_line` writes a- /// line carrying exactly two tabs and one newline, the newline last, with- /// the three terms at the offsets those separators imply. This is the- /// property a forged literal breaks, and the reason- /// `lean/OOCert/Parse.lean` is entitled to say that splitting is exact.+ /// The writer now DECIDES that, so the harness proves the decision as well+ /// as the layout: `push_asserted_line` returns `Ok` exactly when all three+ /// terms fit the format, and when it does, the line it wrote carries+ /// exactly two tabs and one newline, the newline last, with the three terms+ /// at the offsets those separators imply. When it refuses, the buffer is+ /// byte for byte what it was, so a refusal cannot leave half a line behind.///- /// What it does NOT prove: that no term ever carries a separator. That is a- /// fact about `oxrdf` and `oxiri`, not about this function, and it is- /// pinned by test rather than proved.+ /// Until 15 September 2026 this harness ASSUMED separator-freedom, because+ /// nothing in this repository enforced it: it was a property of `oxrdf`'s+ /// `Display` and of `oxiri` refusing to parse. The assumption is now a+ /// branch of the function under test.////// The claim is about the BYTES, not about Rust's `split`. The reader is/// `OOCert.Parse.parseTriples`, which is Lean's `String.splitOn`, so a proof- /// about `str::split` would be a proof about the wrong splitter. What both- /// need is the layout: the line holds exactly two TAB bytes and exactly one- /// NEWLINE, that newline is last, and the three terms sit at the offsets- /// their lengths dictate. Any correct splitter recovers `s`, `p` and `o`- /// from that and from nothing less.- ///- /// Stating it that way is also what makes it verifiable. Asserting on- /// `body.split('\t')` instead put CBMC inside `CharSearcher` over a symbolic- /// buffer and ran ten minutes to two gigabytes without a verdict at two- /// bytes per term. The `split` formulation is kept as a property test in- /// `boundary_tests`, where it is free.- ///- /// Three bytes per term, each byte unconstrained ASCII, the LENGTH fixed.- /// See `any_ascii` for why the length is fixed and what that costs the- /// claim: `boundary_tests` samples the lengths, including the empty string,- /// and this proves every byte pattern at one shape. A bounded proof read as- /// an unbounded one is the defect this layer exists to attack, so the bound- /// is on the harness rather than in a footnote.- ///- /// `with_capacity` so the buffer never reallocates. CBMC models the- /// allocator, and a realloc is state that has nothing to do with the claim.- #[kani::proof]- #[kani::unwind(16)]- fn asserted_line_round_trips() {- const N: usize = 3;+ /// about `str::split` would be a proof about the wrong splitter. Asserting+ /// on `body.split('\t')` also put CBMC inside `CharSearcher` and ran ten+ /// minutes to two gigabytes without a verdict. The `split` formulation is+ /// kept as a property test in `boundary_tests`, where it is free.+ fn asserted_line_layout<const N: usize>() {let (mut a, mut b, mut c) = ([0u8; N], [0u8; N], [0u8; N]);let s = any_ascii(&mut a);let p = any_ascii(&mut b);let o = any_ascii(&mut c);- kani::assume(!s.contains('\t') && !s.contains('\n'));- kani::assume(!p.contains('\t') && !p.contains('\n'));- kani::assume(!o.contains('\t') && !o.contains('\n'));- let mut out = String::with_capacity(4 * N);- push_asserted_line(&mut out, s, p, o);- let w = out.as_bytes();+ // A non-empty buffer, so "nothing was appended" is a real claim and not+ // "the buffer is still empty".+ let mut out = String::with_capacity(4 * N + 8);+ out.push('x');+ let r = push_asserted_line(&mut out, s, p, o);++ let fits =+ term_fits_the_format(s) && term_fits_the_format(p) && term_fits_the_format(o);+ assert!(r.is_ok() == fits);+ if !fits {+ assert!(out.len() == 1);+ assert!(out.as_bytes()[0] == b'x');+ return;+ }++ let w = &out.as_bytes()[1..];// Nothing added and nothing lost: three terms, two tabs, one newline.assert!(w.len() == 3 * N + 3);@@ -2668,9 +3328,6 @@ mod kani_harnesses {assert!(w[3 * N + 2] == b'\n');// And nowhere else, so any correct splitter finds exactly three fields.- // The reader is `OOCert.Parse.parseTriples`, which is Lean's- // `String.splitOn`, so the claim has to be about the bytes rather than- // about Rust's `str::split`.let mut tabs = 0usize;let mut newlines = 0usize;let mut i = 0usize;@@ -2697,25 +3354,66 @@ mod kani_harnesses {}}- /// TCB-2 and TCB-3. Three fields appended to a line already begun come back- /// as three fields, so a step's conclusion and its premises cannot run into- /// one another.+ /// The empty term. Every position is refused and nothing is written.#[kani::proof]- #[kani::unwind(16)]- fn triple_fields_append_exactly_three() {- const N: usize = 3;+ #[kani::unwind(24)]+ fn asserted_line_round_trips_at_0() {+ asserted_line_layout::<0>();+ }++ #[kani::proof]+ #[kani::unwind(24)]+ fn asserted_line_round_trips_at_1() {+ asserted_line_layout::<1>();+ }++ #[kani::proof]+ #[kani::unwind(24)]+ fn asserted_line_round_trips_at_2() {+ asserted_line_layout::<2>();+ }++ /// The length the original harness was fixed at. Renamed from+ /// `asserted_line_round_trips` because `cargo kani --harness NAME` selects+ /// by SUBSTRING: the bare name matched all five of these and ran them+ /// together, which is how `_at_4` first failed inside a run reported under+ /// another harness's heading. Every harness name here is now a full name.+ #[kani::proof]+ #[kani::unwind(24)]+ fn asserted_line_round_trips_at_3() {+ asserted_line_layout::<3>();+ }++ #[kani::proof]+ #[kani::unwind(24)]+ fn asserted_line_round_trips_at_4() {+ asserted_line_layout::<4>();+ }++ /// TCB-2, TCB-3 and TCB-4. Three fields appended to a line already begun+ /// come back as three fields, so a step's conclusion and its premises+ /// cannot run into one another, and the writer refuses exactly the terms+ /// that do not fit the format.+ fn triple_fields_layout<const N: usize>() {let (mut a, mut b, mut c) = ([0u8; N], [0u8; N], [0u8; N]);let s = any_ascii(&mut a);let p = any_ascii(&mut b);let o = any_ascii(&mut c);- kani::assume(!s.contains('\t') && !p.contains('\t') && !o.contains('\t'));- kani::assume(!s.contains('\n') && !p.contains('\n') && !o.contains('\n'));- let mut out = String::with_capacity(4 * N + 4);+ let mut out = String::with_capacity(4 * N + 8);out.push('r');- push_triple_fields(&mut out, s, p, o);- let w = out.as_bytes();+ let r = push_triple_fields(&mut out, s, p, o);++ let fits =+ term_fits_the_format(s) && term_fits_the_format(p) && term_fits_the_format(o);+ assert!(r.is_ok() == fits);+ if !fits {+ assert!(out.len() == 1);+ assert!(out.as_bytes()[0] == b'r');+ return;+ }+ let w = out.as_bytes();assert!(w.len() == 1 + 3 * N + 3);assert!(w[0] == b'r');assert!(w[1] == b'\t');@@ -2744,6 +3442,94 @@ mod kani_harnesses {}}+ #[kani::proof]+ #[kani::unwind(24)]+ fn triple_fields_append_exactly_three_at_0() {+ triple_fields_layout::<0>();+ }++ #[kani::proof]+ #[kani::unwind(24)]+ fn triple_fields_append_exactly_three_at_2() {+ triple_fields_layout::<2>();+ }++ #[kani::proof]+ #[kani::unwind(24)]+ fn triple_fields_append_exactly_three_at_3() {+ triple_fields_layout::<3>();+ }++ #[kani::proof]+ #[kani::unwind(24)]+ fn triple_fields_append_exactly_three_at_4() {+ triple_fields_layout::<4>();+ }++ /// TCB-4. A term the guard accepts carries NO separator, anywhere.+ ///+ /// Stated over a symbolic index rather than as a loop, so it is the+ /// universally quantified claim the Lean parser needs and not a+ /// restatement of the implementation's own scan. This is the property that+ /// used to be an observation about `oxrdf`: the certificate writers are now+ /// the place it is decided, and this is the proof that the decision is the+ /// right one.+ fn term_guard_admits_no_separator<const N: usize>() {+ let mut buf = [0u8; N];+ let t = any_ascii(&mut buf);+ if !term_fits_the_format(t) {+ return;+ }+ assert!(N > 0);+ let i: usize = kani::any();+ kani::assume(i < N);+ let b = t.as_bytes()[i];+ assert!(b != b'\t' && b != b'\n' && b != b'\r');+ }++ #[kani::proof]+ #[kani::unwind(16)]+ fn term_guard_admits_no_separator_at_3() {+ term_guard_admits_no_separator::<3>();+ }++ #[kani::proof]+ #[kani::unwind(24)]+ fn term_guard_admits_no_separator_at_6() {+ term_guard_admits_no_separator::<6>();+ }++ /// TCB-5. The spellings do not collide.+ ///+ /// An accepted term is an IRI, a blank node or a literal and never two of+ /// them, the kind is decided by the leading byte, and two accepted terms of+ /// different kinds are therefore different strings. That is what entitles+ /// `oo-cert` and `oo-horn` to compare terms as opaque strings: a literal+ /// whose lexical form is spelled exactly like an IRI cannot be that IRI,+ /// because the literal is quoted and the IRI is bracketed.+ #[kani::proof]+ #[kani::unwind(16)]+ fn term_guard_separates_the_three_spellings() {+ let (mut x, mut y) = ([0u8; 3], [0u8; 3]);+ let a = any_ascii(&mut x);+ let b = any_ascii(&mut y);+ kani::assume(term_fits_the_format(a));+ kani::assume(term_fits_the_format(b));++ let kinds = |t: &str| -> u8 {+ (t.starts_with('<') as u8)+ + (t.starts_with('"') as u8)+ + (t.starts_with("_:") as u8)+ };+ // Exactly one kind, so the partition is a partition.+ assert!(kinds(a) == 1);+ assert!(kinds(b) == 1);++ if a.as_bytes()[0] != b.as_bytes()[0] {+ assert!(a != b);+ }+ }+/// The guard that fixed the unwritable-predicate defect. For ANY pair of/// strings it decides both positions and never panics. The statement is/// small because the function is; its value is that the engine now has@@ -2758,50 +3544,55 @@ mod kani_harnesses {assert!(ok == (s.as_bytes()[0] != b'"' && p.as_bytes()[0] == b'<'));}- /// TCB-20, one rule-table position at a time. `parse_pat` and- /// `Pat::render` are inverse, so a constant never renders to something that- /// reads back as a variable. Because `parse_pat` returns- /// `anyhow::Result`, this also proves it cannot panic on any input of the- /// bounded length.- /// TCB-20. **THIS HARNESS DOES NOT TERMINATE AND IS NOT IN `make verify`.**- /// It is kept because the attempt is worth more written down than deleted,- /// and because a reader who wants to finish it should not have to rediscover- /// why it is hard.- ///- /// Measured on this machine, with nothing else competing:- ///- /// | input | outcome |- /// |---|---|- /// | 4 ASCII bytes, unconstrained | no verdict at 7 minutes, 3.0 GB |- /// | 2 ASCII bytes, unconstrained | no verdict at 8 minutes, 2.8 GB |- /// | 2 ASCII bytes, first byte constrained to `?`, `<` or `"` | no verdict at 14 minutes, 9.5 GB |+ /// TCB-20. `pat_of` and `Pat::render` are inverse, so a constant never+ /// renders to something that reads back as a variable and a variable name+ /// never renders to something that reads back as a constant. `run_horn`'s+ /// re-parse guard, and therefore the claim that the checker reads the table+ /// the engine evaluated, rests on this.///- /// The cost is not the input. `parse_pat` returns `anyhow::Result` and every- /// refusal formats a message naming the line and the position, so the- /// function body carries the whole formatting machinery, and CBMC flattens a- /// function before it solves: an `assume` that makes the refusals infeasible- /// is a constraint for the solver, not a cut in the program, so it does not- /// remove the work. Constraining the input made it WORSE, which is the- /// evidence for that reading.+ /// **This is the harness the previous version of this file reported as NOT+ /// TERMINATING.** It targeted `parse_pat`, which returns `anyhow::Result`+ /// and formats a message naming the line and the position on every refusal,+ /// so the function body carried the whole formatting machinery. CBMC+ /// flattens a function before it solves, so an `assume` that makes the+ /// refusal paths infeasible is a constraint for the solver and not a cut in+ /// the program: constraining the input made it worse, not better. Measured+ /// then, with nothing else competing: four unconstrained ASCII bytes, no+ /// verdict at 7 minutes and 3.0 GB; two bytes, no verdict at 8 minutes and+ /// 2.8 GB; two bytes with the first constrained to the three spellings the+ /// function accepts, no verdict at 14 minutes and 9.5 GB.///- /// What would close it: lift the classification out of `parse_pat` into a- /// pure function returning an `Option<Pat>`, with `parse_pat` reduced to- /// that call plus the error messages. Then the harness targets a function- /// with no allocation and no formatting, and the messages stay where they- /// are. That is a refactor of shipped code and it was not made here.- ///- /// Until then the property is sampled, not proved:- /// `boundary_tests::tcb_20_parse_pat_and_render_are_inverse` over 1024 cases,- /// and `tests/certificate_boundary_proptest.rs` over whole rule tables.- #[kani::proof]- #[kani::unwind(8)]- fn parse_pat_and_render_are_inverse() {- let mut buf = [0u8; 2];+ /// What that harness said would close it was "lifting the classification+ /// out of `parse_pat` into a pure `Option<Pat>` function, leaving the+ /// messages where they are". That is `pat_of`, and this is the harness. The+ /// input is unconstrained, both verdicts are explored, and the refusal+ /// branch is proved to be exactly the fields that are neither a named+ /// variable nor an N-Triples term.+ fn pat_of_and_render_are_inverse<const N: usize>() {+ let mut buf = [0u8; N];let field = any_ascii(&mut buf);- kani::assume(!field.contains('\t') && !field.contains('\n'));- let head = field.as_bytes()[0];- kani::assume(head == b'?' || head == b'<' || head == b'"');- let p = parse_pat(field, 1, "position").expect("the accepted spellings parse");- assert!(p.render() == field);+ let b = field.as_bytes();+ let named_var = N > 1 && b[0] == b'?';+ let nt_term = N > 0+ && (b[0] == b'<' || b[0] == b'"' || (b[0] == b'_' && N > 1 && b[1] == b':'));+ match pat_of(field) {+ Some(p) => {+ assert!(named_var || nt_term);+ assert!(p.render() == field);+ }+ None => assert!(!named_var && !nt_term),+ }+ }++ #[kani::proof]+ #[kani::unwind(12)]+ fn pat_of_and_render_are_inverse_at_2() {+ pat_of_and_render_are_inverse::<2>();+ }++ #[kani::proof]+ #[kani::unwind(12)]+ fn pat_of_and_render_are_inverse_at_3() {+ pat_of_and_render_are_inverse::<3>();}}diff --git a/src/tableaux.rs b/src/tableaux.rsindex 889f1b0c..8e7c7f69 100644--- a/src/tableaux.rs+++ b/src/tableaux.rs@@ -3772,113 +3772,130 @@ fn name_is_safe(s: &str) -> bool {// ── Serialisation ───────────────────────────────────────────────────────-fn write_concept(out: &mut String, interner: &Interner, c: &Concept) {+/// The ONE place a name enters either file, and therefore the one place the+/// guard has to be.+///+/// TCB-26 used to read: "the `names` vector is built by walking every axiom+/// variant, every role in `model.rext` and every class in `model.cext`.+/// Individuals in `model.ind` are covered only because `DlAxiom::Indiv(i)` is+/// emitted for every individual that reaches the model. That is an argument+/// about two separate loops agreeing, not a check." The separate loop is gone.+/// A name is checked as it is written, so "the guard covers every name that is+/// written" is true by construction: there is no other way to write one.+///+/// `bad` records the FIRST refused name and the caller refuses the whole+/// certificate. It is a sink rather than a `Result` so the serialisers stay+/// total and keep their shape; a certificate is written only after the caller+/// has looked at it.+fn push_name(out: &mut String, interner: &Interner, id: u32, bad: &mut Option<String>) {+ let s = interner.resolve(id);+ if !name_is_safe(s) && bad.is_none() {+ *bad = Some(s.to_string());+ }+ out.push_str(s);+}++fn write_concept(out: &mut String, interner: &Interner, c: &Concept, bad: &mut Option<String>) {match c {Concept::Top => out.push_str("top"),Concept::Bottom => out.push_str("bot"),Concept::Atom(a) => {out.push_str("atom ");- out.push_str(interner.resolve(*a));+ push_name(out, interner, *a, bad);}Concept::NegAtom(a) => {out.push_str("not atom ");- out.push_str(interner.resolve(*a));+ push_name(out, interner, *a, bad);}// `lean/Dl` has binary conjunction and disjunction, so the n-ary OWL// constructors are folded right-associatively here. An empty list is the// unit of the connective, which is how `RawConcept::to_nnf` already// reads it.- Concept::And(cs) => write_nary(out, interner, cs, "and", &Concept::Top),- Concept::Or(cs) => write_nary(out, interner, cs, "or", &Concept::Bottom),+ Concept::And(cs) => write_nary(out, interner, cs, "and", &Concept::Top, bad),+ Concept::Or(cs) => write_nary(out, interner, cs, "or", &Concept::Bottom, bad),Concept::Exists(r, f) => {out.push_str("some ");- out.push_str(interner.resolve(*r));+ push_name(out, interner, *r, bad);out.push(' ');- write_concept(out, interner, f);+ write_concept(out, interner, f, bad);}Concept::ForAll(r, f) => {out.push_str("all ");- out.push_str(interner.resolve(*r));+ push_name(out, interner, *r, bad);out.push(' ');- write_concept(out, interner, f);+ write_concept(out, interner, f, bad);}Concept::MinCard(r, n, f) => {out.push_str("min ");out.push_str(&n.to_string());out.push(' ');- out.push_str(interner.resolve(*r));+ push_name(out, interner, *r, bad);out.push(' ');- write_concept(out, interner, f);+ write_concept(out, interner, f, bad);}Concept::MaxCard(r, n, f) => {out.push_str("max ");out.push_str(&n.to_string());out.push(' ');- out.push_str(interner.resolve(*r));+ push_name(out, interner, *r, bad);out.push(' ');- write_concept(out, interner, f);+ write_concept(out, interner, f, bad);}}}-fn write_nary(out: &mut String, interner: &Interner, cs: &[Concept], op: &str, unit: &Concept) {+fn write_nary(+ out: &mut String,+ interner: &Interner,+ cs: &[Concept],+ op: &str,+ unit: &Concept,+ bad: &mut Option<String>,+) {match cs.split_first() {- None => write_concept(out, interner, unit),- Some((head, [])) => write_concept(out, interner, head),+ None => write_concept(out, interner, unit, bad),+ Some((head, [])) => write_concept(out, interner, head, bad),Some((head, rest)) => {out.push_str(op);out.push(' ');- write_concept(out, interner, head);+ write_concept(out, interner, head, bad);out.push(' ');- write_nary(out, interner, rest, op, unit);+ write_nary(out, interner, rest, op, unit, bad);}}}-fn concept_string(interner: &Interner, c: &Concept) -> String {+fn concept_string(interner: &Interner, c: &Concept, bad: &mut Option<String>) -> String {let mut s = String::new();- write_concept(&mut s, interner, c);+ write_concept(&mut s, interner, c, bad);s}-fn axiom_line(interner: &Interner, a: &DlAxiom) -> String {- let cs = |c: &Concept| concept_string(interner, c);- let r = |id: &u32| interner.resolve(*id).to_string();+fn axiom_line(interner: &Interner, a: &DlAxiom, bad: &mut Option<String>) -> String {+ // Every name in the line goes through `push_name`, including the ones that+ // are not inside a concept, so `bad` is set by the time the line exists.+ let cs = |c: &Concept, bad: &mut Option<String>| concept_string(interner, c, bad);+ let r = |id: &u32, bad: &mut Option<String>| {+ let mut s = String::new();+ push_name(&mut s, interner, *id, bad);+ s+ };match a {- DlAxiom::Sub(c, d) => format!("sub\t{}\t{}", cs(c), cs(d)),- DlAxiom::Disjoint(c, d) => format!("disjoint\t{}\t{}", cs(c), cs(d)),- DlAxiom::Domain(role, c) => format!("domain\t{}\t{}", r(role), cs(c)),- DlAxiom::Range(role, c) => format!("range\t{}\t{}", r(role), cs(c)),- DlAxiom::SubRole(a1, b1) => format!("subrole\t{}\t{}", r(a1), r(b1)),- DlAxiom::Trans(role) => format!("trans\t{}", r(role)),- DlAxiom::Sym(role) => format!("sym\t{}", r(role)),- DlAxiom::Inv(a1, b1) => format!("inv\t{}\t{}", r(a1), r(b1)),- DlAxiom::InvFunc(role) => format!("invfunc\t{}", r(role)),- DlAxiom::Inst(i, c) => format!("inst\t{}\t{}", r(i), cs(c)),- DlAxiom::Rel(a1, role, b1) => format!("rel\t{}\t{}\t{}", r(a1), r(role), r(b1)),- DlAxiom::Indiv(i) => format!("indiv\t{}", r(i)),- DlAxiom::NonEmpty(c) => format!("nonempty\t{}", cs(c)),- }-}--/// Every name a concept mentions, for the safety check.-fn concept_names(interner: &Interner, c: &Concept, out: &mut Vec<String>) {- match c {- Concept::Top | Concept::Bottom => {}- Concept::Atom(a) | Concept::NegAtom(a) => out.push(interner.resolve(*a).to_string()),- Concept::And(cs) | Concept::Or(cs) => {- for c in cs {- concept_names(interner, c, out);- }- }- Concept::Exists(r, f) | Concept::ForAll(r, f) => {- out.push(interner.resolve(*r).to_string());- concept_names(interner, f, out);- }- Concept::MinCard(r, _, f) | Concept::MaxCard(r, _, f) => {- out.push(interner.resolve(*r).to_string());- concept_names(interner, f, out);- }+ DlAxiom::Sub(c, d) => format!("sub\t{}\t{}", cs(c, bad), cs(d, bad)),+ DlAxiom::Disjoint(c, d) => format!("disjoint\t{}\t{}", cs(c, bad), cs(d, bad)),+ DlAxiom::Domain(role, c) => format!("domain\t{}\t{}", r(role, bad), cs(c, bad)),+ DlAxiom::Range(role, c) => format!("range\t{}\t{}", r(role, bad), cs(c, bad)),+ DlAxiom::SubRole(a1, b1) => format!("subrole\t{}\t{}", r(a1, bad), r(b1, bad)),+ DlAxiom::Trans(role) => format!("trans\t{}", r(role, bad)),+ DlAxiom::Sym(role) => format!("sym\t{}", r(role, bad)),+ DlAxiom::Inv(a1, b1) => format!("inv\t{}\t{}", r(a1, bad), r(b1, bad)),+ DlAxiom::InvFunc(role) => format!("invfunc\t{}", r(role, bad)),+ DlAxiom::Inst(i, c) => format!("inst\t{}\t{}", r(i, bad), cs(c, bad)),+ DlAxiom::Rel(a1, role, b1) => {+ format!("rel\t{}\t{}\t{}", r(a1, bad), r(role, bad), r(b1, bad))+ }+ DlAxiom::Indiv(i) => format!("indiv\t{}", r(i, bad)),+ DlAxiom::NonEmpty(c) => format!("nonempty\t{}", cs(c, bad)),}}@@ -4378,71 +4395,23 @@ impl DlReasoner {ind,};- // Every name that will appear in either file has to survive the round- // trip. `owl:hasValue` is approximated by an atom named after the- // individual, and that individual can be a literal with a space in it.- let mut names: Vec<String> = Vec::new();- for a in &axioms {- match a {- DlAxiom::Sub(c, d) | DlAxiom::Disjoint(c, d) => {- concept_names(&self.interner, c, &mut names);- concept_names(&self.interner, d, &mut names);- }- DlAxiom::Domain(r, c) | DlAxiom::Range(r, c) => {- names.push(self.interner.resolve(*r).to_string());- concept_names(&self.interner, c, &mut names);- }- DlAxiom::Inst(i, c) => {- names.push(self.interner.resolve(*i).to_string());- concept_names(&self.interner, c, &mut names);- }- DlAxiom::NonEmpty(c) => concept_names(&self.interner, c, &mut names),- DlAxiom::SubRole(x, y) | DlAxiom::Inv(x, y) => {- names.push(self.interner.resolve(*x).to_string());- names.push(self.interner.resolve(*y).to_string());- }- DlAxiom::Trans(r) | DlAxiom::Sym(r) | DlAxiom::InvFunc(r) => {- names.push(self.interner.resolve(*r).to_string())- }- DlAxiom::Rel(x, r, y) => {- names.push(self.interner.resolve(*x).to_string());- names.push(self.interner.resolve(*r).to_string());- names.push(self.interner.resolve(*y).to_string());- }- DlAxiom::Indiv(i) => names.push(self.interner.resolve(*i).to_string()),- }- }- for &(role, _) in model.rext.keys() {- names.push(self.interner.resolve(role).to_string());- }- for &class in model.cext.keys() {- names.push(self.interner.resolve(class).to_string());- }- if let Some(bad) = names.iter().find(|n| !name_is_safe(n)) {- return Ok(ModelOutcome::Refused(format!(- "the name {bad:?} carries whitespace, so it would not survive the \- tab-and-space separated format; nothing was written"- )));- }-- // The gate. A certificate that will not check is worse than no- // certificate, so the emitter runs the same semantics the checker does- // and refuses when it does not hold.- if let Err(why) = model.well_formed(&axioms) {- return Ok(ModelOutcome::Refused(format!(- "the folded completion graph is not a finite interpretation: {why}"- )));- }- if let Some(bad) = axioms.iter().find(|a| !model.holds(a)) {- return Ok(ModelOutcome::Refused(format!(- "the folded completion graph does not satisfy the axiom `{}`",- axiom_line(&self.interner, bad).replace('\t', " ")- )));- }+ // Every name that appears in either file has to survive the round trip.+ // `owl:hasValue` is approximated by an atom named after the individual,+ // and that individual can be a literal with a space in it.+ //+ // The check is AT THE POINT OF WRITING. It used to be a separate walk+ // over every axiom variant plus `model.rext` and `model.cext`, with+ // individuals in `model.ind` covered only because `DlAxiom::Indiv(i)`+ // happens to be emitted for every individual that reaches the model:+ // TCB-26, an argument about two loops agreeing rather than a check.+ // Building the text first and letting `push_name` record the first+ // refusal makes the coverage question disappear, because `push_name` is+ // the only way a name reaches either buffer.+ let mut bad: Option<String> = None;let mut axiom_text = String::new();for a in &axioms {- axiom_text.push_str(&axiom_line(&self.interner, a));+ axiom_text.push_str(&axiom_line(&self.interner, a, &mut bad));axiom_text.push('\n');}@@ -4462,7 +4431,9 @@ impl DlReasoner {classes.sort_unstable();for (c, ms) in classes {for m in ms {- model_text.push_str(&format!("class\t{}\tn{m}\n", self.interner.resolve(c)));+ model_text.push_str("class\t");+ push_name(&mut model_text, &self.interner, c, &mut bad);+ model_text.push_str(&format!("\tn{m}\n"));}}let mut edge_lines: Vec<(u32, u32, u32)> = Vec::new();@@ -4474,12 +4445,41 @@ impl DlReasoner {edge_lines.sort_unstable();let edge_count = edge_lines.len();for (x, r, y) in edge_lines {- model_text.push_str(&format!("edge\tn{x}\t{}\tn{y}\n", self.interner.resolve(r)));+ model_text.push_str(&format!("edge\tn{x}\t"));+ push_name(&mut model_text, &self.interner, r, &mut bad);+ model_text.push_str(&format!("\tn{y}\n"));}let mut ind_lines: Vec<(u32, u32)> = model.ind.iter().map(|(&i, &n)| (i, n)).collect();ind_lines.sort_unstable();for (i, n) in ind_lines {- model_text.push_str(&format!("ind\t{}\tn{n}\n", self.interner.resolve(i)));+ model_text.push_str("ind\t");+ push_name(&mut model_text, &self.interner, i, &mut bad);+ model_text.push_str(&format!("\tn{n}\n"));+ }++ // Nothing has been written yet, so a refusal here writes nothing. The+ // order is the order it always was: the name guard decides before the+ // semantics gate does.+ if let Some(bad) = bad {+ return Ok(ModelOutcome::Refused(format!(+ "the name {bad:?} carries whitespace, so it would not survive the \+ tab-and-space separated format; nothing was written"+ )));+ }++ // The gate. A certificate that will not check is worse than no+ // certificate, so the emitter runs the same semantics the checker does+ // and refuses when it does not hold.+ if let Err(why) = model.well_formed(&axioms) {+ return Ok(ModelOutcome::Refused(format!(+ "the folded completion graph is not a finite interpretation: {why}"+ )));+ }+ if let Some(bad) = axioms.iter().find(|a| !model.holds(a)) {+ return Ok(ModelOutcome::Refused(format!(+ "the folded completion graph does not satisfy the axiom `{}`",+ axiom_line(&self.interner, bad, &mut None).replace('\t', " ")+ )));}std::fs::create_dir_all(dir)?;@@ -4769,6 +4769,58 @@ mod certificate_boundary_tests {}}+ /// TCB-26, as a statement about this file rather than about a run.+ ///+ /// The guard covers every name that is written because `push_name` is the+ /// only thing that writes one. This reads the source of the two writers and+ /// requires it: no `interner.resolve` may append to a certificate buffer.+ /// It is a crude check and it is the one that matches the claim. The+ /// previous arrangement — a `names` vector built by one loop and the files+ /// written by another — could not be checked this way at all, which is why+ /// TCB-26 was listed as trusted rather than tested.+ #[test]+ fn tcb_26_only_push_name_writes_a_name() {+ let src = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/tableaux.rs"))+ .expect("this file is readable");++ // The two regions that build certificate text: the serialisers, and the+ // emitter that assembles `axioms.tsv` and `model.tsv` out of them.+ let ser_start = src.find("// ── Serialisation ──").expect("the serialisation section");+ let ser_end = src[ser_start..]+ .find("\n// ── The finite interpretation")+ .expect("the section after it")+ + ser_start;+ let emit_start = src.find(" fn emit(\n").expect("the emitter");+ let emit_end = src[emit_start..]+ .find("\n /// Certify that `class_iri` is satisfiable")+ .expect("the method after it")+ + emit_start;+ let regions = [&src[ser_start..ser_end], &src[emit_start..emit_end]];+ assert!(regions[0].contains("fn push_name("), "the guard left the serialisers");+ assert!(regions[1].contains("axioms.tsv"), "the emitter region is not the emitter");++ let mut offenders: Vec<&str> = Vec::new();+ for region in regions {+ for line in region.lines() {+ let t = line.trim();+ if !t.contains("resolve(") || t.starts_with("//") {+ continue;+ }+ // The one inside `push_name`, and the one that names an+ // individual in an ERROR MESSAGE rather than in a line.+ if t == "let s = interner.resolve(id);" || t == "self.interner.resolve(i)" {+ continue;+ }+ offenders.push(line);+ }+ }+ assert!(+ offenders.is_empty(),+ "a name reaches a certificate buffer without passing `push_name`:\n{}",+ offenders.join("\n")+ );+ }+proptest! {#![proptest_config(ProptestConfig { cases: 512, ..ProptestConfig::default() })]@@ -4800,13 +4852,23 @@ mod certificate_boundary_tests {let mut interner = Interner::new();let ids: Vec<u32> = ns.iter().map(|n| interner.intern(n)).collect();let c = build(&sh, &ids);- let s = concept_string(&interner, &c);- if ns.iter().all(|n| name_is_safe(n)) {+ let mut bad = None;+ let s = concept_string(&interner, &c, &mut bad);+ // The condition is now the GUARD's verdict, not the test author's+ // recollection of which names the concept happens to mention. That+ // is TCB-26: `push_name` is the only way a name reaches the buffer,+ // so `bad` is set exactly when the buffer carries an unsafe one.+ if bad.is_none() {prop_assert_eq!(s.split(' ').count(), tokens(&c),"token count drifted from the shape: {:?}", s);prop_assert!(!s.contains('\t') && !s.contains('\n') && !s.contains('\r'));+ } else {+ prop_assert!(+ ns.iter().any(|n| !name_is_safe(n)),+ "the guard refused {:?} but every name is safe", s+ );}}@@ -4834,8 +4896,14 @@ mod certificate_boundary_tests {(DlAxiom::NonEmpty(c), 2),];for (a, want) in cases {- let line = axiom_line(&interner, &a);- if name_is_safe(&n) {+ let mut bad = None;+ let line = axiom_line(&interner, &a, &mut bad);+ // Every one of these variants mentions the generated name, so+ // the guard's verdict and the name's safety have to agree. That+ // is the TCB-26 claim: no variant writes a name the guard did+ // not see, and none reports one it did not write.+ prop_assert_eq!(bad.is_none(), name_is_safe(&n), "{:?}", line);+ if bad.is_none() {prop_assert_eq!(line.split('\t').count(), want,"{:?} is not {} tab-separated fields", line, wantdiff --git a/tests/certificate_boundary_proptest.rs b/tests/certificate_boundary_proptest.rsindex ebba0992..9fe8b903 100644--- a/tests/certificate_boundary_proptest.rs+++ b/tests/certificate_boundary_proptest.rs@@ -1072,23 +1072,34 @@ fn tcb_9_a_quad_in_two_graphs_is_two_lines() {}// ─────────────────────────────────────────────────────────────────────────────-// TCB-8, the part that does NOT hold+// TCB-8 across runs: what was fixed, and what is irreducible// ─────────────────────────────────────────────────────────────────────────────-/// Materialising into the default graph turns run N's conclusions into run-/// N+1's assertions, and nothing in the certificate says which is which.+/// A second certified run does not read the first run's conclusions back as+/// assertions, when the caller asked for them to be kept apart.///-/// This test asserts the DEFECT, because it is real, documented in-/// `docs/lean-certificates.md` and in decision 0001, and mitigated rather than-/// fixed. A test that asserted the property would fail; a test that was absent-/// would let someone believe the property holds. Pinning the failure means the-/// day the behaviour changes, this fails and the documentation gets corrected.+/// **This test used to assert the DEFECT.** `GraphStore::all_triples` read+/// every named graph, so the inferences `inference_graph: true` parked in+/// `https://open-ontologies.org/graph/inferred` came back in the next run's+/// `asserted.tsv` as axioms, with no column saying they were derived. The+/// separation protected `save` and not the certificate, and the second half of+/// this test asserted that it did not work, so that the day it changed the+/// documentation would be forced to change with it. It changed on 15 September+/// 2026: the certified paths read `triples_outside(&[INFERRED_GRAPH])` and the+/// certificate reports the graphs it read. The assertion is now the property.+///+/// The FIRST half still asserts the leak, because that half is not a defect and+/// cannot be fixed here. `InferenceTarget::DefaultGraph` merges conclusions+/// into the default graph beside the assertions, which is what the caller asked+/// for, and after that nothing distinguishes them. That is the irreducible+/// half of TCB-8 and it is why the fix is a fix of the named-graph path.#[test]-fn tcb_8_across_runs_an_inference_becomes_an_assertion() {+fn tcb_8_across_runs_only_the_default_graph_leaks() {let ttl = "<http://e/x> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://e/A> .\n\<http://e/A> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://e/B> .\n";- // Default graph: the inference comes back as an assertion.+ // Default graph: the inference comes back as an assertion, because the+ // caller asked for it to be merged and the merge is lossy.let g = Arc::new(GraphStore::new());g.load_ntriples(ttl).unwrap();let d1 = scratch("leak1");@@ -1105,25 +1116,46 @@ fn tcb_8_across_runs_an_inference_becomes_an_assertion() {std::fs::read_to_string(d2.join("asserted.tsv")).unwrap().lines().map(str::to_string).collect();assert!(concluded.iter().any(|c| asserted2.contains(c)),- "the known limitation is gone; docs/lean-certificates.md and \+ "the default-graph limitation is gone; docs/lean-certificates.md and \docs/trusted-computing-base.md TCB-8 must be corrected");- // The named inference graph does not fix it either: `all_triples` reads- // every graph, so a later certified run still sees them as assertions. It- // protects `save`, not the certificate.+ // The named inference graph DOES fix it. Not one conclusion of the first+ // run appears among the second run's assertions, and the certificate says+ // which graphs it read.let h = Arc::new(GraphStore::new());h.load_ntriples(ttl).unwrap();let d3 = scratch("leak3");- Reasoner::run_full(&h, "rdfs", true, InferenceTarget::Inferred, Some(&d3)).unwrap();+ let r3 = Reasoner::run_full(&h, "rdfs", true, InferenceTarget::Inferred, Some(&d3)).unwrap();+ let j3: serde_json::Value = serde_json::from_str(&r3).unwrap();+ assert!(j3["inferred_count"].as_u64().unwrap() > 0, "run 1 must infer something");let d4 = scratch("leak4");- Reasoner::run_full(&h, "rdfs", true, InferenceTarget::Inferred, Some(&d4)).unwrap();+ let r4 = Reasoner::run_full(&h, "rdfs", true, InferenceTarget::Inferred, Some(&d4)).unwrap();+ let j4: serde_json::Value = serde_json::from_str(&r4).unwrap();let asserted4: BTreeSet<String> =std::fs::read_to_string(d4.join("asserted.tsv")).unwrap().lines().map(str::to_string).collect();- assert!(- concluded.iter().any(|c| asserted4.contains(c)),- "inference_graph now keeps derived triples out of a later asserted.tsv; \- TCB-8 must be corrected"+ for c in &concluded {+ assert!(+ !asserted4.contains(c),+ "the conclusion {c:?} of an earlier run is listed as an assertion of a later one; \+ TCB-8 has regressed"+ );+ }+ // The assertions of run 2 are exactly the assertions of run 1: the store+ // grew, the asserted graph did not.+ assert_eq!(+ j4["certificate"]["asserted"], 2,+ "the second run asserted more than the two triples that were loaded"+ );+ assert_eq!(+ j4["certificate"]["graphs_excluded"][0],+ "https://open-ontologies.org/graph/inferred"+ );+ assert_eq!(j4["certificate"]["graphs_read"][0], "<default>");+ assert_eq!(+ j4["certificate"]["graphs_read"].as_array().unwrap().len(),+ 1,+ "run 2 read a graph run 1 did not");for d in [&d1, &d2, &d3, &d4] {diff --git a/tests/premise_order_test.rs b/tests/premise_order_test.rsnew file mode 100644index 00000000..675b7c64--- /dev/null+++ b/tests/premise_order_test.rs@@ -0,0 +1,468 @@+//! TCB-14: the premise order the engine emits is the order the checker matches,+//! and the two agree BY CONSTRUCTION rather than by a corpus test noticing.+//!+//! `OOCert.checkStep` in `lean/OOCert/Rules.lean` matches a step's premises+//! POSITIONALLY, arm by arm. Until 15 September 2026 the engine passed them in+//! an order written out by hand at each of thirty-one `emit` call sites, and+//! the only thing keeping the two in step was `tests/lean_certificate_test.rs`+//! running the real checker over a corpus. A rule added with its premises in+//! the wrong order produced certificates that failed for a reason no user could+//! act on, and a rule whose corpus coverage was thin could have been wrong for+//! a long time.+//!+//! The engine now computes the premise list and the conclusion from+//! `open_ontologies::reason::BUILTIN_RULES`, so a call site supplies a binding+//! and has no order to get wrong. That moves the question one level up: is THAT+//! table the checker's table? This file answers it by reading the answer out of+//! the checker.+//!+//! It parses the `checkStep` arms — the code, not the prose table in the+//! docstring above them — and rebuilds each arm's premise pattern:+//!+//! * the arm's premise list `[⟨s, p, o⟩, ⟨p', d, c⟩]` gives the arity and the+//! positions;+//! * the conjuncts `p' = p` and `d = V.domain` say which positions are the+//! same variable and which are fixed vocabulary;+//! * `st.conclusion = ⟨s, V.type, c⟩` gives the head.+//!+//! Two patterns are then compared up to renaming of variables, because the+//! names are private to each side. A disagreement in ORDER, in ARITY, in which+//! position is fixed, or in WHICH vocabulary term is fixed, is a failure here.+//!+//! What this does NOT check: the four list rules (`cls-int1`, `cls-int2`,+//! `cls-uni`, `cls-oo`). Their premises are a constructor triple followed by an+//! RDF list chain whose length is the length of the list, so they are not a+//! fixed pattern on either side: the checker matches them with `takeChain` and+//! the engine builds the vector explicitly. They are named and counted rather+//! than passed over silently.++use std::collections::{BTreeMap, BTreeSet};+use std::path::PathBuf;++use open_ontologies::reason::{Kw, Slot, BUILTIN_RULES, CHAINED_RULES};++fn repo() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+}++fn rules_lean() -> String {+ std::fs::read_to_string(repo().join("lean/OOCert/Rules.lean"))+ .expect("lean/OOCert/Rules.lean is tracked by this repository")+}++/// A resolved pattern position: a fixed vocabulary term, or a variable+/// identified by the order of its first appearance.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]+enum Pos {+ Fixed(&'static str),+ Var(usize),+}++/// A rule's premise patterns and its conclusion, canonically numbered.+type Shape = (Vec<[Pos; 3]>, [Pos; 3]);++/// Number the variables by first appearance over body-then-head, so two+/// patterns that differ only in what the two sides call their variables become+/// the same value.+fn canonical(atoms: &[[Option<&'static str>; 3]], names: &[[String; 3]]) -> Shape {+ let mut seen: BTreeMap<String, usize> = BTreeMap::new();+ let mut out: Vec<[Pos; 3]> = Vec::new();+ for (a, n) in atoms.iter().zip(names) {+ let mut row = [Pos::Var(0); 3];+ for i in 0..3 {+ row[i] = match a[i] {+ Some(kw) => Pos::Fixed(kw),+ None => {+ let next = seen.len();+ Pos::Var(*seen.entry(n[i].clone()).or_insert(next))+ }+ };+ }+ out.push(row);+ }+ let head = out.pop().expect("body then head");+ (out, head)+}++// ─────────────────────────────────────────────────────────────────────────────+// The Rust side+// ─────────────────────────────────────────────────────────────────────────────++fn rust_shapes() -> BTreeMap<String, BTreeSet<Shape>> {+ let mut out: BTreeMap<String, BTreeSet<Shape>> = BTreeMap::new();+ for r in BUILTIN_RULES {+ let mut atoms: Vec<[Option<&'static str>; 3]> = Vec::new();+ let mut names: Vec<[String; 3]> = Vec::new();+ for a in r.body.iter().chain(std::iter::once(&r.head)) {+ let mut kws = [None; 3];+ let mut ns = [String::new(), String::new(), String::new()];+ for i in 0..3 {+ match a[i] {+ Slot::Fixed(k) => kws[i] = Some(k.lean_name()),+ Slot::Var(v) => ns[i] = r.vars[v].to_string(),+ }+ }+ atoms.push(kws);+ names.push(ns);+ }+ out.entry(r.name.to_string())+ .or_default()+ .insert(canonical(&atoms, &names));+ }+ out+}++// ─────────────────────────────────────────────────────────────────────────────+// The Lean side+// ─────────────────────────────────────────────────────────────────────────────++/// `| .rdfs2 => "rdfs2"` for every constructor, out of `def Rule.name`.+fn ctor_to_name(src: &str) -> BTreeMap<String, String> {+ let start = src.find("def Rule.name").expect("Rule.name is defined");+ let end = src[start..].find("def Rule.all").expect("Rule.all follows") + start;+ let body = &src[start..end];+ let mut out = BTreeMap::new();+ for chunk in body.split('|').skip(1) {+ let Some((lhs, rhs)) = chunk.split_once("=>") else { continue };+ let ctor = lhs.trim().trim_start_matches('.').trim();+ let Some(q1) = rhs.find('"') else { continue };+ let rest = &rhs[q1 + 1..];+ let Some(q2) = rest.find('"') else { continue };+ if !ctor.is_empty() {+ out.insert(ctor.to_string(), rest[..q2].to_string());+ }+ }+ assert!(out.len() >= 25, "parsed {} constructors out of Rule.name", out.len());+ out+}++/// The identifier triples inside `⟨a, b, c⟩` groups, in source order.+fn angle_triples(s: &str) -> Vec<[String; 3]> {+ let mut out = Vec::new();+ let mut rest = s;+ while let Some(i) = rest.find('\u{27e8}') {+ rest = &rest[i + '\u{27e8}'.len_utf8()..];+ let Some(j) = rest.find('\u{27e9}') else { break };+ let inner = &rest[..j];+ rest = &rest[j + '\u{27e9}'.len_utf8()..];+ let parts: Vec<&str> = inner.split(',').map(str::trim).collect();+ if parts.len() == 3 {+ out.push([+ parts[0].to_string(),+ parts[1].to_string(),+ parts[2].to_string(),+ ]);+ }+ }+ out+}++/// A tiny union-find over identifier names, so `p' = p` and `d = V.domain` can+/// be applied in any order.+#[derive(Default)]+struct Classes {+ parent: BTreeMap<String, String>,+ constant: BTreeMap<String, &'static str>,+}++impl Classes {+ fn find(&mut self, a: &str) -> String {+ let p = self.parent.get(a).cloned().unwrap_or_else(|| a.to_string());+ if p == a {+ return p;+ }+ let root = self.find(&p);+ self.parent.insert(a.to_string(), root.clone());+ root+ }++ fn union(&mut self, a: &str, b: &str) {+ let (ra, rb) = (self.find(a), self.find(b));+ if ra != rb {+ self.parent.insert(ra.clone(), rb.clone());+ if let Some(k) = self.constant.remove(&ra) {+ let prev = self.constant.insert(rb, k);+ assert!(+ prev.is_none() || prev == Some(k),+ "{a} and {b} are equated to two different vocabulary terms"+ );+ }+ }+ }++ fn bind_constant(&mut self, a: &str, k: &'static str) {+ let r = self.find(a);+ let prev = self.constant.insert(r, k);+ assert!(prev.is_none() || prev == Some(k), "{a} is two vocabulary terms");+ }++ fn resolve(&mut self, a: &str) -> (Option<&'static str>, String) {+ let r = self.find(a);+ (self.constant.get(&r).copied(), r)+ }+}++fn kw_by_lean_name(n: &str) -> Option<&'static str> {+ const ALL: &[Kw] = &[+ Kw::Type,+ Kw::SubClassOf,+ Kw::SubPropertyOf,+ Kw::Domain,+ Kw::Range,+ Kw::SameAs,+ Kw::InverseOf,+ Kw::TransitiveProperty,+ Kw::SymmetricProperty,+ Kw::EquivalentClass,+ Kw::EquivalentProperty,+ Kw::OnProperty,+ Kw::SomeValuesFrom,+ Kw::AllValuesFrom,+ Kw::HasValue,+ ];+ ALL.iter().map(|k| k.lean_name()).find(|k| *k == n)+}++struct LeanArms {+ shapes: BTreeMap<String, BTreeSet<Shape>>,+ variadic: BTreeSet<String>,+}++fn lean_arms() -> LeanArms {+ let src = rules_lean();+ let names = ctor_to_name(&src);++ let start = src.find("def checkStep").expect("checkStep is defined");+ let end = src[start..]+ .find("def checkAll")+ .expect("checkAll follows checkStep")+ + start;+ let body = &src[start..end];++ let mut shapes: BTreeMap<String, BTreeSet<Shape>> = BTreeMap::new();+ let mut variadic: BTreeSet<String> = BTreeSet::new();++ // Arms of `checkStep` start at column 2. The `| some (...)` arms of the+ // nested matches are indented further, which is what keeps this split+ // honest; `arms_are_all_accounted_for` is the check that it stayed that way.+ for arm in body.split("\n | ").skip(1) {+ let Some((header, rest)) = arm.split_once("=>") else { continue };+ let header = header.trim();+ if header.starts_with('_') {+ continue; // the catch-all `| _, _ => false`+ }+ let Some((ctor, pattern)) = header.split_once(',') else { continue };+ let ctor = ctor.trim().trim_start_matches('.').trim();+ let name = names+ .get(ctor)+ .unwrap_or_else(|| panic!("checkStep has an arm for `{ctor}`, which Rule.name does not"))+ .clone();+ let pattern = pattern.trim();++ if !(pattern.starts_with('[') && pattern.ends_with(']')) {+ // `⟨c, io, l⟩ :: ps`, a list rule.+ variadic.insert(name);+ continue;+ }++ let premises = angle_triples(pattern);+ assert!(!premises.is_empty(), "{name}: no premises parsed from {pattern}");++ // The arm body, up to the start of the next arm.+ let mut cls = Classes::default();+ for (lhs, rhs) in equalities(rest) {+ match rhs.strip_prefix("V.") {+ Some(v) => {+ let kw = kw_by_lean_name(v).unwrap_or_else(|| {+ panic!("{name}: `V.{v}` has no `Kw` in the Rust table")+ });+ cls.bind_constant(&lhs, kw);+ }+ None => cls.union(&lhs, &rhs),+ }+ }++ let concl = conclusions(rest);+ assert!(!concl.is_empty(), "{name}: no `st.conclusion = ⟨..⟩` found");++ for c in &concl {+ let mut atoms: Vec<[Option<&'static str>; 3]> = Vec::new();+ let mut idents: Vec<[String; 3]> = Vec::new();+ for t in premises.iter().chain(std::iter::once(c)) {+ let mut kws = [None; 3];+ let mut ns = [String::new(), String::new(), String::new()];+ for i in 0..3 {+ // A position written `V.type` directly is fixed; otherwise+ // ask the equality classes.+ if let Some(v) = t[i].strip_prefix("V.") {+ kws[i] = Some(kw_by_lean_name(v).unwrap_or_else(|| {+ panic!("{name}: `V.{v}` has no `Kw` in the Rust table")+ }));+ } else {+ let (k, root) = cls.resolve(&t[i]);+ kws[i] = k;+ ns[i] = root;+ }+ }+ atoms.push(kws);+ idents.push(ns);+ }+ shapes+ .entry(name.clone())+ .or_default()+ .insert(canonical(&atoms, &idents));+ }+ }++ LeanArms { shapes, variadic }+}++/// `a = b` and `a = V.foo` conjuncts. The right-hand side of+/// `st.conclusion = ⟨..⟩` is an angle group and never matches.+fn equalities(body: &str) -> Vec<(String, String)> {+ let mut out = Vec::new();+ let bytes: Vec<char> = body.chars().collect();+ let is_ident = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '\'' || c == '.';+ let mut i = 0;+ while i < bytes.len() {+ if bytes[i] == '=' {+ // Not `==`, not `=>`, not `≠`.+ let next = bytes.get(i + 1).copied().unwrap_or(' ');+ let prev = if i == 0 { ' ' } else { bytes[i - 1] };+ if next == '>' || next == '=' || prev == '=' || prev == '!' {+ i += 1;+ continue;+ }+ let mut a = i;+ while a > 0 && bytes[a - 1] == ' ' {+ a -= 1;+ }+ let end_l = a;+ while a > 0 && is_ident(bytes[a - 1]) {+ a -= 1;+ }+ let lhs: String = bytes[a..end_l].iter().collect();+ let mut b = i + 1;+ while b < bytes.len() && bytes[b] == ' ' {+ b += 1;+ }+ let start_r = b;+ while b < bytes.len() && is_ident(bytes[b]) {+ b += 1;+ }+ let rhs: String = bytes[start_r..b].iter().collect();+ if !lhs.is_empty() && !rhs.is_empty() && !lhs.starts_with("st.") {+ out.push((lhs, rhs));+ }+ i = b;+ continue;+ }+ i += 1;+ }+ out+}++/// Every `st.conclusion = ⟨a, b, c⟩` in an arm. More than one when the rule+/// licenses more than one conclusion from the same premise.+fn conclusions(body: &str) -> Vec<[String; 3]> {+ let mut out = Vec::new();+ let mut rest = body;+ while let Some(i) = rest.find("st.conclusion = ") {+ rest = &rest[i + "st.conclusion = ".len()..];+ let group = angle_triples(rest);+ if let Some(first) = group.first() {+ out.push(first.clone());+ }+ }+ out+}++// ─────────────────────────────────────────────────────────────────────────────+// The tests+// ─────────────────────────────────────────────────────────────────────────────++/// The parser above is itself a parser, and a parser that silently returned+/// nothing would make every assertion below vacuous.+#[test]+fn the_checker_arms_are_recovered() {+ let arms = lean_arms();+ assert_eq!(+ arms.shapes.len() + arms.variadic.len(),+ 27 - 2 + 4,+ "recovered {} fixed-arity arms and {} list arms",+ arms.shapes.len(),+ arms.variadic.len()+ );+ for expect in ["rdfs2", "prp-trp", "cls-avf", "scm-avf2", "scm-rng2"] {+ assert!(arms.shapes.contains_key(expect), "{expect} missing");+ }+ // The rule with two conclusions from one premise really does come back with+ // two shapes, so the `∨` in that arm is being read.+ assert_eq!(arms.shapes["scm-eqc1"].len(), 2);+ assert_eq!(arms.shapes["scm-eqp1"].len(), 2);+ // And a two-premise rule really does come back with two premises, so the+ // arity is being read rather than defaulted.+ let (body, _) = arms.shapes["rdfs2"].iter().next().unwrap();+ assert_eq!(body.len(), 2);+ let (body, _) = arms.shapes["scm-svf1"].iter().next().unwrap();+ assert_eq!(body.len(), 5);+}++/// The list rules are exactly the ones the Rust table also declines to hold,+/// and nothing fell between the two sets.+#[test]+fn the_variadic_arms_are_the_chained_rules() {+ let arms = lean_arms();+ let expected: BTreeSet<String> = CHAINED_RULES.iter().map(|s| s.to_string()).collect();+ assert_eq!(arms.variadic, expected);++ let fixed: BTreeSet<String> = rust_shapes().keys().cloned().collect();+ let all: BTreeSet<String> = fixed.union(&expected).cloned().collect();+ // Every name the checker knows is in one bucket or the other.+ let src = rules_lean();+ let checker_names: BTreeSet<String> = ctor_to_name(&src).into_values().collect();+ assert_eq!(all, checker_names, "a rule is in neither table");+}++/// TCB-14. The premise ORDER the engine emits is the order the checker matches,+/// for every fixed-arity rule, derived from both sides rather than asserted.+#[test]+fn the_emitted_premise_order_is_the_checkers_order() {+ let lean = lean_arms().shapes;+ let rust = rust_shapes();++ assert_eq!(+ rust.keys().collect::<Vec<_>>(),+ lean.keys().collect::<Vec<_>>(),+ "the two tables cover different rules"+ );++ for (name, want) in &lean {+ let got = &rust[name];+ assert_eq!(+ got, want,+ "\n{name}: the engine's premise pattern is not the checker's.\n \+ engine: {got:#?}\n checker: {want:#?}"+ );+ }+}++/// The inverted rule stays inverted. `scm-avf2` concludes `c2 subClassOf c1`+/// where its three siblings conclude `c1 subClassOf c2`, and a table that got+/// it the natural way round would emit a step no model supports.+/// `OOCert.the_natural_avf2_direction_is_not_entailed` is the refutation, and+/// this is the check that the Rust did not quietly normalise it.+#[test]+fn scm_avf2_concludes_the_other_way_round() {+ let rust = rust_shapes();+ let (b1, h1) = rust["scm-svf2"].iter().next().unwrap().clone();+ let (b2, h2) = rust["scm-avf2"].iter().next().unwrap().clone();+ // Same body shape up to the vocabulary term, opposite conclusion.+ assert_eq!(b1.len(), b2.len());+ assert_ne!(+ h1, h2,+ "scm-avf2 concludes in the same direction as scm-svf2, which is unsound"+ );+ let flip = [h2[2], h2[1], h2[0]];+ assert_eq!(h1, flip, "scm-avf2's conclusion is not the reverse of scm-svf2's");+}