Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

merge: the trusted-boundary work, its property tests and the unwritable-conclusion fix

FABIOTESS412f8046eaf0
diff --cc CHANGELOG.md
index c05b38b4,11f34746..01c53ae8
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -5,47 -5,30 +5,71 @@@ All notable changes to Open Ontologies
## [Unreleased]
### Added
+- **The refutation checker has a producer.** `lean/OOCert/Refute.lean` has
+ checked refutations since it landed and nothing in `src/` could write one: a
+ checker with no producer, which is the same shape of defect as a gate that
+ cannot fail. `reason --certificate DIR` (and `onto_reason` with
+ `certificate_dir`) now looks for a contradiction in the closure the fixpoint
+ reached and writes `refutation.tsv` beside `asserted.tsv` and
+ `derivations.tsv`, in the `oo-refute/1` format, with the minimal derivation
+ prefix that reached the clash. `lake exe oo-refute check` accepts it and
+ `oo-refute guard` refuses the derivation certificate over the same graph,
+ which is what `OOCert.a_certificate_adds_nothing_when_the_graph_is_refuted`
+ says to do.
+- **Ten of the seventeen OWL 2 RL rules that conclude `false` are detected, and
+ exactly one is certifiable.** `cax-dw`, `cls-com`, `cls-nothing2`,
+ `cls-maxc1`, `eq-diff1`, `prp-irp`, `prp-asyp`, `prp-pdw`, `prp-npa1` and
+ `prp-npa2` are looked for after the fixpoint. Only `cax-dw` gets a refutation
+ file, because `OOCert.RefuteConditions` carries a semantic condition for that
+ rule alone and `oo-refute` refuses a refutation naming any other with exit 2.
+ The other nine report `clash_found_by_this_engine` and write nothing, and the
+ seven not looked for at all (`cax-adc`, `prp-adp`, `eq-diff2`, `eq-diff3`,
+ `cls-maxqc1`, `cls-maxqc2`, `dt-not-type`) are listed in the response with the
+ reason, so a clean run is never read as a consistency result.
+- **The two verdicts are kept apart by a test.** `clash_found_by_this_engine` is
+ the engine's word and `unsatisfiable_under_disjointness` is what `oo-refute`
+ prints for an ACCEPTED refutation.
+ `tests/lean_refutation_producer_test.rs::the_engine_never_states_the_checkers_verdict`
+ walks every string in the response and fails if the engine ever states the
+ checker's verdict or names its soundness theorem, on the pattern
+ `a_user_rule_never_earns_the_absolute_verdict` set for the Horn layer.
+ `a_consistent_ontology_is_not_refuted` is the test that matters most: no
+ refutation is produced for a consistent ontology and a hand-written one over
+ it is rejected.
+- **The limit is stated and computed, not papered over.** `cax-dw` needs an
+ INDIVIDUAL in two disjoint classes, so a TBox unsatisfiable with no individual
+ asserted is invisible to the rule-based route.
+ `the_tbox_only_case_is_invisible_here_and_the_tableau_sees_it` runs one
+ ontology through both paths: `owl-rl` finds nothing and `owl-dl` reports the
+ unsatisfiable class. No refutation is emitted from the tableau, and the
+ obstruction is written down: `oo-refute/1` can express one contradiction,
+ `cax-dw`, over triples the forward-chaining prefix can reach, and a clash
+ reached through `∃`/`∀` expansion or a cardinality bound has no form in it.
+ Widening that is a change to `lean/`.
+ - **The trusted computing base of the certificate layer is written down and
+ property-tested.** `docs/trusted-computing-base.md` enumerates, as twenty-nine
+ checkable properties, everything `lean/` assumes about the Rust: that
+ `asserted.tsv` is the graph the engine reasoned over with nothing dropped and
+ nothing added, that every emitted step is a step the engine took, that the
+ interner round-trips, that the rule table the certificate is checked against
+ is the table that was evaluated, and that no term can carry the field or
+ record separator of a format that has no escaping layer of its own.
+ `tests/certificate_boundary_proptest.rs` property-tests them with generators
+ built to forge a derivation step: literals holding tabs, newlines, carriage
+ returns, quotes and backslashes, a literal spelled exactly like an IRI, a
+ literal spelled exactly like a whole extra TSV line, combining characters
+ against their precomposed form, percent-encoded separators inside IRIs, the
+ empty graph. `proptest` is a DEV-dependency; the shipped binary's dependency
+ surface is unchanged. Three Kani harnesses in `src/reason.rs` (`make verify`)
+ prove the serialisation properties over every byte pattern at a fixed term
+ length rather than over a sample; the bound is stated on each harness, along
+ with the two formulations that made CBMC measure the wrong function. A fourth,
+ over `parse_pat`, does NOT terminate (no verdict at 14 minutes and 9.5GB,
+ because `anyhow`'s error formatting is flattened whether or not the refusal
+ paths are reachable); it is excluded from `make verify`, carries its
+ measurements, and the property is sampled instead. The first property-test run
+ found the `rdfs7` defect below, and measuring its reach found the `cls-avf`
+ one.
- **First-order export, over the translation a machine-checked adequacy theorem
is about.** `fol --out DIR --format tptp|clif` (also `onto_fol_export` and
batch `fol`) writes the loaded ontology as TPTP FOF or as ISO/IEC 24707
@@@ -152,36 -94,40 +176,70 @@@
trace. See docs/lean-certificates.md and decision 0002.
### Fixed
+- **An ASSERTED role edge skipped its `rdfs:domain` and `rdfs:range`, so an
+ inconsistent ABox was reported consistent.** Domain and range are deliberately
+ not GCIs: as `∃p.⊤ ⊑ D` and `⊤ ⊑ ∀p.R` they put a disjunction on every node,
+ and hqdm.owl alone carries 525 of them, so they are held as role metadata and
+ applied when an edge is created. Two places create an edge and only one
+ consulted that metadata. `Tableau::create_successor` applied it; the ABox
+ builder wrote asserted role assertions, and the inverse back-edges it
+ materialises for them, straight into the edge map. Every other role-sensitive
+ rule reads edges through `successors()` and so was unaffected, which is why
+ exactly these two constraints were weaker on an asserted edge than on a
+ generated one. The consequence was a false clean: an ontology whose only
+ contradiction is that an asserted edge forces its subject into a class
+ disjoint from one it already carries came back `consistent: true` with
+ `undecided: false`, the strongest answer the checker can give. Both paths now
+ go through one `Tableau::add_role_edge` primitive. It also applies the
+ constraints stated on the role's INVERSE, which NEITHER path applied before:
+ `a r b` entails `b r⁻ a`, so `r⁻`'s domain binds `b` and its range binds `a`,
+ and a symmetric role is its own inverse and rides the same clause. Found by
+ the model-certificate layer, which had been refusing to certify these
+ completion graphs because they are not models of the range axiom;
+ `tests/dl_model_certificate_test.rs` pinned the defect and now pins the
+ repair.
+- **GCIs did not reach an individual named only as the object of a role
+ assertion.** The ABox builder gives the GCIs to every typed individual and
+ `create_successor` gives them to every generated successor, but an IRI that
+ appears only as an edge's object got a bare node carrying nothing but its own
+ nominal. A GCI holds of every element of the domain, so that node was a hole
+ the check could not see into, and an ABox whose only contradiction landed
+ there was reported consistent. Same shape as the domain/range split, found in
+ the sweep for it.
+ - **A rule concluding a triple with a non-IRI PREDICATE left the store half
+ materialised, with no certificate, and reported failure.** `rdfs7` reads
+ `s sub o` and `sub rdfs:subPropertyOf super` and concludes `s super o`, and
+ nothing required `super` to be an IRI. `:p rdfs:subPropertyOf [ owl:inverseOf
+ :q ]` is enough, and that is exactly what the OWL 2 mapping to RDF produces
+ for `SubObjectPropertyOf(:p ObjectInverseOf(:q))`, so an ordinary OWL
+ ontology made `reason` fail with `Parser error: The predicate of a triple must
+ be an IRI`. The failure was not clean: `GraphStore::load_ntriples` streams,
+ inserting each quad as it parses it, so the batch failed PARTWAY. Measured on
+ one fixture over three consecutive runs of identical input, 40, 9 and 24 of
+ 40 good inferences stayed in the store, the number being hash iteration order,
+ and `run_full` then returned the error and never wrote the certificate. The
+ store was left holding uncertified inferences while the caller was told the
+ run had failed. In `--dry-run` the materialiser never ran, so the certificate
+ WAS written, containing a conclusion no RDF serialiser can express; the Lean
+ checker holds terms as opaque strings and accepts it. Reachable from `rdfs7`,
+ `prp-inv1`, `prp-inv2` and `cls-hv1`, each of which takes its conclusion's
+ predicate from an object position where RDF permits a blank node or a literal.
+ Found by the new property tests at case 115, shrunk to two triples.
+ - **`cls-avf` could still conclude a triple with a LITERAL subject.** The same
+ defect one position over, found while measuring the reach of the one above.
+ `cls-avf` derives `y rdf:type c` from `x rdf:type ∀P.c` and `x P y`, so an
+ `owl:allValuesFrom` restriction on a property with a literal value derived
+ `"x" rdf:type :D` and broke the materialiser the same way. The subject case
+ was found on 30 August 2026 and guarded at `prp-symp`, `prp-inv1`, `prp-inv2`
+ and `eq-sym`; `cls-avf` was not among them, and this one needs no unusual
+ modelling at all. Both positions are now decided in ONE place,
+ `writable_triple`, shared with `run_horn`, which was the only path that
+ already refused either: a refused conclusion is not materialised, not
+ certified and not available as a premise, and the run reports
+ `skipped_unserialisable` with examples. `tests/reason_unwritable_predicate_test.rs`
+ pins every reachable rule, and pins that `prp-symp` and `prp-trp` are NOT
+ reachable, because their property must already be the predicate of a stored
+ triple and is therefore an IRI.
- **The CLIF export produced files that parse cleanly and yield NOTHING.**
Every sentence was emitted as `(cl:comment '...' SENTENCE)`, the shape
ISO/IEC 21838-2's BFO files use. Measured against both CLIF parsers that
diff --cc README.md
index 251994ca,3c446c01..7e2bf527
--- a/README.md
+++ b/README.md
@@@ -1009,38 -1009,12 +1009,44 @@@ was in the engine: `cls-svf1` derived t
in [docs/lean-certificates.md](docs/lean-certificates.md) and
[decision 0002](docs/decisions/0002-an-inference-carries-a-certificate.md).
+The same run also looks for a contradiction, and writes `refutation.tsv` when it
+finds one `oo-refute` can judge. Ten of the seventeen OWL 2 RL rules that
+conclude `false` are detected; one of them, `cax-dw`, has a semantic condition
+in `lean/` and is the only one a refutation is written for. The other nine are
+reported as found by this engine and nothing more, because a file naming a rule
+the checker cannot judge would be a certificate-shaped object that certifies
+nothing. `cax-dw` needs an individual in two disjoint classes, so a TBox that is
+unsatisfiable with no individual asserted is invisible to the rule-based route:
+the `owl-dl` tableau sees that case and its answer carries no certificate.
+### Rules you wrote
+
+`reason --rules TABLE --certificate DIR` evaluates a rule table you supply and
+writes a certificate `lake exe oo-horn check` verifies against
+`OOCert.horn_certificate_sound`, one theorem proved for every rule table at
+once. `rules-import --from swrl` reads SWRL rules out of a loaded ontology and
+`--from rif` reads RIF Core out of its XML syntax, so the table need not be
+hand-written.
+
+Only a FRAGMENT of each language is a Horn table over triple patterns. SWRL
+built-in atoms, same-individual and different-individual atoms and data ranges
+are refused; RIF equality, `External`, `Expr`, `rif:local` constants, list terms
+and the presentation syntax are refused. Each refusal is named and counted, and
+by default one refusal fails the whole import: a rule set that quietly lost half
+its rules still reaches a fixpoint and its certificate still checks green, which
+is a sound proof about a rule set nobody wrote.
+
+A rule you supply is an assumption nobody checked, so a certificate over it
+earns `entailed_under_supplied_rules` — true in every model of the asserted
+graph **that also satisfies your rules** — and never the `entailed` that only
+the built-in table earns. Details in
+[docs/rule-syntax-front-ends.md](docs/rule-syntax-front-ends.md) and
+[decision 0003](docs/decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md).
+ The theorem is conditional, and what it is conditional on is the Rust writing
+ down the truth: the asserted graph the certificate names, and the steps it
+ records. That boundary is small, it is the whole trusted base of this layer, and
+ it is enumerated as twenty-nine checkable properties in
+ [docs/trusted-computing-base.md](docs/trusted-computing-base.md), with what
+ checks each and what is still trusted. Read it before relying on a certificate.
### Studio
@@@ -1127,7 -1101,7 +1133,8 @@@ flowchart T
| Schema Alignment | [docs/alignment.md](docs/alignment.md) |
| SHIQ Reasoning | [docs/reasoning.md](docs/reasoning.md) |
| Derivation certificates, Lean checker | [docs/lean-certificates.md](docs/lean-certificates.md) |
+| SWRL and RIF Core rule front ends | [docs/rule-syntax-front-ends.md](docs/rule-syntax-front-ends.md) |
+ | What the Lean proofs assume about the Rust | [docs/trusted-computing-base.md](docs/trusted-computing-base.md) |
| Semantic Embeddings | [docs/embeddings.md](docs/embeddings.md) |
| Clinical Crosswalks | [docs/clinical.md](docs/clinical.md) |
| IES Ecosystem | [docs/ies-ecosystem.md](docs/ies-ecosystem.md) |
diff --cc docs/lean-certificates.md
index 43f0be20,80360df1..bf358ced
--- a/docs/lean-certificates.md
+++ b/docs/lean-certificates.md
@@@ -288,42 -168,25 +288,57 @@@ inference and never the premises. The r
runs can be compared, and `tests/lean_horn_certificate_test.rs` fails if a user-rule run ever
reports the absolute verdict.
-Nineteen of the engine's rules are Horn rules and appear in the built-in table. `cls-int1` and
-`cls-uni` are not: their premise count is the length of an RDF list, which is data rather than fixed
-by the rule, so they remain hardcoded arms. A user rule language stops at the same boundary.
+Twenty-seven of the engine's rules are Horn rules and appear in the built-in table, the count
+`the_built_in_rules_are_emitted_as_data` pins. Four are not: `cls-int1`, `cls-int2`, `cls-uni` and
+`cls-oo` each read an RDF list off the graph, so the LIST is a premise and the premise count is data
+rather than fixed by the rule. They remain hardcoded arms. A user rule language stops at the same
+boundary.
+
+`reason --rules TABLE --certificate DIR` evaluates a supplied table to a fixpoint over the loaded
+graph and writes the three files `oo-horn check` reads. Nothing is materialised: a conclusion drawn
+under a table nobody has checked holds only in models that satisfy that table, and writing it into
+the store beside the assertions would lose exactly that distinction. See
+[decision 0003](decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md).
+
+## Rules you wrote in SWRL or RIF Core
+
+`rules.tsv` is an internal encoding, not a language anybody writes in. `rules-import` reads two
+standard rule syntaxes into it.
+
+```bash
+open-ontologies load ontology.ttl
+open-ontologies rules-import --from swrl --out rules.tsv # SWRL, out of the loaded graph
+open-ontologies rules-import --from swrl --file rules.owl --out rules.tsv
+open-ontologies rules-import --from rif --file rules.xml --out rules.tsv
+open-ontologies reason --rules rules.tsv --certificate cert/
+cd lean && lake exe oo-horn check ../cert/rules.tsv ../cert/asserted.tsv ../cert/horn.tsv
+```
+
+**Only part of each language is a Horn table over triple patterns, and the exact fragment is in
+[docs/rule-syntax-front-ends.md](rule-syntax-front-ends.md) and in every response.** A rule outside
+it is named, counted and refused; by default one refusal fails the whole import and writes nothing,
+because a table that quietly lost a rule still reaches a fixpoint and still produces a certificate
+that checks green, which is a sound proof about a rule set nobody wrote. `--allow-partial` imports
+the rest and flags the result `certifies_a_weaker_rule_set`.
+Every imported rule is a rule you wrote, so it lands on the second row of the table above without
+exception: imported rules are named `swrl/…` and `rif/…`, no built-in rule is, and `oo-horn` awards
+the absolute verdict only to a table that renders identically to the built-in one.
+ The Rust reasoner evaluates a supplied rule table through `reason --rules RULES.tsv --certificate
+ DIR`, which writes `rules.tsv`, `asserted.tsv` and `horn.tsv` and states no verdict of its own.
+ Nothing is materialised into the store: a conclusion drawn under a table you wrote holds only in
+ models that satisfy that table, and merging it in beside the assertions would lose exactly the
+ distinction this is about. See
+ [decision 0003](decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md).
+
+ ## What the checker assumes about the engine
+
+ The theorem is conditional. It says that IF the asserted graph is `G` and IF these steps check,
+ THEN the conclusions hold in every model of `G`. Everything to the left of that is the Rust writing
+ down the truth, and the checker cannot see any of it: it reads files, not the store and not the
+ run. `docs/trusted-computing-base.md` enumerates that boundary as twenty-nine checkable properties
+ and says for each what checks it. Read it before relying on a certificate, because a certificate is
+ a claim about a file and the file's relationship to the store is the part nobody proved.
## Known limitations
diff --cc src/reason.rs
index e84931b7,bc34b65e..d5927fc4
--- a/src/reason.rs
+++ b/src/reason.rs
@@@ -53,365 -37,68 +53,428 @@@ struct Derivation
premises: Vec<Fact>,
}
+
+// ── The rules that conclude `false` ─────────────────────────────────────────
+//
+// Seventeen rules of the OWL 2 RL profile conclude `false` rather than a
+// triple: `eq-diff1`, `eq-diff2`, `eq-diff3`, `prp-irp`, `prp-asyp`,
+// `prp-pdw`, `prp-adp`, `prp-npa1`, `prp-npa2`, `cls-nothing2`, `cls-com`,
+// `cls-maxc1`, `cls-maxqc1`, `cls-maxqc2`, `cax-dw`, `cax-adc` and
- // `dt-not-type`. (`lean/OOCert/Refute.lean` says sixteen. Counted against the
- // W3C tables the number is seventeen; the difference is `dt-not-type`, which
- // that file excludes elsewhere on the stated ground that the Lean semantics
- // has no datatype value space. The count is not load-bearing for anything
- // either side computes.)
++// `dt-not-type`. (Seventeen is the count extracted mechanically from the W3C
++// tables, and `lean/OOCert/Refute.lean` now agrees; it said sixteen until the
++// list was checked against the source. `dt-not-type` is the one that is not
++// merely absent from the Lean but INEXPRESSIBLE there, because that semantics
++// has no datatype value space and a literal is its spelling like any other
++// term.)
+//
+// None of them is in the fixpoint's rule table, and none of them could be:
+// `Derivation.conclusion` is a triple. They are looked for HERE, once, over
+// the closure the fixpoint reached, and reported in the separate `oo-refute/1`
+// format.
+//
+// **Only `cax-dw` can be certified**, and the reason is not this file's.
+// `OOCert.RefuteConditions` in `lean/OOCert/Refute.lean` carries exactly one
+// semantic field, for `cax-dw`, and `oo-refute` refuses a refutation naming any
+// other rule with exit 2 rather than judging it. So a clash of any other rule
+// found here is an engine opinion with nothing behind it, it is reported under
+// a different word from the certified one, and no refutation file is written
+// for it.
+
+/// One way the closure contradicts itself: the OWL 2 RL rule that concludes
+/// `false` from it, and the premises that rule reads, in the order the W3C
+/// table writes them (which is also the order `OOCert.checkRefuteStep` matches
+/// on, and a refutation with the right triples in the wrong order is rejected).
+struct Clash {
+ rule: &'static str,
+ premises: Vec<Fact>,
+}
+
+/// The clash rules `lean/` holds a semantic condition for, so that a refutation
+/// naming one can be CHECKED rather than merely asserted.
+///
+/// One rule, and the list is not this file's to extend: adding a name here
+/// without a matching field in `OOCert.RefuteConditions` and a matching arm in
+/// `OOCert.checkRefuteStep` would make the engine write a file the checker
+/// exits 2 on, which is the one failure mode this layer exists to prevent.
+///
+/// One constant, read both by the emitter and by the report, so the two cannot
+/// drift into disagreeing about what was certified.
+const CLASH_RULES_CERTIFIABLE: &[&str] = &["cax-dw"];
+
+fn clash_is_certifiable(rule: &str) -> bool {
+ CLASH_RULES_CERTIFIABLE.contains(&rule)
+}
+
+/// The clash rules this engine does NOT look for, each with the reason. Listed
+/// so that "no clash found" is never read as "consistent": the honest reading
+/// of a clean run is that none of the rules below was even tried.
+const CLASH_RULES_NOT_DETECTED: &[(&str, &str)] = &[
+ ("cax-adc", "owl:AllDisjointClasses states its members in an RDF list, and this detector reads \
+ no lists. The pairwise owl:disjointWith spelling of the same axiom IS detected."),
+ ("prp-adp", "owl:AllDisjointProperties states its members in an RDF list, and this detector \
+ reads no lists. The pairwise owl:propertyDisjointWith spelling IS detected."),
+ ("eq-diff2", "owl:AllDifferent with owl:members is an RDF list. The pairwise owl:differentFrom \
+ spelling IS detected, by eq-diff1."),
+ ("eq-diff3", "owl:AllDifferent with owl:distinctMembers is an RDF list, as above."),
+ ("cls-maxqc1", "owl:maxQualifiedCardinality needs the qualifying owl:onClass and a type check \
+ on the value. Not implemented; owl:maxCardinality 0 IS detected, by cls-maxc1."),
+ ("cls-maxqc2", "the owl:Thing case of the same rule, and not implemented for the same reason."),
+ ("dt-not-type", "an ill-typed literal needs a datatype VALUE space. This engine, and the Lean \
+ semantics under it, read a literal as its N-Triples spelling and compare \
+ nothing by value, so there is no notion here of a literal outside its type."),
+];
+
+/// The interned vocabulary [`find_clashes`] reads. Gathered into one value so
+/// the detector takes three arguments rather than eighteen.
+struct ClashVocab {
+ rdf_type: u32,
+ disjoint_with: u32,
+ nothing: u32,
+ complement_of: u32,
+ irreflexive: u32,
+ asymmetric: u32,
+ prop_disjoint_with: u32,
+ same_as: u32,
+ different_from: u32,
+ max_cardinality: u32,
+ on_property: u32,
+ source_individual: u32,
+ assertion_property: u32,
+ target_individual: u32,
+ target_value: u32,
+}
+
+/// Zero, in whichever spelling the store hands back for a
+/// `xsd:nonNegativeInteger` zero. Only the lexical form is read, because
+/// nothing else in this engine compares a literal by value and a detector that
+/// did would be claiming a datatype semantics the checker underneath it does
+/// not have.
+fn literal_is_zero(term: &str) -> bool {
+ let Some(rest) = term.strip_prefix('"') else {
+ return false;
+ };
+ let Some(end) = rest.find('"') else {
+ return false;
+ };
+ rest[..end].trim().parse::<i128>().map(|n| n == 0).unwrap_or(false)
+}
+
+/// Look for a contradiction in the closure the fixpoint reached.
+///
+/// Deterministic: the result is sorted on the N-Triples spelling of the
+/// premises and duplicates are dropped, so two runs over one store produce the
+/// same refutation file byte for byte.
+fn find_clashes(closure: &HashSet<Fact>, interner: &Interner, v: &ClashVocab) -> Vec<Clash> {
+ // One pass for every index, because the closure is the large thing here.
+ let mut by_class: HashMap<u32, Vec<u32>> = HashMap::new();
+ let mut disjoint: Vec<Fact> = Vec::new();
+ let mut complement: Vec<Fact> = Vec::new();
+ let mut irreflexive: HashSet<u32> = HashSet::new();
+ let mut asymmetric: HashSet<u32> = HashSet::new();
+ let mut prop_disjoint: Vec<Fact> = Vec::new();
+ let mut different: Vec<Fact> = Vec::new();
+ let mut on_property: HashMap<u32, u32> = HashMap::new();
+ let mut max_zero: Vec<(u32, u32)> = Vec::new();
+ let mut npa_source: HashMap<u32, u32> = HashMap::new();
+ let mut npa_prop: HashMap<u32, u32> = HashMap::new();
+ let mut npa_target_ind: HashMap<u32, u32> = HashMap::new();
+ let mut npa_target_val: HashMap<u32, u32> = HashMap::new();
+ for &(s, p, o) in closure.iter() {
+ if p == v.rdf_type {
+ by_class.entry(o).or_default().push(s);
+ if o == v.irreflexive {
+ irreflexive.insert(s);
+ }
+ if o == v.asymmetric {
+ asymmetric.insert(s);
+ }
+ } else if p == v.disjoint_with {
+ disjoint.push((s, p, o));
+ } else if p == v.complement_of {
+ complement.push((s, p, o));
+ } else if p == v.prop_disjoint_with {
+ prop_disjoint.push((s, p, o));
+ } else if p == v.different_from {
+ different.push((s, p, o));
+ } else if p == v.on_property {
+ on_property.insert(s, o);
+ } else if p == v.max_cardinality && literal_is_zero(interner.resolve(o)) {
+ max_zero.push((s, o));
+ } else if p == v.source_individual {
+ npa_source.insert(s, o);
+ } else if p == v.assertion_property {
+ npa_prop.insert(s, o);
+ } else if p == v.target_individual {
+ npa_target_ind.insert(s, o);
+ } else if p == v.target_value {
+ npa_target_val.insert(s, o);
+ }
+ }
+
+ let mut out: Vec<Clash> = Vec::new();
+
+ // cax-dw: c1 owl:disjointWith c2, x rdf:type c1, x rdf:type c2.
+ // The one rule a refutation can be written for.
+ for &(c1, dw, c2) in &disjoint {
+ let Some(xs) = by_class.get(&c1) else { continue };
+ for &x in xs {
+ if closure.contains(&(x, v.rdf_type, c2)) {
+ out.push(Clash {
+ rule: "cax-dw",
+ premises: vec![(c1, dw, c2), (x, v.rdf_type, c1), (x, v.rdf_type, c2)],
+ });
+ }
+ }
+ }
+
+ // cls-com: the same shape, over owl:complementOf.
+ for &(c1, co, c2) in &complement {
+ let Some(xs) = by_class.get(&c1) else { continue };
+ for &x in xs {
+ if closure.contains(&(x, v.rdf_type, c2)) {
+ out.push(Clash {
+ rule: "cls-com",
+ premises: vec![(c1, co, c2), (x, v.rdf_type, c1), (x, v.rdf_type, c2)],
+ });
+ }
+ }
+ }
+
+ // cls-nothing2: x rdf:type owl:Nothing.
+ if let Some(xs) = by_class.get(&v.nothing) {
+ for &x in xs {
+ out.push(Clash {
+ rule: "cls-nothing2",
+ premises: vec![(x, v.rdf_type, v.nothing)],
+ });
+ }
+ }
+
+ // eq-diff1: x owl:sameAs y, x owl:differentFrom y. The spec's pattern
+ // exactly, with both premises on the same subject.
+ for &(x, df, y) in &different {
+ if closure.contains(&(x, v.same_as, y)) {
+ out.push(Clash {
+ rule: "eq-diff1",
+ premises: vec![(x, v.same_as, y), (x, df, y)],
+ });
+ }
+ }
+
+ // prp-irp, prp-asyp and prp-pdw each need a second scan over the closure,
+ // and the scan is skipped entirely when none of their vocabulary is
+ // present, which is the case for every ontology this repository ships.
+ if !irreflexive.is_empty() || !asymmetric.is_empty() || !prop_disjoint.is_empty() {
+ for &(x, p, y) in closure.iter() {
+ // prp-irp: p rdf:type owl:IrreflexiveProperty, x p x.
+ if x == y && irreflexive.contains(&p) {
+ out.push(Clash {
+ rule: "prp-irp",
+ premises: vec![(p, v.rdf_type, v.irreflexive), (x, p, y)],
+ });
+ }
+ // prp-asyp: p rdf:type owl:AsymmetricProperty, x p y, y p x.
+ if asymmetric.contains(&p) && closure.contains(&(y, p, x)) {
+ out.push(Clash {
+ rule: "prp-asyp",
+ premises: vec![(p, v.rdf_type, v.asymmetric), (x, p, y), (y, p, x)],
+ });
+ }
+ // prp-pdw: p1 owl:propertyDisjointWith p2, x p1 y, x p2 y.
+ for &(p1, pdw, p2) in &prop_disjoint {
+ if p == p1 && closure.contains(&(x, p2, y)) {
+ out.push(Clash {
+ rule: "prp-pdw",
+ premises: vec![(p1, pdw, p2), (x, p1, y), (x, p2, y)],
+ });
+ }
+ }
+ }
+ }
+
+ // cls-maxc1: x owl:maxCardinality 0, x owl:onProperty p, u rdf:type x, u p y.
+ // The (subject, predicate) index is built only when the vocabulary is
+ // present, so an ontology with no cardinality-zero restriction pays for
+ // none of it.
+ if !max_zero.is_empty() {
+ let mut values: HashMap<(u32, u32), Vec<u32>> = HashMap::new();
+ for &(s, p, o) in closure.iter() {
+ values.entry((s, p)).or_default().push(o);
+ }
+ for &(r, zero) in &max_zero {
+ let Some(&prop) = on_property.get(&r) else { continue };
+ let Some(us) = by_class.get(&r) else { continue };
+ for &u in us {
+ let Some(ys) = values.get(&(u, prop)) else { continue };
+ for &y in ys {
+ out.push(Clash {
+ rule: "cls-maxc1",
+ premises: vec![
+ (r, v.max_cardinality, zero),
+ (r, v.on_property, prop),
+ (u, v.rdf_type, r),
+ (u, prop, y),
+ ],
+ });
+ }
+ }
+ }
+ }
+
+ // prp-npa1 / prp-npa2: a negative property assertion its own graph
+ // contradicts. One assertion per node is read; a node carrying two
+ // owl:sourceIndividual triples is malformed and the last one seen wins.
+ for (&node, &i) in &npa_source {
+ let Some(&p) = npa_prop.get(&node) else { continue };
+ if let Some(&j) = npa_target_ind.get(&node)
+ && closure.contains(&(i, p, j))
+ {
+ out.push(Clash {
+ rule: "prp-npa1",
+ premises: vec![
+ (node, v.source_individual, i),
+ (node, v.assertion_property, p),
+ (node, v.target_individual, j),
+ (i, p, j),
+ ],
+ });
+ }
+ if let Some(&lt) = npa_target_val.get(&node)
+ && closure.contains(&(i, p, lt))
+ {
+ out.push(Clash {
+ rule: "prp-npa2",
+ premises: vec![
+ (node, v.source_individual, i),
+ (node, v.assertion_property, p),
+ (node, v.target_value, lt),
+ (i, p, lt),
+ ],
+ });
+ }
+ }
+
+ // Deterministic order, so the refutation file does not depend on hash
+ // iteration order and two runs over one store agree byte for byte.
+ let mut keyed: Vec<(String, Clash)> = out
+ .into_iter()
+ .map(|c| {
+ let mut k = String::from(c.rule);
+ for &(s, p, o) in &c.premises {
+ k.push('\t');
+ k.push_str(interner.resolve(s));
+ k.push('\t');
+ k.push_str(interner.resolve(p));
+ k.push('\t');
+ k.push_str(interner.resolve(o));
+ }
+ (k, c)
+ })
+ .collect();
+ keyed.sort_by(|a, b| a.0.cmp(&b.0));
+ keyed.dedup_by(|a, b| a.0 == b.0);
+ keyed.into_iter().map(|(_, c)| c).collect()
+}
+
+/// The derivation steps a refutation must carry so that every premise it cites
+/// is either asserted or concluded by a step BEFORE it.
+///
+/// Returns indices into `derivations`, ascending, which is a valid order:
+/// `derivations` records each conclusion the first time the fixpoint reached
+/// it, and every premise of that step was in the closure of an earlier
+/// iteration, so the recorded order is already a topological one.
+///
+/// `None` when a premise is neither asserted nor derived, which cannot happen
+/// for a clash found in the closure of a certified run and would be a bug here
+/// rather than a refutation.
+fn refutation_prefix(
+ premises: &[Fact],
+ derivations: &[Derivation],
+ asserted: &HashSet<Fact>,
+) -> Option<Vec<usize>> {
+ let mut first: HashMap<Fact, usize> = HashMap::new();
+ for (i, d) in derivations.iter().enumerate() {
+ first.entry(d.conclusion).or_insert(i);
+ }
+ let mut needed: HashSet<usize> = HashSet::new();
+ let mut work: Vec<Fact> = premises.to_vec();
+ while let Some(t) = work.pop() {
+ if asserted.contains(&t) {
+ continue;
+ }
+ let &i = first.get(&t)?;
+ if !needed.insert(i) {
+ continue;
+ }
+ work.extend(derivations[i].premises.iter().copied());
+ }
+ let mut ids: Vec<usize> = needed.into_iter().collect();
+ ids.sort_unstable();
+ Some(ids)
+}
+
+ /// Can this triple be written by an RDF serialiser?
+ ///
+ /// A literal cannot be a subject and only an IRI can be a predicate, in every
+ /// RDF 1.1 serialisation. A rule that concludes otherwise has produced
+ /// something the store cannot hold, and the materialiser does not find out
+ /// until it is halfway through inserting the batch.
+ ///
+ /// Both positions, and ONE definition, because the previous attempt was four
+ /// targeted guards and it missed two things.
+ ///
+ /// The subject case was found on 30 August 2026 and guarded at `prp-symp`,
+ /// `prp-inv1`, `prp-inv2` and `eq-sym`. It was still open at `cls-avf`, which
+ /// concludes `y rdf:type c` from `x type ∀P.c` and `x P y`, so an
+ /// `owl:allValuesFrom` restriction on a property with a literal value derived
+ /// `"x" rdf:type :D`. That needs no unusual modelling at all.
+ ///
+ /// The predicate case was never guarded anywhere outside `run_horn`. It is
+ /// reachable from `rdfs7`, `prp-inv1`, `prp-inv2` and `cls-hv1`, each of which
+ /// takes its conclusion's predicate from an object position where RDF permits a
+ /// blank node or a literal. `:p rdfs:subPropertyOf [ owl:inverseOf :q ]` is
+ /// enough, and that is what the OWL 2 mapping to RDF produces for
+ /// `SubObjectPropertyOf(:p ObjectInverseOf(:q))`. Found by
+ /// `tests/certificate_boundary_proptest.rs` on 14 September 2026 and pinned by
+ /// `tests/reason_unwritable_predicate_test.rs`, which also pins that `prp-symp`
+ /// and `prp-trp` CANNOT reach it, because their property must already be the
+ /// predicate of a stored triple and is therefore an IRI.
+ ///
+ /// Terms arrive in their N-Triples spelling, so a literal begins with `"` and
+ /// an IRI with `<`.
+ fn writable_triple(subject: &str, predicate: &str) -> bool {
+ !subject.starts_with('"') && predicate.starts_with('<')
+ }
+
+ /// 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
+ /// the trusted computing base: `OOCert.certificate_sound` is conditional on the
+ /// asserted graph, `OOCert.Parse.parseTriples` recovers it by splitting on
+ /// those two characters, and nothing between the two escapes anything. It lives
+ /// 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) {
+ out.push_str(s);
+ out.push('\t');
+ out.push_str(p);
+ out.push('\t');
+ out.push_str(o);
+ out.push('\n');
+ }
+
+ /// 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) {
+ out.push('\t');
+ out.push_str(s);
+ out.push('\t');
+ out.push_str(p);
+ out.push('\t');
+ out.push_str(o);
+ }
+
/// Intern strings to u32 IDs for efficient reasoning.
struct Interner {
to_id: HashMap<String, u32>,