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.

reason: produce the refutation certificates the verified checker could already read

FABIOTESS184f3f960f47
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 26f5be19..936da201 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -330,6 +330,15 @@ jobs:
run: OO_REQUIRE_FIXTURES=1 cargo test --test dl_model_certificate_test -- --nocapture
- name: Check the refutation certificates
run: OO_REQUIRE_FIXTURES=1 cargo test --test lean_refutation_test -- --nocapture
+ - name: Check the refutations THIS ENGINE writes, and that it cannot refute a consistent ontology
+ # The line above checks hand-written fixtures, which settles whether the
+ # checker works and says nothing about whether anything can feed it.
+ # This one runs the engine, takes its `refutation.tsv`, and hands that
+ # to the same binary. The two legs that matter most are the consistent
+ # ontology, where no refutation may be produced and none may be
+ # accepted, and the laundering guard, which fails if this engine ever
+ # states the verdict only an accepted refutation earns.
+ run: OO_REQUIRE_FIXTURES=1 cargo test --test lean_refutation_producer_test -- --nocapture
- name: Check the mixed certificate layer
run: OO_REQUIRE_FIXTURES=1 cargo test --test lean_mixed_certificate_test -- --nocapture
- name: Check the generic Horn-rule layer, and that a user rule cannot earn the absolute verdict
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d3f01c7d..5fd0e4a0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,47 @@ All notable changes to Open Ontologies are documented here.
## [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/`.
- **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
diff --git a/CLAUDE.md b/CLAUDE.md
index 1bb6b96b..e9a2f262 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -75,7 +75,7 @@ Claude dynamically decides the next tool call based on what the previous tool re
| `onto_shacl` | To validate loaded data against SHACL shapes (cardinality, datatypes, classes) |
| `onto_vocab_check` | To closed-world-check generated DATA: flags any predicate/class used that is not declared in the loaded ontology (hallucinated terms). Catches what open-world SHACL silently passes. Run on LLM-generated Turtle before `onto_load` |
| `onto_defects` | BEFORE trusting any fact-level result, and on every marketplace pack before adopting it. Checks the ONTOLOGY against itself with no data present: `transitive_and_functional`, `symmetric_and_asymmetric`, `subclass_cycle`, `sub_property_cycle`, `disjoint_with_ancestor`, `inherited_disjoint`, `self_inverse`, `inverse_not_mutual`. A different question from `onto_dl_check`: a transitive functional property is satisfiable and is still a trap, because the pair manufactures contradictions the moment instances arrive. Each kind is listed at most 50 times, with the full total under `truncated` |
-| `onto_reason` | To run RDFS or OWL-RL inference, materializing inferred triples. Pass `inference_graph: true` to keep them in `https://open-ontologies.org/graph/inferred` instead of the default graph, so nothing downstream can read an inference as an assertion and `onto_save` to Turtle/RDF-XML cannot publish one. Default false (unchanged behaviour); not available for `owl-dl`. Pass `certificate_dir` to also write a derivation certificate (`asserted.tsv` + `derivations.tsv`) that the proved-sound Lean checker in `lean/` verifies; see docs/lean-certificates.md |
+| `onto_reason` | To run RDFS or OWL-RL inference, materializing inferred triples. Pass `inference_graph: true` to keep them in `https://open-ontologies.org/graph/inferred` instead of the default graph, so nothing downstream can read an inference as an assertion and `onto_save` to Turtle/RDF-XML cannot publish one. Default false (unchanged behaviour); not available for `owl-dl`. Pass `certificate_dir` to also write a derivation certificate (`asserted.tsv` + `derivations.tsv`) that the proved-sound Lean checker in `lean/` verifies, plus `refutation.tsv` when the run finds a contradiction `oo-refute` can judge. Ten of the seventeen OWL 2 RL rules that conclude `false` are detected and only `cax-dw` is certifiable, so `inconsistency.verdict` is `clash_found_by_this_engine` and NEVER the checker's `unsatisfiable_under_disjointness`; no clash found is not consistency; see docs/lean-certificates.md |
| `onto_reason_incremental` | After adding facts to an already-materialised graph. Derives the consequences of the ADDED triples only (semi-naive evaluation, joining the delta against the closure), so the cost tracks what changed rather than the size of the store: effectively instant against a 1.9M-triple store where full re-materialisation takes seconds. Refuses schema axioms (subClassOf, domain, range, inverseOf, equivalentClass) with an explanation, because those change what the whole store entails: run `onto_reason` for them |
| `onto_extend` | To run the full pipeline: ingest → SHACL validate → reason in one call |
| `onto_import_schema` | To import a PostgreSQL or DuckDB database schema as an OWL ontology (requires `postgres` and/or `duckdb` features). Auto-dispatches on connection-string scheme. |
diff --git a/README.md b/README.md
index eb4d21ca..85b10e71 100644
--- a/README.md
+++ b/README.md
@@ -1009,6 +1009,16 @@ was in the engine: `cls-svf1` derived the converse of a subclass axiom. Details
in [docs/lean-certificates.md](docs/lean-certificates.md) and
[decision 0002](docs/decisions/0002-an-inference-carries-a-certificate.md).
+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.
+
### Studio
```mermaid
diff --git a/docs/decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md b/docs/decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md
index 8383580c..77dcd79d 100644
--- a/docs/decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md
+++ b/docs/decisions/0003-a-rule-is-data-and-an-assumption-is-not-a-fact.md
@@ -62,5 +62,15 @@ because their premise count is the length of an RDF list.
## Still not done
-- Nothing in `src/` writes the refutation format, so inconsistency can be checked and not yet
- produced by this engine.
+- ~~Nothing in `src/` writes the refutation format, so inconsistency can be checked and not yet
+ produced by this engine.~~ Landed. `reason --certificate DIR` now looks for a contradiction in the
+ closure it reached and writes `refutation.tsv` for the one clash rule the checker has a semantic
+ condition for, `cax-dw`. Nine further clash rules are detected and deliberately NOT written,
+ because a file naming a rule `OOCert.RefuteConditions` has no field for is refused with exit 2 and
+ would be a certificate-shaped object that certifies nothing. See
+ [lean-certificates.md](../lean-certificates.md#refutations-certifying-that-a-graph-has-no-model).
+- The tableau's unsatisfiability findings still carry no refutation. `oo-refute/1` can express one
+ contradiction, `cax-dw`, over triples the forward-chaining prefix can reach; a clash the tableau
+ reaches through `∃`/`∀` expansion or a cardinality bound is not expressible in it, and giving it a
+ form would be a change to `lean/`. The precise obstruction is written down rather than left as
+ "future work".
diff --git a/docs/lean-certificates.md b/docs/lean-certificates.md
index 63a03004..1326d588 100644
--- a/docs/lean-certificates.md
+++ b/docs/lean-certificates.md
@@ -59,13 +59,16 @@ one with its rule, conclusion and premises; `2` a file could not be read or pars
## The files
-Two tab-separated files. Terms are in N-Triples spelling, exactly as the engine's interner holds
+Tab-separated. Terms are in N-Triples spelling, exactly as the engine's interner holds
them, so a term is spelled identically wherever it appears and tabs and newlines cannot occur
inside one.
- `asserted.tsv`: one triple per line, `s TAB p TAB o`. Every triple the run started from.
- `derivations.tsv`: one step per line, `rule TAB s TAB p TAB o` for the conclusion, then the
premises as further triples, in the order documented per rule in `lean/OOCert/Rules.lean`.
+- `refutation.tsv`, only when the run found a contradiction it can certify: the line `oo-refute/1`,
+ then the derivation steps that reached the clash in the same spelling as `derivations.tsv`, then
+ one `refute TAB rule` line with the clash rule's premises. See the refutation section below.
## What is proved
@@ -141,6 +144,123 @@ repository's RDF was never walked and was excluded without being named. Widening
surfaced the literal-subject defect in `prp-symp`, `prp-inv1`, `prp-inv2` and `eq-sym`, which lived
in `benchmark/`.
+## Refutations: certifying that a graph has NO model
+
+A derivation certificate says a triple follows. A *refutation* says the graph contradicts itself, and
+it needs a second format because there is no triple to conclude. `lean/OOCert/Refute.lean` holds it,
+`oo-refute` checks it, and `OOCert.refutation_sound` is proved about it.
+
+The reasoner now writes one. `reason --certificate DIR` looks for a contradiction in the closure it
+reached and, when it finds one the checker can judge, writes `DIR/refutation.tsv` beside the other
+two files.
+
+```bash
+open-ontologies reason --profile owl-rl --certificate /tmp/cert
+cd lean
+lake exe oo-refute check /tmp/cert/asserted.tsv /tmp/cert/refutation.tsv
+lake exe oo-refute guard /tmp/cert/asserted.tsv /tmp/cert/derivations.tsv /tmp/cert/refutation.tsv
+```
+
+`check` exits 0 when the refutation is valid, which is a good exit code reporting bad news. `guard`
+runs both checkers and REFUSES the derivation certificate when the refutation succeeds, because over
+a refuted graph every triple is entailed under the disjointness reading and an ordinary certificate
+carries no information (`OOCert.a_certificate_adds_nothing_when_the_graph_is_refuted`). `oo-cert`
+will still accept that certificate and will still be telling the truth: its verdict quantifies over
+a model class that ignores disjointness, and that class is never empty.
+
+The response gains an `inconsistency` object:
+
+```json
+{
+ "inconsistency": {
+ "found": true,
+ "verdict": "clash_found_by_this_engine",
+ "checked_by_lean": false,
+ "by_rule": {"cax-dw": 1},
+ "refutation": {
+ "written": true,
+ "rule": "cax-dw",
+ "prefix": 2,
+ "verdict": "refutation_written_not_yet_checked",
+ "check_with": "cd lean && lake exe oo-refute check /tmp/cert/asserted.tsv /tmp/cert/refutation.tsv"
+ }
+ }
+}
+```
+
+**Read the two verdicts apart.** `clash_found_by_this_engine` is this engine saying so, with nothing
+behind it. `unsatisfiable_under_disjointness` is what `oo-refute` prints when it has ACCEPTED a
+refutation, and the engine never states it.
+`tests/lean_refutation_producer_test.rs::the_engine_never_states_the_checkers_verdict` fails if any
+string in the response is ever that verdict, on the pattern the Horn layer's laundering guard set.
+
+### Which rules conclude `false`, and which of them can be certified
+
+Seventeen rules of the OWL 2 RL profile conclude `false` rather than a triple. None of them is in the
+forward-chaining table, and none could be: a certificate step's conclusion is a triple. They are
+looked for once, after the fixpoint.
+
+| rule | detected | certifiable |
+|---|---|---|
+| `cax-dw` (`c1 owl:disjointWith c2`, `x a c1`, `x a c2`) | yes | **yes** |
+| `cls-com` (`owl:complementOf`) | yes | no |
+| `cls-nothing2` (`x a owl:Nothing`) | yes | no |
+| `cls-maxc1` (`owl:maxCardinality 0`) | yes | no |
+| `eq-diff1` (`owl:sameAs` and `owl:differentFrom`) | yes | no |
+| `prp-irp` (`owl:IrreflexiveProperty`) | yes | no |
+| `prp-asyp` (`owl:AsymmetricProperty`) | yes | no |
+| `prp-pdw` (`owl:propertyDisjointWith`) | yes | no |
+| `prp-npa1`, `prp-npa2` (negative property assertions) | yes | no |
+| `cax-adc`, `prp-adp`, `eq-diff2`, `eq-diff3` | no, they read an RDF list | no |
+| `cls-maxqc1`, `cls-maxqc2` | no, qualified cardinality is not implemented | no |
+| `dt-not-type` | no, an ill-typed literal needs a datatype value space | no |
+
+Only `cax-dw` is certifiable, and the reason belongs to the checker rather than to the engine.
+`OOCert.RefuteConditions` carries exactly one semantic field, for `cax-dw`, and `oo-refute` refuses a
+refutation naming any other clash rule with exit 2 rather than guessing at it. So the producer writes
+a refutation for that rule alone. For the other nine it detects, the response says a clash was found
+and `"refutation": {"written": false}` with the reason. Every rule the engine does not look for is
+listed in `rules_not_detected` with its own reason, so a run with no clash is never a consistency
+result: most of the table was not tried.
+
+`lean/OOCert/Refute.lean` says sixteen rules conclude `false`. Counted against the W3C tables it 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. Nothing computes with the number.
+
+### The limit, which is real
+
+`cax-dw` needs an INDIVIDUAL in two disjoint classes. A TBox that is unsatisfiable with no individual
+asserted cannot be seen this way at all. `:Lion rdfs:subClassOf :Carnivore, :Herbivore` with those
+two disjoint makes `:Lion` unsatisfiable, and until something is asserted to BE a `:Lion` the
+rule-based route has nothing to fire on. That is a boundary of forward chaining, not a defect in the
+producer.
+
+The SHIQ tableau (`--profile owl-dl`, `src/tableaux.rs`) does see it, and reports
+`unsatisfiable_classes`. **Its answer carries no certificate**, which its own report already states
+(`"not_covered": "unsatisfiability and inconsistency carry no certificate"`). No refutation is
+emitted from it, and the obstruction is precise rather than a matter of effort:
+
+- `oo-refute/1` can express exactly one contradiction, `cax-dw`, whose three premises must each be
+ asserted or concluded by a step of the 29-rule forward-chaining prefix. A tableau clash reached
+ through `∃`/`∀` expansion, node merging or a cardinality bound is not three triples of that shape
+ and there is nothing in the format to write it as.
+- Where a tableau clash IS a `cax-dw` instance over triples the forward-chaining rules can reach, the
+ rule-based producer has already found it, so the tableau adds nothing that can be certified.
+- Feeding the tableau's inferred subsumptions back into the store and re-reasoning would let more
+ clashes surface, but those subsumptions would then appear in `asserted.tsv` as axioms with nothing
+ marking them derived. That is the assumption-laundering failure this layer exists to prevent, so it
+ is not done.
+- Adding a clash rule to the format means a new field in `OOCert.RefuteConditions`, a new arm in
+ `OOCert.checkRefuteStep` and a new soundness case. That is a change to `lean/`, not to the producer.
+
+`tests/lean_refutation_producer_test.rs::the_tbox_only_case_is_invisible_here_and_the_tableau_sees_it`
+computes this boundary on one ontology rather than asserting it here.
+
+`onto_defects` asks a different question again, and the three do not substitute for one another.
+It checks the ontology against ITSELF with no data present, so `disjoint_with_ancestor` and
+`inherited_disjoint` catch the schema that will contradict itself the moment an instance arrives.
+This layer needs the instance to be there. The tableau needs neither and certifies nothing.
+
## User-written rules
The twenty built-in rules were twenty arms in the checker, which does not extend to rules you write.
@@ -189,6 +309,18 @@ Stated rather than discovered later.
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.
+- **No clash found is not consistency.** Seven of the seventeen clash rules are not looked for at
+ all and eight of the ten that are cannot be certified, so a clean `reason` run means "none of the
+ ten rules tried fired", never "this ontology is consistent". A rejected refutation means the same:
+ `oo-refute`'s own report says so in every verdict it prints.
+- **One clash is reported per refutation, and only the first certifiable one is written.** A graph
+ with twenty disjointness clashes gets one `refutation.tsv`. `clash_count` and `by_rule` carry the
+ rest; ten are listed in full under `clashes`. Refuting a graph once is enough to invalidate every
+ derivation over it, so a second refutation would add nothing.
+- **The refutation's derivation prefix is not byte-stable across runs.** Which of several valid
+ derivations of a premise the fixpoint recorded first depends on the same hash iteration order that
+ already decides the line order of `derivations.tsv`. The contradiction itself IS stable: clashes
+ are sorted on their N-Triples spelling before one is chosen.
- **A SHACL report double-counts a node selected by two target declarations of one shape.** Both
`focus_nodes` and `violation_count` are affected. Collapsing identical results is not the fix:
SHACL emits one result per SPARQL solution, pyshacl does too, and deduplicating breaks an exact
diff --git a/src/main.rs b/src/main.rs
index d53049f2..30e2e761 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -431,6 +431,11 @@ enum Commands {
/// Write a derivation certificate (asserted.tsv + derivations.tsv)
/// to this directory. `lean/` holds a checker for it whose soundness
/// is a machine-checked theorem; see docs/lean-certificates.md.
+ ///
+ /// When the run also finds a contradiction that the checker can judge,
+ /// a refutation.tsv lands here too, for `lake exe oo-refute check`.
+ /// Only `cax-dw` is certifiable; other clash rules are reported in the
+ /// response as found by this engine and nothing is written for them.
#[arg(long)]
certificate: Option<String>,
/// Evaluate a SUPPLIED Horn rule table instead of a built-in profile,
diff --git a/src/reason.rs b/src/reason.rs
index 42009d16..e84931b7 100644
--- a/src/reason.rs
+++ b/src/reason.rs
@@ -26,6 +26,22 @@ const RDF_FIRST: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#first>";
const RDF_REST: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#rest>";
const RDF_NIL: &str = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#nil>";
+// The vocabulary the clash detector reads. None of it drives a rule: nothing in
+// the table above concludes a triple from any of these terms. They are read
+// once, after the fixpoint, by `find_clashes`.
+const OWL_DISJOINT_WITH: &str = "<http://www.w3.org/2002/07/owl#disjointWith>";
+const OWL_NOTHING: &str = "<http://www.w3.org/2002/07/owl#Nothing>";
+const OWL_COMPLEMENT_OF: &str = "<http://www.w3.org/2002/07/owl#complementOf>";
+const OWL_IRREFLEXIVE: &str = "<http://www.w3.org/2002/07/owl#IrreflexiveProperty>";
+const OWL_ASYMMETRIC: &str = "<http://www.w3.org/2002/07/owl#AsymmetricProperty>";
+const OWL_PROP_DISJOINT_WITH: &str = "<http://www.w3.org/2002/07/owl#propertyDisjointWith>";
+const OWL_DIFFERENT_FROM: &str = "<http://www.w3.org/2002/07/owl#differentFrom>";
+const OWL_MAX_CARDINALITY: &str = "<http://www.w3.org/2002/07/owl#maxCardinality>";
+const OWL_SOURCE_INDIVIDUAL: &str = "<http://www.w3.org/2002/07/owl#sourceIndividual>";
+const OWL_ASSERTION_PROPERTY: &str = "<http://www.w3.org/2002/07/owl#assertionProperty>";
+const OWL_TARGET_INDIVIDUAL: &str = "<http://www.w3.org/2002/07/owl#targetIndividual>";
+const OWL_TARGET_VALUE: &str = "<http://www.w3.org/2002/07/owl#targetValue>";
+
/// A triple over interned ids.
type Fact = (u32, u32, u32);
@@ -37,6 +53,365 @@ 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.)
+//
+// 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)
+}
+
/// Intern strings to u32 IDs for efficient reasoning.
struct Interner {
to_id: HashMap<String, u32>,
@@ -106,9 +481,14 @@ impl Interner {
/// * The `dt-*` family needs a datatype VALUE space. `OOCert.Semantics`
/// reads a literal as its N-Triples spelling and says so, so there is no
/// condition here for those rules to be sound against.
-/// * Nothing concludes `false`. The profile's inconsistency rules need a
-/// certificate format that can carry a refutation, which this format
-/// cannot.
+/// * Nothing concludes `false`. Every rule above concludes a triple, which
+/// is what the `oo-cert/1` format can carry. The seventeen rules of the
+/// profile that conclude `false` are handled AFTER the fixpoint instead,
+/// by [`find_clashes`], and written in the separate `oo-refute/1` format
+/// that `lean/OOCert/Refute.lean` checks. Only `cax-dw` earns a
+/// certificate there, because it is the only clash rule the Lean checker
+/// has a semantic condition for; the rest are reported as found and
+/// uncertified, and the two must never share a word.
///
/// The graph materialised inferences are written to when the caller asks for
/// them to be kept apart from what was asserted.
@@ -238,6 +618,28 @@ impl Reasoner {
let rdf_rest = interner.intern(RDF_REST);
let rdf_nil = interner.intern(RDF_NIL);
+ // 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
+ // a u32 comparison, the same as every other well-known id here.
+ let clash_vocab = ClashVocab {
+ rdf_type,
+ disjoint_with: interner.intern(OWL_DISJOINT_WITH),
+ nothing: interner.intern(OWL_NOTHING),
+ complement_of: interner.intern(OWL_COMPLEMENT_OF),
+ irreflexive: interner.intern(OWL_IRREFLEXIVE),
+ asymmetric: interner.intern(OWL_ASYMMETRIC),
+ prop_disjoint_with: interner.intern(OWL_PROP_DISJOINT_WITH),
+ same_as: owl_sameas,
+ different_from: interner.intern(OWL_DIFFERENT_FROM),
+ max_cardinality: interner.intern(OWL_MAX_CARDINALITY),
+ on_property: owl_on_property,
+ source_individual: interner.intern(OWL_SOURCE_INDIVIDUAL),
+ assertion_property: interner.intern(OWL_ASSERTION_PROPERTY),
+ target_individual: interner.intern(OWL_TARGET_INDIVIDUAL),
+ target_value: interner.intern(OWL_TARGET_VALUE),
+ };
+
// ── Fixpoint iteration ──────────────────────────────────────
let mut triple_set: HashSet<Fact> = facts.iter().copied().collect();
let initial_size = triple_set.len();
@@ -1044,6 +1446,15 @@ impl Reasoner {
}
std::fs::write(dir.join("derivations.tsv"), lines)?;
+ // A refutation left behind by an earlier run into this directory
+ // would be checked against THIS run's asserted.tsv, which is a
+ // different graph. It would almost certainly be rejected, and
+ // "almost certainly" is not the standard here: the stale file goes
+ // before the clash detector below decides whether to write a new
+ // one. Ignoring the error is correct; the usual case is that there
+ // is no such file.
+ let _ = std::fs::remove_file(dir.join("refutation.tsv"));
+
result["certificate"] = serde_json::json!({
"dir": dir.display().to_string(),
"format": "oo-cert/1",
@@ -1054,6 +1465,196 @@ impl Reasoner {
});
}
+ // ── Inconsistency ───────────────────────────────────────────────────
+ //
+ // The clash rules, looked for over the closure the fixpoint reached.
+ // The key appears only when something was found, so a run over a graph
+ // with no clash is byte for byte the run it always was.
+ let clashes = find_clashes(&triple_set, &interner, &clash_vocab);
+ if !clashes.is_empty() {
+ let show = |t: &Fact| {
+ serde_json::json!([
+ interner.resolve(t.0),
+ interner.resolve(t.1),
+ interner.resolve(t.2)
+ ])
+ };
+ let mut by_rule: std::collections::BTreeMap<&str, usize> =
+ std::collections::BTreeMap::new();
+ for c in &clashes {
+ *by_rule.entry(c.rule).or_default() += 1;
+ }
+ let listed: Vec<serde_json::Value> = clashes
+ .iter()
+ .take(10)
+ .map(|c| {
+ serde_json::json!({
+ "rule": c.rule,
+ "certifiable": clash_is_certifiable(c.rule),
+ "premises": c.premises.iter().map(show).collect::<Vec<_>>(),
+ })
+ })
+ .collect();
+ let uncertifiable: Vec<&str> = by_rule
+ .keys()
+ .copied()
+ .filter(|r| !clash_is_certifiable(r))
+ .collect();
+ let mut inconsistency = serde_json::json!({
+ "found": true,
+ // THIS ENGINE'S WORD, and deliberately not the checker's.
+ // `oo-refute` says `unsatisfiable_under_disjointness` when it
+ // has accepted a refutation. Nothing here may say that, or an
+ // engine opinion and a machine-checked result share a string
+ // and a consumer cannot tell them apart.
+ "verdict": "clash_found_by_this_engine",
+ "checked_by_lean": false,
+ "clash_count": clashes.len(),
+ "by_rule": by_rule,
+ "clashes_listed": listed.len(),
+ "clashes": listed,
+ "certifiable_rules": CLASH_RULES_CERTIFIABLE,
+ "uncertifiable_rules_found": uncertifiable,
+ "rules_not_detected": CLASH_RULES_NOT_DETECTED
+ .iter()
+ .map(|(r, why)| serde_json::json!({"rule": r, "why": why}))
+ .collect::<Vec<_>>(),
+ "means": "this engine found a contradiction in the closure it computed, and \
+ NOTHING HAS CHECKED THAT. A refutation the Lean checker accepted is a \
+ different kind of result with a different word for it: run `oo-refute \
+ check` and read its verdict, which is `unsatisfiable_under_disjointness` \
+ and is never stated here.",
+ "limits": "cax-dw needs an INDIVIDUAL in two disjoint classes, so a TBox that is \
+ unsatisfiable with no individual asserted is invisible to this route \
+ entirely: it is a boundary of rule-based reasoning, not a bug. The SHIQ \
+ tableau in src/tableaux.rs (--profile owl-dl) does see that case, and \
+ its unsatisfiability finding carries NO certificate, which the owl-dl \
+ report states as `unsatisfiability and inconsistency carry no \
+ certificate`. Nothing found by the rules listed under \
+ rules_not_detected was looked for at all, so a clean run is not a \
+ consistency result.",
+ });
+
+ if let Some(dir) = certificate_dir {
+ // A refutation file is written for the one rule the checker can
+ // judge, and for nothing else. The engine's own detection of
+ // any other clash rule stays a report, because a file naming a
+ // rule `OOCert.RefuteConditions` has no field for is refused by
+ // `oo-refute` with exit 2 and would be a certificate-shaped
+ // object that certifies nothing.
+ let certifiable = clashes.iter().find(|c| clash_is_certifiable(c.rule));
+ match certifiable {
+ Some(c) => match refutation_prefix(&c.premises, &derivations, &original) {
+ Some(ids) => {
+ let mut text = String::from("oo-refute/1\n");
+ for &i in &ids {
+ let d = &derivations[i];
+ text.push_str(d.rule);
+ for &(s, p, o) in
+ std::iter::once(&d.conclusion).chain(d.premises.iter())
+ {
+ text.push('\t');
+ text.push_str(interner.resolve(s));
+ text.push('\t');
+ text.push_str(interner.resolve(p));
+ text.push('\t');
+ text.push_str(interner.resolve(o));
+ }
+ text.push('\n');
+ }
+ text.push_str("refute\t");
+ text.push_str(c.rule);
+ for &(s, p, o) in &c.premises {
+ text.push('\t');
+ text.push_str(interner.resolve(s));
+ text.push('\t');
+ text.push_str(interner.resolve(p));
+ text.push('\t');
+ text.push_str(interner.resolve(o));
+ }
+ text.push('\n');
+ std::fs::write(dir.join("refutation.tsv"), text)?;
+ inconsistency["refutation"] = serde_json::json!({
+ "written": true,
+ "file": dir.join("refutation.tsv").display().to_string(),
+ "format": "oo-refute/1",
+ "rule": c.rule,
+ "prefix": ids.len(),
+ "premises": c.premises.iter().map(show).collect::<Vec<_>>(),
+ // Written, not checked. The word for a checked
+ // one is `oo-refute`'s to say.
+ "verdict": "refutation_written_not_yet_checked",
+ "check_with": format!(
+ "cd lean && lake exe oo-refute check {a} {r}",
+ a = dir.join("asserted.tsv").display(),
+ r = dir.join("refutation.tsv").display()
+ ),
+ "guard_with": format!(
+ "cd lean && lake exe oo-refute guard {a} {d} {r}",
+ a = dir.join("asserted.tsv").display(),
+ d = dir.join("derivations.tsv").display(),
+ r = dir.join("refutation.tsv").display()
+ ),
+ "means": "a file in the format OOCert.RefuteParse.parseRefutation \
+ reads. Exit 0 from `oo-refute check` is the result that \
+ means anything; this engine writing the file means only \
+ that it wrote it.",
+ });
+ }
+ None => {
+ inconsistency["refutation"] = serde_json::json!({
+ "written": false,
+ "why": "a premise of the clash is neither asserted nor recorded in \
+ the derivation log, so no checkable prefix could be built. \
+ That is a defect in this producer, not a property of the \
+ ontology; please report it.",
+ });
+ }
+ },
+ None => {
+ inconsistency["refutation"] = serde_json::json!({
+ "written": false,
+ "why": "every clash found is of a rule the Lean checker has no \
+ semantic condition for. `OOCert.RefuteConditions` carries one \
+ field, for cax-dw, and `oo-refute` refuses a refutation naming \
+ any other rule with exit 2 rather than judging it. Writing one \
+ anyway would produce a certificate-shaped file that certifies \
+ nothing.",
+ });
+ }
+ }
+ } else {
+ inconsistency["refutation"] = serde_json::json!({
+ "written": false,
+ "why": "no certificate directory was given. Pass --certificate DIR (or \
+ certificate_dir over MCP) and a refutation is written there for the \
+ one clash rule the Lean checker can judge.",
+ });
+ }
+
+ // A derivation certificate over a graph with a clash in it is worth
+ // nothing under the disjointness reading, and the certificate block
+ // must not be read without that.
+ // `OOCert.a_certificate_adds_nothing_when_the_graph_is_refuted`.
+ if let Some(cert) = result.get_mut("certificate")
+ && let Some(obj) = cert.as_object_mut()
+ {
+ obj.insert("graph_has_a_clash".into(), serde_json::json!(true));
+ obj.insert(
+ "read_with".into(),
+ serde_json::json!(
+ "this graph contradicts itself, so under the disjointness reading EVERY \
+ triple is entailed and this certificate carries no information. \
+ `oo-cert` will still accept it and will still be telling the truth, \
+ because its verdict quantifies over a model class that ignores \
+ disjointness. Run `oo-refute guard` instead of `oo-cert`."
+ ),
+ );
+ }
+
+ result["inconsistency"] = inconsistency;
+ }
+
Ok(result.to_string())
}
}
diff --git a/src/server.rs b/src/server.rs
index 8a7d22f7..a8884255 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -1876,7 +1876,7 @@ impl OpenOntologiesServer {
body.to_string()
}
- #[tool(name = "onto_reason", description = "Run inference over the loaded ontology. Profiles: 'rdfs' (subclass, domain/range), 'owl-rl' (+ transitive/symmetric/inverse, sameAs, equivalentClass), 'owl-rl-ext' (+ someValuesFrom, allValuesFrom, hasValue, intersectionOf, unionOf), 'owl-dl' (SHIQ tableaux: satisfiability, classification, qualified number restrictions with node merging, inverse/symmetric roles, functional properties, parallel agent-based classification, explanation traces, ABox reasoning. Nominals are not implemented: owl:oneOf is not read and owl:hasValue is approximated as an atomic concept, so an ontology that uses either returns undetermined classes rather than a classification. Datatype ranges are skipped). Materializes inferred triples. Set `inference_graph` to keep them in a separate graph, where nothing downstream can read an inference as an assertion and a Turtle/RDF-XML save cannot publish one. Pass `rules_file` to evaluate a SUPPLIED Horn rule table instead of a built-in profile: it needs `certificate_dir`, materialises nothing, and writes a certificate the proved-sound Lean checker verifies with `lake exe oo-horn check`. The verdict comes from that checker and not from here, because rules you supply are assumed and never checked: a conclusion then holds in every model of the asserted graph that ALSO satisfies your rules.")]
+ #[tool(name = "onto_reason", description = "Run inference over the loaded ontology. Profiles: 'rdfs' (subclass, domain/range), 'owl-rl' (+ transitive/symmetric/inverse, sameAs, equivalentClass), 'owl-rl-ext' (+ someValuesFrom, allValuesFrom, hasValue, intersectionOf, unionOf), 'owl-dl' (SHIQ tableaux: satisfiability, classification, qualified number restrictions with node merging, inverse/symmetric roles, functional properties, parallel agent-based classification, explanation traces, ABox reasoning. Nominals are not implemented: owl:oneOf is not read and owl:hasValue is approximated as an atomic concept, so an ontology that uses either returns undetermined classes rather than a classification. Datatype ranges are skipped). Materializes inferred triples. Set `inference_graph` to keep them in a separate graph, where nothing downstream can read an inference as an assertion and a Turtle/RDF-XML save cannot publish one. Pass `rules_file` to evaluate a SUPPLIED Horn rule table instead of a built-in profile: it needs `certificate_dir`, materialises nothing, and writes a certificate the proved-sound Lean checker verifies with `lake exe oo-horn check`. The verdict comes from that checker and not from here, because rules you supply are assumed and never checked: a conclusion then holds in every model of the asserted graph that ALSO satisfies your rules. With `certificate_dir` the run ALSO looks for a contradiction in the closure it reached, and writes refutation.tsv when it finds one the Lean refutation checker can judge: `lake exe oo-refute check`, or `oo-refute guard` which refuses the derivation certificate over a graph it can refute. Seventeen OWL 2 RL rules conclude false, ten are detected here and exactly ONE, cax-dw, is certifiable, because OOCert.RefuteConditions carries a semantic condition for that rule alone. The other nine are reported as `clash_found_by_this_engine` with no file written, and that word is not the checker's `unsatisfiable_under_disjointness`: an engine opinion and a machine-checked result never share a string here. cax-dw needs an INDIVIDUAL in two disjoint classes, so a TBox unsatisfiable with no individual asserted is invisible to this route; profile 'owl-dl' sees that case and its answer carries no certificate. No clash found is never a consistency result.")]
async fn onto_reason(&self, Parameters(input): Parameters<OntoReasonInput>) -> String {
use crate::reason::Reasoner;
// A supplied Horn rule table takes a different path: it is evaluated
diff --git a/tests/lean_refutation_producer_test.rs b/tests/lean_refutation_producer_test.rs
new file mode 100644
index 00000000..5d7abe03
--- /dev/null
+++ b/tests/lean_refutation_producer_test.rs
@@ -0,0 +1,546 @@
+//! The producer for `oo-refute/1`, end to end.
+//!
+//! `lean/OOCert/Refute.lean` has checked refutations since the day it landed,
+//! and until now nothing in `src/` wrote one: a checker with no producer, which
+//! is the same shape of defect as a gate that cannot fail. `Reasoner::run_full`
+//! now looks for a contradiction in the closure it reached and writes
+//! `refutation.tsv` beside `asserted.tsv` and `derivations.tsv`.
+//!
+//! # The three things this file exists to protect
+//!
+//! **A produced refutation must actually check.** The format is defined by the
+//! Lean parser and the hand-written fixtures in `tests/fixtures/refute`, not by
+//! this producer, so the round trip is the only thing that settles whether the
+//! two agree. `the_produced_refutation_is_accepted_by_the_checker` runs
+//! `oo-refute` on the engine's own output.
+//!
+//! **An uncertified inconsistency must never look certified.** Seventeen rules
+//! of OWL 2 RL conclude `false`; `OOCert.RefuteConditions` carries a semantic
+//! condition for exactly one of them, `cax-dw`. The engine detects ten and can
+//! write a refutation for one. For the other nine it says it found a clash and
+//! says nothing else, because a file naming a rule the checker has no condition
+//! for is refused with exit 2 and would be a certificate-shaped object that
+//! certifies nothing. `the_engine_never_states_the_checkers_verdict` is the
+//! laundering guard, written to the pattern
+//! `tests/lean_horn_certificate_test.rs` set for the Horn layer.
+//!
+//! **A consistent ontology must never be refutable.** A refutation checker that
+//! can be made to accept a refutation of a consistent ontology is worse than no
+//! checker at all, and a producer that writes one is how that would happen.
+//! `a_consistent_ontology_is_not_refuted` is that test, and
+//! `a_forged_refutation_is_rejected` closes the other end by checking a valid
+//! refutation of one graph against a different graph's asserted triples.
+//!
+//! # The limit, which is real and is not a bug
+//!
+//! `cax-dw` needs an INDIVIDUAL in two disjoint classes. A TBox that is
+//! unsatisfiable with no individual asserted is invisible to the rule-based
+//! route entirely. `the_tbox_only_case_is_invisible_here_and_the_tableau_sees_it`
+//! computes that boundary rather than asserting it in a docstring: the same
+//! ontology yields no clash under `owl-rl` and an unsatisfiable class under
+//! `owl-dl`. The tableau's finding carries no certificate of its own, which is
+//! what its report already says, so the more valuable half of this layer is
+//! still missing and is named rather than hidden.
+
+mod common;
+
+use open_ontologies::graph::GraphStore;
+use open_ontologies::reason::{InferenceTarget, Reasoner};
+use std::path::{Path, PathBuf};
+use std::process::Command;
+use std::sync::{Arc, OnceLock};
+
+fn repo() -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+}
+
+fn lean_dir() -> PathBuf {
+ repo().join("lean")
+}
+
+fn lake_available() -> bool {
+ // `.current_dir(lean_dir())`: elan resolves the toolchain from the working
+ // directory, and the crate root has no `lean-toolchain` in its ancestry.
+ Command::new("lake")
+ .arg("--version")
+ .current_dir(lean_dir())
+ .output()
+ .map(|o| o.status.success())
+ .unwrap_or(false)
+}
+
+fn skip() -> bool {
+ common::skip_unless(
+ lake_available(),
+ "lake (the Lean 4 build tool)",
+ "install elan from https://github.com/leanprover/elan; lean/lean-toolchain pins the version",
+ )
+}
+
+/// Build once per test binary. `oo-refute` is NOT in the lakefile's
+/// `defaultTargets`, so naming it here is what puts `OOCert/Refute.lean` and
+/// `OOCert/RefuteWitness.lean`, and the `#guard_msgs` axiom tripwires in them,
+/// in front of a compiler.
+fn refute_bin() -> &'static Path {
+ static BUILT: OnceLock<PathBuf> = OnceLock::new();
+ BUILT.get_or_init(|| {
+ let out = Command::new("lake")
+ .arg("build")
+ .arg("oo-refute")
+ .current_dir(lean_dir())
+ .output()
+ .expect("run lake build oo-refute");
+ assert!(
+ out.status.success(),
+ "lake build oo-refute failed:\n{}\n{}",
+ String::from_utf8_lossy(&out.stdout),
+ String::from_utf8_lossy(&out.stderr)
+ );
+ let exe = lean_dir().join(".lake").join("build").join("bin").join("oo-refute");
+ assert!(exe.exists(), "binary missing at {}", exe.display());
+ exe
+ })
+}
+
+/// Returns (exit code, stdout, stderr).
+fn run_refute(args: &[&Path]) -> (i32, String, String) {
+ let mut cmd = Command::new(refute_bin());
+ for a in args {
+ cmd.arg(a);
+ }
+ let out = cmd.output().expect("run oo-refute");
+ (
+ out.status.code().unwrap_or(-1),
+ String::from_utf8_lossy(&out.stdout).to_string(),
+ String::from_utf8_lossy(&out.stderr).to_string(),
+ )
+}
+
+fn check_refutation(asserted: &Path, refutation: &Path) -> (i32, String, String) {
+ run_refute(&[Path::new("check"), asserted, refutation])
+}
+
+fn scratch(name: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!("oo-refute-prod-{}-{}", name, std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+}
+
+/// Load Turtle, reason with a certificate, return the response. `materialize`
+/// is false so the store is never written back into and `asserted.tsv` is the
+/// file, not the file plus a previous run's conclusions.
+fn reason(ttl: &str, profile: &str, dir: Option<&Path>) -> serde_json::Value {
+ let store = Arc::new(GraphStore::new());
+ store.load_turtle(ttl, None).unwrap();
+ let out =
+ Reasoner::run_full(&store, profile, false, InferenceTarget::DefaultGraph, dir).unwrap();
+ serde_json::from_str(&out).unwrap()
+}
+
+const PREFIXES: &str = "@prefix : <http://ex.org/> .\n\
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .\n\
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n";
+
+/// `leo` is a Lion, Lions are BigCats, BigCats are Carnivores, and `leo` is
+/// also a Herbivore. The clash is two `rdfs9` hops away from what is asserted,
+/// so a refutation over it CANNOT be written without a derivation prefix, which
+/// is the half of the format a producer is most likely to get wrong.
+const INCONSISTENT: &str = ":Herbivore owl:disjointWith :Carnivore .\n\
+ :Lion rdfs:subClassOf :BigCat . :BigCat rdfs:subClassOf :Carnivore .\n\
+ :leo a :Lion ; a :Herbivore .\n";
+
+/// The same schema with the one assertion that clashes removed. Every other
+/// triple, and the whole disjointness axiom, is still there.
+const CONSISTENT: &str = ":Herbivore owl:disjointWith :Carnivore .\n\
+ :Lion rdfs:subClassOf :BigCat . :BigCat rdfs:subClassOf :Carnivore .\n\
+ :leo a :Lion .\n";
+
+/// `:Lion` is an unsatisfiable CLASS and no individual is asserted. The
+/// ontology is consistent, `:Lion` is not, and `cax-dw` has nothing to fire on
+/// because it needs an individual.
+const TBOX_ONLY: &str = ":Herbivore owl:disjointWith :Carnivore .\n\
+ :Lion rdfs:subClassOf :Carnivore . :Lion rdfs:subClassOf :Herbivore .\n";
+
+/// Contradictions of three rules the Lean checker has no semantic condition
+/// for. Each is a real inconsistency and none of them can be certified here.
+const UNCERTIFIABLE: &str = ":parentOf a owl:IrreflexiveProperty . :bob :parentOf :bob .\n\
+ :alice owl:sameAs :bob . :alice owl:differentFrom :bob .\n\
+ :ghost a owl:Nothing .\n";
+
+fn ontology(body: &str) -> String {
+ format!("{PREFIXES}{body}")
+}
+
+/// Every string value anywhere in a JSON document, so a verdict cannot hide in
+/// a nested object.
+fn string_values(v: &serde_json::Value, out: &mut Vec<String>) {
+ match v {
+ serde_json::Value::String(s) => out.push(s.clone()),
+ serde_json::Value::Array(a) => a.iter().for_each(|x| string_values(x, out)),
+ serde_json::Value::Object(o) => o.values().for_each(|x| string_values(x, out)),
+ _ => {}
+ }
+}
+
+#[test]
+fn the_produced_refutation_is_accepted_by_the_checker() {
+ if skip() {
+ return;
+ }
+ let dir = scratch("accepted");
+ let r = reason(&ontology(INCONSISTENT), "owl-rl", Some(&dir));
+
+ assert_eq!(r["inconsistency"]["found"], true, "{r}");
+ assert_eq!(r["inconsistency"]["refutation"]["written"], true, "{r}");
+ assert_eq!(r["inconsistency"]["refutation"]["rule"], "cax-dw", "{r}");
+ // The clash is not in the asserted triples. If the prefix were empty the
+ // producer would have cited a premise it never derived.
+ assert!(
+ r["inconsistency"]["refutation"]["prefix"].as_u64().unwrap() >= 1,
+ "the refutation must carry the derivation that reached the clash: {r}"
+ );
+
+ let (code, out, err) = check_refutation(&dir.join("asserted.tsv"), &dir.join("refutation.tsv"));
+ assert_eq!(code, 0, "the checker rejected the engine's own refutation:\n{out}{err}");
+ assert!(out.contains("\"ok\":true"), "{out}");
+ assert!(out.contains("\"verdict\":\"unsatisfiable_under_disjointness\""), "{out}");
+ assert!(out.contains("\"theorem\":\"OOCert.refutation_fast_sound\""), "{out}");
+ println!("ACCEPTED: {out}");
+}
+
+#[test]
+fn the_guard_refuses_the_derivation_certificate_over_the_graph_the_engine_refuted() {
+ // The trap `oo-refute guard` exists for. The derivation certificate from
+ // the same run still checks, and `oo-cert` would accept it and be telling
+ // the truth; over a refuted graph it carries no information, which is
+ // `OOCert.a_certificate_adds_nothing_when_the_graph_is_refuted`.
+ if skip() {
+ return;
+ }
+ let dir = scratch("guard");
+ let r = reason(&ontology(INCONSISTENT), "owl-rl", Some(&dir));
+ // The engine's own certificate block must carry the warning, or a consumer
+ // reads `by_rule` counts off a graph where every triple is entailed.
+ assert_eq!(r["certificate"]["graph_has_a_clash"], true, "{r}");
+
+ let (code, out, err) = run_refute(&[
+ Path::new("guard"),
+ &dir.join("asserted.tsv"),
+ &dir.join("derivations.tsv"),
+ &dir.join("refutation.tsv"),
+ ]);
+ assert_eq!(code, 1, "the guard must refuse: {out}{err}");
+ assert!(out.contains("\"certificate_ok\":true"), "{out}");
+ assert!(out.contains("\"refuted\":true"), "{out}");
+ assert!(
+ out.contains("\"verdict\":\"certificate_refused_graph_is_unsatisfiable\""),
+ "{out}"
+ );
+ println!("GUARD: {out}");
+}
+
+#[test]
+fn a_consistent_ontology_is_not_refuted() {
+ // THE test. A producer that writes a refutation for a consistent ontology
+ // turns a verified checker into a machine for laundering a false claim, and
+ // it is worse than having no checker at all.
+ let dir = scratch("consistent");
+ let r = reason(&ontology(CONSISTENT), "owl-rl", Some(&dir));
+
+ assert!(
+ r.get("inconsistency").is_none(),
+ "a consistent ontology must report no clash at all: {r}"
+ );
+ assert!(
+ !dir.join("refutation.tsv").exists(),
+ "no refutation file may be written for a consistent ontology"
+ );
+ assert!(dir.join("derivations.tsv").exists(), "the ordinary certificate is still written");
+ // And the certificate over it carries no clash warning, because there is
+ // nothing to warn about.
+ assert!(r["certificate"]["graph_has_a_clash"].is_null(), "{r}");
+
+ if skip() {
+ return;
+ }
+ // The checker must also reject a refutation built by hand over this graph.
+ // `OOCert.feed_is_not_refuted` proves that rejection is correct rather than
+ // a gap: the consistent graph really does have a model satisfying both
+ // `Model` and `RefuteConditions`.
+ let ex = "<http://ex.org/";
+ let ty = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>";
+ let sc = "<http://www.w3.org/2000/01/rdf-schema#subClassOf>";
+ let dw = "<http://www.w3.org/2002/07/owl#disjointWith>";
+ let attempt = format!(
+ "oo-refute/1\n\
+ rdfs9\t{ex}leo>\t{ty}\t{ex}Carnivore>\t{ex}leo>\t{ty}\t{ex}Lion>\t{ex}Lion>\t{sc}\t{ex}Carnivore>\n\
+ refute\tcax-dw\t{ex}Herbivore>\t{dw}\t{ex}Carnivore>\t{ex}leo>\t{ty}\t{ex}Herbivore>\t\
+ {ex}leo>\t{ty}\t{ex}Carnivore>\n"
+ );
+ let path = dir.join("hand_written_attempt.tsv");
+ std::fs::write(&path, attempt).unwrap();
+ let (code, out, err) = check_refutation(&dir.join("asserted.tsv"), &path);
+ assert_eq!(code, 1, "a consistent graph must not be refutable: {out}{err}");
+ assert!(out.contains("\"ok\":false"), "{out}");
+ println!("CONSISTENT ONTOLOGY, REFUTATION REJECTED: {out}");
+}
+
+#[test]
+fn a_forged_refutation_is_rejected() {
+ // Three ways to lie about a graph the engine really can refute. Each has to
+ // be caught on its own, and the honest refutation from the same run has to
+ // pass first, or the test would be green because nothing works.
+ if skip() {
+ return;
+ }
+ let dir = scratch("forgery");
+ reason(&ontology(INCONSISTENT), "owl-rl", Some(&dir));
+ let asserted = dir.join("asserted.tsv");
+ let honest = std::fs::read_to_string(dir.join("refutation.tsv")).unwrap();
+ let (code, _, _) = check_refutation(&asserted, &dir.join("refutation.tsv"));
+ assert_eq!(code, 0, "the honest refutation must be accepted first");
+
+ let ex = "<http://ex.org/";
+ let ty = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>";
+ let sc = "<http://www.w3.org/2000/01/rdf-schema#subClassOf>";
+
+ // 1. Premises that do not yield a contradiction. All three triples are
+ // ASSERTED, so nothing is missing from the graph and nothing is missing
+ // from the prefix; `:Lion rdfs:subClassOf :BigCat` is simply not a
+ // disjointness axiom, so no contradiction follows from the three.
+ let mut lines: Vec<&str> = honest.lines().collect();
+ let no_contradiction = format!(
+ "refute\tcax-dw\t{ex}Lion>\t{sc}\t{ex}BigCat>\t{ex}leo>\t{ty}\t{ex}Lion>\t\
+ {ex}leo>\t{ty}\t{ex}Herbivore>"
+ );
+ lines.pop();
+ let mut forged = lines.join("\n");
+ forged.push('\n');
+ forged.push_str(&no_contradiction);
+ forged.push('\n');
+
+ // 2. A premise no step ever concluded. The prefix is dropped, so
+ // `:leo a :Carnivore` is neither asserted nor derived by this file.
+ let refute_line = honest.lines().next_back().unwrap();
+ let missing_step = format!("oo-refute/1\n{refute_line}\n");
+
+ let cases = [
+ (
+ "premises that do not yield a contradiction",
+ forged,
+ "the first premise is a subClassOf triple, so cax-dw's shape does not match",
+ ),
+ (
+ "a premise no derivation step concluded",
+ missing_step,
+ "the derivation prefix that reached the clash was removed",
+ ),
+ ];
+ for (name, content, why) in cases {
+ let path = dir.join("forged.tsv");
+ std::fs::write(&path, &content).unwrap();
+ let (code, out, err) = check_refutation(&asserted, &path);
+ assert_eq!(code, 1, "{name} must be rejected because {why}: {out}{err}");
+ assert!(out.contains("\"ok\":false"), "{name}: {out}");
+ assert!(
+ out.contains("not a proof of consistency"),
+ "{name}: a rejection says nothing about consistency and the report must say so: {out}"
+ );
+ println!("REJECTED ({name}): {out}");
+ }
+
+ // 3. A refutation for a DIFFERENT graph: the honest one, checked against
+ // the consistent ontology's asserted triples.
+ let other = scratch("forgery-other");
+ reason(&ontology(CONSISTENT), "owl-rl", Some(&other));
+ let (code, out, err) =
+ check_refutation(&other.join("asserted.tsv"), &dir.join("refutation.tsv"));
+ assert_eq!(
+ code, 1,
+ "a refutation of one graph must not check against another: {out}{err}"
+ );
+ assert!(out.contains("\"ok\":false"), "{out}");
+ println!("REJECTED (a refutation of a different graph): {out}");
+}
+
+#[test]
+fn an_uncertifiable_clash_is_never_written_as_a_refutation() {
+ // `OOCert.RefuteConditions` carries one field, for `cax-dw`. A refutation
+ // naming any other clash rule is refused by `oo-refute` with exit 2, which
+ // is a file that could not be judged rather than a graph that could not be
+ // refuted. The engine must therefore say it found a clash and write
+ // nothing, and the two outcomes must not share a word.
+ let dir = scratch("uncertifiable");
+ let r = reason(&ontology(UNCERTIFIABLE), "owl-rl", Some(&dir));
+
+ assert_eq!(r["inconsistency"]["found"], true, "{r}");
+ let by_rule = r["inconsistency"]["by_rule"].as_object().unwrap();
+ for rule in ["prp-irp", "eq-diff1", "cls-nothing2"] {
+ assert!(by_rule.contains_key(rule), "{rule} must be detected: {r}");
+ }
+ assert!(
+ !by_rule.contains_key("cax-dw"),
+ "this ontology has no disjointness clash: {r}"
+ );
+ for c in r["inconsistency"]["clashes"].as_array().unwrap() {
+ assert_eq!(c["certifiable"], false, "no clash here is certifiable: {r}");
+ }
+ assert_eq!(r["inconsistency"]["refutation"]["written"], false, "{r}");
+ assert!(
+ !dir.join("refutation.tsv").exists(),
+ "no refutation file may be written for a clash the checker cannot judge"
+ );
+ let why = r["inconsistency"]["refutation"]["why"].as_str().unwrap();
+ assert!(why.contains("cax-dw"), "the reason must name the one rule that IS judged: {why}");
+ println!("UNCERTIFIABLE CLASH: {}", r["inconsistency"]["by_rule"]);
+}
+
+#[test]
+fn the_engine_never_states_the_checkers_verdict() {
+ // The laundering guard, in the pattern
+ // `tests/lean_horn_certificate_test.rs::a_user_rule_never_earns_the_absolute_verdict`
+ // set for the Horn layer. `unsatisfiable_under_disjointness` is what
+ // `oo-refute` prints when it has ACCEPTED a refutation, and
+ // `OOCert.refutation_fast_sound` is the theorem behind it. Neither may be a
+ // verdict this engine states about its own findings: an engine opinion and
+ // a machine-checked result must never share a string, or a consumer cannot
+ // tell them apart.
+ for (name, ttl) in [("cax-dw", INCONSISTENT), ("uncertifiable", UNCERTIFIABLE)] {
+ let dir = scratch(&format!("laundering-{name}"));
+ let r = reason(&ontology(ttl), "owl-rl", Some(&dir));
+
+ assert_eq!(r["inconsistency"]["verdict"], "clash_found_by_this_engine", "{r}");
+ assert_eq!(r["inconsistency"]["checked_by_lean"], false, "{r}");
+
+ let mut values = Vec::new();
+ string_values(&r, &mut values);
+ for v in &values {
+ assert_ne!(
+ v, "unsatisfiable_under_disjointness",
+ "{name}: that verdict is the CHECKER's, earned by an accepted refutation, and \
+ this engine must not state it: {r}"
+ );
+ assert!(
+ !v.contains("OOCert.refutation_fast_sound"),
+ "{name}: naming the soundness theorem is claiming its conclusion: {r}"
+ );
+ }
+ }
+ // And the word the engine does use for a written refutation says plainly
+ // that nothing has checked it.
+ let dir = scratch("laundering-word");
+ let r = reason(&ontology(INCONSISTENT), "owl-rl", Some(&dir));
+ assert_eq!(
+ r["inconsistency"]["refutation"]["verdict"],
+ "refutation_written_not_yet_checked",
+ "{r}"
+ );
+}
+
+#[test]
+fn the_tbox_only_case_is_invisible_here_and_the_tableau_sees_it() {
+ // The documented boundary, computed rather than asserted. `cax-dw` needs an
+ // individual in two disjoint classes. `:Lion` is unsatisfiable and nothing
+ // is an instance of it, so the rule-based route sees nothing at all, and
+ // the report must not pretend otherwise by staying silent about the limit
+ // elsewhere. The SHIQ tableau does see it, and its finding carries no
+ // certificate: that is the more valuable half of this layer and it is not
+ // built.
+ let dir = scratch("tbox-only");
+ let rl = reason(&ontology(TBOX_ONLY), "owl-rl", Some(&dir));
+ assert!(
+ rl.get("inconsistency").is_none(),
+ "an unsatisfiable class with no instance is invisible to cax-dw: {rl}"
+ );
+ assert!(!dir.join("refutation.tsv").exists());
+
+ let store = Arc::new(GraphStore::new());
+ store.load_turtle(&ontology(TBOX_ONLY), None).unwrap();
+ let dl: serde_json::Value = serde_json::from_str(
+ &Reasoner::run_full(&store, "owl-dl", false, InferenceTarget::DefaultGraph, None).unwrap(),
+ )
+ .unwrap();
+ let unsat = dl["unsatisfiable_classes"].as_array().unwrap();
+ assert!(
+ unsat.iter().any(|c| c.as_str() == Some("<http://ex.org/Lion>")),
+ "the tableau must see the case the rules cannot: {dl}"
+ );
+ // And it says, itself, that it certifies nothing when it answers this way.
+ println!("owl-rl: no clash. owl-dl: unsatisfiable_classes = {unsat:?}, with no certificate.");
+
+ // Add ONE individual and the same ontology becomes visible to cax-dw, which
+ // is exactly what the boundary is.
+ let dir2 = scratch("tbox-plus-one");
+ let with_instance = reason(
+ &ontology(&format!("{TBOX_ONLY}:leo a :Lion .\n")),
+ "owl-rl",
+ Some(&dir2),
+ );
+ assert_eq!(with_instance["inconsistency"]["refutation"]["written"], true, "{with_instance}");
+}
+
+#[test]
+fn a_run_without_a_certificate_directory_reports_the_clash_and_writes_nothing() {
+ // The finding is not conditional on being asked for a certificate, or an
+ // ontology reasoned over without `--certificate` would be silently
+ // contradictory. What IS conditional is the file, and the report says so
+ // rather than leaving the caller to wonder where it went.
+ let r = reason(&ontology(INCONSISTENT), "owl-rl", None);
+ assert_eq!(r["inconsistency"]["found"], true, "{r}");
+ assert_eq!(r["inconsistency"]["refutation"]["written"], false, "{r}");
+ let why = r["inconsistency"]["refutation"]["why"].as_str().unwrap();
+ assert!(why.contains("certificate"), "the report must say how to get one: {why}");
+}
+
+#[test]
+fn a_stale_refutation_does_not_survive_a_run_that_finds_nothing() {
+ // A refutation left in the directory by an earlier run would be checked
+ // against THIS run's asserted.tsv, which is a different graph. It would
+ // almost certainly be rejected, and "almost certainly" is not the standard:
+ // a consumer reading the directory must not find a file describing a graph
+ // that is no longer there.
+ let dir = scratch("stale");
+ reason(&ontology(INCONSISTENT), "owl-rl", Some(&dir));
+ assert!(dir.join("refutation.tsv").exists(), "the first run must write one");
+
+ reason(&ontology(CONSISTENT), "owl-rl", Some(&dir));
+ assert!(
+ !dir.join("refutation.tsv").exists(),
+ "a run that finds no clash must leave no refutation behind it"
+ );
+}
+
+#[test]
+fn two_runs_reach_the_same_contradiction() {
+ // The closure lives in a HashSet, so without an explicit order the CHOSEN
+ // CLASH would depend on hash iteration and two runs over one ontology could
+ // report different contradictions. `find_clashes` sorts on the N-Triples
+ // spelling, so the `refute` line is the same every time.
+ //
+ // THE PREFIX IS NOT PINNED HERE, and the reason is not this producer's.
+ // `:leo a :Carnivore` has two derivations in this ontology, one through
+ // `:BigCat` and one through the `rdfs11` transitive subclass triple, and
+ // which one the fixpoint records first depends on the same hash iteration
+ // order that already decides the line order of `derivations.tsv`. Either is
+ // a valid prefix and the checker accepts either. Claiming byte-for-byte
+ // stability for the whole file would be claiming a property the engine's
+ // derivation log does not have.
+ let a = scratch("determinism-a");
+ let b = scratch("determinism-b");
+ reason(&ontology(INCONSISTENT), "owl-rl", Some(&a));
+ reason(&ontology(INCONSISTENT), "owl-rl", Some(&b));
+ let last = |d: &Path| {
+ std::fs::read_to_string(d.join("refutation.tsv"))
+ .unwrap()
+ .lines()
+ .next_back()
+ .unwrap()
+ .to_string()
+ };
+ assert_eq!(
+ last(&a),
+ last(&b),
+ "two runs over one ontology must reach one contradiction"
+ );
+}